Note that there are some explanatory texts on larger screens.

plurals
  1. POSetting a timeout for mechanize.Browser
    primarykey
    data
    text
    <p>I was perusing the question posted here: </p> <p><a href="https://stackoverflow.com/questions/8464391/what-should-i-do-if-socket-setdefaulttimeout-is-not-working">What should I do if socket.setdefaulttimeout() is not working?</a></p> <p>to try and come up with a solution to kill requests when my <code>mechanize.Browser</code> object is taking too long, and I have been experimenting with the first solution in tomasz's edit (reposted here for clarity):</p> <pre><code>import signal, time def request(arg): """Your http request""" time.sleep(2) return arg class Timeout(): """Timeout class using ALARM signal""" class Timeout(Exception): pass def __init__(self, sec): self.sec = sec def __enter__(self): signal.signal(signal.SIGALRM, self.raise_timeout) signal.alarm(self.sec) def __exit__(self, *args): signal.alarm(0) # disable alarm def raise_timeout(self, *args): raise Timeout.Timeout() # Run block of code with timeouts try: with Timeout(3): print request("Request 1") with Timeout(1): print request("Request 2") except Timeout.Timeout: print "Timeout" # Prints "Request 1" and "Timeout" </code></pre> <p>When I run this from my terminal using <code>python timeout.py</code> (version is<code>Python 2.7.2+</code> and I am on Ubuntu 11.10 Oneiric Ocelot), there is no exception thrown- instead it simply prints</p> <pre><code>Request 1 Request 2 </code></pre> <p>Could someone please explain how to fix this? An explanation of what's going on with those <code>signal.alarm</code> and <code>signal.signal</code> calls would be awesome too.</p> <p>Thank you very much for your time!</p> <p>EDIT:</p> <p>Running <code>strace -f python timeout.py</code> yields:</p> <pre><code>alarm(3) = 0 select(0, NULL, NULL, NULL, {2, 0}) = 0 (Timeout) fstat64(1, {st_mode=S_IFREG|0664, st_size=0, ...}) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb740c000 alarm(0) = 1 rt_sigaction(SIGALRM, {0x812f450, [], 0}, {0x812f450, [], 0}, 8) = 0 alarm(1) = 0 select(0, NULL, NULL, NULL, {2, 0}) = 0 (Timeout) alarm(0) = 0 rt_sigaction(SIGINT, {SIG_DFL, [], 0}, {0x812f450, [], 0}, 8) = 0 rt_sigaction(SIGALRM, {SIG_DFL, [], 0}, {0x812f450, [], 0}, 8) = 0 write(1, "Request 1\nRequest 2\n", 20) = 20 exit_group(0) = ? </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload