Python:控制超时长度

标签 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 只尝试一次,如果不成功,立即退出?我为此使用的平台是 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/

相关文章:

python - 从 pandas 列的列表中删除字典

python - 使用 Python 3.2 和 cx_Freeze 创建 Windows 可执行文件

python - 如何在 df python 的组中连续数周?

python - Django 项目寻找 "attribute ' _session_cache'”

python - 我需要不同的 MIB 和那些 OID 吗?

python - 如果指定用户名,为什么我的 getopts 会失败?

Python:使用 Reportlab Canvas 在 PDF 中打印 Html

python - 跟踪 Telegram channel 的新订阅者数量?

python - 如何将命令行参数从 oc start-build 传递到 dockerfile 以在 dockerfile 内设置环境变量

python - 如何将Python日期时间对象拆分为日期和时间数字?