gpt4 book ai didi

python - 确定进程是否已成功终止

转载 作者:行者123 更新时间:2023-11-28 22:06:46 25 4
gpt4 key购买 nike

我有一些代码可以在 python 后台执行 unix shell 命令

 import subprocess
process = subprocess.Popen('find / > tmp.txt &',shell=True)

我需要捕获我知道流程已成功完成的场景 完成。

请用示例代码说明

塔齐姆

最佳答案

不需要&:该命令在单独的进程中启动,并独立运行。

如果您想等到进程终止,请使用 wait() :

process = subprocess.Popen('find / > tmp.txt', shell = True)
exitcode = process.wait()
if exitcode == 0:
# successful completion
else:
# error happened

如果您的程序可以同时做一些有意义的事情,您可以使用 poll()确定该过程是否已完成。

此外,您可以直接从管道中读取,而不是将输出写入临时文件,然后从 Python 程序中读取。请参阅subprocess documentation了解详情。

关于python - 确定进程是否已成功终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3084214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com