[Python3]subprocess.check_output() 在python3的输出为bytes而非string,在实际使用过程中得增加一个解码过程decode(),不然会有问题...

按以往python2的习惯编码输出报错

 1 #-*- coding:utf-8 -*-
 2 '''
 3 Created on 2018年7月21日
 4 
 5 @author: lenovo
 6 '''
 7 import os
 8 import sys
 9 import subprocess
10 from uiautomator import device as d
11 cmd = r'adb install F:\听力.apk'
12 info = subprocess.check_output(cmd).split("\r\n")
13 print (info)

输出如下,报错

1 Traceback (most recent call last):
2   File "C:\Users\lenovo\eclipse-workspace\WOO\src\debug\debug1.py", line 12, in <module>
3     info = subprocess.check_output(cmd).split("\r\n")
4 TypeError: a bytes-like object is required, not 'str'

查询python3文档有下面描述:

By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.
也就是说,返回的其实是一个编码后的比特值,实际的编码格式取决于调用的命令,因此python3将解码过程交给应用层,也就是我们使用的人来做啦。

证实过程是不是这样,我们把这个subprocess.check_output()的类型打印出来如下,确实为bytes类型,需要人为再转换一次为string

 1 #-*- coding:utf-8 -*-
 2 '''
 3 Created on 2018年7月21日
 4 
 5 @author: lenovo
 6 '''
 7 import os
 8 import sys
 9 import subprocess
10 from uiautomator import device as d
11 cmd = r'adb install F:\听力.apk'
12 info = subprocess.check_output(cmd)
13 print (type(info))

输出如下:

<class 'bytes'>

 

正确的如下:

 1 #-*- coding:utf-8 -*-
 2 '''
 3 Created on 2018年7月21日
 4 
 5 @author: lenovo
 6 '''
 7 import os
 8 import sys
 9 import subprocess
10 from uiautomator import device as d
11 cmd = r'adb install F:\听力.apk'
12 info = subprocess.check_output(cmd)
13 info1 = info.decode()
14 print (info1.split('\r\n'))

输出如下:

['Success', '']

转载于:https://www.cnblogs.com/aziji/p/9347672.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值