简体   繁体   中英

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. 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. 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. How can I time the read() operation and see whether content is empty after 10 seconds? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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