Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - How can I get the cursor's position in an ANSI terminal?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...