Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a single character from the user?

Tags:

python

input

Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()). I know there's a function in Windows for it, but I'd like something that is cross-platform.

like image 268
Evan Fosmark Avatar asked Feb 04 '09 07:02

Evan Fosmark


People also ask

How will you read a single character from keyboard?

getchar() to read one character from keyboard We can use getchar function to read a single character from the keyboard. We will try to take one sample character and display by using printf function. Once the program encounters the getchar() function it will wait for the user to enter data by keyboard.

How do you read a single character value at runtime?

During the program execution, a single character is get or read through the getchar(). The given value is displayed on the screen and the compiler wait for another character to be typed. If you press the enter key/any other characters and then only the given character is printed through the printf function.

How do you read a single character in Java?

To read a character in Java, we use next() method followed by charAt(0). The next() method returns the next token/ word in the input as a string and chatAt() method returns the first character in that string. We use the next() and charAt() method in the following way to read a character.

Which function is used to read one character?

The getchar() function reads a single character from the standard input device( keyboard).


1 Answers

Here's a link to the ActiveState Recipes site that says how you can read a single character in Windows, Linux and OSX:

    getch()-like unbuffered character reading from stdin on both Windows and Unix

class _Getch:     """Gets a single character from standard input.  Does not echo to the screen."""     def __init__(self):         try:             self.impl = _GetchWindows()         except ImportError:             self.impl = _GetchUnix()      def __call__(self): return self.impl()   class _GetchUnix:     def __init__(self):         import tty, sys      def __call__(self):         import sys, tty, termios         fd = sys.stdin.fileno()         old_settings = termios.tcgetattr(fd)         try:             tty.setraw(sys.stdin.fileno())             ch = sys.stdin.read(1)         finally:             termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)         return ch   class _GetchWindows:     def __init__(self):         import msvcrt      def __call__(self):         import msvcrt         return msvcrt.getch()   getch = _Getch() 
like image 193
tehvan Avatar answered Oct 01 '22 01:10

tehvan