TypeError: 'str' does not support the buffer interface

摘要:

 If you use Python3x then string is not the same type as for Python 2.x, you must cast it to bytes (encode it).

In python 3, bytes strings and unicode strings are now two different types. Whenever you have a unicode string that you need to use as a byte string, you need to encode() it. And when you have a byte string, you need to decode it to use it as a regular (python 2.x) string.

================================================================

windows vista 系统 Eclipse+PyDev 环境

 

如下代码在 python2.7 环境下运行良好:

# coding=gbk # 如果不加这个,输出的中文是乱码

import subprocess

cmd = "cmd.exe"
ip = "172.29.69."
for i in range(139, 145) :
    p = subprocess.Popen(cmd, shell = True, 
                         stdout = subprocess.PIPE,
                         stdin  = subprocess.PIPE, 
                         stderr = subprocess.PIPE)
    cmdstr = "ping 172.29.69." + str(i) + "\n"
    
    p.stdin.write(cmdstr) 
    
    p.stdin.close()
    p.wait()
    print("execution result : %s" % p.stdout.read())
#end for

代码出处:

[1] http://yinzhezq.blog.163.com/blog/static/164862890201241224219884/

[2] http://zhidao.baidu.com/link?url=UuAS4IuGxDm_9g9hY4-VHkV3ufc_31VzL0jsd83Ow17UI6Wr3Ji7biImYO2oF3LH7g0hDOV0kCaS_HSfQQiZ3q

 

但在 python3.3 环境下就会运行出错:

Traceback (most recent call last):
  File "xxx\ping.py", line 14, in <module>
    p.stdin.write(cmdstr)
TypeError: 'str' does not support the buffer interface
================================================================

解决方法:

将代码修改为(代码编辑器不能改格式,真蛋疼)

 

# coding=GBK

import subprocess

cmd = "cmd.exe"
ip = "172.29.69."
for i in range(139, 145) :
    p = subprocess.Popen(cmd, shell = True,
                         stdout = subprocess.PIPE,
                         stdin  = subprocess.PIPE,
                         stderr = subprocess.PIPE)
    cmdstr = "ping 172.29.69." + str(i) + "\n"
  
    #p.stdin.write(cmdstr)
    p.stdin.write(bytes(cmdstr, "UTF-8"))


    p.stdin.close()
    p.wait()


    #print("execution result : %s" % p.stdout.read())
    print("execution result : %s" % p.stdout.read().decode("gb2312"))
#end for

 

解决方法出处:

[1] http://stackoverflow.com/questions/11781639/typeerror-str-does-not-support-buffer-interface

[2] http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值