Four Ways to Execute Shell Commands in Python
This article explains four Python techniques—os.system, os.popen, the commands module, and subprocess—for running shell commands, comparing their ability to capture output, return status, and recommending subprocess as the most flexible modern solution.
Python provides several built‑in ways to run shell commands. The first method uses os.system() , which executes the command but does not capture its output.
<code>>> os.system('ls')</code>Note that this method cannot retrieve the command’s output.
The second method uses os.popen() , which returns the command output as a string that can be processed further.
<code>>> import os<br>>> result = os.popen('ls').read()<br>>> lines = result.split("\n")<br>>> for line in lines:<br> print(line)</code>Its result is similar to the first method, but you can manipulate the output string.
The third method employs the deprecated commands module, offering getstatusoutput() to obtain both the exit status and the output.
<code>>> import commands<br>>> status, output = commands.getstatusoutput('ls')</code>commands.getoutput() returns only the output, while commands.getstatus() is not recommended.
The fourth method uses the modern subprocess module, which can create new processes, connect to their I/O pipes, and retrieve return codes, effectively replacing the older functions.
<code>>> import subprocess<br>>> subprocess.call('ls', shell=True) # prints output directly<br>>> proc = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE)<br>>> out, _ = proc.communicate()</code>All four approaches allow execution of shell commands from Python, with subprocess being the preferred and most flexible option.
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.