参见英文答案 Python subprocess in parallel 3个我有以下代码将md5sums写入日志文件for file in files_output:p=subprocess.Popen([md5sum,file],stdout=logfile)p.wait()...

参见英文答案 > Python subprocess in parallel 3个
我有以下代码将md5sums写入日志文件
for file in files_output:
p=subprocess.Popen(['md5sum',file],stdout=logfile)
p.wait()
>这些是并行写的吗?即如果md5sum对其中一个文件花费很长时间,那么在等待前一个文件完成之前是否会启动另一个文件?
>如果上面的答案是肯定的,我可以假设写入日志文件的md5sums的顺序可能因md5sum对每个文件的持续时间而有所不同吗? (有些文件可能很大,有些文件很小)
解决方法:
所有子流程并行运行. (为了避免这一点,必须明确等待它们的完成.)它们甚至可以同时写入日志文件,从而使输出变得混乱.为避免这种情况,您应该让每个进程写入不同的日志文件,并在所有进程完成后收集所有输出.
q = Queue.Queue()
result = {} # used to store the results
for fileName in fileNames:
q.put(fileName)
def worker():
while True:
fileName = q.get()
if fileName is None: # EOF?
return
subprocess_stuff_using(fileName)
wait_for_finishing_subprocess()
checksum = collect_md5_result_for(fileName)
result[fileName] = checksum # store it
threads = [ threading.Thread(target=worker) for _i in range(20) ]
for thread in threads:
thread.start()
q.put(None) # one EOF marker for each thread
在此之后,结果应存储在结果中.
本文标题为:Python:并行运行子进程


基础教程推荐
- 13行python代码实现对微信进行推送消息的示例代码 2022-08-30
- Ubuntu18.04安装Python虚拟环境 2023-09-03
- python开发之virtualenv与virtualenvwrapper(linux下安装与配置) 2023-09-04
- Python 运算符Inplace 与Standard 2022-10-20
- Python+OpenCV实战之实现文档扫描 2022-10-20
- c-如何将Python脚本中的串行数据发送到Windows上的Arduino-无效 2023-11-13
- 进程与子进程(python3入门) 2023-09-04
- python分析inkscape路径数据方案简单介绍 2022-10-20
- 如何利用python turtle绘图自定义画布背景颜色 2023-08-04
- Python办公自动化之Excel介绍 2023-08-09