windows Python sendto() 不适用于 3.1(适用于 2.6)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1297505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:00:36  来源:igfitidea点击:

Python sendto() not working on 3.1 (works on 2.6)

pythonwindowsubuntuudpsendto

提问by mozami

For some reason, the following seems to work perfectly on my ubuntu machine running python 2.6 and returns an error on my windows xp box running python 3.1

出于某种原因,以下内容似乎在我运行 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))

Below is the error that the python 3.1 throws:

下面是 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)

I have consulted the documentation for python 3.1 and the sendto() only requires two parameters. Any ideas as to what may be causing this?

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

回答by Ned Deily

In Python 3, the string (first) argument must be of type bytes or buffer, not str. You'll get that error message if you supply the optional flags parameter. Change data to:

在 Python 3 中,字符串(第一个)参数必须是字节或缓冲区类型,而不是 str。如果您提供可选的标志参数,您将收到该错误消息。将数据更改为:

data = b'UDP Test Data'

data = b'UDP Test Data'

You might want to file a bug report about that at the python.org bug tracker. [EDIT: already filed as noted by Dav]

您可能希望在 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

回答by Amber

Related issue on the Python bugtracker: http://bugs.python.org/issue5421

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