Ste*_*ven 323 python command-line function
我的文件中有以下代码:
def hello():
return 'Hi :)'
Run Code Online (Sandbox Code Playgroud)
我如何从命令行运行它?
Fré*_*idi 504
使用-c
(命令)参数(假设您的文件已命名foo.py
):
$ python -c 'import foo; print foo.hello()'
Run Code Online (Sandbox Code Playgroud)
或者,如果您不关心命名空间污染:
$ python -c 'from foo import *; print hello()'
Run Code Online (Sandbox Code Playgroud)
中间地带:
$ python -c 'from foo import hello; print hello()'
Run Code Online (Sandbox Code Playgroud)
Wol*_*lph 121
只需放在hello()
函数下面的某个位置,它就会在你执行时执行python your_file.py
对于更简洁的解决方案,您可以使用:
if __name__ == '__main__':
hello()
Run Code Online (Sandbox Code Playgroud)
这样,只有在运行文件时才会执行该功能,而不是在导入文件时执行.
Tam*_*más 56
python -c 'from myfile import hello; hello()'
这里myfile
必须使用Python脚本的基本名称来代替.(例如,myfile.py
变成myfile
).
但是,如果hello()
您的Python脚本是"永久"主要入口点,那么通常的方法如下:
def hello():
print "Hi :)"
if __name__ == "__main__":
hello()
Run Code Online (Sandbox Code Playgroud)
这允许您只需运行python myfile.py
或执行脚本python -m myfile
.
这里有一些解释:__name__
是一个特殊的Python变量,它保存当前正在执行的模块的名称,除非从命令行启动模块,在这种情况下它变为"__main__"
.
D. *_*iya 35
我们可以写这样的东西。我已经与 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:])
Run Code Online (Sandbox Code Playgroud)
python demo.py print_fn
python demo.py sum_fn 5 8
Run Code Online (Sandbox Code Playgroud)
Jos*_*rdo 27
我写了一个快速的小Python脚本,可以从bash命令行调用.它采用您要调用的模块,类和方法的名称以及要传递的参数.我称之为PyRun并且不使用.py扩展名并使用chmod + x PyRun使其可执行,以便我可以快速调用它,如下所示:
./PyRun PyTest.ClassName.Method1 Param1
Run Code Online (Sandbox Code Playgroud)
将其保存在名为PyRun的文件中
#!/usr/bin/env python
#make executable in bash chmod +x PyRun
import sys
import inspect
import importlib
import os
if __name__ == "__main__":
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# get the second argument from the command line
methodname = sys.argv[1]
# split this into module, class and function name
modulename, classname, funcname = methodname.split(".")
# get pointers to the objects based on the string names
themodule = importlib.import_module(modulename)
theclass = getattr(themodule, classname)
thefunc = getattr(theclass, funcname)
# pass all the parameters from the third until the end of
# what the function needs & ignore the rest
args = inspect.getargspec(thefunc)
z = len(args[0]) + 2
params=sys.argv[2:z]
thefunc(*params)
Run Code Online (Sandbox Code Playgroud)
这是一个示例模块,展示它是如何工作的.这保存在名为PyTest.py的文件中:
class SomeClass:
@staticmethod
def First():
print "First"
@staticmethod
def Second(x):
print(x)
# for x1 in x:
# print x1
@staticmethod
def Third(x, y):
print x
print y
class OtherClass:
@staticmethod
def Uno():
print("Uno")
Run Code Online (Sandbox Code Playgroud)
尝试运行这些示例:
./PyRun PyTest.SomeClass.First
./PyRun PyTest.SomeClass.Second Hello
./PyRun PyTest.SomeClass.Third Hello World
./PyRun PyTest.OtherClass.Uno
./PyRun PyTest.SomeClass.Second "Hello"
./PyRun PyTest.SomeClass.Second \(Hello, World\)
Run Code Online (Sandbox Code Playgroud)
注意最后一个转义括号的例子,它将元组作为第二个方法的唯一参数传入.
如果为方法所需的参数传递的参数太少,则会出现错误.如果你传球太多,它会忽略额外的东西.该模块必须在当前工作文件夹中,放入PyRun可以在您的路径中的任何位置.
Noa*_*ker 18
将此代码段添加到脚本底部
def myfunction():
...
if __name__ == '__main__':
globals()[sys.argv[1]]()
Run Code Online (Sandbox Code Playgroud)
您现在可以通过运行来调用您的函数
python myscript.py myfunction
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为您将命令行参数(函数名称的字符串)传递给locals
具有当前本地符号表的字典.最后的parantheses将使函数被调用
我需要在命令行上使用各种 python 实用程序(范围、字符串等),并专门为此编写了工具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
Run Code Online (Sandbox Code Playgroud)
让我们自己更容易一点,只需使用一个模块......
尝试: pip install 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()
Run Code Online (Sandbox Code Playgroud)
然后使用如下:
$ python test.py hello
hi there!
$ python test.py goodbye
see ya later.
Run Code Online (Sandbox Code Playgroud)
注意:目前Python 3中存在一个错误,但在Python 2中效果很好.
编辑:一个更好的选择,在我看来是谷歌的模块火,这使得传递函数参数变得容易.它是安装的pip install fire
.从他们的GitHub:
这是一个简单的例子.
import fire
class Calculator(object):
"""A simple calculator class."""
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
Run Code Online (Sandbox Code Playgroud)
然后,从命令行,您可以运行:
python calculator.py double 10 # 20
python calculator.py double --number=15 # 30
Run Code Online (Sandbox Code Playgroud)
该脚本与此处的其他答案类似,但它还列出了可用的函数,以及参数和文档字符串:
"""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)
Run Code Online (Sandbox Code Playgroud)
不带参数运行此脚本以列出可用函数:
$ 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 Code Online (Sandbox Code Playgroud)
使用参数运行此脚本以尝试调用相应的函数:
$ 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
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果目标是打印到命令行控制台或执行其他一些微小的python操作,您可以将输入管道输入python解释器,如下所示:
echo print("hi:)") | python
Run Code Online (Sandbox Code Playgroud)
以及管道文件..
python < foo.py
Run Code Online (Sandbox Code Playgroud)
*请注意,扩展名不一定是.py,第二个工作.**另请注意,对于bash,您可能需要转义字符
echo print\(\"hi:\)\"\) | python
Run Code Online (Sandbox Code Playgroud)