clitools.py 文件源码

python
阅读 24 收藏 0 点赞 0 评论 0

项目:skaff 作者: jhxie 项目源码 文件源码
def key_get() -> str:
    """
    Waits for a single keypress on stdin.

    This is a silly function to call if you need to do it a lot because it has
    to store stdin's current setup, setup stdin for reading single keystrokes
    then read the single keystroke then revert stdin back after reading the
    keystroke.

    Returns the character of the key that was pressed (zero on
    KeyboardInterrupt which can happen when a signal gets handled)

    Reference (StackOverflow):
    /questions/983354/how-do-i-make-python-to-wait-for-a-pressed-key
    """
    if "posix" == os.name:
        fd = sys.stdin.fileno()
        # save old state
        flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
        attrs_save = termios.tcgetattr(fd)
        # make raw - the way to do this comes from the termios(3) man page.
        attrs = list(attrs_save)  # copy the stored version to update
        # iflag
        attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
                      | termios.ISTRIP | termios.INLCR | termios. IGNCR
                      | termios.ICRNL | termios.IXON)
        # oflag
        attrs[1] &= ~termios.OPOST
        # cflag
        attrs[2] &= ~(termios.CSIZE | termios. PARENB)
        attrs[2] |= termios.CS8
        # lflag
        attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
                      | termios.ISIG | termios.IEXTEN)
        termios.tcsetattr(fd, termios.TCSANOW, attrs)
        # turn off non-blocking
        fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
        # read a single keystroke
        try:
            ret = sys.stdin.read(1)  # returns a single character
        except KeyboardInterrupt:
            ret = str()
        finally:
            # restore old state
            termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
            fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
        return ret
    elif "nt" == os.name:
        try:
            # 'getch' by default returns a 'bytes' object;
            # so an extra conversion is required
            ret = msvcrt.getch().decode()
        except KeyboardInterrupt:
            ret = str()
        return ret
# -------------------------------- FUNCTIONS ----------------------------------
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号