我有一个 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")
..因为这会阻塞主线程,我也无法检查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)
这有效,但几乎不优雅..
基本上,我有一个后台子进程,并且希望在它退出时删除临时文件,即使 Python 进程不再存在。