【发布时间】:2011-04-28 13:45:17
【问题描述】:
我有这个代码:
def hello():
return 'Hi :)'
如何直接从命令行运行它?
【问题讨论】:
-
您的意思可能是
print "Hi :)"而不是return 'Hi :)'。
标签: python function command-line
我有这个代码:
def hello():
return 'Hi :)'
如何直接从命令行运行它?
【问题讨论】:
print "Hi :)" 而不是return 'Hi :)'。
标签: python function command-line
使用-c (command) 参数(假设您的文件名为foo.py):
$ python -c 'import foo; print foo.hello()'
或者,如果您不关心命名空间污染:
$ python -c 'from foo import *; print hello()'
中间立场:
$ python -c 'from foo import hello; print hello()'
【讨论】:
$python -c "import foo;foo.hello()"
print foo.hello() 替换为 print(foo.hello()) 确实有效。我没有 python 知识来解释为什么会这样,所以如果其他人可以解释会发生什么,那将不胜感激
只需将hello() 放在函数下方的某个位置,当您执行python your_file.py 时它就会执行
对于更简洁的解决方案,您可以使用以下方法:
if __name__ == '__main__':
hello()
这样该函数只会在您运行文件时执行,而不是在您导入文件时执行。
【讨论】:
hello() 采用了应该由命令行提供的参数呢?
sys.argv 发送到该方法。或者通过 hello 方法访问它
hello() 中)并从命令行运行它?
python -c 'from myfile import hello; hello()' 其中myfile 必须替换为 Python 脚本的基本名称。 (例如,myfile.py 变为 myfile)。
但是,如果 hello() 是 Python 脚本中的“永久”主入口点,那么通常的执行方式如下:
def hello():
print "Hi :)"
if __name__ == "__main__":
hello()
这使您只需运行python myfile.py 或python -m myfile 即可执行脚本。
这里有一些解释:__name__是一个特殊的Python变量,它保存着当前正在执行的模块的名称,除了当模块从命令行启动时,在这种情况下它变成@ 987654330@.
【讨论】:
python -m foo -c 'foo.bar()' 和python -c 'import foo; foo.bar()' 有什么区别?我得到不同的行为,在第一种情况下似乎忽略了 -c 参数。
将此 sn-p 添加到脚本的底部
def myfunction():
...
if __name__ == '__main__':
globals()[sys.argv[1]]()
您现在可以通过运行来调用您的函数
python myscript.py myfunction
之所以有效,是因为您将命令行参数(函数名称的字符串)传递给locals,这是一个具有当前本地符号表的字典。最后的括号将使函数被调用。
更新:如果你希望函数从命令行接受参数,你可以像这样传入sys.argv[2]:
def myfunction(mystring):
print(mystring)
if __name__ == '__main__':
globals()[sys.argv[1]](sys.argv[2])
这样,运行python myscript.py myfunction "hello" 将输出hello。
【讨论】:
myfunction(12)
我编写了一个可从 bash 命令行调用的快速 Python 小脚本。它需要您要调用的模块、类和方法的名称以及您要传递的参数。我将其命名为 PyRun 并省略了 .py 扩展名并使用 chmod +x PyRun 使其可执行,这样我就可以快速调用它,如下所示:
./PyRun PyTest.ClassName.Method1 Param1
将其保存在一个名为 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)
这里有一个示例模块来展示它是如何工作的。这保存在一个名为 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")
尝试运行这些示例:
./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\)
注意最后一个转义括号以将元组作为唯一参数传递给 Second 方法的示例。
如果您传递的参数太少而无法满足该方法的需要,则会出现错误。如果你传递太多,它会忽略额外的。模块必须在当前工作文件夹中,PyRun 可以放在路径中的任何位置。
【讨论】:
让我们自己简化一点,只使用一个模块...
试试: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()
然后像这样使用:
$ python test.py hello
hi there!
$ python test.py goodbye
see ya later.
注意:目前 Python 3 中有一个 bug,但在 Python 2 中效果很好。
编辑:在我看来,一个更好的选择是 Google 的模块 fire,它可以很容易地传递函数参数。它与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)
然后,您可以从命令行运行:
python calculator.py double 10 # 20
python calculator.py double --number=15 # 30
【讨论】:
python -m fire file_name method_name。它还有一个内置的 argparser。
我们可以这样写。我用过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
【讨论】:
有趣的是,如果目标是打印到命令行控制台或执行一些其他微小的 python 操作,您可以像这样将输入管道输入到 python 解释器:
echo print("hi:)") | python
还有管道文件..
python < foo.py
*请注意,扩展名不必是 .py 才能使第二个工作。 **另请注意,对于 bash,您可能需要转义字符
echo print\(\"hi:\)\"\) | python
【讨论】:
echo import foo;foo.hello() | python
echo 'print("hi:)")' | python
如果您使用 pip install runp 安装 runp 包,则需要运行:
runp myfile.py hello
您可以在以下位置找到存储库:https://github.com/vascop/runp
【讨论】:
我需要在命令行上使用各种 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
【讨论】:
类似这样的: 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
【讨论】:
在命令行中输入 python 总是一个选项 python
然后导入您的文件,以便 import example_file
然后使用 example_file.hello()
运行命令这避免了每次运行 python -c 等时出现的奇怪的 .pyc 复制功能。
可能不如单个命令方便,但可以快速修复从命令行向文件发送文本,并允许您使用 python 调用和执行您的文件。
【讨论】:
下面是包含函数定义的 Odd_Even_function.py 文件。
def OE(n):
for a in range(n):
if a % 2 == 0:
print(a)
else:
print(a, "ODD")
现在从下面的命令提示符调用相同的选项对我有用。
选项 1 exe的完整路径\python.exe -c "导入奇偶函数;奇偶函数.OE(100)"
选项 2 exe的完整路径\python.exe -c "从奇偶函数导入 OE;OE(100)"
谢谢。
【讨论】:
此函数不能从命令行运行,因为它返回的值将不经处理。您可以删除 return 并使用 print 代替
【讨论】:
使用python-c 工具(pip install python-c)然后简单地写:
$ python-c foo 'hello()'
或者如果你的 python 文件中没有函数名冲突:
$ python-c 'hello()'
【讨论】:
首先您必须按照他们告诉您的方法调用该函数,否则该函数将在输出中不显示任何内容,然后保存文件并通过右键单击文件的文件夹复制文件的路径并单击“复制”文件”然后转到终端并写入: - cd "文件的路径" - python“文件名例如(main.py)” 之后它将显示您的代码的输出。
【讨论】:
让您的生活更轻松,安装 Spyder。打开您的文件,然后运行它(单击绿色箭头)。之后,您的 hello() 方法被定义并为 IPython 控制台所知,因此您可以从控制台调用它。
【讨论】: