[英]Confusing on subprocess.Popen
这个问题让我很困惑
我只想在 18 个不同的输入文件上运行 1 个命令,所以我这样写
while filenames or running:
while filenames and len(running) < N_CORES:
filename = filenames.pop(0)
print 'Submiting process for %s' % filename
cmd = COMMAND % dict(filename=filename, localdir=localdir)
p = subprocess.Popen(cmd, shell=True)
print 'running:', cmd
running.append((cmd, p))
i = 0
while i < len(running):
(cmd, p) = running[i]
ret = p.poll()
if ret is not None:
rep = open('Crux.report.%d' % (report_number), 'w')
rep.write('Command: %s' % cmd)
print localdir
print 'done!'
report_number += 1
running.remove((cmd, p))
else:
i += 1
time.sleep(1)
但是当我在 3 小时后运行它时,所有过程都会进入睡眠模式。
但是如果我从终端手动调用命令(对于所有不同的文件),所有这些都可以。
任何帮助将不胜感激。
我假设您希望并行运行 18 个进程(每个文件一个进程),但不超过N_CORES
进程。
最简单的方法是在这里使用multiprocessing.Pool
:
import multiprocessing as mp
import subprocess
def process_file(filename):
try:
return filename, subprocess.call([cmd, filename], cwd=localdir)
except OSError:
return filename, None # failed to start subprocess
if __name__ == "__main__":
pool = mp.Pool()
for result in pool.imap_unordered(process_file, filenames):
# report result here
在不知道您的子流程应该做什么以及它们应该运行多长时间的情况下,很难在这里给出准确的答案。
我看到您的程序存在一些问题:
i < len(running)
,同时增加 i 并从running
删除。i
的每个进程还没有完成的时候,你可能想增加如果一个进程已经完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.