出于某种原因,以下似乎在我运行python 2.6的ubuntu机器上运行完美,并在运行python 3.1的windows xp框中返回错误
from socket import socket, AF_INET, SOCK_DGRAM data = 'UDP Test Data' port = 12345 hostname = '192.168.0.1' udp = socket(AF_INET,SOCK_DGRAM) udp.sendto(data, (hostname, port))
下面是python 3.1抛出的错误:
Traceback (most recent call last): File "sendto.py", line 6, inudp.sendto(data, (hostname, port)) TypeError: sendto() takes exactly 3 arguments (2 given)
我查阅了python 3.1的文档,sendto()只需要两个参数.关于可能导致这种情况的任何想法?
在Python 3中,字符串(第一个)参数必须是bytes或buffer类型,而不是str.如果提供可选的flags参数,您将收到该错误消息.将数据更改为:
data = b'UDP Test Data'
您可能希望在python.org错误跟踪器上提交有关该错误报告.[编辑:如Dav所述已提交]
...
>>> data = 'UDP Test Data' >>> udp.sendto(data, (hostname, port)) Traceback (most recent call last): File "", line 1, in TypeError: sendto() takes exactly 3 arguments (2 given) >>> udp.sendto(data, 0, (hostname, port)) Traceback (most recent call last): File " ", line 1, in TypeError: sendto() argument 1 must be bytes or buffer, not str >>> data = b'UDP Test Data' >>> udp.sendto(data, 0, (hostname, port)) 13 >>> udp.sendto(data, (hostname, port)) 13