Using Python to Execute Shell Commands: os.system, os.popen, commands, and subprocess
This article explains Python's built‑in methods for invoking shell commands—including os.system, os.popen, the commands module, and the subprocess module—detailing their return values, usage examples, and when to choose each approach for capturing command output.
Python provides several functions for calling shell commands, each with different capabilities. Understanding their return values and behavior helps you select the most suitable method for various tasks.
os.system
os.system(cmd) returns the exit status of the command: 0 indicates success, while any non‑zero value signals an error. The returned integer encodes both the signal that terminated the process (low byte) and the exit status (high byte).
<code>import os
result = os.system('cat /etc/passwd')
print(result) # 0</code>os.popen
os.popen() not only executes the command but also returns a file‑like object containing the command's output. You can read the output using read() on the returned object.
<code>import os
result = os.popen('cat /etc/passwd')
print(result.read())</code>commands (Python 2 only)
The commands module offers functions such as getstatus , getoutput , and getstatusoutput to run shell commands and retrieve status codes or output strings.
<code>import commands
status = commands.getstatus('cat /etc/passwd')
print(status)
output = commands.getoutput('cat /etc/passwd')
print(output)
(status, output) = commands.getstatusoutput('cat /etc/passwd')
print(status, output)</code>subprocess
The subprocess module is a powerful way to manage child processes. It is especially recommended when command arguments or output contain non‑ASCII characters (e.g., Chinese). Using Popen with stdout=subprocess.PIPE allows you to capture and process the output line by line.
<code>import subprocess
res = subprocess.Popen('cat /etc/passwd', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in res.stdout.readlines():
print line
res.stdout.close()</code>Conclusion
Except for os.system , the other methods ( os.popen , commands , and subprocess ) can retrieve the command's output. While os.system is simpler, you should choose one of the other three when you need to capture the result.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.