我是 python 的 subprocess 模块的新手,目前我的实现不是多处理的。
import subprocess,shlex
def forcedParsing(fname):
cmd = 'strings "%s"' % (fname)
#print cmd
args= shlex.split(cmd)
try:
sp = subprocess.Popen( args, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE )
out, err = sp.communicate()
except OSError:
print "Error no %s Message %s" % (OSError.errno,OSError.message)
pass
if sp.returncode== 0:
#print "Processed %s" %fname
return out
res=[]
for f in file_list: res.append(forcedParsing(f))
我的问题:
sp.communicate 是个好方法吗?我应该使用投票吗?
如果我使用轮询,我需要一个单独的进程来监控进程是否正确完成?
我应该在
for
循环处 fork 吗?
最佳答案
1) subprocess.communicate() 似乎是您尝试做的事情的正确选择。而且您不需要轮询过程,communicate() 仅在完成时返回。
2) 你的意思是 fork 并行化工作?看看multiprocessing ( python > = 2.6)。使用子进程运行并行进程当然是可能的,但这是一项相当大的工作,你不能只调用 communicate(),这是阻塞的。
关于您的代码:
cmd = 'strings "%s"' % (fname)
args= shlex.split(cmd)
为什么不简单呢?
args = ["strings", fname]
至于这个丑陋的模式:
res=[]
for f in file_list: res.append(forcedParsing(f))
您应该尽可能使用列表理解:
res = [forcedParsing(f) for f in file_list]
关于python - 多处理子流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3530806/