Canceling/interrupting raw_input

J

J. W. McCall

I'm working on a MUD server and I have a thread that gets keyboard input
so that you can enter commands from the command line while it's in its
main server loop. Everything works fine except that if a player enters
the 'shutdown' command, everything shuts down, but the input thread is
still sitting waiting for enter to be pressed for raw_input. After
enter is pressed, it exits back to the command prompt as it should.

I'm wondering if there's a way that I can make the thread stop waiting
for input. Even sys.exit() still leaves it waiting. It's not a big
deal, but it bugs me.

Any ideas? Should I be using something other than raw_input? I'm on
Windows2000 and running this from the DOS prompt. I'm using Python 2.4.
 
D

Daniel Cer

For what it's worth, this looks like a Windows specific problem.

The code below seems to work as expected on a Linux box. That is,
everything terminates, including the "inputLoop", after sys.exit() is
called, without the user needing to press 'enter' one last time.

However, if I try to run the code on Windows XP, it exhibits the exact
same behavior you described.

#!/usr/bin/python

import thread
import time
import sys

def inputLoop():
while 1:
input_string = raw_input("Type something: ")
print "You entered: ", input_string

thread.start_new_thread(inputLoop, () )

time.sleep(15)

sys.exit()

-Dan
 
D

Daniel Cer

Just a little bit of a follow up on this...

If you use win32api.TerminateProcess() instead of sys.exit(), everything
works as it should on Windows. That is, there is no longer a need to hit
'enter' one last time in order to get "inputLoop" to terminate.

So, modifying the sample code I posted earlier, the new Win32 specific
code would be the following:

import thread
import time
import sys
import win32api

def inputLoop():
while 1:
input_string = raw_input("Type something: ")
print "You entered: ", input_string

thread.start_new_thread(inputLoop, () )
time.sleep(3)
print "\nTime's up exiting...."
win32api.TerminateProcess(-1, 0)

-Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top