`

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

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics