155. Subprocess Management with subprocess
Here are 10 Python snippets demonstrating subprocess management with the subprocess module for running system commands and interacting with external processes. Each snippet is separated by a delimiter.
Snippet 1: Running a Simple Command
import subprocess
result = subprocess.run(['echo', 'Hello, World!'], capture_output=True, text=True)
print("Output:", result.stdout)Snippet 2: Capturing Errors
import subprocess
result = subprocess.run(['ls', 'non_existent_directory'], capture_output=True, text=True)
print("Error:", result.stderr)Snippet 3: Checking Command Success
import subprocess
result = subprocess.run(['ls'], capture_output=True, text=True)
if result.returncode == 0:
print("Command succeeded")
else:
print("Command failed with return code:", result.returncode)Snippet 4: Running a Shell Command
Snippet 5: Redirecting Output to a File
Snippet 6: Passing Input to a Command
Snippet 7: Running a Command Without Waiting for Completion
Snippet 8: Communicating with a Process
Snippet 9: Running Multiple Commands Sequentially
Snippet 10: Using subprocess.PIPE for Real-Time Output
Last updated