首页 > 解决方案 > 如何同时运行10个python程序?

问题描述

我有a_1.py~a_10.py

我想并行运行 10 个 python 程序。

我试过了:

from multiprocessing import Process
import os

def info(title):
    I want to execute python program

def f(name):
    for i in range(1, 11):
        subprocess.Popen(['python3', f'a_{i}.py'])


if __name__ == '__main__':
    info('main line')
    p = Process(target=f)
    p.start()
    p.join()

但它不起作用

我该如何解决这个问题?

标签: python

解决方案


我建议使用该subprocess模块而不是multiprocessing

import os
import subprocess
import sys


MAX_SUB_PROCESSES = 10

def info(title):
    print(title, flush=True)

if __name__ == '__main__':
    info('main line')

    # Create a list of subprocesses.
    processes = []
    for i in range(1, MAX_SUB_PROCESSES+1):
        pgm_path = f'a_{i}.py'  # Path to Python program.
        command = f'"{sys.executable}" "{pgm_path}" "{os.path.basename(pgm_path)}"'
        process = subprocess.Popen(command, bufsize=0)
        processes.append(process)

    # Wait for all of them to finish.
    for process in processes:
        process.wait()

    print('Done')

推荐阅读