I want to get the cursor’s position in a terminal window. I know I can echo -e "33[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", "33[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
?
Advertisement
Answer
You can simply read sys.stdin
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.