How to change the location of the pointer in python?

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

Leave a Comment