6

Is there a way to print a character to a certain point on console using Python (3)? Here's an ideal example on what I'm trying to achieve:

def print_char(x, y, char):
    # Move console cursor to 'x', 'y'
    # Set character under cursor to 'char'

I know it's possible in some other languages, how about Python? I don't mind if I have to use an external library.

I'm on a Windows 7.

Markus Meskanen
  • 19,939
  • 18
  • 80
  • 119

2 Answers2

7

If you are on UNIX (if you are not, see below), use curses:

import curses

stdscr = curses.initscr()

def print_char(x, y, char):
    stdscr.addch(y, x, char)

Only the Python package for UNIX platforms includes the curses module. But don't worry if that doesn't apply to you, as a ported version called UniCurses is available for Windows and Mac OS.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
3

If your console/terminal supports ANSI escape characters, then this is a good solution that doesn't require any modules.

def print_char(x, y, char):
    print("\033["+str(y)+";"+str(x)+"H"+char)

You may have to translate the coordinates slightly to get it in the correct position, but it works. You can print a string of any length in place of a single character. Also, if you want to execute the function multiple times repeatedly in-between clearing the screen, you may want to do this.

def print_char(x, y, char):
    compstring += "\033["+str(y)+";"+str(x)+"H"+char

Then print compstring after all of print_char's have executed. This will reduce flickering from clearing the screen.

bblhd
  • 41
  • 4