Member-only story
Running Shell Commands in Python
Python’s versatility extends to interacting with the operating system, and one of the most useful tools for this is the subprocess
module. This built-in module allows you to run shell commands, interact with processes, and capture their output. Whether you're automating tasks, processing files, or running system commands, subprocess
is a go-to solution.
In this blog post, we’ll explore how to effectively run shell commands in Python, with examples and a detailed explanation of the available options.
Read the full story here: https://allwin-raju-12.medium.com/running-shell-commands-in-python-78f86a501dbc?sk=d22ce7f46594490eca0521c74f083e9a
Basic Usage
Example 1: Running a Simple Command
To execute a simple shell command, use subprocess.run
:
import subprocess
# Run a command
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
# Display the output
print("STDOUT:", result.stdout)
print("STDERR:", result.stderr)
print("Return Code:", result.returncode)
Here’s what happens:
['ls', '-l']
: The command and arguments as a list.capture_output=True
: Captures both stdout and stderr.text=True
: Converts the output to a…