python - ftplib.FTP 超时具有不一致的行为

标签 python python-2.7 ftp timeout ftplib

我正在尝试使用带有超时选项的 ftplib.FTP() 作为特定主机名的超时值。但我遇到了奇怪的行为。为了测试它,我编写了一段非常简单的代码。

import ftplib
from ftplib import FTP
ftp = ftplib.FTP("google.com",timeout=2)

API 文档说以秒为单位输入超时值,但似乎需要更长的时间,对我来说几乎需要 8 秒以上。谁能解释一下这种行为。我正在使用 python2.7

最佳答案

ftplib.FTP 调用 socket.create_connection()。根据 到文档 https://docs.python.org/2/library/socket.html#socket.create_connection

if host is a non-numeric hostname, it will try to resolve it for both AF_INET and AF_INET6, and then try to connect to all possible addresses in turn until a connection succeeds.

快速检查 google.com 会显示大约一打(或更多) 取决于您所在的国家/地区。你的 2 秒超时 应用于每个 主机。

如果您想将总时间限制为 2 秒,请先进行查找并将数字地址传递给您的 ftplib.FTP 调用:

import socket, ftplib
host = socket.gethostbyname('google.com')
ftp = ftplib.FTP(host, timeout=2)

关于python - ftplib.FTP 超时具有不一致的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28429501/

相关文章:

python - 类型错误 : Object of type TypeError is not JSON serializable Python

python - 非常奇怪的 python NameError

python-2.7 - 同一个系列中的时间序列日期时间有两种格式,如何将它们更改为一种格式?

windows - 如何在 Windows 主机上通过 FTP 删除 svn 文件夹

linux - 在 Windows 机器上安装的 sftp 服务器上是否可以进行基于 ssh key 的身份验证?

python - 在 Azure Synapse 笔记本中运行 nltk.download ValueError : I/O operation on closed file

python - Python 中的单元测试装饰器

Python:如何在函数的本地范围内运行 eval()

python - 连接两列并获得新列

encoding - 使用 Filezilla 到 FTP 时,俄语字符会变成垃圾