[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', '']

posted @ 2018-07-21 19:09  iSZ  阅读(982)  评论(0编辑  收藏  举报