【发布时间】:2024-01-15 21:59:01
【问题描述】:
我有一个 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 进程不再存在。
【问题讨论】:
-
您不能只附加
rm命令,以便子shell 串行运行两个命令吗? imageviewer /example/image1.jpg /example/image2.jpg;rm -f /example/*.jpg 注意还要看commands.mkarg()函数处理子命令中的转义空格。
标签: python subprocess temporary-files