本文翻译自:Run function from the command line
I have this code: 我有这个代码:
def hello(): return 'Hi :)'How would I run this directly from the command line? 我如何直接从命令行运行它?
参考:https://stackoom.com/question/GjD7/从命令行运行函数
It is always an option to enter python on the command line with the command python 使用命令python在命令行上输入python始终是一个选项
then import your file so import example_file 然后导入您的文件, 导入example_file
then run the command with example_file.hello() 然后使用example_file.hello()运行该命令
This avoids the weird .pyc copy function that crops up every time you run python -c etc. 这避免了每次运行python -c等时出现的奇怪的.pyc复制函数。
Maybe not as convenient as a single-command, but a good quick fix to text a file from the command line, and allows you to use python to call and execute your file. 可能不像单个命令那样方便,但是可以快速修复从命令行发送文件,并允许您使用python来调用和执行您的文件。
Something like this: call_from_terminal.py 像这样: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 ipThis works in bash. 这适用于bash。
$ ip='"hi"' ; fun_name='call_from_terminal' $ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})" hiI wrote a quick little Python script that is callable from a bash command line. 我写了一个快速的小Python脚本,可以从bash命令行调用。 It takes the name of the module, class and method you want to call and the parameters you want to pass. 它采用您要调用的模块,类和方法的名称以及要传递的参数。 I call it PyRun and left off the .py extension and made it executable with chmod +x PyRun so that I can just call it quickly as follow: 我称之为PyRun并且不使用.py扩展名并使用chmod + x PyRun使其可执行,以便我可以快速调用它,如下所示:
./PyRun PyTest.ClassName.Method1 Param1Save this in a file called PyRun 将其保存在名为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)Here is a sample module to show how it works. 这是一个示例模块,展示它是如何工作的。 This is saved in a file called PyTest.py: 这保存在名为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")Try running these examples: 尝试运行这些示例:
./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\)Note the last example of escaping the parentheses to pass in a tuple as the only parameter to the Second method. 注意最后一个转义括号的示例,以传入元组作为Second方法的唯一参数。
If you pass too few parameters for what the method needs you get an error. 如果为方法所需的参数传递的参数太少,则会出现错误。 If you pass too many, it ignores the extras. 如果你传球太多,它会忽略额外的东西。 The module must be in the current working folder, put PyRun can be anywhere in your path. 模块必须在当前工作文件夹中,把PyRun放在你的路径的任何地方。
If you install the runp package with pip install runp its a matter of running: 如果使用pip install runp安装runp软件包,则需要运行:
runp myfile.py hello
You can find the repository at: https://github.com/vascop/runp 您可以在以下网址找到存储库: https : //github.com/vascop/runp
Interestingly enough, if the goal was to print to the command line console or perform some other minute python operation, you can pipe input into the python interpreter like so: 有趣的是,如果目标是打印到命令行控制台或执行其他一些微小的python操作,你可以将输入管道输入python解释器,如下所示:
echo print("hi:)") | pythonas well as pipe files.. 以及管道文件..
python < foo.py*Note that the extension does not have to be .py for the second to work. *请注意,扩展名不一定是.py,第二个工作。 **Also note that for bash you may need to escape the characters **另请注意,对于bash,您可能需要转义字符
echo print\(\"hi:\)\"\) | python