Nonblocking input: the quest continues

Nolan Darilek nolan_d at bigfoot.com
Thu Jul 6 18:12:10 EDT 2000


I'm continuing to try to figure out this non-blocking input
thing. Yesterday I didn't want to use curses since cmd provided much
of the interface that I wanted. But, after grep'ing through Python
libraries, I don't feel any closer to a solution.

So, I thought that it might be possible to use curses for nonblocking
input only, and to ignore the additional functionality. I wrote up an
ugly, but semi-functional, replacement for raw_input which may do what
I want. But, I'm still encountering problems. Here is the ugly test
code which I've written:

#!/usr/bin/env python

import curses
import time

input=""
prompted=0
window=None

def raw_input(prompt = ""):
    global input, prompted, window
    if prompted == 0:
        print prompt
        prompted = 1
    ch = window.getch()
    if ch == -1:
        return None
    if chr(ch) == '\n':
        prompted = 0
        r = input
        input = ""
        return r
    input = input+chr(ch)

window = curses.initscr()
window.nodelay(1)
window.nooutrefresh()

for x in range(0, 10000000):
    time.sleep(0.1)
    line = raw_input(">")
    if line is not None:
        print line

While this does seem to except input nicely, and despite the fact that
it stores all incoming input in a global variable so that my program
can reconstruct the prompt when new data arrives, it still exhibits
problems. First, it doesn't print the prompt string. I'm wondering if
this is due to the fact that I'm mixing curses with print? Or is there
some silly error which I've missed due to the fact that I've been
staring at this for hours? :)

And, even if this approach excepts input, how will it behave when the
prompt is reconstructed and if someone wants to erase the text? Does
the text need to be stuffed into an input buffer, or will the terminal
nicely handle the program's request to erase text which was printed to
the display? I suspect not, so I'm wondering if I'm taking the wrong
approach with this? I had originally thought of trying to write to
stdin, hoping to cram text back into the input buffer, but this seems
to be impossible.





More information about the Python-list mailing list