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

标签 python windows

我必须在 Windows 7 上启动并执行 24 个独立的 Python 脚本。我希望一个脚本同时启动它们……而不是全部统治它们(我不是索伦)或等待它们结束。我发现 os.startfile() 对此很有趣。但是我没有成功地向那 24 个人发送论据。

coincoin1.py(要上线的24个脚本之一)

import sys
print "hello:",sys.argv 

Anti_Sauron_script.py(将同时启动 24 个)

sys.argv=["send","those","arguments"] 
os.startfile("C:\\Users\\coincoin1.py")

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

最佳答案

您可以使用独立进程 (multiprocessing.Process) 并使用两个队列与其通信 (multiprocessing.Queue),一个用于输入,另一个用于输出。 启动流程的示例:

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 可以是一个计数器,当队列充满新工作时递增)。 multiprocessing.Queue 的使用是健壮的,因为你不需要依赖 stdout/err 解析,你也避免了相关的限制。 此外,您可以轻松管理更多子流程。

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

import Queue
try:
    res = result.get(block = True, timeout = 10)
except Queue.Empty:
    print error

关于python - 如何从一个脚本一起启动多个其他 python 脚本并向它们发送参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6764189/

相关文章:

python - Selenium 与 Python : how to increase resolution for full screen screenshot?

windows - RegSvr32.exe的/n和/i参数有什么区别?

Python - 为什么类列在内置函数列表中?

python - 如何使用 python 以更快的方式执行 100000 次 2d fft?

java - 如何在Java中的Windows资源管理器中获取文件右键单击菜单

windows - hg 作为 Windows 服务

windows - git 在 Windows 上稳定吗?

.net - 禁用交换(页面文件)以确保所有内容都在内存中

python - 在经过证书身份验证的资源上使用 python 请求下载列表文件

python - numpy.histogram 返回值的大小不同