How to Fix subprocess.CalledProcessError in Python
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=Falseand inspectreturncodefor expected failures. - Use
shlex.quote()when constructing commands with user input. - Set appropriate timeouts with the
timeoutparameter.
Common Mistakes with subprocess error
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - 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
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro