4

出于某种原因,以下似乎在我运行 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, in <module>
    udp.sendto(data, (hostname, port))
TypeError: sendto() takes exactly 3 arguments (2 given)

我已经查阅了 python 3.1 的文档,并且 sendto() 只需要两个参数。关于可能导致这种情况的任何想法?

4

2 回答 2

6

在 Python 3 中,字符串(第一个)参数必须是字节或缓冲区类型,而不是 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 "<stdin>", line 1, in <module>
TypeError: sendto() takes exactly 3 arguments (2 given)
>>> udp.sendto(data, 0, (hostname, port))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
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
于 2009-08-19T02:27:37.450 回答
4

Python bugtracker 的相关问题:http: //bugs.python.org/issue5421

于 2009-08-19T02:26:57.543 回答