我有这样的代码:

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。

其他回答

就像这样: 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

首先,你必须像他们告诉你的那样调用函数,否则该函数将在输出中不显示任何内容,然后保存文件并通过右键单击文件的文件夹复制文件的路径,然后单击“复制文件”,然后转到终端并写入: - CD文件的路径 - python "文件名为例(main.py)" 之后,它将显示代码的输出。

我需要在命令行上使用各种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

有趣的是,如果目标是打印到命令行控制台或执行其他一些minute python操作,你可以像这样将输入管道到python解释器:

echo print("hi:)") | python

以及管道文件..

python < foo.py

*请注意,第二个扩展名不一定是.py。 **还请注意,对于bash,您可能需要转义字符

echo print\(\"hi:\)\"\) | python

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

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。