subprocess.Popen subprocess.run
时间: 2023-10-27 14:10:45 浏览: 186
subprocess.Popen and subprocess.run are both modules in Python's subprocess module that are used for running external commands. Here's a brief explanation of each:
1. subprocess.Popen: This function is used to create a new process and execute a command within it. It provides more flexibility and control over the execution process. Popen returns a Popen object, which allows you to interact with the running process, such as reading its output or terminating it.
Example usage:
```python
import subprocess
# Run a command and get its output
result = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
output = result.communicate()
print(output.decode('utf-8'))
```
2. subprocess.run: This function is a higher-level convenience function introduced in Python 3.5. It is used to run a command and wait for it to complete. It returns a CompletedProcess object that provides information about the completed process, such as return code and output.
Example usage:
```python
import subprocess
# Run a command and get its output
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
```
Both functions can be used to execute external commands, but the choice between them depends on your requirements. Popen offers more flexibility, while run provides a simpler and more straightforward way to execute commands.
阅读全文