Skip to content

How to Fix Python subprocess CalledProcessError

DodaTech 2 min read

In this tutorial, you'll learn about How to Fix Python subprocess CalledProcessError. We cover key concepts, practical examples, and best practices.

The Problem

Your Python script using subprocess.run() raises subprocess.CalledProcessError when the external command exits with a non-zero status code, crashing your program. This is the default behavior when check=True is used and the command fails.

Quick Fix

Capture Output and Check returncode Manually

python3 -c "
import subprocess

result = subprocess.run(['false'], capture_output=True, text=True)
if result.returncode != 0:
    print(f'Command failed with code {result.returncode}')
    print(f'stderr: {result.stderr}')
"
# Command failed with code 1
# stderr:

Set capture_output=True to collect stdout and stderr instead of printing them directly. This lets you inspect the output even when the command fails.

Use check=False to Suppress the Exception

python3 -c "
import subprocess

result = subprocess.run(['ls', '/nonexistent'], capture_output=True, text=True, check=False)
if result.returncode != 0:
    print(f'Error: {result.stderr.strip()}')
else:
    print(result.stdout)
"
# Error: ls: cannot access '/nonexistent': No such file or directory

The default check=False lets you inspect the result without raising exceptions. Use check=True only when a failure truly should halt execution.

python3 -c "
import subprocess

try:
    subprocess.run(['ls', '/nonexistent'], capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
    print(f'Return code: {e.returncode}')
    print(f'stderr: {e.stderr}')
"
# Return code: 2
# stderr: ls: cannot access '/nonexistent': No such file or directory

Wrap check=True calls in try/except to log the error details that the exception carries, such as stdout, stderr, and the command string.

Verify Your Python Environment

python3 --version
# Python 3.10.12
pip list | grep requests
# requests            2.31.0

Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Use subprocess.CompletedProcess for Structured Output

python3 -c "
import subprocess
proc = subprocess.run(['echo', 'hello'], capture_output=True, text=True)
print(f'stdout: {proc.stdout.strip()}')
print(f'returncode: {proc.returncode}')
"
# stdout: hello
# returncode: 0

The CompletedProcess object gives you structured access to stdout, stderr, and the return code. This is cleaner than using Popen manually and avoids common mistakes with pipe handling.

Prevention

  • Use check=False (the default) and inspect result.returncode for expected failures
  • Always capture stderr by setting capture_output=True so error messages are available for debugging
  • Log both stdout and stderr when a command fails to capture full diagnostic information
  • Use shlex.split() to safely parse command strings instead of hardcoding argument lists

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro