我有一些代码可以在 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/