subprocess.run
时间: 2023-11-25 17:32:56 浏览: 87
`subprocess.run` is a function in the Python `subprocess` module that allows you to run a command in a subprocess and capture its output. It was introduced in Python 3.5 as a simpler and more powerful replacement for the older `subprocess.call` function.
Here is an example usage of `subprocess.run`:
```python
import subprocess
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))
```
In this example, we call the `ls` command with the `-l` option to list the contents of the current directory in long format. The output of the command is captured as a byte string in the `stdout` attribute of the `CompletedProcess` object returned by `subprocess.run`. We decode the byte string to a UTF-8 string and print it to the console.
`subprocess.run` has many options that allow you to customize its behavior, such as setting the working directory, redirecting input and output, and controlling timeouts and signals. You can find more information about these options in the Python documentation.
阅读全文