mcocdawc mcocdawc - 5 months ago 15
Python Question

Doing something after popen is finished

I want to make a background process that displays a

with an external
. When the process is stopped, it should delete the file.
The following piece of code does what I want to do, but it is ugly and I guess there is a more idiomatic way.
It would be perfect, if it is even OS independent.

subprocess.Popen(viewer + ' ' + file + ' && rm ' + file, shell=True)


Using to open the viewer and view the file will exactly do that. Subsequently, run the command to delete the file.

If you want the script to continue while the process is running, use threading

An example:

from threading import Thread
import subprocess
import os

def test():
    file = "/path/to/somefile.jpg"["eog", file])

Thread(target = test).start()
# the print command runs, no matter if the process above is finished or not

This will do exactly what you describe:

  • open the file with eog (viewer), wait for it to finish (closeeog) and remove the file.
  • In the meantime continue the script and print "Banana".