0

I'm trying to find a way to get the terminal cursor position on Python 3, and store it in a variable. There's an escape sequence (\x1b[6n) which writes the position to the standard input file. I'm struggling on finding a proper way to get this sequence. I tried to override sys.stdin with my own class temporary, so I could get the sequence, and then use the original sys.stdin again:

import sys

class Test:
    def __init__(self, ogstdin) -> None:
        self.ogstdin = ogstdin
        self.buff = []

    def write(self, text: str) -> None:
        self.buff.append(text)

    def fileno(self):
        return self.ogstdin.fileno()


sys.stdin = Test(sys.stdin)


print("\x1b[6n", end="")

print(sys.stdin.buff)

Unfortunately, buff is still an empty list, and the sequence is still shown on input. Meaning that the override did nothing useful.

As a side note, I wanted to use this for fixing this issue of my project.

DarviL
  • 13
  • 4
  • Terminal escape sequences don't work like that. When you tell your TTY to tell you the current cursor location, the result goes _to the tty_. What Python thinks `sys.stdin` is has no influence on the terminal's behavior; the terminal doesn't know or care -- if Python is trying to read from something other than the tty, it won't get the response, whether it's calling that thing "stdin" or not. – Charles Duffy Oct 22 '21 at 23:25
  • Damn... That's a shame. Is there still any way to get that string? Thanks for responding by the way. – DarviL Oct 23 '21 at 00:08
  • I'd need to know more about your project to understand why this question came up -- which is to say, why you don't read the result from a file handle with the TTY open for read (which is typically what a program run interactively has on its stdin by default). If the thing that's a problem is the result being locally echoed, my first instinct would just be up _turn off local echo_ for the relevant time period. – Charles Duffy Oct 23 '21 at 01:07
  • For the purpose of my project, I needed to get the position of the terminal cursor, so then I could do some operations with that (like printing some characters on a relative position to it). After a lot of research, I found [this answer](https://stackoverflow.com/a/36974338/14546524) which helps me a lot for what I need. – DarviL Oct 23 '21 at 12:43

0 Answers0