54. Python's subprocess Module
Here are 10 Python code snippets demonstrating how to use the subprocess module for running and managing system commands and processes from Python:
1. Running a Simple Command
Running a simple system command like ls or dir using subprocess.run().
import subprocess
# Run a system command (list files in current directory)
result = subprocess.run(['ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Print output and errors
print('Output:', result.stdout.decode())
print('Errors:', result.stderr.decode())This runs the ls command (or dir on Windows) and captures its output and error streams.
2. Capturing Command Output
Capturing the output of a command in a variable.
import subprocess
# Run a command and capture the output
result = subprocess.run(['echo', 'Hello, World!'], stdout=subprocess.PIPE)
# Print the captured output
print(result.stdout.decode())This code runs the echo command and captures its output.
3. Running a Command with Shell=True
Running a command as a string with the shell.
The shell=True argument allows running shell commands directly as a string.
4. Handling Command Errors
Handling errors when running a system command.
This runs a non-existent command and catches the error using CalledProcessError.
5. Piping Output to Another Command
Piping the output of one command into another.
This demonstrates piping output from one process to another using Popen objects.
6. Running a Command with Input
Running a command that requires user input.
This sends input to a command and captures the output.
7. Timeout Handling
Running a command with a timeout.
This snippet runs the sleep command for 5 seconds, but a timeout is set for 3 seconds, causing the command to be terminated.
8. Running a Command in the Background
Running a process in the background.
This runs the sleep command in the background and prints its process ID.
9. Getting Command Return Code
Getting the return code of a command to check for success or failure.
This checks the return code to determine whether the command ran successfully.
10. Using Subprocess with Environment Variables
Passing custom environment variables to a subprocess.
This example demonstrates how to pass custom environment variables to a subprocess.
These snippets show how to interact with system processes, run commands, capture their output, and handle errors or custom conditions in Python using the subprocess module.
Last updated