Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

raw_input without pressing enter

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.

like image 805
Somebody still uses you MS-DOS Avatar asked Aug 19 '10 15:08

Somebody still uses you MS-DOS


People also ask

How do you enter without pressing in Python?

If you use the input()-function it will always wait for a press of the Enter-key. You would have to modify or rewrite the input()-function, but with means of oop this should be possible.

What is the difference between input () and raw_input ()?

There are two functions that can be used to read data or input from the user in python: raw_input() and input(). The results can be stored into a variable. raw_input() – It reads the input or command and returns a string. input() – Reads the input and returns a python type like list, tuple, int, etc.

How do I get raw input in Python 3?

a = input() will take the user input and put it in the correct type. Eg: if user types 5 then the value in a is integer 5. a = raw_input() will take the user input and put it as a string. Eg: if user types 5 then the value in a is string '5' and not an integer.

How do I use raw input in Python?

The raw_input() function reads a line from input (i.e. the user) and returns a string by stripping a trailing newline. This page shows some common and useful raw_input() examples for new users. Please note that raw_input() was renamed to input() in Python version 3.


1 Answers

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).

like image 146
Alex Martelli Avatar answered Oct 05 '22 22:10

Alex Martelli