How to use the subprocess module in Python?
The subprocess module in Python is used for creating and managing child processes. It offers a simple way to execute external commands and interact with them. Here are some common methods and usage examples of the subprocess module.
- run() method: This method is used to execute an external command and wait for the command to complete. It returns a CompletedProcess object that contains the output of the command execution.
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
- Popen() function: This function is used to create a child process object, which can be used for executing, controlling, and interacting with the child process.
import subprocess
process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output, error = process.communicate()
print(output)
- check_output() method: This method is used to execute an external command and return the output of the command. If the command execution fails, a CalledProcessError exception will be raised.
import subprocess
output = subprocess.check_output(['ls', '-l'], text=True)
print(output)
- The communicate() method is used to interact with a subprocess, including sending input data to the subprocess and retrieving the output and error messages from the subprocess.
import subprocess
process = subprocess.Popen(['grep', 'hello'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output, error = process.communicate(input='hello world')
print(output)
Here are some common methods and usage examples of the subprocess module. Depending on your specific needs, you can choose the appropriate method to execute and manage subprocesses.