0
我可以直接与你们核对一下,我的概念在使用Python的多处理并行执行exe文件时有什么根本性的错误。使用多处理进程()进行并行执行的正确方法
所以我有一大堆作业(在示例代码中为100000),我想使用所有可用的核心(我的计算机中有16个)来并行运行它们。下面的代码没有像我看到的许多例子那样使用队列,但它似乎工作。只是为了避免代码“起作用”的情况,但是当我扩展到运行多个计算节点时,有一个巨大的错误在等待炸毁。谁能帮忙?
import subprocess
import multiprocessing
def task_fn(task_dir) :
cmd_str = ["my_exe","-my_exe_arguments"]
try :
msg = subprocess.check_output(cmd_str,cwd=task_dir,stderr=subprocess.STDOUT,universal_newlines=True)
except subprocess.CalledProcessError as e :
with open("a_unique_err_log_file.log","w") as f :
f.write(e.output)
return;
if __name__ == "__main__":
n_cpu = multiprocessing.cpu_count()
num_jobs = 100000
proc_list = [multiprocessing.Process() for p in range(n_cpu)]
for i in range(num_jobs):
task_dir = str(i)
task_processed = False
while not(task_processed) :
# Search through all processes in p_list repeatedly until a
# terminated processs is found to take on a new task
for p in range(len(p_list)) :
if not(p_list[p].is_alive()) :
p_list[p] = multiprocessing.Process(target=task_fn,args=(task_dir,))
p_list[p].start()
task_processed = True
# At the end of the outermost for loop
# Wait until all the processes have finished
for p in p_list :
p.join()
print("All Done!")
嘿,谢谢你的回复!将尝试它。但基本上,我编码的方式没有任何问题吗? – bFig8
是的。事实上,如果发生错误,由于未受保护的文件访问,您的日志文件将全部被打乱。而且,那里的流程的使用是过度的。只需使用线程。 – noxdafox
好吧,也许有一个误解,“a_unique_err_log_file.log”是我懒惰的说,每个日志文件将是唯一的。这并不意味着从字面上理解,因为在文件名中真的是“a_unique_err_log_file.log”,所以每个进程都将写入一个独特的文件。 – bFig8