# Python 子进程

> 原文： [https://pythonspot.com/python-subprocess/](https://pythonspot.com/python-subprocess/)

子流程模块使您可以从 Python 程序启动新应用程序。 多么酷啊？

## 在 Python 中启动一个过程：

You can start a process in Python using the Popen function call. The program below starts the unix program ‘cat’ and the second parameter is the argument. This is equivalent to ‘cat test.py’.  You can start any program with any parameter.

```py
#!/usr/bin/env python

from subprocess import Popen, PIPE

process = Popen(['cat', 'test.py'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print stdout

```

process.communicate（）调用从过程中读取输入和输出。 stdout 是进程输出。 仅当发生错误时，stderr 才会被写入。 如果要等待程序完成，可以调用 Popen.wait（）。

## 子流程 call（）：

Subprocess has a method call() which can be used to start a program. The parameter is a list of which the first argument must be the program name. The full definition is:

```py
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
# Run the command described by args.
# Wait for command to complete, then return the returncode attribute.

```

在下面的示例中，完整的命令将为“ ls -l”

```py
#!/usr/bin/env python

import subprocess
subprocess.call(["ls", "-l"])

```

## 保存进程输出（标准输出）

We can get the output of a program and store it in a string directly using check_output. The method is defined as:

```py
 subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
# Run command with arguments and return its output as a byte string.

```

用法示例：

```py
#!/usr/bin/env python
import subprocess

s = subprocess.check_output(["echo", "Hello World!"])
print("s = " + s)

```