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

后端 未结 3 673
失恋的感觉
失恋的感觉 2021-02-19 03:04

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

相关标签:
3条回答
  • 2021-02-19 03:29

    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()
    
    0 讨论(0)
  • 2021-02-19 03:29

    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.

    0 讨论(0)
  • 2021-02-19 03:32

    I believe something along the lines of

    mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT = 100
    

    will override the default value Mechanize uses.

    0 讨论(0)
提交回复
热议问题