Doing something after popen is finished
<p>I want to make a background process that displays a <code>file</code> with an external <code>viewer</code>. 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.</p>

<pre><code> subprocess.Popen(viewer + ' ' + file + ' &amp;&amp; rm ' + file, shell=True)
</code></pre>

<p>Using <code>subprocess.call()</code> to open the viewer and view the file will exactly do that. Subsequently, run the command to delete the file.</p>

<p>If you want the script to continue while the process is running, use <code>threading</code></p>

<p>An example:</p>

<pre><code>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")
</code></pre>

<p>This will do exactly what you describe:</p>

<ul>
<li>open the file with <code>eog</code> (viewer), wait for it to finish (close<code>eog</code>) and remove the file. </li>
<li>In the meantime continue the script and print "Banana".</li>
</ul>

python python-3.x subprocess popen