Using OS time

Donn Cave donn at u.washington.edu
Fri Jun 20 14:29:44 EDT 2003


In article <mailman.1056123940.18251.python-list at python.org>,
 valhalla <tireseas at onetel.com> wrote:
> The problem:
> I am writing a rather simple guessing game (a random number is generated, 
> user 
> has to guess the number).
> I am wanting to introduce a time-limit on the game-play so that the user has 
> - 
> e.g. 60 seconds - within which to guess the correct number otherwise they 
> lose.

I would call this imposing a timeout on input, so the place to start
is your input.  If that's something fancy, like X11 or some Windows
user interface API, then there will probably be some provision for
that kind of thing but finding it is up to you.  If you're just reading
from a UNIX terminal, this would do something like that  -

import os
import select

class TimeoutError(Exception):
        pass

def readto(maxsize, timeout):
        r, w, e = select.select([0], [], [], timeout)
        if r:
                return os.read(0, maxsize)
        else:
                raise TimeoutError

I used 0 and os.read where you might currently be using the stdin
file object.  stdin reads from unit 0, but it adds some buffering
that can confuse matters when also using select.

Stay away from signals when possible - if there's anything worse
than signals, it's signals in Python.

   Donn Cave, donn at u.washington.edu




More information about the Python-list mailing list