Last modified: Feb 19, 2026 By Alexander Williams
Python OS System Get Output Guide
Python is a powerful language for system automation. You often need to run shell commands from within a script. The os.system() function is a common starting point. However, it has a key limitation. It does not capture the command's output.
This article explains this limitation. It then shows you the better tools for the job. You will learn how to reliably execute commands and get their results.
Understanding os.system()
The os.system() function is part of Python's standard library. It lets you run a command as if you were in a terminal. It takes a command string as its argument.
When you call it, the command executes. The function returns the exit status of the command. An exit status of 0 typically means success. Any other number usually indicates an error.
The critical point is that it prints output directly to the console. Your Python program cannot store or process that output. This makes it less useful for automation.
import os
# Running a simple command with os.system
exit_code = os.system("echo Hello from the shell")
print(f"The command exited with code: {exit_code}")
Hello from the shell
The command exited with code: 0
The text "Hello from the shell" appears on the screen. But it is not stored in a variable. Only the number 0 is captured in `exit_code`.
The Solution: The subprocess Module
For modern Python, the subprocess module is the recommended tool. It is more powerful and flexible than os.system(). It is designed specifically for spawning processes and communicating with them.
The subprocess.run() function is the best high-level choice. It was introduced in Python 3.5. It simplifies the process of running commands and capturing results.
Using subprocess.run() to Capture Output
The key to capturing output is the `capture_output=True` argument. This tells Python to grab anything the command prints to standard output (stdout) or standard error (stderr). The result is stored in a `CompletedProcess` object.
import subprocess
# Run a command and capture its output
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print("Return Code:", result.returncode)
print("Standard Output:")
print(result.stdout)
print("Standard Error:")
print(result.stderr)
Return Code: 0
Standard Output:
total 24
-rw-r--r-- 1 user staff 893 Feb 10 10:00 script.py
-rw-r--r-- 1 user staff 220 Feb 9 14:30 data.txt
Standard Error:
Now the directory listing is stored in `result.stdout`. You can use it in your program. You can search it, save it to a file, or parse it for data.
The `text=True` argument is important. It tells Python to return the output as a regular string. Without it, the output is returned as raw bytes.
Handling Errors and Checking Results
You should always check the return code. A non-zero code often means the command failed. The subprocess module can also raise an exception automatically. Use `check=True` for this.
import subprocess
try:
# This command will fail because 'nonexistentcommand' doesn't exist
result = subprocess.run(["nonexistentcommand"], capture_output=True, text=True, check=True)
print(result.stdout)
except subprocess.CalledProcessError as e:
print(f"Command failed with exit code {e.returncode}")
print(f"Error output: {e.stderr}")
Command failed with exit code 127
Error output: /bin/sh: nonexistentcommand: command not found
This makes your scripts more robust. They can handle failures gracefully instead of crashing.
Practical Examples and Use Cases
Let's look at some practical ways to use this capability. Capturing command output is useful for many automation tasks.
Example 1: Getting System Information
You can run system commands to gather information. This script gets the current username and system uptime.
import subprocess
# Get the current user
user_result = subprocess.run(["whoami"], capture_output=True, text=True)
current_user = user_result.stdout.strip()
# Get the system uptime
uptime_result = subprocess.run(["uptime"], capture_output=True, text=True)
uptime_info = uptime_result.stdout
print(f"Current User: {current_user}")
print(f"System Uptime: {uptime_info}")
Example 2: Processing Command Data
Once you have the output as a string, you can process it like any other text. This example lists files and counts them.
import subprocess
# List files and count them
result = subprocess.run(["ls"], capture_output=True, text=True)
files = result.stdout.splitlines() # Creates a list of filenames
print(f"Found {len(files)} file(s) in the directory:")
for file in files:
print(f" - {file}")
This technique is powerful. You can filter results, extract specific lines, or format data for reports. For instance, if you later wanted to change font size in Python output for a report, you could process the captured data first.
Key Differences: os.system vs. subprocess
It's important to know why subprocess is better. Here is a simple comparison.
os.system: Simple, but limited. Runs a command. Returns an exit code. Output goes directly to the screen. It is harder to control and secure.
subprocess.run: Modern and full-featured. Can capture output and error streams. Allows fine-grained control over the process. Better security against shell injection attacks. It is the clear winner for new code.
You should avoid os.system() for any task where you need the command's output. The subprocess module is the standard solution.
Security Considerations
Running shell commands from Python can be risky. If you use input from a user to build a command, you risk shell injection attacks. A malicious user could run dangerous commands.
Always prefer the list form of arguments in subprocess.run(). This method is safer. It does not invoke the system shell by default.
# SAFE: Pass command and arguments as a list
subprocess.run(["ls", "-l", "/home/user"])
# UNSAFE: Building a command string from user input can be dangerous
user_input = "/home/user; rm -rf /" # Malicious input!
subprocess.run(f"ls -l {user_input}", shell=True) # This is dangerous!
The unsafe example would list a directory and then try to delete everything. Using the list format prevents the shell from interpreting special characters like `;`.
Conclusion
You cannot get output directly from os.system(). It is designed only to run commands and give back an exit code. For capturing output, you must use the subprocess module.
Remember these steps. Import subprocess. Use subprocess.run() with `capture_output=True` and `text=True`. Access the output from the `stdout` attribute of the result object.
This method gives you full control. You can automate system tasks, process results, and build robust tools. It is an essential skill for any Python developer working with the operating system. Start using subprocess today for all your command execution needs.