Package: console
┌───────────────────────────┐
│   ┏━╸┏━┓┏┓╻┏━┓┏━┓╻  ┏━╸   │
│   ┃  ┃ ┃┃┗┫┗━┓┃ ┃┃  ┣╸    │
│   ┗━╸┗━┛╹ ╹┗━┛┗━┛┗━╸┗━╸   │
└───────────────────────────┘Tonight we’re gonna party like it’s 1979…╰─(˙𝀓˙)─╮  ╭─(＾0＾)─╯ConsoleTestimonials“👍 Ayyyyyy… 👍”—The Fonz“DYN-O-MITE!!” —J.J. from Good Times“Better… Stronger… Faster” —Oscar Goldman“There is nothing we won’t try…” —Laverne and Shirley“Nothin’ can stand in our way…” —Olivia Newton-John“Fightin’ the system like a true modern-day Robin Hood” —Waylon JenningsYet another package that makes it easy to generate the inline codes used to
display colors and character styles in ANSI-compatible terminals and emulators,
as well as other functionality such clearing screens,
moving cursors,
setting title bars,
and detecting capabilities.How is this one different?
Well,
it’s highly composable and more comprehensive than most.
How does it work?
It’s a piece of cake.“Piece of cake?
Oh, I wish somebody would tell me what that means.” —Dr. Huer␛[1;3mHello World␛[0mThere are many flexible ways to use console’s styling functionality.
Most simply, adding a little color with console might look like this.
First, import the styling palettes and go to town.
The palette entries (aka attributes) can be used in place of strings and handle
everything a string might:>>>fromconsoleimportfg,bg,fx>>>fg.green+'Hello World!'+fg.default'\x1b[32mHello World!\x1b[39m'>>>f'{fx.dim}Lo-key text:{fx.end}''\x1b[2mLo-key text:\x1b[0m'>>>print(fg.red,fx.italic,'♥ Heart',fx.end,...' of Glass…',sep='')♥HeartofGlass…# ← not styled due to readme limits 😉FYI, the string'\x1b'represents the ASCII Escape character
(27in decimal,1bhex).
Command[32mturns the text green
and[39mback to the default color.
But, there’s no need to worry about any of that.
That’s why you’re here, right?NoteApologies, text output can’t be styled due to PyPI/github readme
limitations.
Try theSphinx docsinstead.
When you see “😉” in a comment, that’s a reminder you’re not getting
the full monty.Call() FormAbove,fx.endis a convenient object to note—it ends all styles and fore/background colors at once,
where asfg.defaultorbg.defaultfor example,
resets only the fore or background to its default color.
To avoid that responsibility
(while increasing specificity in what styles are deactivated),
one may also use the call-form instead,
whereit’s automatic:>>>fg.yellow('Far Out!')# <-- ends fg color only'\x1b[33mFar Out!\x1b[39m'>>>fx.italic('Up your nose with a rubber hose!')# italic only'\x1b[3mUp your nose with a rubber hose!\x1b[23m'This is neat because call-form will end specific colors/styles and not
interfere with others.There’s also a rich-text printer that handles basic HTML
(and evenhyperlinksif your terminal supports it):>>>fromconsole.viewersimporthprintasprint>>>print('<i>Hello <b>World!</b> ;-)</i>')*HelloWorld!;-)*# 😉But there’s a shitload,^H^H^H^H^H, crap-ton,^H^H^H^H^H
err…lot more!Kindly read on.Composability++“East bound and down, loaded up and truckin’…We gonna do what they say can’t be done”—Smokey and the BanditConsole’s palette entry objects are meant to be highly composable and useful in
multiple ways.
For example,
you might like to create your own compound styles to use over and over again.
How to?
Just add ‘em up:>>>muy_importante=fg.white+fx.bold+bg.red>>>print(muy_importante('¡AHORITA!',fx.underline))# ← mixin¡AHORITA!# ← not styled due to readme limits 😉One nice feature—when palette objects are combined together as done above,
the list of codes to be rendered is kept on ice until final output as a string.
Meaning, there won’t be redundant styling (Select Graphic Rendition) sequences
in the output,
no matter how many you add:'\x1b[37;1;41;4m¡AHORITA!\x1b[0m'# ⇤-----------⇥  One compound sequence, not four 😎Styles can be built on the fly as well, if need-be:>>>print(...f'{fg.i208+fx.reverse}Tangerine Dream{fx.end}',# or...(fg.i208+fx.reverse)('Tangerine Dream'),...)TangerineDream# 😉TemplatingTo build templates,
call a palette entry with placeholder strings,
with (or instead of) text:>>>sam_template=bg.i22('{}')# dark green>>>print(sam_template.format(' GREEN Eggs… '))GREENEggs…# No, I do not like… 😉Other template formats are no problem either,
try%sor${}.PerformanceOutta Sight!Console is lightweight,
but perhaps you’d like a pre-rendered string to be used in a tight loop for
performance reasons.
Simply usestr()to finalize the output then use it in the loop.>>>msg=str(muy_importante('¡AHORITA!'))>>>foriinrange(100000000):...print(msg)# rapidinho, por favorManagersPalette entries work as context-managers as well:withbg.dodgerblue:print('Infield: Garvey, Lopes, Russel, Cey, Yeager')print('Outfield: Baker, Monday, Smith')print('Coach: Lasorda')⚾
¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.⫽⫽¸¸.·´¯`·.¸¸¸.·´¯`·.¸¸¸
                          ⫻⫻    Tok!Color Palettes“Looo-king Gooood!”—Chico and the ManThe color palettes entries may be further broken down into three main
categories of available colors.
Unleash your innerBrittobelow:Basic, the original 8/16 ANSI named colorsExtended, a set of 256 indexed colors“True” or “Direct”, a.k.a. 16 million colors, consisting of either:RGB specified colorsX11-named colors (built-in), orWebcolors-named colorsAs mentioned,
the original palette,
X11,
and Webcolor palettes
may be accessed directly from a palette object by name.
For example:# Basic                Commentfg.red# One of the original 8 colorsfg.lightred# Another 8 brighter colors w/o bold# Truecolor variantsfg.bisque# Webcolors or X11 color namefg.navyblue# Webcolors takes precedence, if installedAdvanced Color SelectionSpecificpalettes/colors may be chosen via a prefix letter and number of digits
(or name) to specify the color.
For example:# Extended     Format  Commentbg.i_123iDDD# Extended/indexed 256-color palettebg.n_f0fnHHH# Hex to *nearest* indexed color# Truecolorbg.t_ff00bbtHHH# Direct/true color, 3 or 6 digitsbg.x_navybluex_NM# Force an X11 color name (built-in)bg.w_bisquew_NM# Force Webcolors, if installed(The underscores in the attribute names that are numbers are optional.
Choose depending whether brevity or readability are more important to you.)The assorted truecolor forms are used to specify a color explicitly without
ambiguity—X11 and Webcolorsdifferon a few obscure colors.
Though nothing beats “þe auld” hexdigits for certainty.NoteBe aware,
an unrecognized color name or index will result in anAttributeError.Installen-Sie, Bitte⏵pip3install--userconsoleSuggested additional support packages,
some of which may be installed automatically if needed:webcolors# Moar! color namesfuture_fstrings# Needed for: Python Version < 3.6colorama# Needed for: Windows Version < 10win_unicode_console# Useful: for Win Python < 3.6jinxed# terminfo, for SSH *into* WindowsJah!
While console is cross-platform,coloramawill need to be installed and .init() run beforehand to view these examples
under the lame (no-ANSI support) versions of Windows < 10Noteconsolesupports Python 3.6 and over by default.
However!  It is trying out“future-fstrings”for experimental support under Python versions 3.5 and 3.4,
perhaps earlier.
Keep an eye peeled for oddities under older Pythons.
Sorry, neither 2.X or 1.X is supported.:-PDerconsolepackage has recently been tested on:Ubuntu Linux 20.04 - Python 3.8xterm, mate-terminal, linux console, fbtermVery occasionally on kitty, guakeFreeBSD 11 - Python 3.7MacOS 11.2 - Python 3.8MacOS 10.13 - Python 3.6Terminal.app, iTerm2Windows 10 - Python 3.7 - 64bitConhost, WSL, Windows TerminalNot so recently:Windows XP - Python 3.4 - 32 bit + colorama, ansiconWindows 7 - Python 3.6 - 32 bit + colorama¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸¸.·´¯`·.¸¸¸Package Overview“Hey, Mr. Kot-tair!”—Freddie “Boom Boom” WashingtonAs mentioned,
console handles lots more than color and styles.Utils Moduleconsole.utilsincludes a number of nifty functions:>>>fromconsole.utilsimportcls,set_title>>>cls()# whammo! a.k.a. reset terminal>>>set_title('Le Freak')# c'est chic'\x1b]2;Le Freak\x07'It can alsostrip_ansifrom strings,
wait for keypresses,
clear a line or the screen (with or without scrollback),
make hyperlinks,
or easilypausea script like the oldDOScommands of yesteryear.There are also modules to print stylish progress bars:console.progress,
or beep up a storm withconsole.beep.Screen ModuleWithconsole.screenyou can
save, create a new, or restore a screen.
Move the cursor around,
get its position,
and enablebracketed pasteif any of that floats your boat.Blessings-compatible context managers are available for full-screen fun.>>>fromconsole.screenimportsc>>>withsc.location(40,20):...print('Hello, Woild.')Detection ModuleDetect the terminal environment withconsole.detection:Determine palette supportRedirection—is this an interactive “tty” or not?Check relevant user preferences through environment variables,
such asNO_COLOR,COLORFGBG,
andCLICOLOR,
and evenTERM.Query terminal colors and themes—light or dark?Get titles, cursor position, and more.Legacy Windows routines are inconsole.windowsConsole does its best to figure out what your terminal supports on startup
and will configure its convenience objects
(we imported above)
to do the right thing.
They willdeactivate themselves automaticallyat startup when output is
redirected into a pipe,
for example.Detection can be bypassed and handled manually when needed however.
Simply use the detection functions in the module or write your own as desired,
then create your own objects from the classes in theconsole.styleandconsole.screenmodules.
(See the Environment Variables section for full deactivation.)There’s also logging done—enable the debug level before loading the console package and you’ll see the
results of the queries from the detection module.
See below for a ready-made CLI example.ConstantsA number of useful constants are provided inconsole.constants,
such asCSIandOSCfor building your own apps.
You can:fromconsole.constantsimportBELprint(f'Ring my{BEL}… Ring my{BEL}')# ring-a-ling-a-ling…ASCII Table, and Command-Line InterfaceA four-column ASCII table in fruity flavors is provided for your convenience
and learning opportunities.
This format is great for spotting Control key correspondence with letters,
e.g.: Ctrl+M=Enter, Ctrl+H=Backspace, etc.This might be a good time for a quick mention of the console command-line
program that runs quite a few of these utility functions and methods:⏵consoleascii--link00111707BEL3927'7147G10367g...# 😉Remember the detection CLI we mentioned above?  Here’s how to use it:⏵consoledetect-vThe RestSee the Advanced page for more details.Demos and Tests“I got chills, they’re multiplyin’…”—Danny ZukoA series of positively jaw-dropping demos (haha, ok maybe not) may be run at
the command-line with:⏵ python3 -m console.demosIf you have pytest installed,
tests can be run from the install folder.⏵pytest-sThe Makefile in the repoat githubhas more details on such topics.Wrapping UpContributions“Use the Source, Luke!”—‘Ben’ KenobiCould use some help testing on Windows and MacOS as my daily driver is a 🐧 Tux
racer.
Can you help?Release NotesVersion 0.9907 - Apologies, the Screen class will have a few changes in the
names of attributes to make them more consistent.
Stick with 0.9906 until older code can be ported.
This should be rare before 1.0 and non-existent afterwards.DocumentationAdditional docs may be foundhere at bitbucket.Legalese“Stickin’ it to the Man”Copyright 2018-2021, Mike MillerReleased under the LGPL, version 3+.Enterprise Pricing:6 MEEllion dollars…Bwah-haha-ha!(only have to sellonecopy!)