ftplib.FTP超时具有不一致的行为 [英] ftplib.FTP timeout has inconsistent behaviour

查看:151
本文介绍了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)

以秒为单位输入超时值,但似乎需要比此更长的时间,对我而言,它几乎需要超过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


如果主机是非数字主机名,它会尝试解决它
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)

这篇关于ftplib.FTP超时具有不一致的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆