Getting User Input Without Pressing Enter in the Shell
You want to use raw_input in Python to interact with a user in the shell, but without requiring them to press enter after inputting their response.
Windows Solution
For Windows, you can use the msvcrt module, specifically the msvcrt.getch function:
import msvcrt c = msvcrt.getch() if c.upper() == 'S': print('YES')
Unix Solution
For Unix, you can refer to this recipe to create a similar getch function:
import tty import termios def getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(fd) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch
With this function, you can retrieve user input without the need for pressing enter:
c = getch() if c.upper() == 'S': print('YES')
The above is the detailed content of How to Get User Input Without Pressing Enter in the Shell?. For more information, please follow other related articles on the PHP Chinese website!