我有这样的代码:

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

将此代码片段添加到脚本底部

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。

使用-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()'

只要把hello()放在函数下面的某个地方,它就会在你执行python your_file.py时执行

为了一个更简洁的解决方案,你可以使用这个:

if __name__ == '__main__':
    hello()

这样,函数只会在运行文件时执行,而不会在导入文件时执行。

此函数不能从命令行运行,因为它返回的值将不被传递。您可以删除返回并使用print代替