Python 3:捕获“\x1b[6n`”(`\033[6n`,`\e[6n`)ansi序列的返回
我正在写一本“libansi”。 我想捕获ansi序列的返回码\x1b[6n 我试着四处转转,但什么也没做 例如:Python 3:捕获“\x1b[6n`”(`\033[6n`,`\e[6n`)ansi序列的返回,python,terminal,python-3.4,ansi-escape,Python,Terminal,Python 3.4,Ansi Escape,我正在写一本“libansi”。 我想捕获ansi序列的返回码\x1b[6n 我试着四处转转,但什么也没做 例如: #!/usr/bin/python3.4 rep = os.popen("""a=$(echo "\033[6n") && echo $a""").read() 代表返回“\033[6n” 有人有主意吗 谢谢你的帮助 编辑: 我有一个局部解决方案: a=input(print("\033[6n", end='') 但这需要我在输入时按“回车”键来获取光标位置。问
#!/usr/bin/python3.4
rep = os.popen("""a=$(echo "\033[6n") && echo $a""").read()
代表返回“\033[6n”
有人有主意吗
谢谢你的帮助
编辑:
我有一个局部解决方案:
a=input(print("\033[6n", end='')
但这需要我在输入时按“回车”键来获取光标位置。问题是
tty.setcbreak(sys.stdin.fileno(),termios.TCSANOW)
并在此之前通过变量termios.getattr
存储终端属性,以恢复默认行为。使用cbreak
set,os.read(sys.stdin.fileno(),1)
您可以立即从stdin读取。这也会抑制来自终端的ansi控制代码响应
def getpos():
buf = ""
stdin = sys.stdin.fileno()
tattr = termios.tcgetattr(stdin)
try:
tty.setcbreak(stdin, termios.TCSANOW)
sys.stdout.write("\x1b[6n")
sys.stdout.flush()
while True:
buf += sys.stdin.read(1)
if buf[-1] == "R":
break
finally:
termios.tcsetattr(stdin, termios.TCSANOW, tattr)
# reading the actual values, but what if a keystroke appears while reading
# from stdin? As dirty work around, getpos() returns if this fails: None
try:
matches = re.match(r"^\x1b\[(\d*);(\d*)R", buf)
groups = matches.groups()
except AttributeError:
return None
return (int(groups[0]), int(groups[1]))
像这样的所有解决方案都无法工作,因为sh/bash cmd中的ANSI序列在子shell中得到响应。