繁体   English   中英

在Python中感觉到向上箭头?

[英]Sense up arrow in Python?

我有这个剧本

import sys, os, termios, tty
home = os.path.expanduser("~")
history = []
if os.path.exists(home+"/.incro_repl_history"):
    readhist = open(home+"/.incro_repl_history", "r+").readlines()
    findex = 0
    for j in readhist:
        if j[-1] == "\n":
            readhist[findex] = j[:-1]
        else:
            readhist[findex] = j
        findex += 1
    history = readhist
    del readhist, findex

class _Getch:
    def __call__(self):
            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(sys.stdin.fileno())
                ch = sys.stdin.read(3)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
            return ch

while True:
    try:
        cur = raw_input("> ")
        key = _Getch()
        print key
        if key == "\x1b[A":
            print "\b" * 1000
            print history[0]
        history.append(cur)
    except EOFError:
        sys.stdout.write("^D\n")
        history.append("^D")
    except KeyboardInterrupt:
        if not os.path.exists(home+"/.incro_repl_history"):
            histfile = open(home+"/.incro_repl_history", "w+")
            for i in history:
                histfile.write(i+"\n")
        else:
            os.remove(home+"/.incro_repl_history")
            histfile = open(home+"/.incro_repl_history", "w+")
            for i in history:
                histfile.write(i+"\n")
    sys.exit("")

运行时,它获取/home/bjskistad/.incro_repl_history的内容,读取各行,并删除换行符,然后定义_Getch类/函数。 然后,它运行脚本的主循环。 trycur设置为raw_input() 然后,我尝试使用定义的_Getch类来感测向上箭头。 这是我遇到麻烦的地方。 我无法使用_Getch类感觉到向上箭头。 如何用当前代码感应上箭头?

raw_input函数始终读取字符串直到ENTER,而不是单个字符(箭头等)。

您需要定义自己的getch函数,请参见: Python从用户读取单个字符

然后,您可以使用getch`函数通过循环重新实现“输入”函数。

这是一个简单的用法:

while True:
    char = getch()
    if char == '\x03':
        raise SystemExit("Bye.")
    elif char in '\x00\xe0':
        next_char = getch()
        print("special: {!r}+{!r}".format(char, next_char))
    else:
        print("normal:  {!r}".format(char))

在Windows下,使用以下键: Hello<up><down><left><right><ctrl+c> ,您将获得:

normal:  'H'
normal:  'e'
normal:  'l'
normal:  'l'
normal:  'o'
special: '\xe0'+'H'
special: '\xe0'+'P'
special: '\xe0'+'K'
special: '\xe0'+'M'

因此箭头对应于组合字符:“ \\ xe0H”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM