gpt4 book ai didi

python - 从 subprocess.Popen 到多处理

转载 作者:行者123 更新时间:2023-12-03 21:29:43 31 4
gpt4 key购买 nike

我得到了一个使用 subprocess.Popen 调用进程的函数通过以下方式:

    def func():
...
process = subprocess.Popen(substr, shell=True, stdout=subprocess.PIPE)

timeout = {"value": False}
timer = Timer(timeout_sec, kill_proc, [process, timeout])
timer.start()

for line in process.stdout:
lines.append(line)

timer.cancel()
if timeout["value"] == True:
return 0
...

我使用循环从其他函数调用此函数(例如 from range(1,100) ),如何使用多处理对函数进行多次调用?每次都会有几个进程并行运行

进程不相互依赖,唯一的限制是每个进程只能在一个索引上“工作”(例如,没有两个进程可以在索引 1 上工作)

谢谢你的帮助

最佳答案

只需将索引添加到您的 Popen调用并创建一个 worker pool拥有尽可能多的 CPU 内核。

import multiprocessing

def func(index):
....
process = subprocess.Popen(substr + " --index {}".format(index), shell=True, stdout=subprocess.PIPE)
....

if __name__ == '__main__':
p = multiprocessing.Pool(multiprocessing.cpu_count())
p.map(func, range(1, 100))

关于python - 从 subprocess.Popen 到多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39943281/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com