我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
当前回答
将此代码片段添加到脚本底部
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。
其他回答
从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__"。
此函数不能从命令行运行,因为它返回的值将不被传递。您可以删除返回并使用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
我需要在命令行上使用各种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