Home >Backend Development >Python Tutorial >How to Retrieve Input in Python Without Pressing Enter?

How to Retrieve Input in Python Without Pressing Enter?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 00:56:02309browse

How to Retrieve Input in Python Without Pressing Enter?

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!

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