我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
当前回答
让您的生活更轻松,安装Spyder。打开文件,然后运行它(单击绿色箭头)。之后,您的hello()方法被定义并被IPython控制台所知道,因此您可以从控制台调用它。
其他回答
此函数不能从命令行运行,因为它返回的值将不被传递。您可以删除返回并使用print代替
在命令行上使用python命令输入python始终是一个选项
然后导入您的文件,因此导入example_file
然后使用example_file.hello()运行命令
这避免了每次运行python -c等时突然出现的奇怪的.pyc复制函数。
也许不像单个命令那么方便,但是从命令行文本文件的一个很好的快速修复,并允许您使用python来调用和执行您的文件。
就像这样: call_from_terminal.py
# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
print ip
这在bash中工作。
$ ip='"hi"' ; fun_name='call_from_terminal'
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi
有趣的是,如果目标是打印到命令行控制台或执行其他一些minute python操作,你可以像这样将输入管道到python解释器:
echo print("hi:)") | python
以及管道文件..
python < foo.py
*请注意,第二个扩展名不一定是.py。 **还请注意,对于bash,您可能需要转义字符
echo print\(\"hi:\)\"\) | python
只要把hello()放在函数下面的某个地方,它就会在你执行python your_file.py时执行
为了一个更简洁的解决方案,你可以使用这个:
if __name__ == '__main__':
hello()
这样,函数只会在运行文件时执行,而不会在导入文件时执行。