参考
Python模块之subprocess用法实例详解 - 腾讯云开发者社区-腾讯云
上面这个链接主要说了一些用法
补充
通用示例
先来看一个的用法,执行 ls 命令,返回结果,没有报错,执行完命令后需要用 wait 等待执行完毕,要不然会卡死
import subprocess
import shlex
ret = dict()
cmd = 'ls'
p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, close_fds=True)
p.wait()
ret['code'] = p.returncode
ret['out'] = p.communicate()[0]
ret['err'] = p.communicate()[1]
print(ret)
{'code': 0, 'out': b'123.py\n123.txt\ntest.py\n', 'err': b''}
有报错
{'code': 127, 'out': b'', 'err': b'/bin/sh: 1: lsi: not found\n'}
- stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
- close_fds=True表示子进程将不会继承父进程的输入、输出、错误管道。
管道符
stdin, stdout, stderr 这三个常用参数,例如现在要执行 ls | grep test.py 这条命令是先执行 ls 再执行 grep test.py
shell 中是管道符连接两个命令,subprocess 也可以
import subprocess
import shlex
ret = dict()
p1=subprocess.Popen('ls',shell=True,stdout=subprocess.PIPE)
p=subprocess.Popen('grep test.py',shell=True,stdin=p1.stdout,stdout=subprocess.PIPE)
p.wait()
ret['code'] = p.returncode
ret['out'] = p.communicate()
print(ret)
{'code': 0, 'out': (b'test.py\n', None)}
shell=True 参数使用来判断是否用 shell 执行,可以参考
subprocess 执行命令,调用脚本,输入密码等操作_木下瞳的博客-CSDN博客_subprocess输入密码