Search code examples
pythonlinuxconsolecommand-line-interface

Python Linux Console - Get cursor position


The title of the post is self-explanatory.
I wanna know how can I take the Linux terminal cursor position.

For instance, I'm currently setting the position like so:

print('\033[10;10f')

Solution

  • After some more research I found the correct answer is here. And after some fixes it ended like so:

    import re, sys, termios, tty
    
    def getpos():
      buff = ''
      stdin = sys.stdin.fileno()
      tattr = termios.tcgetattr(stdin)
    
      try:
        tty.setcbreak(stdin, termios.TCSANOW)
        sys.stdout.write('\033[6n')
        sys.stdout.flush()
    
        while True:
          buff += sys.stdin.read(1)
          if buff[-1] == 'R': break
      finally:
        termios.tcsetattr(stdin, termios.TCSANOW, tattr)
    
      matches = re.match(r'^\033\[(\d*);(\d*)R', buff)
      if matches == None: return None
    
      groups = matches.groups()
      return (int(groups[0]), int(groups[1]))