2

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)
mcocdawc
  • 1,748
  • 1
  • 12
  • 21

1 Answers1

3

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".
Jacob Vlijm
  • 3,099
  • 1
  • 21
  • 37
  • Thank you very much for your answer. But in this case it is not put into background and I can't work on. – mcocdawc Sep 17 '16 at 14:23
  • What do you exactly mean by background? If you want the script to continue, use `Threading` – Jacob Vlijm Sep 17 '16 at 14:28
  • Yes, I want the script to continue. I am probably missing the exact vocabulary to rigorously define it. I want a behaviour like``nohup bash -c 'command1 && command2' &``, if I would work in the Linux terminal. Is ``Threading`` really necessary? – mcocdawc Sep 17 '16 at 14:47
  • @mcocdawc see my updated answer. Either you throw out the process the way you do, using `subprocess.Popen()`, or you let `subprocess.call()` handle the job and wait for the process to finish. If you want to continue the script in the meantime, doing other stuff, you need to use `threading`. – Jacob Vlijm Sep 17 '16 at 15:03
  • @mcocdawc: you could use `process = Popen(['eog', path])` instead of the `call()`, to avoid blocking the current thread. To check whether the process has exited, you could [call `process.poll()` later](http://stackoverflow.com/a/14533902/4279). Or you could configure a SIGCHLD signal, to be notified when the process exits (here's [code example for a complicated case, the code in your case is likely to be much simpler](http://stackoverflow.com/a/30281111/4279)). – jfs Oct 29 '16 at 09:51