How to Retrieve Input in Python Without Pressing Enter?

Patricia Arquette
Release: 2024-11-10 00:56:02
Original
220 people have browsed it

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

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

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!

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