mcocdawc mcocdawc - 1 year ago 59
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)

Answer Source

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".
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download