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
內容,讀取線,並刪除時訊字符,然後定義_Getch
類/函數。然後,它運行腳本的主循環。它try
s設置cur
到raw_input()
。然後我嘗試使用定義的_Getch
類來感知向上箭頭。這是我遇到麻煩的地方。我無法使用我的_Getch
類來感知向上箭頭。我如何使用當前的代碼感知向上箭頭?
此代碼看起來有點古老。 – baranskistad
輸入的代碼是什麼? – baranskistad
古代但可用於Python 3.請嘗試chr(13)輸入,chr(27)for Escape ... –