我在脚本中运行了类似于以下的代码:
try:
s = ftplib.FTP('xxx.xxx.xxx.xxx','username','password')
except:
print ('Could not contact FTP serer')
sys.exit()
如果无法访问 FTP 站点,脚本似乎几乎“挂起”……在 sys.exit() 似乎被调用之前平均需要大约 75 秒……我知道这 75 秒可能非常主观的,并且依赖于它运行的系统......但是有没有办法让 python 只尝试一次,如果不成功,立即退出?我为此使用的平台是 Mac OS X 10.5/python 2.5.1。
最佳答案
从 2.6 开始,FTP constructor
有一个可选的 timeout
参数:
class ftplib.FTP([host[, user[, passwd[, acct[, timeout]]]]])
Return a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is given, additionally the method call login(user, passwd, acct) is made (where passwd and acct default to the empty string when not given). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if is not specified, the global default timeout setting will be used).
Changed in version 2.6: timeout was added.
从 2.3 版开始,可以使用全局默认超时:
socket.setdefaulttimeout(timeout)
Set the default timeout in floating seconds for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.
New in version 2.3.
关于Python:控制超时长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2355743/