我需要一个在python上并行运行脚本的方法.子处理是可行的,还是有其他方法值得研究



所以我有一个大脚本,我必须对其进行优化,并将其分为不同的部分:假设我们现在有3个脚本,分别称为S1.py、S2.py和S3.py。脚本过去直接运行,S1和S2都需要大约2分钟,S3需要大约15分钟。

我把它们分开,这样我就可以访问S1和S2的结果,而不需要等待S3。现在我正在进行优化,我想知道是否可以有一个脚本在两个子流程中启动S1和S2,并在运行S3之前等待这两个脚本完成(谁需要S1和S2的结果(。

subprocess.pop((是正确的方法吗?还是在这种情况下我应该使用线程?还有哪些其他方法可以实现这一目标?

您可以在此处了解更多信息https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor

from concurrent.futures import ProcessPoolExecutor
import time
def s1():
return 1
def s2():
return 2
def s3(x,y):
return x+y
def foo(f):
return f()
def main():
with ProcessPoolExecutor(max_workers = 3) as executor:
results = executor.map(foo, [s1, s2])
# now that we have the results
print(s3(*results)) #3
if __name__ == '__main__':
main()

最新更新