multiprocessing - 多处理命令列表

标签 multiprocessing python-3.6

我正在尝试运行命令列表。问题是该列表可能会很长,因此同时运行多个命令会很棒。

如何使用多处理模块执行此操作?

list_of_commands = [cmd foo, cmd bar, ...]

main_log_file = open( os.getcwd() + '/Error.log', 'w+')

Count = 0
for Job in list_of_commands:
    Count += 1
    child = subprocess.Popen(Job, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    streamdata = child.communicate()[0]
    errcode = child.returncode
    if errcode == 0:
        print ( 'Job', Count, 'Success' )
    elif errcode == 1:
        print ( 'Job', Count, 'Completed With Errors' )
    elif errcode == 2:
        print ( 'Job', Count, 'Error' )
        main_log_file.write ( streamdata.decode('ascii') + str(errcode) + '\n' )

main_log_file.close()

执行顺序并不重要

最佳答案

您可以使用concurrent.futures.ThreadPoolExecutor map 函数来运行恒定数量的并行执行。

WORKERS = 5  # amount of concurrent executions you want

def launcher(job):
    child = subprocess.Popen(job, ... )
    streamdata = child.communicate()[0]
    ...

with concurrent.futures.ThreadPoolExecutor(max_workers=WORKERS) as pool:
    pool.map(launcher, jobs)

关于multiprocessing - 多处理命令列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45686984/

相关文章:

python - 使用 python 的多处理并行化 keras 中的模型预测

multithreading - 超线程处理器内核可以完全同时执行两个线程吗?

python - conda 安装 python=3.6 UnsatisfiableError

python - 如何在 Python 3 Click 应用程序中遍历 shell 提供的文件列表?

python - 同时分配给一个numpy数组

c++ - OpenMP:循环遍历 'std::map' 基准(动态调度)

python - 使用多进程和子进程在 python 中运行并行 Stata do 文件

python - 如何让随机大小的形状从屏幕顶部落到底部?

python - 尝试使用 sk learn 绘制线性回归模型时遇到模糊的 RuntimeWarning

python - 安装 python 3.6 virtualenv 而不修改我的 python 3.5 安装