遇到的python3 不兼容 python2的地方

python3中执行以下代码

>>> import subprocess
>>> p=subprocess.Popen('ls',shell=True,stdout=subprocess.PIPE) 
>>> d=p.stdout.read()
>>> d
b'agent2.0.tgz\njdk1.8.0_152\njdk-8u152-linux-x64.tar.gz\nmha4mysql-manager-0.56-0.el6.noarch.rpm\nmha4mysql-node-0.56-0.el6.noarch.rpm\nscript.rpm.sh\nscripts\n'
>>> d.split('\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

buffer interface允许对象公开其底层缓冲区的信息,使用 buffer interface的的一个例子是file对象的write()方法,任何通过buffer interface 导出一系列字节的对象都可以被写入文件。python3开始只支持bytes和Unicode编码,不再支持str

解决方法是,将str 转换为tytes,处理完之后再转回str类型

>>> p=subprocess.Popen('ls',shell=True,stdout=subprocess.PIPE)
>>> d=p.stdout.read()
>>> d.split(bytes('\n','utf8'))
[b'agent2.0.tgz', b'jdk1.8.0_152', b'jdk-8u152-linux-x64.tar.gz', b'mha4mysql-manager-0.56-0.el6.noarch.rpm', b'mha4mysql-node-0.56-0.el6.noarch.rpm', b'script.rpm.sh', b'scripts', b'']

 

posted @ 2018-04-11 18:08  西橙  阅读(1170)  评论(0编辑  收藏  举报