繁体   English   中英

在后台运行的单个调用中一个接一个地运行一个子进程

[英]Run one subprocess after another in a single call that works in the background

为了在后台运行子进程而不干扰主代码的连续性,我这样调用 Python 文件:

Popen(['secondary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

有什么方法可以使用此调用运行第一个文件( 'secondary.py' ),然后在完成该过程时运行另一个文件( 'tertiary.py' )?

例如:

Popen(['secondary.py','tertiary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

笔记:

我不能这样称呼一个低于另一个:

Popen(['secondary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
Popen(['tertiary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

因为它们将成为两个独立的子流程,这不是我的预期目标,所以我需要完成一个然后运行另一个。

subprocess.run等到命令完成。 您可以创建一个后台线程来连续运行您想要的所有命令。

import threading
import subprocess

def run_background():
    subprocess.run(['secondary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
    subprocess.run(['tertiary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

bg_thread = threading.Thread(target=run_background)
bg_thread.start()

因为这没有被标记为守护线程,所以主线程将等到该线程完成并退出程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM