简体   繁体   中英

Get position of terminal cursor python

I want to know at what line the terminal's cursor is located in my Python script.

Let's take this code example:

print("Hello, world", end="\n")

print("Cursor is at line: ", get_cursor_line())

The output of this snippet should be:

Hello, world
Cursor is at line: 2

Considering the first line is line 1 ^

Does someone know how to achieve this?

I don't know if it cover all cases, but you can analyze if this solution is suitable for you. You can use a standard-output interceptor:

import sys

class PrintInterceptor:
    def __init__(self):
        self._stdout = sys.stdout
        self._line_count = 1

    def write(self, msg):
        # Every time you write to the terminal, count
        # how many lines were written (starting with 1)
        self._line_count += msg.count('\n')
        self._stdout.write(msg)

    @property
    def line_count(self):
        return self._line_count

Using contextlib , you can use like this:

import contextlib

with contextlib.redirect_stdout(PrintInterceptor()) as interceptor:
    print("Hello, world")
    print(interceptor.line_count)
    print("Good bye, world! \n")
    print("Cursor is at line: ", interceptor.line_count)

This will output

Hello, world
2
Good bye, world! 

Cursor is at line:  5

The only drawback is that all your code must be inside the with-statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM