subprocess32 Backport for Python 2

3.5.4 · abandoned · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates the recommended import pattern and basic usage of the `subprocess.run()` function, which was backported from Python 3.5. It includes capturing output, handling errors with `check=True`, and setting a timeout. Note that `text=True` is an alias for `universal_newlines=True` within `subprocess32` for Python 2.

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}")

view raw JSON →