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
Release: 2024-11-10 02:03:02
Original
660 people have browsed it

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')
Copy after login

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
Copy after login

With this function, you can retrieve user input without the need for pressing enter:

c = getch()
if c.upper() == 'S':
    print('YES')
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template