ftplib.FTP 超时行为不一致
问题描述
我正在尝试使用带有超时选项的 ftplib.FTP()
作为特定主机名的超时值.但我正在经历奇怪的行为.为了测试它,我编写了一段非常简单的代码.
I am trying to use ftplib.FTP()
with timeout option as some timeout value for a particular hostname. But i am experiencing weird behaviour. To test it i have written a very simple piece of code.
import ftplib
from ftplib import FTP
ftp = ftplib.FTP("google.com",timeout=2)
API文档说以秒为单位输入超时值,但似乎需要更长的时间,对我来说几乎需要8秒以上.谁能解释一下这个行为.我正在使用 python2.7
The API document says to enter timeout value in seconds, but it seems that it takes longer than that, for me it almost takes more than 8 secs. Can anybody please explain the behaviour.I am using python2.7
解决方案
ftplib.FTP
调用 socket.create_connection()
.根据到文档 https://docs.python.org/2/library/socket.html#socket.create_connection
ftplib.FTP
invokes socket.create_connection()
. According
to the docs https://docs.python.org/2/library/socket.html#socket.create_connection
如果主机是非数字主机名,它将尝试为两者解析AF_INET 和 AF_INET6,然后尝试连接所有可能的依次分配地址,直到连接成功.
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 秒超时应用于每个主机.
A quick check of google.com
will show about a dozen (or more)
depending on your region of the country. Your 2 second timeout
is applied to each of the hosts.
如果您想将总时间限制为 2 秒,请先进行查找并将数字地址传递给您的 ftplib.FTP
调用:
If you want to limit total time to 2 seconds, do the lookup first and pass the numeric address to your ftplib.FTP
call:
import socket, ftplib
host = socket.gethostbyname('google.com')
ftp = ftplib.FTP(host, timeout=2)
相关文章