2016-09-28 20 views
0

実行すると、私はこのスクリプトを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の内容のget、行を読み込み、newspace文字を削除し、その後、_Getchクラス/関数を定義します。次に、スクリプトのメインループを実行します。 trycurからraw_input()に設定してください。次に、_Getchクラスを定義して上向き矢印を検出しようとします。これは私が困っているところです。私は_Getchクラスを使って上向きの矢印を感じることができません。現在のコードで上矢印をどのように感じることができますか?

答えて

0

raw_input機能常にENTERではなく、単一の文字(矢印など)までの文字列を読んで

あなたが見る、あなた自身のgetch関数を定義する必要があります:Python read a single character from the user

次に、getch関数を使用してループを使って "input"関数を再実装することができます。 Windowsでは

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)) 

、以下のキーを持つ:ここで

は簡単な使用である 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)、chr(27)を試す... –

関連する問題