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

 

相关文章:

  • 2021-11-25
  • 2021-09-13
  • 2021-08-24
  • 2021-06-23
  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
  • 2021-10-16
猜你喜欢
  • 2022-12-23
  • 2021-07-04
  • 2021-11-19
  • 2021-07-29
  • 2018-12-05
  • 2021-05-28
  • 2021-09-27
相关资源
相似解决方案