How do i set a timeout value for python's mechanize?
Asked
Active
Viewed 1.0k times
3 Answers
13
Alex is correct: mechanize.urlopen
takes a timeout
argument. Therefore, just insert a number of seconds in floating point: mechanize.urlopen('http://url/', timeout=30.0)
.
The background, from the source of mechanize.urlopen
:
def urlopen(url, data=None, timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT):
...
return _opener.open(url, data, timeout)
What is mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT
you ask? It's just the socket
module's setting.
import socket
try:
_GLOBAL_DEFAULT_TIMEOUT = socket._GLOBAL_DEFAULT_TIMEOUT
except AttributeError:
_GLOBAL_DEFAULT_TIMEOUT = object()

Tim McNamara
- 18,019
- 4
- 52
- 83
-
1Good old `br.open()` looks to have a timeout parameter as well: https://github.com/jjlee/mechanize/blob/b1d786906946f0193051920a7c716b339bd7bf95/mechanize/_mechanize.py#L200 – Mikeumus Apr 21 '15 at 17:55
3
If you're using Python 2.6 or better, and a correspondingly updated version of mechanize
, mechanize.urlopen
should accept a timeout=...
optional argument which seems to be what you're looking for.

Alex Martelli
- 854,459
- 170
- 1,222
- 1,395
1
I believe something along the lines of
mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT = 100
will override the default value Mechanize uses.

James
- 11
- 1
-
-
mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT.__sizeof__() this one is giving 16 – brainLoop Feb 27 '19 at 08:01