python-3.x - 使用子进程启动多个程序
问题描述
我正在尝试使用 Python 脚本来启动多个程序。我面临的问题是,虽然这些程序中的第一个程序在 shell 中按预期执行,但第二个程序永远不会执行。有没有办法启动第一个程序而不是让子进程等待启动第二个程序?
我尝试使用模块中的call
功能subprocess
,让主程序等待 5 秒,然后启动第二个。
import subprocess
subprocess.call(['xxx', 'xxxxxx', 'xxxxxxxx', 'shell=True'])
time.sleep(5)
subprocess.call(['xxx', '-x', 'xxxxxx'])
我希望程序在 shell 中启动这些程序中的每一个,但只有第一个程序启动。
解决方案
直接使用模块中的Popen
构造函数在subprocess
后台启动进程。
由于它有效地启动了一个进程,但不等待它完成,我喜欢将它重命名为start
in 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
确实需要添加选项来运行外部进程。
推荐阅读
- c++ - 这个主函数计算奇整数值是什么?
- typescript - 如何从 TypeScript 中的对象数组创建类型?
- java - Spring Boot SLF4J 日志记录性能
- angular11 - 如何在angular11的其他页面中显示路由器链接文本
- ios - 如何检查 ViewController 中单例的变量更新?
- javascript - Pwa Workbox 同步后台 UI
- hive - 我们可以通过元数据提取在 hive 上运行的查询吗
- visual-studio-code - VSCode 市场扩展:损坏的 ZIP:未找到中央目录记录签名的结尾
- elasticsearch - Kibana Visualize 未显示索引数据上可用的所有字段
- android - 无法更改 android 10 的权限,也无法运行 webview