2010-06-21 125 views
2

终止我有一些代码在后台在python确定过程已成功

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

我需要捕捉的场景,我都知道,过程完成成功完成 执行UNIX shell命令。

请示例代码解释

Tazim

+0

只需再次注意'shell = True'也是不必要的,因为您传递的命令是一个字符串,并且必须生成一个shell来评估它。 – 2010-06-21 14:09:48

回答

2

请勿使用shell = True。这对你的健康有害。

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

如果你真的需要一个文件,使用import tempfile而不是硬编码的临时文件名。如果您不需要该文件,请使用管道(请参阅托马斯建议的子流程文档)。

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

3

没有必要为&:该命令是在一个单独的进程中启动,而独立运行。

如果要等到进程终止,使用wait()

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

如果你的程序可以做一些事情在此期间有意义,您可以使用poll()来确定过程已经完成。

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