Python3和Python2中的字符串编码的区别

  下面的代码是用来”简单测试局域网中的电脑是否连通“的。

 1 import subprocess
 2 cmd="cmd.exe"
 3 begin=101
 4 end=200
 5 while begin<end:
 6     p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
 7         stdin=subprocess.PIPE,
 8         stderr=subprocess.PIPE)
 9     cmd1='ping 192.168.1.'+str(begin)+'\n'
10     begin=begin+1
11     p.stdin.write(cmd1)
12     p.stdin.close()
13     p.wait()
14     print ("execution result: %s"%p.stdout.read())

  在Python3.0中运行总是提示错误。

>>> 
Traceback (most recent call last):
  File "F:\Study\Python\test.py", line 12, in <module>
    p.stdin.write(cmd1)
TypeError: 'str' does not support the buffer interface
>>> 

  最终,确定是Python版本问题,Python3中的字符串默认是Unicode编码,而Python2中的字符串默认是GBK编码,而Window中的cmd默认是GBK编码。

  因此,只要将第11行修改为p.stdin.write(cmd1.encode("GBK"))就行了。

原文地址:https://www.cnblogs.com/hibernation/p/2969900.html