如何从一个脚本启动多个其他python脚本并向它们发送参数?

2024-06-28 18:47:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须在Windows7上启动并执行24个独立的python脚本。我要一个脚本同时启动它们。。。不统治他们(我不是索伦)或等待他们的结局。我发现操作系统启动文件()很有趣。但我没能成功地向这24人发出论据。在

coincoin1.py(即将启动的24个脚本之一)

import sys
print "hello:",sys.argv 

安提苏伦_脚本.py(将共同推出24款手机)

^{pr2}$

如何向这些脚本发送参数并一起启动它们?


Tags: 文件pyimport脚本hellosys手机print
3条回答

您可以使用独立进程(多处理过程)并使用两个队列与它通信(多处理队列)一个用于输入,另一个用于输出。 启动流程的示例:

import multiprocessing

def processWorker(input, result):
    work = input.get()
    ## execute your command here
    pipe = subprocess.Popen(command, stdout = subprocess.PIPE,
                             stderr = subprocess.PIPE, shell = True)
    stdout, stderr = pipe.communicate()
    result.put(pipe.returncode)

input  = multiprocessing.Queue()
result = multiprocessing.Queue()

p = multiprocessing.Process(target = processWorker, args = (input, result))
p.start()
commandlist = ['ls -l /', 'ls -l /tmp/']
for command in commandlist:
    input.put(command)
for i in xrange(len(commandlist)):
    res = result.get(block = True)
    if not res is 0:
        print 'One command failed'

然后,您可以跟踪每个子进程正在执行的命令,只需存储与workid相关联的命令(当队列被新工作填充时,workid可以是递增的计数器)。 使用多处理队列是健壮的,因为您不需要依赖stdout/err解析,而且还避免了相关的限制。 此外,您可以轻松地管理更多的子流程。在

然后,您还可以设置一个超时值,以确定您希望get调用在最大值时等待多长时间,例如:

^{pr2}$

您希望使用subprocess模块:http://docs.python.org/library/subprocess.html,特别是本小节中关于生成进程的第一个示例,而不需要等待它们完成http://docs.python.org/library/subprocess.html#replacing-the-os-spawn-family

像这样?在

from subprocess import Popen, PIPE

python_scripts = ['coincoin1.py','coincoin2.py','coincoin3.py'...]
args = ' -w hat -e ver'

procs = []
for f in python_scripts:
    procs.append(Popen(f+args, shell=True,stdout=PIPE,stderr=PIPE))

results = []

while procs:
    results.append (procs.pop(0).communicate())

do_something_with_results(resuls)

相关问题 更多 >