[PYTHON] Yes / No confirmation without having to press ENTER

Introduction

Sometimes you want to check Yes / No while executing a script. If you want to delete something, or if you need to be careful and don't want to execute it unconditionally, you want to check it just in case. However, when operating, it becomes troublesome to press "Y" "ENTER" or "N" "ENTER". I wonder if "Y" and "N" are not enough. And if you want to check Yes / No without pressing "ENTER", you can handle it by preparing a function like this.

Code example

import sys
import termios


def yesno():
    result = ''
    attribute = termios.tcgetattr(sys.stdin)
    temp = termios.tcgetattr(sys.stdin)
    temp[3] &= ~(termios.ICANON | termios.ECHO)
    termios.tcsetattr(sys.stdin, termios.TCSAFLUSH, temp)
    try:
        while True:
            char = sys.stdin.read(1)
            if char == 'y' or char == 'Y':
                result = 'Y'
                break
            elif char == 'n' or char == 'N':
                result = 'N'
                break
    except KeyboardInterrupt:
        result = '^C'
    termios.tcsetattr(sys.stdin, termios.TCSAFLUSH, attribute)
    return result


key = yesno()
# key: 'Y' or 'N' or '^C'

I wrote it in Python here, but if you can operate termios, you can write something similar.

Supplement

In the code example that uses termios in Python, there is a description of fd = sys.stdin.fileno (), and after that, you may see that using fd. But I prefer to use sys.stdin. I hate writing sys.stdin where it looks like I need a file descriptor, but I like to shorten it by one line.

https://docs.python.org/3/library/termios.html

All functions in this module take a file descriptor fd as their first argument. This can be an integer file descriptor, such as returned by sys.stdin.fileno(), or a file object, such as sys.stdin itself.

https://docs.python.org/ja/3/library/termios.html

All functions in this module take the file descriptor fd as the first argument. This value can be an integer file descriptor such as that sys.stdin.fileno () returns, or a file object such as sys.stdin itself.

Recommended Posts

Yes / No confirmation without having to press ENTER