site logo

Ask. Code. Learn. Grow with the Developer Community.


Category: (All)
❮  Go Back

How to Run External Commands from Python Safely

How can I call an external command from Python as if I had typed it in a shell or command prompt?

How to Run External Commands from Python Safely

coldshadow44 on 2025-10-13





Make a comment


Showing comments related to this post.

_

2025-10-14

The recommended way in modern Python is to use the subprocess module, which is safe and flexible.


Python 3.5+ Example with subprocess.run
import subprocess

# Run 'ls -l' (or any other shell command)
subprocess.run(["ls", "-l"])
  1. Pass the command and arguments as a list of strings.
  2. subprocess.run executes the command, waits for it to finish, and returns a CompletedProcess object.
  3. You can capture the output if needed:
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)

Why Not os.system?

import os
os.system("ls -l")
  1. Works, but unsafe if the command includes user input.
  2. Limited: you can’t easily capture stdout/stderr or handle errors robustly.
  3. The official Python documentation recommends subprocess instead.

Python 3.4 and Earlier

If you’re using Python 3.4 or older:

import subprocess
subprocess.call(["ls", "-l"])
  1. subprocess.call is similar to subprocess.run, but does not return a CompletedProcess object.
  2. For more advanced usage, upgrade to Python 3.5+ and use subprocess.run.





Member's Sites: