从 python 同时运行多个命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1639912/
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
Running multiple commands simultaneously from python
提问by randomThought
I want to run three commands at the same time from python. The command format is query.pl -args
我想从 python 同时运行三个命令。命令格式为 query.pl -args
Currently I am doing
目前我正在做
os.system("query.pl -results '10000' -serverName 'server1' >> log1.txt")
os.system("query.pl -results '10000' -serverName 'server2' >> log2.txt")
os.system("query.pl -results '10000' -serverName 'server3' >> log3.txt")
I want to query all three servers at the same time but in this case, each command executes only after the last one has finished. How can I make them simultaneous? I was thinking of using '&' at the end but I want the next part of the code to be run only when all three command finish
我想同时查询所有三个服务器,但在这种情况下,每个命令仅在最后一个完成后执行。我怎样才能让它们同时发生?我想在最后使用 '&' 但我希望代码的下一部分仅在所有三个命令都完成时运行
回答by jldupont
You could use the subprocessmodule and have all three running independently: use subprocess.Popen. Take care in setting the "shell" parameter correctly.
您可以使用subprocess模块并使所有三个独立运行:使用 subprocess.Popen。注意正确设置“shell”参数。
Use the wait() or poll() method to determine when the subprocesses are finished.
使用 wait() 或 poll() 方法确定子进程何时完成。
回答by Oduvan
os.system("query.pl -results '10000' -serverName 'server1' &")
os.system("query.pl -results '10000' -serverName 'server2' &")
os.system("query.pl -results '10000' -serverName 'server3' &")
in this case - process will be started in background
在这种情况下 - 进程将在后台启动
回答by Oduvan
You can use Queue
您可以使用队列
tasks = ("query.pl -results '10000' -serverName 'server1'",\
"query.pl -results '10000' -serverName 'server2'",\
"query.pl -results '10000' -serverName 'server1'")
def worker():
while True:
item = q.get()
os.system(item)
q = Queue()
for i in tasks:
t = Thread(target=worker)
t.setDaemon(True)
t.start()
for item in tasks:
q.put(item)
q.join()