views:

34

answers:

1

I have a Python script (running inside another application) which generates a bunch of temporary images. I then use subprocess to launch an application to view these.

When the image-viewing process exists, I want to remove the temporary images.

I can't do this from Python, as the Python process may have exited before the subprocess completes. I.e I cannot do the following:

p = subprocess.Popen(["imgviewer", "/example/image1.jpg", "/example/image1.jpg"])
p.communicate()
os.unlink("/example/image1.jpg")
os.unlink("/example/image2.jpg")

..as this blocks the main thread, nor could I check for the pid exiting in a thread etc

The only solution I can think of means I have to use shell=True, which I would rather avoid:

cmd = ['imgviewer']
cmd.append("/example/image2.jpg")

for x in cleanup:
    cmd.extend(["&&", "rm", x])

cmdstr = " ".join(cmd)
subprocess.Popen(cmdstr, shell = True)

This works, but is hardly elegant, and will fail with filenames containing spaces etc..

Basically, I have a background subprocess, and want to remove the temp files when it exits, even if the Python process no longer exists.

A: 

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).

Alex Martelli