首页 > 解决方案 > 使用子进程启动多个程序

问题描述

我正在尝试使用 Python 脚本来启动多个程序。我面临的问题是,虽然这些程序中的第一个程序在 shell 中按预期执行,但第二个程序永远不会执行。有没有办法启动第一个程序而不是让子进程等待启动第二个程序?

我尝试使用模块中的call功能subprocess,让主程序等待 5 秒,然后启动第二个。

import subprocess

subprocess.call(['xxx', 'xxxxxx', 'xxxxxxxx', 'shell=True'])
time.sleep(5)
subprocess.call(['xxx', '-x', 'xxxxxx'])

我希望程序在 shell 中启动这些程序中的每一个,但只有第一个程序启动。

标签: python-3.xsubprocess

解决方案


直接使用模块中的Popen构造函数subprocess后台启动进程。

由于它有效地启动了一个进程,但不等待它完成,我喜欢将它重命名为startin code。像这样:

from subprocess import Popen as start
process = start('python process.py')

就像在您的示例中一样,您可以只给流程或每个流程足够的时间来完成。但是,最好在退出调用脚本之前等待它们单独完成:

from subprocess import Popen as start

processes = []

for i in range(3):
    process = start(f'python process{i}.py')
    processes.append(process)

for process in processes:
    process.wait()

请参阅模块的文档subprocess以确定是否shell=True确实需要添加选项来运行外部进程。


推荐阅读