views:

66

answers:

4

I'm using raw_input in Python to interact with user in shell.

c = raw_input('Press s or n to continue:')
if c.upper() == 'S':
    print 'YES'

It works as intended, but the user has to press enter in the shell after pressing 's'. Is there a way to accomplish what I need from an user input without needing to press enter in the shell? I'm using *nixes machines.

A: 

http://stackoverflow.com/questions/292095/polling-the-keyboard-in-python

K. Brafford
Post these things in comments.
Zonda333
+1  A: 

Under Windows, you need the msvcrt module, specifically, it seems from the way you describe your problem, the function msvcrt.getch:

Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed.

(etc -- see the docs I just pointed to). For Unix, see e.g. this recipe for a simple way to build a similar getch function (see also several alternatives &c in the comment thread of that recipe).

Alex Martelli
It works as intended, and having a cross-platform solution is great. Thanks for answering!
Somebody still uses you MS-DOS
@Somebody, you're welcome!
Alex Martelli
+2  A: 

Python does not provide a multiplatform solution out of the box.
If you are on Windows you could try msvcrt with:

import msvcrt
print 'Press s or n to continue:\n'
input_char = msvcrt.getch()
if input_char.upper() == 'S': 
   print 'YES'
systempuntoout
I've come across this module, but I need it to work on *nixes. Thanks anyway!
Somebody still uses you MS-DOS
+1  A: 

Instead of the msvcrt module you could also use WConio:

>>> import WConio
>>> ans = WConio.getkey()
>>> ans
'y'
Zonda333