Created
November 14, 2022 00:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.The
term_print()
function accepts either a list of arguments, likeprint()
, or a single list that it pulls items out of. Each item that is a string is simply printed as-is. Theterm_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):Here's the output: