Skip to content

Instantly share code, notes, and snippets.

@tylerneylon
Created November 14, 2022 00:03
Show Gist options
  • Save tylerneylon/7e735d7358ca66a9c22d505f51a14d25 to your computer and use it in GitHub Desktop.
Save tylerneylon/7e735d7358ca66a9c22d505f51a14d25 to your computer and use it in GitHub Desktop.
A handy function to assist in printing in color or doing other fun things in the terminal
import curses
import sys
# NOTE: It's up to YOU, dear coder, to call curses.setupterm() first.
# I believe in you. (If this called setupterm(), then we'd call it more than needed.)
def term_print(strs, *args, flush=True):
''' This expects `strs` to be a list of strings and tuples. Each
string is printed, while each tuple is interpreted as a tput command
with any needed parameters supplied. For example, the tuple ('smul',)
turns on underlined printing. The command ('setaf', 15) changes the font
color to color 15 (which is typically white).
'''
if args:
strs = [strs] + list(args)
# As an edge case, we may receive just a single tuple.
if type(strs) is tuple:
strs = [strs]
for s in strs:
if type(s) is str:
s = s.encode()
elif type(s) is list:
term_print(s)
s = b''
else:
assert type(s) is tuple
if len(s) == 1:
s = curses.tigetstr(s[0])
else:
s = curses.tparm(curses.tigetstr(s[0]), *s[1:])
sys.stdout.buffer.write(s)
sys.stdout.buffer.flush()
@tylerneylon
Copy link
Author

tylerneylon commented Nov 14, 2022

This is a little function to simplify writing in color, or doing other fun things on the terminal.

As a quick reference, here are a few things you might want to do. These
little strings are called "capnames" (short for capability names), and you can
read more about them by running man terminfo in your shell.

setaf NUM    Set the foreground text color.
setab NUM    Set the background text color.
smul         Start underline mode.
rmul         Stop underline mode.
sgr0         Reset to normal mode (normal colors, no underline, etc).

The term_print() function accepts either a list of arguments, like print(), or a single list that it pulls items out of. Each item that is a string is simply printed as-is. The term_print() function expects formatting commands in the form of tuples. For example, here is a command that will underline one word, and print another in red (color 196 is typically red):

term_print(
    'So ',
    ('smul',),
    'this is underlined',
    ('rmul',),
    ' and the word ',
    ('setaf', 196),
    'red',
    ('sgr0',),
    ' is red.'
)

Here's the output:
Screen Shot 2022-11-13 at 4 13 29 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment