views:

43

answers:

3

How do i set a timeout value for python's mechanize?

A: 
import socket

socket.setdefaulttimeout(1000) # in Milliseconds

mechanize uses urllib2, and urllib2 uses sockets, but it doesn't exports the timeout value, so you'll have to set it application-wide.

leoluk
In general this is a bad idea, as it sets a value that is global to the process. Every sock will have that timeout, whether you want to to or not.
Gabe
A: 

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
+1  A: 

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