2016-09-28 8 views
0

У меня есть этот скриптSense стрелка вверх в 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, читает строки, и удаляет Newspace характер, а затем определяет/функцию _Getch класса. Затем он запускает основной цикл скрипта. Это try s для установки cur на raw_input(). Затем я пытаюсь определить стрелку вверх, используя класс _Getch. Здесь я испытываю проблемы. Я не могу почувствовать стрелку вверх, используя мой класс _Getch. Как я могу ощущать стрелку вверх с моим текущим кодом?

ответ

0

raw_input функция всегда читать строку, пока не ENTER, а не один символ (стрелка и т.д.)

Вы должны определить свою собственную getch функцию, см: Python read a single character from the user.

Затем вы можете выполнить повторную реализацию функции «ввода» с помощью функции 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 ».

+0

Этот код выглядит немного древним. – baranskistad

+0

Какой код для входа? – baranskistad

+0

Древний, но доступный с Python 3. Попробуйте chr (13) для Enter, chr (27) для Escape ... –