問題描述
我正在嘗試使用帶有超時選項的 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)
這篇關于ftplib.FTP 超時行為不一致的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!