2024年4月16日发(作者:)

`subprocess` 模块是 Python 中用于创建和管理子进程的标准库。它提供了一种在 Python

中启动新进程、连接它们的输入、输出和错误管道,并获取它们的返回值的方法。下面是

`subprocess` 模块的一些常见用法:

1. 启动新进程并等待其完成:

```python

import subprocess

# 执行命令并等待其完成

(["ls", "-l"])

```

2. 获取命令的输出:

```python

import subprocess

# 获取命令的输出

result = (["ls", "-l"], capture_output=True, text=True)

print()

```

3. 传递输入给子进程:

```python

import subprocess

# 传递输入给子进程

result = (["grep", "hello"], input="hello worldnhow

capture_output=True, text=True)

print()

```

4. 检查命令的返回值:

```python

import subprocess

# 检查命令的返回值

result = (["ls", "nonexistentfile"])

if code != 0:

print("Error:", )

```

are youn",

5. 使用管道连接多个子进程:

```python

import subprocess

# 使用管道连接多个子进程

p1 = (["ls", "-l"], stdout=)

p2 = (["grep", "test"], stdin=, stdout=)

() # Allow p1 to receive a SIGPIPE if p2 exits.

output = icate()[0]

print(('utf-8'))

```

以上是 `subprocess` 模块的一些基本用法,你可以根据自己的需求和场景进一步查阅官方

文档,以了解更多用法和选项。