Home >Backend Development >Python Tutorial >How to Get User Input Without Pressing Enter in the Shell?

How to Get User Input Without Pressing Enter in the Shell?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 02:03:02694browse

How to Get User Input Without Pressing Enter in the Shell?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn