是否可以在 python 中的 try 块中添加超时
Is it possible to add a timeout in try block in python
我正在尝试使用 python-wget 下载 URL,下载自:
https://pypi.python.org/pypi/wget
这个包不支持超时选项,因此查询失败大约需要一些时间(大约 10 秒)。是否可以在我们的 try 块中添加超时以减少函数的等待时间。
像这样:
try(timeout=5s):
wget.download(URL)
except:
print "Query timed out"
最简单的方法(即,如果 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'
我正在尝试使用 python-wget 下载 URL,下载自: https://pypi.python.org/pypi/wget
这个包不支持超时选项,因此查询失败大约需要一些时间(大约 10 秒)。是否可以在我们的 try 块中添加超时以减少函数的等待时间。
像这样:
try(timeout=5s):
wget.download(URL)
except:
print "Query timed out"
最简单的方法(即,如果 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'