将Python 2套接字示例转换为Python 3
whois.py
import sysimport socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.arin.net", 43))
s.send((sys.argv[1] + "\r\n").encode())
response = ""while True:
data = s.recv(4096)
response += dataif not data:break
s.close()
print(response)
如果使用Python 3进行编译,是否会提示以下错误?
Traceback (most recent call last):File "C:\repos\hc\whois\python\whois.py", line 12, in <module>
response += data
TypeError: Can't convert 'bytes' object to str implicitly
解
在Python 3中,套接字以bytes
为bytes
返回数据(在Python 2中为string
)。由于响应是一个string
,因此您不能直接添加两种不同的类型( bytes + string
)。要修复它 ,您需要转换类型:#Solution 1将响应从string to bytes
转换string to bytes
whois.py
import sysimport socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.arin.net", 43))
s.send((sys.argv[1] + "\r\n").encode())#Convert response to bytes
response = b""# or use encode()#response = "".encode()while True:
data = s.recv(4096)
response += dataif not data:break
s.close()
print(response.decode())
#Solution 2将数据从bytes to string
转换bytes to string
whois.py
import sysimport socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.arin.net", 43))
s.send((sys.argv[1] + "\r\n").encode())
response = ""while True:
data = s.recv(4096)#convert data from bytes to string#response += data
response += data.decode()if not data:break
s.close()
print(response)
参考文献:
- Python 3内置类型
- Python Whois客户端示例
推荐阅读--
我司空降了一名专家后,一半程序员疯了...
程序员长假相亲图鉴(文末惊喜)
每日一课 | Python –如何在函数中使用全局变量
每日一课 | Python将文件读入列表
每日一课 | 如何将String转换为int
球分享
球点赞
球在看