简体   繁体   English

10 秒后停止阻塞操作?

[英]Stop a blocking operation after 10 seconds?

I'm currently writing a Python 2.7 program that queries a website for some URL information using Mechanize.我目前正在编写一个 Python 2.7 程序,该程序使用 Mechanize 查询网站的某些 URL 信息。 The pseudo-code is like the following:伪代码如下:

for URL in urls:
   # first submit a form to query the URL...
   # then wait and parse the results:
   while 1:
      content = response.read(1024)
      # followed by some other simple parsing operations ...

The read() operation in the while 1 loop is a blocking, and due to network and other conditions, sometimes it runs forever. while 1 循环中的 read() 操作是阻塞的,并且由于网络等条件,有时会永远运行。 What I'm trying to achieve is to stop waiting for the read() and jump to query the next URL if the current read() operation hasn't returned after 10 seconds.我想要实现的是,如果当前的 read() 操作在 10 秒后没有返回,则停止等待 read() 并跳转到查询下一个 URL。 How can I time the read() operation and see whether content is empty after 10 seconds?如何计时 read() 操作并查看 10 秒后content是否为空? I'm thinking about using threads, but am not sure how to proceed.我正在考虑使用线程,但不确定如何进行。 Can anyone help?任何人都可以帮忙吗? Thanks in advance!提前致谢!

尝试使用这里描述的超时装饰器 - https://pypi.python.org/pypi/timeout-decorator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM