Timeout on read()?

Gerrit Holl gerrit at NOSPAM.nl.linux.org
Sun Aug 20 15:07:27 EDT 2000


On Wed, 16 Aug 2000 10:46:08 +0800, lec wrote:
> Is it possible to implement timeout on read?
> 
> eg.
> 
> answer = sys.stdin.readline()
> 
> but I want it to timeout after 30 seconds.

It's not crossplatform, but on Unix, the signal
module is your friend.

You could use such code:

<example>
#!/usr/bin/python

import signal
import sys

TIMEOUT = 10

def f(signum, frame):
    print "Too late!"
    print "Signal handler called with signal number", signum
    print frame, "is a", type(frame), "with some useful information"

signal.signal(signal.SIGALRM, f)
signal.alarm(TIMEOUT)

line = sys.stdin.readline()

print "I read: '%s'" % line
</example>

I don't know any cross-platform solution.

Please consult for details:
http://www.python.org/doc/current/lib/module-signal.html

regards,
Gerrit.

-- 
1011001 1101111 1110101 1110010 1110011 0101100
1000111 1100101 1110010 1110010 1101001 1110100



More information about the Python-list mailing list