Python 从命令行运行函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3987041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run function from the command line
提问by Steven
I have this code:
我有这个代码:
def hello():
return 'Hi :)'
How would I run this directly from the command line?
我如何直接从命令行运行它?
采纳答案by Frédéric Hamidi
With the -c(command)argument (assuming your file is named foo.py):
使用-c(command)参数(假设您的文件名为foo.py):
$ python -c 'import foo; print foo.hello()'
Alternatively, if you don't care about namespace pollution:
或者,如果您不关心命名空间污染:
$ python -c 'from foo import *; print hello()'
And the middle ground:
中间地带:
$ python -c 'from foo import hello; print hello()'
回答by Tamás
python -c 'from myfile import hello; hello()'where myfilemust be replaced with the basename of your Python script. (E.g., myfile.pybecomes myfile).
python -c 'from myfile import hello; hello()'wheremyfile必须替换为 Python 脚本的基本名称。(例如,myfile.py变成myfile)。
However, if hello()is your "permanent" main entry point in your Python script, then the usual way to do this is as follows:
但是,如果hello()是 Python 脚本中的“永久”主要入口点,那么通常的方法如下:
def hello():
print "Hi :)"
if __name__ == "__main__":
hello()
This allows you to execute the script simply by running python myfile.pyor python -m myfile.
这允许您通过运行python myfile.py或来执行脚本python -m myfile。
Some explanation here: __name__is a special Python variable that holds the name of the module currently being executed, exceptwhen the module is started from the command line, in which case it becomes "__main__".
这里有一些解释:__name__是一个特殊的 Python 变量,它保存当前正在执行的模块的名称,除非模块从命令行启动,在这种情况下它变成"__main__".
回答by Wolph
Just put hello()somewhere below the function and it will execute when you do python your_file.py
只需放在hello()函数下方的某个位置,它就会在您执行时执行python your_file.py
For a neater solution you can use this:
对于更简洁的解决方案,您可以使用:
if __name__ == '__main__':
hello()
That way the function will only be executed if you run the file, not when you import the file.
这样,函数只会在您运行文件时执行,而不是在导入文件时执行。
回答by Shubham
This function cannot be run from the command line as it returns a value which will go unhanded. You can remove the return and use print instead
此函数不能从命令行运行,因为它返回一个将无人处理的值。您可以删除返回并使用打印代替
回答by user2495144
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 调用和执行您的文件。
回答by Al Conrad
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 ip
This works in bash.
这适用于 bash。
$ ip='"hi"' ; fun_name='call_from_terminal'
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi
回答by Joseph Gagliardo
I wrote a quick little Python script that is callable from a bash command line. 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:
我编写了一个可从 bash 命令行调用的快速小 Python 脚本。它接受您要调用的模块、类和方法的名称以及您要传递的参数。我将其称为 PyRun 并取消了 .py 扩展名,并使用 chmod +x PyRun 使其可执行,以便我可以快速调用它,如下所示:
./PyRun PyTest.ClassName.Method1 Param1
Save 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 可以放在您路径中的任何位置。
回答by vascop
If you install the runp package with pip install runpits a matter of running:
如果你安装 runp 包,pip install runp它的运行问题:
runp myfile.py hello
runp myfile.py hello
You can find the repository at: https://github.com/vascop/runp
您可以在以下位置找到存储库:https: //github.com/vascop/runp
回答by Torie J
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:)") | python
as well as pipe files..
以及管道文件..
python < foo.py
*Note that the extension does not have to be .py for the second to work. **Also note that for bash you may need to escape the characters
*请注意,第二个工作的扩展名不必是 .py。**另请注意,对于 bash,您可能需要对字符进行转义
echo print\(\"hi:\)\"\) | python
回答by Saurabh Hirani
I had a requirement of using various python utilities (range, string, etc.) on the command line and had written the tool pyfuncspecifically for that. You can use it to enrich you command line usage experience:
我需要在命令行上使用各种 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

