How to change pointer location in python?

I want to draw some special words while the program receives them, actually in real time. so I wrote this piece of code that does it well, but I still have a problem with changing the location of the pointer using the navigation keys on the keyboard and start typing from where I moved it. can anyone give me a hint how to do this? here is the CODE:

from colorama import init
from colorama import Fore
import sys
import msvcrt
special_words = ['test' , 'foo' , 'bar', 'Ham']
my_text = ''
init( autoreset = True)
while True:
    c = msvcrt.getch()
    if ord(c) == ord('\r'):  # newline, stop
        break
    elif ord(c) == ord('\b') :
        sys.stdout.write('\b')
        sys.stdout.write(' ')
        my_text = my_text[:-1]
        #CURSOR_UP_ONE = '\x1b[1A'
        #ERASE_LINE = '\x1b[2K'
        #print ERASE_LINE,
    elif ord(c) == 224 :
        set (-1, 1)
    else:
        my_text += c

    sys.stdout.write("\r")  # move to the line beginning
    for j, word in enumerate(my_text.split()):
        if word in special_words:
            sys.stdout.write(Fore.GREEN+ word)
        else:
            sys.stdout.write(Fore.RESET + word)
        if j != len(my_text.split())-1:
            sys.stdout.write(' ')
        else:
            for i in range(0, len(my_text) - my_text.rfind(word) - len(word)):
                sys.stdout.write(' ')
    sys.stdout.flush()
+4
source share
1 answer

Doing this simple way

, , colorama, ANSI (.: http://en.m.wikipedia.org/wiki/ANSI_escape_code)

, , CUP - (CSI n; m H), n m.

:

def move (y, x):
    print("\033[%d;%dH" % (y, x))

,

Windows, , - API .

, colorama () , colorama.init().

, colorama, .

import ctypes
from ctypes import c_long, c_wchar_p, c_ulong, c_void_p


#==== GLOBAL VARIABLES ======================

gHandle = ctypes.windll.kernel32.GetStdHandle (c_long (-11))


def move (y, x):
   """Move cursor to position indicated by x and y."""
   value = (x + (y << 16)
   ctypes.windll.kernel32.SetConsoleCursorPosition (gHandle, c_ulong (value))


def addstr (string):
   """Write string"""
   ctypes.windll.kernel32.WriteConsoleW (gHandle, c_wchar_p (string), c_ulong(len (string)), c_void_p (), None)

, - , , , , curses.

, API , - .

#==== IMPORTS =================================================================
try:
    import curses
    HAVE_CURSES = True
except:
    HAVE_CURSES = False
    pass
+6

Source: https://habr.com/ru/post/1568688/


All Articles