繁体   English   中英

Python - 启动分离的进程,等待标准输出中的特定 output,然后继续

[英]Python - Launch detached process, wait for specific output in stdout, then continue

我目前有以下 Python 代码:

my_process = subprocess.Popen(["cmd.exe", "/c", "unchangable_long_running_script.bat"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(my_process.stdout.readline, b""):
    print(f">>> {line.rstrip()}")
    if b"Setup complete" in line:
        break
print("All done!")

它启动了一个长时间运行的 Windows 批处理脚本(我无法修改),当遇到特定短语时,表明一切正常,我的 Python 脚本将继续。 因此,运行上述脚本时的控制台 output 类似于:

>>> Doing stuff
>>> Doing more stuff
>>> Setup complete
All done!

我遇到的问题是,我希望子进程在我的 Python 脚本的生命周期之后继续运行。

为了实现这一点,我可以使用此答案中描述的标志,但随后我遇到了问题,即DETACHED_PROCESS导致批处理脚本在父级的单独控制台中运行,根据文档 在这种情况下,标准输出现在被限制在新的控制台中,我的 Python 脚本无法访问。

tldr; 有没有办法在 Python 中启动一个分离的进程,但仍然从该进程读取标准输出以确定分离的进程何时达到其执行的某个点?

好的,所以我想出了这个问题的“解决方法”。

解决方法是启动一个子进程并从中分离,同时让该子进程将其 output 写入文件:

import tempfile

creation_flags = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_BREAKAWAY_FROM_JOB

with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err:
    out.write(str(f"{datetime.now()}\n").encode("utf-8"))
    subprocess.Popen(["cmd.exe", "/c", "unchangable_long_running_script.bat"], creationflags=creation_flags, stdin=subprocess.DEVNULL,
                     stdout=out, stderr=err)

然后,启动子进程的脚本可以读取文件,以确定分离的子进程何时到达其执行所需的点。

暂无
暂无

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

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