subprocess32 Backport for Python 2
subprocess32 is a backport of the `subprocess` standard library module from Python 3 (specifically APIs from versions 3.2 through 3.5) for use on Python 2.x. It includes critical bugfixes, notably for reliability in threaded applications on POSIX systems, and new features like timeout support (from Python 3.3) and the `run()` API (from Python 3.5). The latest version is 3.5.4, released in May 2019. The project is explicitly end-of-life (EOL) as Python 2 itself has reached EOL, meaning there are no further active developments or planned releases.
Warnings
- breaking The `subprocess32` library is explicitly end-of-life (EOL) along with Python 2. This means no further development, bug fixes, or security updates are planned. Relying on it in new projects is strongly discouraged.
- gotcha `subprocess32` is primarily designed for POSIX systems (Linux, macOS) and has not been tested or fully supported on Windows or other non-POSIX platforms. Attempts to install or use it on Windows may lead to compilation errors (e.g., missing `unistd.h`) or unexpected behavior.
- gotcha While `subprocess32` backports `timeout` support (from Python 3.3) and the `run()` API (from Python 3.5), other features and APIs are 'frozen at the 3.2 level'. This means `subprocess32` is not a complete, feature-for-feature replica of the latest Python 3 `subprocess` module.
- gotcha The primary motivation for `subprocess32` was to address race conditions and improve thread-safety in Python 2.x's native `subprocess` module on POSIX systems, particularly in multi-threaded applications. Not using `subprocess32` (i.e., using the built-in `subprocess` on Python 2) can lead to unreliable behavior and crashes when processes are spawned in threaded contexts.
Install
-
pip install subprocess32
Imports
- subprocess
import os, sys if sys.version_info[0] < 3: try: import subprocess32 as subprocess except ImportError: import subprocess else: import subprocess
Quickstart
import os, sys
# Recommended import pattern for cross-version compatibility
if sys.version_info[0] < 3:
try:
import subprocess32 as subprocess
except ImportError:
print("Warning: subprocess32 not found, using native subprocess module.")
import subprocess
else:
import subprocess
try:
# Execute a simple command
result = subprocess.run(
['echo', 'Hello, subprocess32!'],
capture_output=True,
text=True, # In Python 2, this maps to universal_newlines=True
check=True,
timeout=5
)
print("STDOUT:", result.stdout.strip())
print("STDERR:", result.stderr.strip())
# Example with error
subprocess.run(['false'], check=True)
except subprocess.CalledProcessError as e:
print(f"Command failed with exit code {e.returncode}")
except subprocess.TimeoutExpired:
print("Command timed out")
except Exception as e:
print(f"An unexpected error occurred: {e}")