Python:控制超时长度

2024-04-26 03:34:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有类似于脚本中运行的以下代码:

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只尝试一次,如果不成功,立即退出?我使用的平台是MacOSX10.5/Python2.5.1。


Tags: 代码脚本sysexitusernamenotftpcontact
3条回答

从2.6开始,^{}有一个可选的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.

由于您使用的是Python2.5,因此可以使用以下命令为所有套接字操作(包括FTP请求)设置全局超时:

socket.setdefaulttimeout()

(这是在Python2.3中添加的)

相关问题 更多 >