我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
当前回答
如果你用pip安装runp包,这是一个运行的问题:
润普 myfile.py 你好
您可以在https://github.com/vascop/runp上找到该存储库
其他回答
让我们简单一点,使用一个模块。
尝试: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
此函数不能从命令行运行,因为它返回的值将不被传递。您可以删除返回并使用print代替
将此代码片段添加到脚本底部
def myfunction():
...
if __name__ == '__main__':
globals()[sys.argv[1]]()
现在可以通过运行来调用函数
python myscript.py myfunction
这是因为您将命令行参数(函数名的字符串)传递到locals中,locals是一个包含当前局部符号表的字典。最后的parantheses将使函数被调用。
更新:如果你想让函数从命令行接受一个参数,你可以传入sys。Argv[2]像这样:
def myfunction(mystring):
print(mystring)
if __name__ == '__main__':
globals()[sys.argv[1]](sys.argv[2])
这样,运行python myscript.py myfunction "hello"将输出hello。
就像这样: 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
从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__"。