我正在编写一个脚本(多线程)来从一个网站检索内容,而该网站并不十分稳定,因此时不时会有挂起的http请求,甚至无法通过socket.setdefaulttimeout()
进行时间路由。因为我无法控制那个网站,我唯一能做的就是改进我的代码,但我现在已经没有什么想法了。
示例代码:
socket.setdefaulttimeout(150)
MechBrowser = mechanize.Browser()
Header = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 GTB7.1 (.NET CLR 3.5.30729)'}
Url = "http://example.com"
Data = "Justatest=whatever&letstry=doit"
Request = urllib2.Request(Url, Data, Header)
Response = MechBrowser.open(Request)
Response.close()
我该怎么做才能迫使绞刑请求退出?实际上,我想知道为什么socket.setdefaulttimeout(150)
一开始不起作用。有人能帮我吗?
添加:(是的问题仍未解决)
好的,我已经遵循了tomasz的建议,并将代码改为MechBrowser.open(Request, timeout = 60)
,但是同样的事情发生了。到目前为止,我仍然随机收到一些绞刑请求,有时是几个小时,有时可能是几天。我现在该怎么办?有没有办法迫使这些绞刑请求退出?
您可以尝试使用mechanize with eventlet。它不能解决超时问题,但greenlet是非阻塞的,所以它可以解决性能问题。
从他们的文件来看:
也许您应该尝试用mechanize.Request替换urllib2.Request。
虽然
socket.setsocketimeout
将为新套接字设置默认超时,但如果不直接使用套接字,则很容易覆盖该设置。特别是,如果库在其套接字上调用socket.setblocking
,它将重置超时。urllib2.open
有一个超时参数,hoviewer,urllib2.Request
中没有超时。在使用mechanize
时,应参考他们的文档:来源:http://wwwsearch.sourceforge.net/mechanize/documentation.html
---编辑---
如果
socket.setsockettimeout
或将超时传递给mechanize
的值很小,但不是更高,则问题的根源可能完全不同。一件事是你的库可能会打开多个连接(这里归功于@Cédric Julien),因此超时适用于socket.open的每次尝试,如果它没有在第一次失败时停止,则可能需要长达timeout * num_of_conn
秒的时间。另一件事是socket.recv
:如果连接真的很慢,而且你够不走运,那么整个请求可能需要timeout * incoming_bytes
的时间,就像每个socket.recv
我们可以得到一个字节一样,每个这样的调用可能需要timeout
秒。因为您不太可能遭受这种黑暗场景的影响(每超时秒一个字节?你必须是一个非常粗鲁的男孩),这很可能要求花很长时间非常慢的连接和非常高的超时。唯一的解决方案是强制整个请求超时,但这里与套接字无关。如果您在Unix上,可以使用带有
ALARM
信号的简单解决方案。您将信号设置为在timeout
秒内发出,您的请求将被终止(不要忘记捕获它)。您可能希望使用with
语句使其干净且易于使用,例如:如果想要比这更便携,您必须使用一些更大的枪,例如
multiprocessing
,因此您将生成一个进程来调用您的请求,并在过期时终止它。由于这是一个单独的过程,您必须使用一些东西将结果传输回您的应用程序,它可能是multiprocessing.Pipe
。下面是一个例子:如果你想强制请求在固定的秒数后终止,你真的没有太多选择。
socket.timeout
将为单个套接字操作(connect/recv/send)提供超时,但如果有多个套接字操作,则可能会导致执行时间过长。相关问题 更多 >
编程相关推荐