Input Retrieval Without Pressing Enter in Python
When using the raw_input function in Python, users must typically press "Enter" after entering an input value. To eliminate this requirement, various techniques can be employed depending on the operating system.
Windows
On Windows systems, the msvcrt module provides the msvcrt.getch function:
import msvcrt c = msvcrt.getch() if c.upper() == b'S': print('YES')
This function reads a keypress without echoing it to the console and will not wait for Enter to be pressed.
Unix
For Unix systems, a simple function to achieve similar functionality can be created:
def getch(): import tty, sys fd = sys.stdin.fileno() old_settings = tty.tcgetattr(fd) try: tty.setraw(fd) ch = sys.stdin.read(1) finally: tty.tcsetattr(fd, tty.TCSADRAIN, old_settings) return ch c = getch() if c.upper() == 'S': print('YES')
The above is the detailed content of How to Retrieve Input in Python Without Pressing Enter?. For more information, please follow other related articles on the PHP Chinese website!