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
  • 235,170
  • 19
  • 170
  • 241
Mauricio
  • 414
  • 2
  • 11

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
  • 1,180
  • 13
  • 29
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
  • 18,892
  • 11
  • 54
  • 87