正在确定进程是否已成功终止

2024-05-20 17:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我需要捕捉到这样一个场景:我知道流程已经成功完成 完成。在

请用示例代码解释

塔齐姆


Tags: 代码import命令txttrue场景流程find
2条回答

不要使用shell。这对你的健康有害。在

proc = subprocess.Popen(['find', '/'], stdout=open('tmp.txt', 'w'))
if proc.wait() == 0:
  pass

如果确实需要文件,请使用import tempfile而不是硬编码的临时文件名。如果不需要该文件,请使用管道(参见Thomas建议的子流程文档)。在

另外,不要用Python编写shell脚本。请改用os.walk函数。在

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

如果要等到进程终止,请使用^{}

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

如果您的程序同时可以做一些有意义的事情,可以使用^{}来确定进程是否已经完成。在

此外,您可以直接从管道中读取,而不是将输出写入临时文件,然后从Python程序中读取。有关详细信息,请参阅^{} documentation。在

相关问题 更多 >