Print character to a certain point on console in Python?

安稳与你 提交于 2019-12-23 17:08:59

问题


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.


回答1:


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.




回答2:


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)

I had to translate it slightly to get it correct, but it works. You can print a string of any length in place of a single character. Also, if you want this to execute the function multiple times repeatedly, you should 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.



来源:https://stackoverflow.com/questions/22286194/print-character-to-a-certain-point-on-console-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!