我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
当前回答
我们可以这样写。我在python-3.7.x中使用过
import sys
def print_fn():
print("Hi")
def sum_fn(a, b):
print(a + b)
if __name__ == "__main__":
args = sys.argv
# args[0] = current file
# args[1] = function name
# args[2:] = function args : (*unpacked)
globals()[args[1]](*args[2:])
python demo.py print_fn
python demo.py sum_fn 5 8
其他回答
如果你用pip安装runp包,这是一个运行的问题:
润普 myfile.py 你好
您可以在https://github.com/vascop/runp上找到该存储库
我需要在命令行上使用各种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
这个脚本类似于这里的其他答案,但它也列出了可用的函数,带有参数和文档字符串:
"""Small script to allow functions to be called from the command line.
Run this script without argument to list the available functions:
$ python many_functions.py
Available functions in many_functions.py:
python many_functions.py a : Do some stuff
python many_functions.py b : Do another stuff
python many_functions.py c x y : Calculate x + y
python many_functions.py d : ?
Run this script with arguments to try to call the corresponding function:
$ python many_functions.py a
Function a
$ python many_functions.py c 3 5
3 + 5 = 8
$ python many_functions.py z
Function z not found
"""
import sys
import inspect
#######################################################################
# Your functions here #
#######################################################################
def a():
"""Do some stuff"""
print("Function a")
def b():
"""Do another stuff"""
a()
print("Function b")
def c(x, y):
"""Calculate x + y"""
print(f"{x} + {y} = {int(x) + int(y)}")
def d():
# No doc
print("Function d")
#######################################################################
# Some logic to find and display available functions #
#######################################################################
def _get_local_functions():
local_functions = {}
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isfunction(obj) and not name.startswith('_') and obj.__module__ == __name__:
local_functions[name] = obj
return local_functions
def _list_functions(script_name):
print(f"Available functions in {script_name}:")
for name, f in _get_local_functions().items():
print()
arguments = inspect.signature(f).parameters
print(f"python {script_name} {name} {' '.join(arguments)} : {f.__doc__ or '?'}")
if __name__ == '__main__':
script_name, *args = sys.argv
if args:
functions = _get_local_functions()
function_name = args.pop(0)
if function_name in functions:
function = functions[function_name]
function(*args)
else:
print(f"Function {function_name} not found")
_list_functions(script_name)
else:
_list_functions(script_name)
运行不带参数的脚本列出可用的函数:
$ python many_functions.py
Available functions in many_functions.py:
python many_functions.py a : Do some stuff
python many_functions.py b : Do another stuff
python many_functions.py c x y : Calculate x + y
python many_functions.py d : ?
运行这个带有参数的脚本,尝试调用相应的函数:
$ python many_functions.py a
Function a
$ python many_functions.py c 3 5
3 + 5 = 8
$ python many_functions.py z
Function z not found
让我们简单一点,使用一个模块。
尝试: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
使用-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()'