nonblocking_subprocess - Subprocesses with non-blocking I/O

Allow non-blocking interaction with a subprocess.

This module was taken from this recipe in the ActiveState Code Recipes website, with only minor modifications. This is the original description:

Title:        Module to allow Asynchronous subprocess use on Windows and Posix platforms
Submitter:    Josiah Carlson (other recipes)
Last Updated: 2006/12/01
Version no:   1.9
Category:     System 

On Windows pywin32 is required.

class NonblockingPopen(cmd, encoding=None, **kwargs)[source]

An asynchronous variant to subprocess.Popen, which doesn’t block on incomplete I/O operations.

Note that the terms input, output and error refer to the controlled program streams, so we receive from output or error and we send to input.

__init__(cmd, encoding=None, **kwargs)[source]

Execute cmd in a subprocess, using encoding to convert to and from binary data written or read from/to the subprocess’s input, output and error streams.

Additional keyword arguments are as specified by subprocess.Popen.__init__() method.

get_conn_maxsize(which, maxsize)[source]

Return which output pipe (either stdout or stderr) and maxsize constrained to the [1, 1024] interval in a tuple.


Receive at most maxsize bytes from the subprocess’s standard output.


Receive at most maxsize bytes from the subprocess’s standard error.


Send input_ to the subprocess’s standard input.

send_recv(input_='', maxsize=None)[source]

Send input_ to the subprocess’s standard input and then receive at most maxsize bytes from both its standard output and standard error.

recv_some(p, t=0.1, e=1, tr=5, stderr=0)[source]

Try and receive data from NonblockingPopen object p’s stdout in at most tr tries and with a timeout of t. If stderr is True receive from the subprocess’s stderr instead.

send_all(p, data)[source]

Send all of data to NonblockingPopen object p’s stdin.