54. Python's subprocess Module
1. Running a Simple Command
Running a simple system command like ls or dir using subprocess.run().
Copy
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.
Copy
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.
Copy
The shell=True argument allows running shell commands directly as a string.
4. Handling Command Errors
Handling errors when running a system command.
Copy
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.
Copy
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.
Copy
This sends input to a command and captures the output.
7. Timeout Handling
Running a command with a timeout.
Copy
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.
Copy
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.
Copy
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.
Copy
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