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

标签 python bash unix

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

相关文章:

linux - 如何在bash中提取子字符串

linux - 如何使用sudo获取运行命令的pid

c - 使用 csh 脚本从文件中读取多行

c - mkstemp 和硬盘压力

python - Sklearn语法错误?

python - Dropbox Python API : File size detection may have failed

python - 你如何在 python 中进行双阶乘?

Python:遍历受约束的所有整数组合(找到函数的最小值)

regex - Linux bash : sed, awk 等工具将行尾正则表达式 '$' 匹配为终端宽度

linux - 迭代linux文件ldif