python - 如何同时运行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()
但它不起作用
我该如何解决这个问题?
解决方案
我建议使用该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')
推荐阅读
- java - 如何避免 Java 类的这个帮助方法中的代码重复?
- postgresql - 将 ssl 证书路径传递给 PostgreSQL ODBC 驱动程序
- javascript - Vue 生命钩子中的先前和当前数据
- javascript - 如何从虚拟内存在 node.js 中提供 html+js?
- python - Python在列表中移动多个元素
- python-2.7 - 使用 matlotlib linecollection 的列表格式错误
- php - laravel graphql playground 设置时出错
- visual-studio - Visual Studio - Intellij 帮助快捷方式
- python - PYTHON:如何将同名的项目添加在一起,并将它们添加到列表中以查找列表的长度?
- javascript - 当路由配置中的其他路由被命中时反应路由问题