Home > Back-end >  Python - How to exit while loop with command line input() by pressing Esc
Python - How to exit while loop with command line input() by pressing Esc

Time:09-29

I am new to Python. I am working on windows OS. My application is getting name text from command prompt using input() method in while loop. I want to exit while loop by pressing Esc key but input() is not recognizing Esc key. How to handle both input() method and Esc key press in while loop in Python

def get_name_from_user():
    result = False
    while True:
        name = input("Enter the name:")
        if validate_name(name):
            return True
        else:
            print("Name allows only alpha numeric characters.")
    return result

CodePudding user response:

Why not instead check for an empty string? Most CLI tools that take multiple inputs will check for an empty string to indicate that the user is finished with input.

def get_name_from_user():
    result = False
    while True:
        name = input("Enter the name:")
        if name == "":
            break

        if validate_name(name):
            return True
        else:
            print("Name allows only alpha numeric characters.")
    return result

CodePudding user response:

Try using msvcrt. On Windows, this module allows users to input individual keystrokes.

import msvcrt

def get_name_from_user():
    result = False
    while True:
        name = ""
        while True:
            char = msvcrt.getch()
            if char == chr(13): # enter key
                break
            elif char == chr(27): # escape key
                return result
            else:
                name  = char
        if validate_name(name):
            return True
        else:
            print("Name allows only alpha numeric characters.")
    return result

Alternatively tkinter bind may help but that is probably not a good idea because of the modifications you'll need to make.

  • Related