[Tutor] Non Blocking I/O on stdin

Ignacio Vazquez-Abrams ignacio@openservices.net
Tue, 11 Sep 2001 16:03:18 -0400 (EDT)


On Wed, 12 Sep 2001, Girish Gajwani wrote:

> Hi,
>
> I wish to read the keyboard(stdin) but the read should not
> be blocking
>
>  [snip]
>
> #### DOES NOT WORK ####
>
> #! /usr/bin/env python
> def acc(args):
>     while(1):
>         print "just b4"    # comes here
>         str = input()
>         print "just after" # never comes here :(
>
> args = 0,                  # create list of arguments
> thread.start_new_thread(acc, args)
> #######################

No wonder this doesn't work; if the main thread dies, then all the others die
too.

>                   ----------------------
>                    & consider this now
>                   ----------------------
>
> #### THIS WORKS ####
>
> #! /usr/bin/env python
> def acc(args):
>     while(1):
>         print "just b4"    # comes here
>         str = input()
>         print "just after" # comes here but still not what i
> want :(
>
> args = 0,                  # create list of arguments
> acc(args)
> #######################
> Also please advise on reading the keyboard in non-blocking
> mode
>
> Help wrt the thread module (scheduling, etc) will also be
> helpful.

A couple of tips:

1) Use the threading module instead of the thread module. That way your main
thread can join a spawned thread and not die immediately.
2) Use the select module in conjunction with sys.stdin instead of input() or
raw_input().

-- 
Ignacio Vazquez-Abrams  <ignacio@openservices.net>