subprocess 使用执行 cmd

参考

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输入密码

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值