Python Shell Interaction
Executing Shell Commands with Python
Python provides multiple methods to interact with shell environments, enabling seamless system automation and command execution.
Subprocess Module
import subprocess
## Execute shell command
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
## Run complex shell commands
output = subprocess.check_output('df -h', shell=True, text=True)
print(output)
Command Line Arguments
import sys
## Access command line arguments
script_name = sys.argv[0]
arguments = sys.argv[1:]
for arg in arguments:
print(f"Processing argument: {arg}")
Shell Command Interaction Methods
Method |
Module |
Use Case |
subprocess.run() |
subprocess |
Simple command execution |
os.system() |
os |
Basic command running |
subprocess.Popen() |
subprocess |
Advanced process management |
subprocess.check_output() |
subprocess |
Capture command output |
Error Handling in Shell Commands
import subprocess
try:
result = subprocess.run(['ls', '/nonexistent'],
capture_output=True,
text=True,
check=True)
except subprocess.CalledProcessError as e:
print(f"Command failed with error: {e}")
flowchart TD
A[Python Script] --> B{Execute Shell Command}
B --> C{Command Successful?}
C -->|Yes| D[Process Output]
C -->|No| E[Handle Error]
D --> F[Continue Execution]
E --> G[Log/Raise Exception]