views:

83

answers:

2

Is there a way to programmatically interrupt Python's raw_input? Specifically, I would like to present a prompt to the user, but also listen on a socket descriptor (using select, for instance) and interrupt the prompt, output something, and redisplay the prompt if data comes in on the socket.

The reason for using raw_input rather than simply doing select on sys.stdin is that I would like to use the readline module to provide line editing functionality for the prompt.

+1  A: 

As far as I know... "Sort of".

raw_input is blocking so the only way I can think of is spawning a subprocess/thread to retrieve the input, and then simply communicate with the thread/subprocess. It's a pretty dirty hack (at least it seems that way to me), but it should work cross platform. The other alternative, of course, is to use either the curses module on linux or get this one for windows.

Wayne Werner
A: 

Hello, use threads. In the first thread start the raw_input and with the other listen on the socket and if there are news, kill the first thread, output something and than restart the prompt-thread. maybie you could also only pause the prompt-thread to keep its state.

import threading 

class FirstThread(threading.Thread): 
    def __init__(self, question): 
        threading.Thread.__init__(self) 
        self.question = question 

    def run(self):
        return raw_input(self.question) # prompt the users
        # when this method returns something (even None) this thread is finished

# the other thread class here

threads = [] 

thread = FirstThread("Enter you text: ")
thread.start()
threads.append(thread)

# same with the other thread

for t in threads:
    t.join() # wait until all threads are finished
Joschua