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.
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With