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

前端 未结 1 1186
傲寒
傲寒 2021-01-19 18:11

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 thi

相关标签:
1条回答
  • 2021-01-19 18:57

    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.

    0 讨论(0)
提交回复
热议问题