Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print character to a certain point on console in Python?

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.

like image 447
Markus Meskanen Avatar asked Mar 09 '14 18:03

Markus Meskanen


People also ask

How do you print a specific character in Python?

all you need to do is add brackets with the char number to the end of the name of the string you want to print, i.e. Show activity on this post. Well if you know the character you want to search you can use this approach. you can change the print statement according to your logic.

How do I print a specific item in a list Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.

How do you print a character on one line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

How do you print to console in Python?

Print to Console in Python. To print strings to console or echo some data to console output, use Python inbuilt print() function. print() function can take different type of values as argument(s), like string, integer, float, etc., or object of a class type.


2 Answers

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.

like image 153
anon582847382 Avatar answered Oct 13 '22 07:10

anon582847382


If your console/terminal supports ANSI escape characters, then this is a good non-module solution.

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.

like image 31
bblhd Avatar answered Oct 13 '22 06:10

bblhd