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

Copy

import subprocess

result = subprocess.run(['echo', 'Hello, World!'], capture_output=True, text=True)
print("Output:", result.stdout)

Snippet 2: Capturing Errors

Copy

import subprocess

result = subprocess.run(['ls', 'non_existent_directory'], capture_output=True, text=True)
print("Error:", result.stderr)

Snippet 3: Checking Command Success

Copy

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

Copy


Snippet 5: Redirecting Output to a File

Copy


Snippet 6: Passing Input to a Command

Copy


Snippet 7: Running a Command Without Waiting for Completion

Copy


Snippet 8: Communicating with a Process

Copy


Snippet 9: Running Multiple Commands Sequentially

Copy


Snippet 10: Using subprocess.PIPE for Real-Time Output

Copy


Last updated