Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 确定进程是否已成功终止_Python_Bash_Unix - Fatal编程技术网

Python 确定进程是否已成功终止

Python 确定进程是否已成功终止,python,bash,unix,Python,Bash,Unix,我有一些代码可以在后台用python执行unix shell命令 import subprocess process = subprocess.Popen('find / > tmp.txt &',shell=True) 我需要捕捉一个场景,在这个场景中,我知道这个过程已经成功完成 完成 请用示例代码解释 Tazim不需要&:该命令在单独的进程中启动,并独立运行 如果要等待进程终止,请使用: 如果您的程序可以同时执行一些有意义的操作,则可以使用来确定该过程是否已完成 此外,您

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

 import subprocess
 process = subprocess.Popen('find / > tmp.txt &',shell=True)
我需要捕捉一个场景,在这个场景中,我知道这个过程已经成功完成 完成

请用示例代码解释


Tazim

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

如果要等待进程终止,请使用:

如果您的程序可以同时执行一些有意义的操作,则可以使用来确定该过程是否已完成


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

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

proc = subprocess.Popen(['find', '/'], stdout=open('tmp.txt', 'w'))
if proc.wait() == 0:
  pass
如果确实需要文件,请使用
import tempfile
而不是硬编码的临时文件名。如果不需要该文件,请使用管道(参见Thomas建议的子流程文档)


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

另一个注意事项是
shell=True
也是不必要的,因为您传递的命令是一个字符串,必须生成一个shell来计算它。
proc = subprocess.Popen(['find', '/'], stdout=open('tmp.txt', 'w'))
if proc.wait() == 0:
  pass