我有一个脚本(a.py),需要多次调用另一个脚本(b.py),每次执行b.py 需要 1 分钟。如果我在 for 循环中运行,这会花费很多时间。
我想知道如何优化它,以减少时间。 任何帮助或建议都会非常有帮助。
源代码:
# a.py
import os
if __name__ == '__main__':
inputs = ['file1', 'file2', 'file3', 'file4']
script_path = 'b.py'
# Some logging statements.
for infile in inputs:
os.system("{} -i {}".format(script_path, infile))
# b.py
# take arguments
# perform some operations
# log the execution
到目前为止,我一直在使用 os.system 来调用其他脚本。如何并行调用脚本 b.py n 次?
最佳答案
您可以使用muliprocessing.Process
并行运行它:
from multiprocessing import Process
inputs = ['file1', 'file2', 'file3', 'file4']
script_path = 'b.py'
def run(script, name):
os.system("{} -i {}".format(script, name))
if __name__ == '__main__':
inputs = ['file1', 'file2', 'file3', 'file4']
script_path = 'b.py'
for infile in inputs:
p = Process(target=run, args=(script_path, infile))
p.start()
p.join()
注意:使用 os.system 从 Python 脚本执行 Python 脚本并不是很优雅。您应该修改脚本 b.py
,使其作为一个模块运行,并通过函数或类提供其主要功能。然后您可以导入 b
并使用这些函数或类。
关于Python运行多个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48355495/