1

urllib.request.urlopen has a timeout option. However, when my internet is down that option does not seem to work.

import urllib
urllib.request.urlopen(url, timeout=1)

Hangs and eventually gives

URLError: <urlopen error [Errno -3] Temporary failure in name resolution>

How can I impose a timeout when my internet is down?

eyllanesc
  • 190,383
  • 15
  • 87
  • 142
Mauricio
  • 284
  • 1
  • 9

2 Answers2

2

That isn't trivial. You have a DNS timeout as your system cannot figure out what to do with the URL given. However, this is out of control of python as noted by David Murray here: https://bugs.python.org/issue22889

You may want to go for this custom timeout implementation: Timeout function if it takes too long to finish

Jan
  • 808
  • 9
  • 26
0

You can read this post. It explains well that currently timeout is a very obscure concept. Even in requests which claims "For human", timeout is not really for human.

In your case, name resolution is a pre-process before http connection, but timeout only works for http(s) and ftp connection.

To obtain a consistent behavior of timeout, I guess the best way is to use thread. Or you can use signal.alarm but it only works on UNIX system.

Sraw
  • 14,837
  • 5
  • 37
  • 62