returncode of Popen object is None after the process is terminated
<p>I'm running a process with the use of <code>Popen</code>. I need to wait for the process to terminate. I'm checking that the process have terminated through the <code>returncode</code>. When <code>returncode</code> is different from <code>None</code> the process must have terminated. The problem is that when <code>print_output</code> is <code>False</code> the <code>returncode</code> is always <code>None</code>, even when the process have finished running (terminated). This is however not the case when <code>print_output</code> is <code>True</code>. I'm using the following code to run the process:</p>

<pre><code>def run(command, print_output=True):
    # code mostly from: http://sharats.me/the-ever-useful-and-neat-subprocess-module.html
    from subprocess import Popen, PIPE
    from threading import Thread
    from queue import Queue, Empty
    from time import sleep

    io_q = Queue()

    def stream_watcher(identifier, stream):
        for line in stream:
            io_q.put((identifier, line))

        if not stream.closed:
            stream.close()

    with Popen(command, stdout=PIPE, stderr=PIPE, universal_newlines=True) as proc:
        if print_output:

            Thread(target=stream_watcher, name='stdout-watcher', args=('STDOUT', proc.stdout)).start()
            Thread(target=stream_watcher, name='stderr-watcher', args=('STDERR', proc.stderr)).start()

            def printer():
                while True:
                    try:
                        # Block for 1 second.
                        item = io_q.get(True, 1)
                    except Empty:
                        # No output in either streams for a second. Are we done?
                        if proc.poll() is not None:
                            break
                    else:
                        identifier, line = item
                        print(identifier + ':', line, end='')

            Thread(target=printer, name='printer').start()

        while proc.returncode is None:
            sleep(2)
            proc.poll()

        if not proc.returncode == 0:
            raise RuntimeError(
                'The process call "{}" returned with code {}. The return code is not 0, thus an error '
                'occurred.'.format(list(command), proc.returncode))

        return proc.stdout, proc.stderr
</code></pre>

<p>Any clues to what might cause this problem? </p>

<p>EDIT: Discovered something pretty weird. I'm running the following code:</p>

<pre><code>run(my_command, True)
print('--------done--------')
run(my_command, False)
print('--------done--------')
</code></pre>

<p><code>'--------done--------'</code> is never printed even though <code>run(my_command, False)</code> gets executed.</p>