More flexibility with Popen

suggest change

Using subprocess.Popen gives more fine-grained control over launched processes than subprocess.call. The snippets below assume import subprocess.

Launching a subprocess

process = subprocess.Popen([r'C:\path\to\app.exe', 'arg1', '--flag', 'arg'])

The signature for Popen is very similar to the call function; however, Popen will return immediately instead of waiting for the subprocess to complete like call does.

Waiting on a subprocess to complete

process = subprocess.Popen([r'C:\path\to\app.exe', 'arg1', '--flag', 'arg'])
process.wait()

Reading output from a subprocess

Interactive access to running subprocesses

You can read and write on stdin and stdout even while the subprocess hasn’t completed. This could be useful when automating functionality in another program.

Writing to a subprocess

process = subprocess.Popen([r'C:\path\to\app.exe'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, text=True)

process.stdin.write('line of input\n') # Write input

line = process.stdout.readline() # Read a line from stdout

# Do logic on line read.

Without text=True the pipes are binary, so write requires bytes and readline returns bytes. If you only need one set of input and output, rather than dynamic interaction, you should use communicate() rather than directly accessing stdin and stdout.

Reading a stream from a subprocess

In case you want to see the output of a subprocess line by line, you can use the following snippet:

process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
while process.poll() is None:
    output_line = process.stdout.readline()

your_command stands for the argument list. If the subprocess output has no newline, readline waits until one arrives or the pipe closes. You can then read the output one byte at a time, or one character at a time if you pass text=True:

process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
while process.poll() is None:
    output_line = process.stdout.read(1)

The 1 passed to read asks for one byte in binary mode. A negative size reads until EOF. read(0) returns an empty result and does not read until EOF (see here).

In both snippets, process.poll() is None until the subprocess finishes. The loop then stops, so data still buffered in the pipe is not read.

The same procedure could be applied to the stderr of the subprocess.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents