python_day6 subprocess模块,

本文介绍了Python中subprocess模块的基本用法,包括如何使用Popen类执行外部命令,并通过管道读取输出结果。此外还讲解了如何处理错误输出及实现命令间的数据传递。

os.system功能,不直接打印到屏幕,而是传递参数

如果想将结果放入变量再随意打印 就需要 subprocess 模块了

将执行结果丢入管道(正确的进stdout,错误的进stderr, 执行双命令,第二个命令  用stdin);管道的值只能取一次

 

import subprocess
subprocess.Popen('dir',shell=True) -->直接打印

res=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)
-->结果扔进管道 stdout->subprocess.PIPE
JG=res.stdout.read().decode('gbk')-->字符编码参考当前软件
print(JG)


res=subprocess.Popen('abcddir',shell=True,stdout=process.PIPE,
stderr=subprocess.PIPE)

JG=res.stdout.read().decode('gbk')-->没结果
print(JG)

ERR=res.stderr.read().decode('gbk')
print(ERR) -->打印错误信息


##stdin-->管道功能,(爬虫可以使用,爬下来之后传递给下面截取)

res=subprocess.Popen('ls /|grep bin',shell=True,stdout=process.PIPE)
print(res)

等于这种:
res=subprocess.Popen('ls /',shell=True,
stdout=process.PIPE)


res1=subprocess.Popen('grep bin',shell=True,
stdin=res.stdout, -->res的结果作为这里的输出
stdout=process.PIPE)

 

转载于:https://www.cnblogs.com/onda/p/6955062.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值