Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the location of the pointer in python?

I want to paint some special words while the program is getting them , actually in real-time . so I've wrote this piece of code which do it quite good but i still have problem with changing the location of the pointer with move keys on keyboard and start typing from where i moved it . can anyone give me a hint how to do it ? 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()
like image 727
Mohammad Siavashi Avatar asked Dec 23 '14 00:12

Mohammad Siavashi


People also ask

How do I change the cursor position in Python?

Step 1: First, import the library tkinter. Step 2: Now, create a GUI app using tkinter. Step 3: Then, create a function with an argument as None to move the cursor wherever you want in the entry widget. Step 4: Next, create and display an entry widget in which you want to change the position.

How can you reposition a file pointer within a file?

We can move the file pointer to the beginning of the file using the seek() method by passing the setting whence to 0. The 0 indicates the first byte, which is the beginning of the file.

How do I get the cursor position in Python?

To determine the mouse's current position, we use the statement, pyautogui. position(). This function returns a tuple of the position of the mouse's cursor. The first value is the x-coordinate of where the mouse cursor is.


1 Answers

Doing it the easy way

As you already seem to be using the colorama module, the most easy and portable way to position the cursor should be to use the corresponding ANSI controlsequence (see: http://en.m.wikipedia.org/wiki/ANSI_escape_code)

The one you are looking for should be CUP – Cursor Position (CSI n ; m H)positioning the cursor in row n and column m.

The code would look like this then:

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

Suffering by doing everything by hand

The long and painful way to make things work even in a windows console, that doesn't know about the above mentioned control sequence would be to use the windows API.

Fortunately the colorama module will do this (hard) work for you, as long as you don't forget a call to colorama.init().

For didactic purposes, I left the code of the most painful approach leaving out the functionality of the colorama module, doing everything by hand.

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)

As already stated in the comment section this attempt still leaves you with the problem, that your application will only work in the named console, so maybe you will still want to supply a curses version too.

To detect if curses is supported or you will have to use the windows API, you might try something like this.

#==== IMPORTS =================================================================
try:
    import curses
    HAVE_CURSES = True
except:
    HAVE_CURSES = False
    pass
like image 88
mikyra Avatar answered Oct 05 '22 09:10

mikyra