帖子的标题是不言自明的。
我想知道如何获取 Linux 终端光标位置。
例如,我目前正在这样设置位置:
print('\033[10;10f')
经过更多研究,我发现正确的答案是这里。经过一些修复后,结果如下:
import re, sys, termios, tty
def getpos():
buff = ''
stdin = sys.stdin.fileno()
tattr = termios.tcgetattr(stdin)
try:
tty.setcbreak(stdin, termios.TCSANOW)
sys.stdout.write('\033[6n')
sys.stdout.flush()
while True:
buff += sys.stdin.read(1)
if buff[-1] == 'R': break
finally:
termios.tcsetattr(stdin, termios.TCSANOW, tattr)
matches = re.match(r'^\033\[(\d*);(\d*)R', buff)
if matches == None: return None
groups = matches.groups()
return (int(groups[0]), int(groups[1]))