我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
当前回答
此函数不能从命令行运行,因为它返回的值将不被传递。您可以删除返回并使用print代替
其他回答
我需要在命令行上使用各种python实用程序(range, string等),并为此专门编写了pyfunc工具。你可以用它来丰富你的命令行使用经验:
$ pyfunc -m range -a 1 7 2
1
3
5
$ pyfunc -m string.upper -a test
TEST
$ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
analyze this
此函数不能从命令行运行,因为它返回的值将不被传递。您可以删除返回并使用print代替
从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__"。
只要把hello()放在函数下面的某个地方,它就会在你执行python your_file.py时执行
为了一个更简洁的解决方案,你可以使用这个:
if __name__ == '__main__':
hello()
这样,函数只会在运行文件时执行,而不会在导入文件时执行。
将此代码片段添加到脚本底部
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。