Skip to content

How to Fix subprocess.CalledProcessError in Python

DodaTech Updated 2026-06-24 2 min read

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

Python raises subprocess.CalledProcessError when a subprocess command executed with check=True returns a non-zero exit code.

The Wrong Way

import subprocess

result = subprocess.run(["ls", "/nonexistent"], check=True, capture_output=True)
print(result.stdout)

This produces:

Traceback (most recent call last):
  File "script.py", line 3, in <module>
    result = subprocess.run(["ls", "/nonexistent"], check=True, capture_output=True)
subprocess.CalledProcessError: Command '['ls', '/nonexistent']' returned non-zero exit status 2.

The Right Way

Check the return code and stderr for useful information:

import subprocess

result = subprocess.run(["ls", "/nonexistent"], capture_output=True, text=True)
if result.returncode != 0:
    print(f"Command failed with code {result.returncode}")
    print(f"stderr: {result.stderr}")
else:
    print(result.stdout)

Output:

Command failed with code 2
stderr: ls: cannot access '/nonexistent': No such file or directory

Step-by-Step Fix

1. Use try-except for check=True

import subprocess

try:
    result = subprocess.run(["ls", "/nonexistent"], check=True, capture_output=True, text=True)
    print(result.stdout)
except subprocess.CalledProcessError as e:
    print(f"Error (code {e.returncode}): {e.stderr}")

2. Inspect stderr for details

import subprocess

result = subprocess.run(["git", "commit", "-m", "test"], capture_output=True, text=True)
if result.returncode != 0:
    print("Git error output:")
    print(result.stderr)

3. Use shell=True carefully (security risk)

import subprocess

result = subprocess.run("ls /nonexistent", shell=True, capture_output=True, text=True)
# shell=True accepts a string instead of list

4. Log the failing command

import subprocess
import logging

logging.basicConfig(level=logging.ERROR)

def run_safe(cmd):
    try:
        return subprocess.run(cmd, check=True, capture_output=True, text=True)
    except subprocess.CalledProcessError as e:
        logging.error(f"Command '{' '.join(e.cmd)}' failed: {e.stderr}")
        return None

Prevention Tips

  • Always capture stderr when running subprocess commands.
  • Check the command syntax by running it in the terminal first.
  • Use check=False and inspect returncode for expected failures.
  • Use shlex.quote() when constructing commands with user input.
  • Set appropriate timeouts with the timeout parameter.

Common Mistakes with subprocess error

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What exit codes are non-zero?

In Unix, exit code 0 means success. Any non-zero code indicates an error. Code 1 is a general error, code 2 is misuse of shell builtins, code 127 means command not found, and code 137 means killed by signal.

How do I get the stdout of a failed command?

Do not use check=True if you need stdout after a failure. Run with check=False and access result.stdout and result.stderr regardless of the return code.

What is the difference between run() and Popen()?

subprocess.run() is a high-level wrapper that waits for the process to complete. subprocess.Popen() is a low-level class that gives you more control over pipes and non-blocking execution.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro