共计 2477 个字符,预计需要花费 7 分钟才能阅读完成。
导读 | 这次来说 Python 的第三方库 subprocess 库,在 python2.4 以上的版本 commands 模块被 subprocess 取代了。一般当我们在用 Python 写运维脚本时,需要履行一些 Linux shell 的命令,Python 中 subprocess 模块就是专门用于调用 Linux shell 命令,并返回状态和结果,可以完美的解决这个问题 |
subprocess
官方中文文档
介绍参考文档,我的直观感受和实际用法是:subprocess 可以开启一个子进程来运行 cmd 命令。那就意味着可以在一个 py 文件里运行另一个 py 文件
例 1 - 快速使用 subprocess
新建一个目录,目录下有两个文件
|-demo | |
|-main.py | |
|-hello.py |
在 hello.py 中
# hello.py | |
print('hello world!') |
在 main.py 中
import subprocess | |
subprocess.run(['python', 'hello.py']) |
执行 main.py 文件得到如下结果
hello world!
例 2 -subprocess.run() 的返回值
修改代码如下:
# main.py | |
import subprocess | |
res = subprocess.run(['python', 'hello.py']) | |
print("args:", res.args) | |
print("returncode", res.returncode) |
运行后
hello world! | |
args: ['python', 'hello.py'] | |
returncode: 0 |
returncode 表示你 run 的这个 py 文件过程是否正确,如果正确,返回 0,否则返回 1
例 3 - 全面的返回值介绍
修改 main.py
# main.py | |
import subprocess | |
res = subprocess.run(['python', 'hello.py']) | |
print("args:", res.args) | |
print("returncode", res.returncode) | |
print("stdout", res.stdout) | |
print("stderr", res.stderr) |
结果:
hello world! | |
args: ['python', 'hello.py'] | |
returncode 0 | |
stdout None | |
stderr None | |
Process finished with exit code 0 |
可以看到,没有设置 subprocess.run() 中的参数 stdout 和 stderr 时,这两项都是 None
例 4 - 代码有 bug 的情况
新建 fail.py,故意制造一个 bug
# fail.py | |
a = |
修改 main.py
# main.py | |
import subprocess | |
res = subprocess.run(['python', 'hello.py']) | |
res2 = subprocess.run(['python', 'fail.py']) |
再运行 main 函数,得到返回
hello world! | |
File "fail.py", line 2 | |
a = | |
^ | |
SyntaxError: invalid syntax |
可以看到,先是正确打印了 hello.py 的内容,然后是 fail.py 的错误信息。
例 5 - 捕获 stdout 和 stderr
修改 main.py
# main.py | |
import subprocess | |
res = subprocess.run(['python', 'hello.py'], stdout=subprocess.PIPE) | |
res2 = subprocess.run(['python', 'fail.py'], stderr=subprocess.PIPE) | |
print('hello.py stdout:', res.stdout) | |
print('fail.py stderr:', res2.stderr) |
结果
hello.py stdout: b'hello world!\r\n' | |
fail.py stderr: b'File"fail.py", line 2\r\n a =\r\n ^\r\nSyntaxError: invalid syntax\r\n' |
可以通过 res.stdout 与 res2.stderr 分别拿到正确 print 的信息和错误信息。
同时可以发现,子进程 print 和报错内容就不会在父进程打印输出了。
注意这里的 res.stdout 是一串二进制字符串。如果设置 encoding 参数,拿到的就是字符串。
res = subprocess.run(['python', 'hello.py'], | |
stdout=subprocess.PIPE, | |
encoding='utf8') |
例 6 - 与子进程进行通信
可以通过 subprocess.run() 的 input 参数给子进程发送消息。如果不设置 encoding,就要传入二进制串,比如 b ’hello input’
# main.py | |
import subprocess | |
from subprocess import PIPE | |
res = subprocess.run(['python', 'hello.py'], | |
input='hello input', | |
encoding='utf8') |
修改 hello.py 接收传进来的字符串。
# hello.py | |
import sys | |
data = sys.stdin.read() | |
print(data) |
结果
hello input | |
Process finished with exit code 0 |
正文完
星哥玩云-微信公众号
