从另一个 Python 脚本运行 Python 脚本,传入参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3781851/
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 a Python script from another Python script, passing in arguments
提问by Gern Blanston
I want to run a Python script from another Python script. I want to pass variables like I would using the command line.
我想从另一个 Python 脚本运行一个 Python 脚本。我想像使用命令行一样传递变量。
For example, I would run my first script that would iterate through a list of values (0,1,2,3) and pass those to the 2nd script script2.py 0then script2.py 1, etc.
例如,我将运行我的第一个脚本,该脚本将遍历值列表 (0,1,2,3) 并将它们传递给第二个脚本script2.py 0thenscript2.py 1等。
I found Stack Overflow question 1186789which is a similar question, but ars's answer calls a function, where as I want to run the whole script, not just a function, and balpha's answer calls the script but with no arguments. I changed this to something like the below as a test:
我发现Stack Overflow 问题 1186789是一个类似的问题,但 ars 的回答调用了一个函数,因为我想运行整个脚本,而不仅仅是一个函数,而 balpha 的回答调用了脚本但没有参数。我将其更改为如下所示的内容作为测试:
execfile("script2.py 1")
But it is not accepting variables properly. When I print out the sys.argvin script2.py it is the original command call to first script "['C:\script1.py'].
但它没有正确接受变量。当我打印出sys.argv在 script2.py 中时,它是对第一个脚本“['C:\script1.py'] 的原始命令调用。
I don't really want to change the original script (i.e. script2.py in my example) since I don't own it.
我真的不想更改原始脚本(即我的示例中的 script2.py),因为我不拥有它。
I figure there must be a way to do this; I am just confused how you do it.
我想一定有办法做到这一点;我只是很困惑你是如何做到的。
采纳答案by Greg Hewgill
回答by Chris Adams
SubProcess module:
http://docs.python.org/dev/library/subprocess.html#using-the-subprocess-module
子进程模块:http:
//docs.python.org/dev/library/subprocess.html#using-the-subprocess-module
import subprocess
subprocess.Popen("script2.py 1", shell=True)
With this, you can also redirect stdin, stdout, and stderr.
有了这个,您还可以重定向 stdin、stdout 和 stderr。
回答by Katriel
This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:
这本质上是错误的做法。如果您从另一个 Python 脚本运行 Python 脚本,则应通过 Python 而不是通过操作系统进行通信:
import script1
In an ideal world, you will be able to call a function inside script1directly:
在理想的世界中,您将能够script1直接调用内部函数:
for i in range(whatever):
script1.some_function(i)
If necessary, you can hack sys.argv. There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.
如有必要,您可以 hack sys.argv。使用上下文管理器有一种巧妙的方法可以确保您不会进行任何永久性更改。
import contextlib
@contextlib.contextmanager
def redirect_argv(num):
sys._argv = sys.argv[:]
sys.argv=[str(num)]
yield
sys.argv = sys._argv
with redirect_argv(1):
print(sys.argv)
I think this is preferable to passing all your data to the OS and back; that's just silly.
我认为这比将所有数据传递给操作系统并返回更可取;那太傻了。
回答by kindall
Ideally, the Python script you want to run will be set up with code like this near the end:
理想情况下,您要运行的 Python 脚本将在接近尾声时使用如下代码进行设置:
def main(arg1, arg2, etc):
# do whatever the script does
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2], sys.argv[3])
In other words, ifthe module is called from the command line, it parses the command line options and then calls another function, main(), to do the actual work. (The actual arguments will vary, and the parsing may be more involved.)
换句话说,如果模块是从命令行调用的,它会解析命令行选项,然后调用另一个函数main()来完成实际工作。(实际参数会有所不同,解析可能更复杂。)
If you want to call such a script from another Python script, however, you can simply importit and call modulename.main()directly, rather than going through the operating system.
但是,如果您想从另一个 Python 脚本调用这样的脚本,您可以简单地直接import调用它modulename.main(),而不是通过操作系统。
os.systemwill work, but it is the roundabout (read "slow") way to do it, as you are starting a whole new Python interpreter process each time for no raisin.
os.system会起作用,但这是一种迂回(读作“慢”)的方式,因为您每次都在启动一个全新的 Python 解释器过程,而没有葡萄干。
回答by Nikos
import subprocess
subprocess.call(" python script2.py 1", shell=True)
回答by Medhat
I think the good practice may be something like this;
我认为好的做法可能是这样的;
import subprocess
cmd = 'python script.py'
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()
result = out.split('\n')
for lin in result:
if not lin.startswith('#'):
print(lin)
according to documentation The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:
根据文档 subprocess 模块允许您生成新进程,连接到它们的输入/输出/错误管道,并获取它们的返回代码。该模块打算替换几个较旧的模块和功能:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. Read Here
使用communication() 而不是.stdin.write、.stdout.read 或.stderr.read 来避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致的死锁。 在这里阅读

