1

我有一个 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 进程不再存在。

4

1 回答 1

1

If you're on any variant of Unix, you could fork your Python program, and have the parent process go on with its life while the child process daemonized, runs the viewer (doesn't matter in the least if that blocks the child process, which has no other job in life anyway;-), and cleans up after it. The original Python process may or may not exist at this point, but the "waiting to clean up" child process of course will (some process or other has to do the clean-up, after all, right?-).

If you're on Windows, or need cross-platform code, then have your Python program "spawn" (i.e., just start with subprocess, then go on with life) another (much smaller) one, which is the one tasked to run the viewer (blocking, who cares) and then do the clean-up. (If on Unix, even in this case you may want to daemonize, otherwise the child process might go away when the parent process does).

于 2010-05-12T02:11:10.233 回答