mcocdawc mcocdawc - 2 months ago 9
Python Question

Doing something after popen is finished

I want to make a background process that displays a

file
with an external
viewer
. 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

Using subprocess.call() 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"
    subprocess.call(["eog", file])
    os.remove(file)

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

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".
Comments