在 2.7 中使用套接字时出现 Python 类型错误
在 python 2.7 中使用套接字时,我遇到了如下类型错误:
TypeError: coercing to Unicode: need string or buffer, instance found。
我确信这与 python2 和 python3 在 unicode 方面的差异有关。但我对这些差异还不够熟悉,无法缩小解决问题的范围。我确信我知道问题出在哪里,但我谷歌未能帮助我找到解决方案。这是我遇到问题的代码段。
from IPy import IP
ip = IP(sys.argv[1])
for x in ip:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
svr = (x, 25)
s.connect(svr)
data = s.recv(2048)
s.close()
print(repr(data))
这是错误的确切打印输出:
Traceback (most recent call last):
File "relayscanner.py", line 17, in <module>
s.connect(tgt)
File "C:\Python27\lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
TypeError: coercing to Unicode: need string or buffer, instance found
Working with sockets in python 2.7, and I've encountered a Type error as follows:
TypeError: coercing to Unicode: need string or buffer, instance found.
I'm sure this has something to do with the differences between python2 and python3 in terms of unicode. But I'm not familiar enough with the differences to narrow down how to fix the problem. I'm sure I know where the problem is, but I google has failed to assist me in finding a solution. Here's the code segment I'm having problems with.
from IPy import IP
ip = IP(sys.argv[1])
for x in ip:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
svr = (x, 25)
s.connect(svr)
data = s.recv(2048)
s.close()
print(repr(data))
Here is the exact printout of the error:
Traceback (most recent call last):
File "relayscanner.py", line 17, in <module>
s.connect(tgt)
File "C:\Python27\lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
TypeError: coercing to Unicode: need string or buffer, instance found
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为问题是您给了
socket.connect()
一个IPy.IP
对象,但它需要一个字符串。首先尝试将其强制为字符串,即:I think the problem is that you are giving
socket.connect()
anIPy.IP
object, but it expects a string. Try coercing it to a string first, IE:看起来它不喜欢服务器元组中具有 x 值的内容,我建议通过每次迭代检查 x 值。如果它是一个对象,请尝试
.strNormal()
方法。It looks like it doesn't like something with the value of x in your server tuple I recommend checking the value of x through each iteration. If it's an object, try the
.strNormal()
method.