【问题标题】:Is it possible to add a timeout in try block in python是否可以在 python 的 try 块中添加超时
【发布时间】:2018-02-02 02:09:48
【问题描述】:

我正在尝试使用从以下位置下载的 python-wget 下载 URL: https://pypi.python.org/pypi/wget

这个包不支持超时选项,因此查询失败大约需要一些时间(大约 10 秒)。是否可以在我们的 try 块中添加超时以减少函数的等待时间。

类似这样的:

try(timeout=5s):
     wget.download(URL)
except:
    print "Query timed out"

【问题讨论】:

标签: python try-except


【解决方案1】:

最简单的方法(即如果download 不支持超时并且您无法修改代码)是通过在另一个线程中运行代码来实现:

from threading import Thread

t = Thread(target=wget.download, args=(URL,))
t.daemon = True
t.start()
t.join(5)
if t.is_alive():
    print 'Timeout'

【讨论】:

  • 上面的代码在wget.download之后是不是需要一个连续的循环来检查它是否已经超时?
  • @brianlmerritt 当然。
猜你喜欢
  • 2015-06-21
  • 2019-08-24
  • 2016-11-26
  • 2016-04-19
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
相关资源
最近更新 更多