在Python 3中使用ANSI序列确定终端光标位置

时间:2017-10-09 17:08:12

标签: python python-3.x terminal ansi-escape

我想编写一个小脚本,用/usr/lib/w3mimgdisplay将图像打印到终端(就像在mac osx lsi中一样)。因此,我需要脚本启动时的实际光标位置(或插入位置)。到目前为止,我想出了一个带有ANSI序列的shell中的光标位置:

$ echo -en "\e[6n"
^[[2;1R$ 1R

这是ANSI序列的响应的样子(urvxt和bash - 不知道这是否重要)。所以这个序列立即打印出结果(^[[2;1R)。这是我不明白的。这是怎么做到的?如果我编写一个非常简单的shell脚本,只需使用该指令并对脚本进行操作,这就不会清除以太内容。什么?然后我试着通过查看terminfo手册页来弄清楚这是如何发生的。在这里找不到(也许我没有努力尝试)。在这一点上,我发现自己对这个概念非常困惑。终端是否将位置写入stdout?

终端

#!/bin/bash
echo -en "\e[6n"

$ strace sh curpos.sh
[...]
read(255, "#!/bin/bash\necho -en \"\\e[6n\"\n", 29) = 29
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 8), ...}) = 0
write(1, "\33[6n", 4)                   = 4
^[[54;21Rread(255, "", 29)                       = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
exit_group(0)                           = ?
+++ exited with 0 +++

的Python

首先我尝试使用subprocess.check_output,当然只返回我回复的字符串。如何捕获对此ANSI序列的响应?

>>> subprocess.check_output(["echo", "-en", "\x1b[6n"])
b"\x1b[6n"

我还尝试了很多其他的东西,比如读stdin和stdout!?有和没有线程,但所有这些更多的是猜测和嘲笑而不是知道该怎么做。我也在互联网上搜索了一段时间,希望找到一个如何做到这一点的例子,但是没有运气。我找到了同一问题的答案:https://stackoverflow.com/a/35526389/2787738但这不起作用。实际上我不知道这是否曾经有效,因为在这个答案中,ANSI序列在开始从stdin读取之前被写入stdout?在这里,我再次意识到我不理解这些ANSI序列如何真正起作用的概念/机制。所以在这一点上,每一个清除事物的解释都非常受欢迎。我找到的最有用的帖子就是这个:https://www.linuxquestions.org/questions/programming-9/get-cursor-position-in-c-947833/。在这个帖子中有人发布了这个bash脚本:

#!/bin/bash
# Restore terminal settings when the script exits.
termios="$(stty -g)"
trap "stty '$termios'" EXIT
# Disable ICANON ECHO. Should probably also disable CREAD.
stty -icanon -echo
# Request cursor coordinates
printf '\033[6n'
# Read response from standard input; note, it ends at R, not at newline
read -d "R" rowscols
# Clean up the rowscols (from \033[rows;cols -- the R at end was eaten)
rowscols="${rowscols//[^0-9;]/}"
rowscols=("${rowscols//;/ }")
printf '(row %d, column %d) ' ${rowscols[0]} ${rowscols[1]}
# Reset original terminal settings.
stty "$termios"

在这里我们可以看到,确实反应在某种程度上神奇地出现在屏幕上:)。这就是为什么此脚本禁用终端上的回显,并在读取响应后通过stty重置原始终端设置。

1 个答案:

答案 0 :(得分:2)

这是一个POC片段,如何通过ansi / vt100控制序列读取当前光标位置。

<强> curpos.py

import os, re, sys, termios, tty

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

if __name__ == "__main__":
    print(getpos())

示例输出

$ python ./curpos.py
(2, 1)

警告

这并不完美。为了使其更加健壮,在从stdin读取时从用户那里挑选键击的例程会很不错。