Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use extended characters in Python's curses library?

Tags:

python

curses

I've been reading tutorials about Curses programming in Python, and many refer to an ability to use extended characters, such as line-drawing symbols. They're characters > 255, and the curses library knows how to display them in the current terminal font.

Some of the tutorials say you use it like this:

c = ACS_ULCORNER

...and some say you use it like this:

c = curses.ACS_ULCORNER

(That's supposed to be the upper-left corner of a box, like an L flipped vertically)

Anyway, regardless of which method I use, the name is not defined and the program thus fails. I tried "import curses" and "from curses import *", and neither works.

Curses' window() function makes use of these characters, so I even tried poking around on my box for the source to see how it does it, but I can't find it anywhere.

like image 840
mike Avatar asked Dec 14 '22 03:12

mike


2 Answers

you have to set your local to all, then encode your output as utf-8 as follows:

import curses
import locale

locale.setlocale(locale.LC_ALL, '')    # set your locale

scr = curses.initscr()
scr.clear()
scr.addstr(0, 0, u'\u3042'.encode('utf-8'))
scr.refresh()
# here implement simple code to wait for user input to quit
scr.endwin()

output: あ

like image 131
moeabdol Avatar answered Mar 25 '23 08:03

moeabdol


From curses/__init__.py:

Some constants, most notably the ACS_* ones, are only added to the C _curses module's dictionary after initscr() is called. (Some versions of SGI's curses don't define values for those constants until initscr() has been called.) This wrapper function calls the underlying C initscr(), and then copies the constants from the _curses module to the curses package's dictionary. Don't do 'from curses import *' if you'll be needing the ACS_* constants.

In other words:

>>> import curses
>>> curses.ACS_ULCORNER
exception
>>> curses.initscr()
>>> curses.ACS_ULCORNER
>>> 4194412
like image 32
John Millikin Avatar answered Mar 25 '23 06:03

John Millikin