如何在 ANSI 终端中获取光标的位置? [英] How can I get the cursor's position in an ANSI terminal?
问题描述
我想在终端窗口中获取光标的位置.我知道我可以像 这个答案,但我如何在 Python 中做到这一点?
我试过这样这个上下文管理器:
以 Capturing() 作为输出:sys.stdout.write("\e[6n")打印(输出)
但它只捕获我写的 \e[6n
('\x1b[6n'
) 转义序列,而不是 ^[[x;yR1
我需要的序列.
我也试过生成一个 subprocess
并获取它的输出,但同样,只有我写的转义序列被捕获:
output = subprocess.check_output(["echo", "\033[6n"], shell=False)打印(输出)
shell=True
使输出为空字符串列表.
避免curses
(因为这应该是一个简单,可怜人的光标pos getter),我怎样才能通过打印\获取返回的转义序列e[6n
?
我们开始吧 - 您可以自己阅读 sys.stdout
以获取值.我在一个和你一样的问题中找到了答案,但对于一个试图从 C 程序中做到这一点的人:
http://www.linuxquestions.org/questions/programming-9/get-cursor-position-in-c-947833/
所以,当我从 Python 交互式终端尝试一些东西时:
<预><代码>>>>导入系统>>>sys.stdout.write("\x1b[6n");a=sys.stdin.read(10)]^[[46;1R>>>>>>一种'\x1b[46;1R'>>>sys.stdin.isatty()真的您将不得不使用其他 ANSI 技巧/位置/重印来避免实际显示在终端上的输出,并防止在标准输入读取时发生阻塞 - 但我认为可以通过一些反复试验来完成.
I want to get the cursor's position in a terminal window. I know I can echo -e "\033[6n"
and read
the output -s
silently as in this answer, but how can I do this in Python?
I've tried this contextmanager like this:
with Capturing() as output:
sys.stdout.write("\e[6n")
print(output)
but it only captures the \e[6n
('\x1b[6n'
) escape sequence I write, not the ^[[x;yR1
sequence I need.
I've also tried spawning a subprocess
and getting its output, but again, only the escape sequence I write is captured:
output = subprocess.check_output(["echo", "\033[6n"], shell=False)
print(output)
shell=True
makes the output be a list of empty strings.
Avoiding curses
(because this is supposed to be a simple, poor man's cursor pos getter), how can I get the escape sequence returned by printing \e[6n
?
Here we go -you can simply read sys.stdout
yourself to get the value.
I found the answer in a question just like yours, but for one trying to do that from a C program:
http://www.linuxquestions.org/questions/programming-9/get-cursor-position-in-c-947833/
So, when I tried something along that from the Python interactive terminal:
>>> import sys
>>> sys.stdout.write("\x1b[6n");a=sys.stdin.read(10)
]^[[46;1R
>>>
>>> a
'\x1b[46;1R'
>>> sys.stdin.isatty()
True
You will have to use other ANSI tricks/position/reprint to avoid the output actually showing up on the terminal, and prevent blocking on stdin read - but I think it can be done with some trial and error.
这篇关于如何在 ANSI 终端中获取光标的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!