我正在尝试使用带有超时选项的 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/