我正在写一个“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='')
但这需要我在输入时按“输入”以获取光标位置。
最佳答案
问题是
诀窍是使用
tty.setcbreak(sys.stdin.fileno(), termios.TCSANOW)
并在此之前通过 termios.getattr
存储终端属性在变量中恢复默认行为。与 cbreak
套装,os.read(sys.stdin.fileno(), 1)
您可以立即从标准输入读取。这也抑制了来自终端的 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]))
关于Python 3 : Capture return of `\x1b[6n` (`\033[6n` , `\e[6n` ) ansi 序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38465171/