Package: python-console
PyConsoleA (basic) cross-platform python console managerTable of ContentsAbout The ProjectInstallationUsageLicenseFeaturesConsoleCursorKeyboardKeyColorColor ParserBoxOtherAcknowledgementsAbout The ProjectThis project aims to implement a cross-platform console manager and other console related 'graphical' functions, like box containers.It draws inpiration from the curses module andrich.InstallationTo install simply usepip:To install runpipinstallpython-consoleTo uninstall runpipuninstallpython-consoleUsageTo begin with, we can import the library with:importpyconsoleOr you can import specific things like theConsoleclass:frompyconsoleimportConsoleFor more complete examples check thefeaturessection or run thetest.pyfile in this repository.FeaturesThe main features of this library are:TheConsoleclassTheKeyboardclassTheCursorclassColors with theColorclassBoxes with theBoxandTitleBoxclassPretty printing exceptions, warnings and interactive sessionsIf you want to know more information that is not displayed here check out the docstrings in the code or using the intellisense of your IDE.ConsoleThe focus of this library is theConsole, it can be used like so:frompyconsoleimportConsoleconsole=Console()Or it can be customized with keyword arguments:frompyconsoleimportConsole,RGBconsole=Console(indent=4,pass_prompt="#",color_mode=RGB)The console methods are:printerrorwarnget_keyget_passprint_tracebackclearcommandOther useful attributes are:systemcolorcursorkeyboardsizeSome examples:Print colored traceback withprint_tracebackfrompyconsoleimportConsole,RGBconsole=Console(color_mode=RGB)try:invalid=1/0exceptZeroDivisionError:console.print_traceback()Print the registered key name from a key pressfrompyconsoleimportConsoleconsole=Console()key=console.get_key()console.print("The int",key,f"represents the key '{console.keyboard.Key(key)}'")Print the terminal size and the OS namefrompyconsoleimportConsoleconsole=Console()console.print("The console dimensions are:",console.size)console.print(f"The current system is: '{console.system}'")CursorThe cursor key can be used to modify some cursor properties.It can be used like so:importtimefrompyconsoleimportConsoleconsole=Console()console.cursor.hide()time.sleep(5)console.cursor.restore()Or it can wrap around a function and restore its values in case of an error, like using Ctrl+C to stop the execution:importtimefrompyconsoleimportConsoleconsole=Console()console.cursor.wrap(time.sleep,5)It can also be moved to any valid position on the screen usingmovefrompyconsoleimportConsoleconsole=Console()console.cursor.move(4,1)# 4th row, 1st column (starting from the 1st row and the 1st column)KeyboardThe keyboard is the class that's in charge of registering keys and associating them according to platform.Registering a new keyfrompyconsoleimportConsoleconsole=Console()console.keyboard.register_key("TILDE","~")The list of registered keys can be found when using intellisense.KeyThe key class is the one that does the association between key and integer, but it still needs the keyboard to know the actual symbol.Registering a new key but omiting the keyboard instancefrompyconsoleimportKeyboardKeyboard.Key.register("TILDE")Or alternativelyfrompyconsoleimportKeyboardKeyboard.Key.TILDE=Keyboard.Key.next_numIt should be noted that it's not really recommended to do the registration this way and should use it through the keyboard instance instead.The key class can also be instantiated from an integer to return the corresponding string representation.Getting the key representation from a numberfrompyconsoleimportKeyboardprint(Keyboard.Key(1))# prints 'LEFT' for left arrowColorThe color class is a class that abstracts the ansi escape codes used for colors and other effects, like underline. If your Windows console (like the ancient cmd.exe) does not support ansi escape sequences then consider usingcoloramafor a fully cross platform option.Do note that the new Windows Terminal does support colors.You can import some basic colors and use them like:fromconsoleimportConsole,REDconsole=Console()console.print(f"{RED}This is red text")Or you can do a manual resetfrompyconsoleimportConsole,RED,BLUE,RESETconsole=Console()console.print(f"{RED}This is red{RESET}and{BLUE}this is blue{RESET}",reset=False)You can also create simple colors withColorCodes andColorModsfrompyconsoleimportConsole,Color,ColorCode,ColorModconsole=Console()color=Color(ColorCode.CYAN,[ColorMod.UNDERLINE,ColorMod.OVERLINE])console.print(f"{color}Hello")You can even add two colors properties togetherfrompyconsoleimportColor,ColorCode,ColorModcolor=Color(ColorCode.YELLOW,[ColorMod.BOLD])color+=Color(mods=[ColorMod.STRIKE])Or if you want more complex colors, you can create them using rgb valuesfrompyconsoleimportColorcolor=Color.from_rgb(246,38,129,bg=True)# Use bg=True for background colorAdditionally, you can add the__color__method to a custom class and define how you want it to look with colorfrompyconsoleimportConsole,LIME,BLUE,RESETclassExample:def__init__(self,value):self.value=valuedef__color__(self):returnf"{LIME}Example{RESET}(value={BLUE}{self.value}{RESET})"console=Console()example=Example(5)console.print(example)# Will print the colored string defined by '__color__'Color ParserThe color parser is the classin charge of parsing different object types to different colors.You can register a type and a color (or even change an already existing one)frompyconsoleimportConsole,Color,RGBconsole=Console(color_mode=RGB)console.color.set_color(bytearray,Color.from_rgb(48,25,52))And you can parse an object into a colored stringfrompyconsoleimportConsoleconsole=Console()console.print(f"This '{console.color.parse(12)}' is an f-string colored number")By default it ignores string unless it's inside a container like a dictionary, but it can be changed by passingignore_str=FalsefrompyconsoleimportConsoleconsole=Console()console.print(f"A{console.color.parse('colored',ignore_str=False)}string")Do note that it will returned the colored representation of the string, meaning, it will add quotes.BoxTheBoxandTitleBoxclasses surround your text wwith a border making a box or a titled box respectively.You can create a box with multiple lines and border colorfrompyconsoleimportBox,LIMEbox=Box("Multiple lines\nin one box\nwith a border color :)",color=LIME)TheTitleBoxclass works the same way, but with an added titlefrompyconsoleimportTitleBox,GREEN,LIME,RESETbox=TitleBox("A Cool Title",f"Just a box\nwith a title\nand{LIME}COLOR{RESET}",color=GREEN)OtherSome other useful functions include:install_errorsfor pretty error formatting all the time (no need to callconsole.print_tracebackinside a try-except block)install_warningsfor pretty warnings formattingpretty.installfor pretty interactive session printinginstallfor installing all of the aboveget_consoleto get the global console instance that the functions above useset_consoleto change the global console propertiesLicenseDistributed under the MIT License. SeeLICENSEfor more information.AcknowledgementsNone of the following are associated with the project in any way. They are mentioned as a source of
learning and inspiration for parts of this project.Rich