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

房东的猫 提交于 2019-12-06 17:39:04

问题


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


回答1:


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()



回答2:


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.




回答3:


I believe something along the lines of

mechanize._sockettimeout._GLOBAL_DEFAULT_TIMEOUT = 100

will override the default value Mechanize uses.



来源:https://stackoverflow.com/questions/3552928/how-do-i-set-a-timeout-value-for-pythons-mechanize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!