Python运行多个进程

标签 python multiprocessing

我有一个脚本(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/

相关文章:

Python 多处理意外阻塞

Python Shell 需要一个缩进 block

具有 multiprocessing.Manager 的 Python multiprocessing.Process 对象在 Windows 任务管理器中创建多个多处理分支

multithreading - 计算最小值的最短时间

c - 您如何分析多核处理器的所有内核?

python - `as_completed`模块中的模拟 `multiprocessing`

python - 如何在 Pandas Python 中过滤和取消过滤?

python - 将包含两部分的列转换为 MultiIndex

python - 不在 MySQL 表中插入值

python - 来自 Pandas Dataframe 的文本