我有一个Python脚本(在另一个应用程序内部运行)生成一堆临时图像。然后我使用subprocess
来启动一个应用程序来查看这些。在长时间运行的子进程退出后清理临时文件夹
当图像查看过程存在时,我想删除临时图像。
我不能从Python做到这一点,因为Python进程可能已经在子进程完成之前退出。即我不能做到以下几点:
p = subprocess.Popen(["imgviewer", "/example/image1.jpg", "/example/image1.jpg"])
p.communicate()
os.unlink("/example/image1.jpg")
os.unlink("/example/image2.jpg")
..as此块为主线,也不是我可以检查为pid
在螺纹等
唯一的解决办法我能想到的办法我必须离开使用shell=True
,我宁愿回避:
import pipes
import subprocess
cmd = ['imgviewer']
cmd.append("/example/image2.jpg")
for x in cleanup:
cmd.extend(["&&", "rm", pipes.quote(x)])
cmdstr = " ".join(cmd)
subprocess.Popen(cmdstr, shell = True)
这工作,但几乎没有优雅..
基本上,我有一个背景和基础d子进程,并且要在退出时删除临时文件,即使Python进程不再存在。
难道你不能只追加'rm'命令,以便subshell在串行中运行两个命令? imageviewer /example/image1.jpg /example/image2.jpg;rm -f /example/*.jpg 还要注意commands.mkarg()函数来处理子命令中的转义空格。 – 2010-05-12 02:05:05