我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
当前回答
使用-c(命令)参数(假设你的文件名为foo.py):
$ python -c 'import foo; print foo.hello()'
或者,如果你不关心命名空间污染:
$ python -c 'from foo import *; print hello()'
中间立场是:
$ python -c 'from foo import hello; print hello()'
其他回答
从myfile导入hello;hello() `,其中myfile必须替换为Python脚本的基名。(例如,myfile.py变成myfile)。
但是,如果hello()是Python脚本中的“永久”主入口点,那么通常的方法如下:
def hello():
print "Hi :)"
if __name__ == "__main__":
hello()
这允许您通过运行python myfile.py或python -m myfile来执行脚本。
这里解释一下:__name__是一个特殊的Python变量,保存当前正在执行的模块的名称,除非从命令行启动模块,在这种情况下,它会变成"__main__"。
让我们简单一点,使用一个模块。
尝试:pip安装compago
然后写:
import compago
app = compago.Application()
@app.command
def hello():
print "hi there!"
@app.command
def goodbye():
print "see ya later."
if __name__ == "__main__":
app.run()
然后用like so:
$ python test.py hello
hi there!
$ python test.py goodbye
see ya later.
注意:目前在Python 3中有一个bug,但在Python 2中工作得很好。
编辑:一个更好的选择,在我看来是模块fire谷歌,它可以很容易地传递函数参数。它安装有pip安装火。来自他们的GitHub:
这里有一个简单的例子。
import fire
class Calculator(object):
"""A simple calculator class."""
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
然后,从命令行,你可以运行:
python calculator.py double 10 # 20
python calculator.py double --number=15 # 30
让您的生活更轻松,安装Spyder。打开文件,然后运行它(单击绿色箭头)。之后,您的hello()方法被定义并被IPython控制台所知道,因此您可以从控制台调用它。
只要把hello()放在函数下面的某个地方,它就会在你执行python your_file.py时执行
为了一个更简洁的解决方案,你可以使用这个:
if __name__ == '__main__':
hello()
这样,函数只会在运行文件时执行,而不会在导入文件时执行。
使用-c(命令)参数(假设你的文件名为foo.py):
$ python -c 'import foo; print foo.hello()'
或者,如果你不关心命名空间污染:
$ python -c 'from foo import *; print hello()'
中间立场是:
$ python -c 'from foo import hello; print hello()'