Improving Python Console Output With Rich

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
unleashing the power of the console with Rich when creating applications in Python you often have two broad choices to make either create a text-based console app or a graphical user interface commonly known as a GUI while console-based applications are generally quicker and easier to make their appearance can leave a lot to be desired Python's Rich package is a toolkit that helps you generate beautifully formatted and highlighted text in the console more broadly it allows you to build an attractive text-based user interface known as a tuy so why would you choose a Tui over a graphical user interface or guy sometimes a text display feels more appropriate why use a full-blown guey for a simple application when an elegant text interface will do the job it can be refreshing to work with plain text it works in almost any hardware environment even on an SSH terminal or single board computer display and many applications don't need the complexity of a full graphical window system in this course you'll learn how rich can help you enhance the user interface of command line tools improve the readability of console output create attractive dashboard displays for realtime tabular data and generate well formatted reports Rich has support for engaging Dynamic display and this may be all your application needs Rich's author has also created a textual Library which is an entire application development framework but Rich alone may well be sufficient for your application by following this course you'll experiment with many of the cool features of rich and you'll finish up by using your skills to build a dynamically scrolling tabular display of cryptocurrency prices to fully understand Rich's syntax for animation you should have a good grasp of context managers but if you're a bit Rusty don't worry you'll get a quick refresher in this course and if you want to dive deeper into the topic then real python has you covered with this course so now you know what's going to be covered let's get started installing Rich you can start using Rich very quickly as always when starting a new project or investigation it's best to create a vir environment first to avoid polluting your system's python installation you can install Rich solely for use with the python repple but in addition you can also add support for Jupiter notebooks at the same time so that's the installation you'll see here the commands vary slightly between platforms here's how to create and activate a virtual environment and then install rich on Mac OS or Linux in this case using python 312 and here are the commands when using Windows terminal now that you've installed rich in your new virtual environment you can test it and also get a nice overview of its capabilities as you can see running this command makes a lot happen the terminal will fill with color and you'll see see several options for customizing your text based user interface scrolling back to the top to see the full content you can see richest support for colors text Styles and formatting Asian language support markup tables syntax highlighting and pretty printing markdown and more apart from displaying colorful text in a variety of styles this demo also illustrates a few more of Rich's exciting features there's much more you can do with Rich As you'll discover throughout this course you can also try some of the command line demos that Rich has thoughtfully provided for its sub packages so that you can get a flavor of what each one can do without writing any code on screen you'll see a few that you can try from your operating system console execute them one by one to get a feel for the power of rich you may need to scroll up for the table demo as there are several example tables which will fill your screen the settings for each table style demo are shown on screen above the table the progress demo shows how rich can create progress bars and maintain their location on screen while other elements are being printed to it when you've seen enough it will need to be interrupted with control and C the status demo shows other useful Rich features with the installation done and a glimpse of what's ahead you're ready to start exploring rich and you'll start that exploration in the next part of the course looking at using Rich for python development using Rich for python development Rich can help to make your life as a veler a little bit easier for instance it has built-in support for formatting and syntax highlighting python code and data structures and it has a useful inspect function that lets you examine deeply nested data the rich installation has support for IPython and Jupiter but here you'll be exploring it with Python's built-in repple the first Rich feature that you'll explore is syntax highlighting this helps to clarify the structure of programming statements and data syntax highlighting is built into Rich's print function open the python repple Define a simple data structure and print it using Python's built-in print function this does exactly what you'd expect the output has all the information that you want to display but it doesn't look very exciting it would be nice if the different data types were colorcoded to provide some visual variety and help you keep the information straight fortunately Rich's version does exactly that Rich's print is a dropin replacement for Python's built-in function so you could safely override the built-in print but here to make comparisons easier it's been imported under the Alias R print now the differ data types are highlighted the syntax highlighting makes easy to see what types the structure contains python standard Library includes a package named PR print that supports pretty printing while its formatting of complex data structures is a definite improvement over the built-in print it doesn't support colored text the real benefits of pretty printing code appear when you're dealing with more complex structures on screen you'll see a small example let's suppose your designing a data structure for your latest app and you've hand coded this dictionary the python reppel is fairly forgiving about input format so as long as the code is valid python as it is here then the reppel is happy to accept it you carry on coding and a little later you decide to write the code that passes this data structure to remind yourself of the details you print it to the screen the data is all there but the reel's formatting leaves a lot to be desired it's certainly possible to troll through this print output and identify the nested dictionaries and lists but it's not easy to do and it's easy to miss something or make a mistake with a larger data structure this would be next to Impossible now let's see what happens when you print it with Rich the code is neatly formatted and takes advantage of syntax highlighting the layout of the print out makes much more sense and the data types are colored differently this makes the structure of the data much easier to understand do you always want your data structures presented like this while you're developing as you probably know when you simply type a variable name into the reppel and press enter it Echo that variable's value to the console by default the format is the same as for print but it would be nice to have that value pretty printed by default and you can do that by installing Rich pretty printing to the repple now when you type the variable's name into the repple you automatically get a pretty printed and highlighted representation just as you saw with our print having your data structures displayed in a pleasing and readable format can make your coding experience much more pleasant and productive you can even configure your reppel to always install Rich's pretty printing at startup to do so you'll need to edit the hidden python startup file which is located in your home directory as you might expect the code is standard python which is executed silently when the reppel is started pretty and Trace back are imported from Rich and in the case of them not being found the exception is just passed over the else Clause will only be performed if there's no exception and it installs pretty and Trace back to the reppel so they will be present every time it's great that your data structures are now prettily colorcoded and formatted but that's not always enough in development sometimes you want to have a look under the hood of a data structure and really get a snapshot of how it works works for that you can use Rich's inspect function here you can see what it does with your example data structure with inspect you can really examine the inner workings of an object since superhero is a dictionary Rich also shows you all the available Constructors before displaying the pretty printed data as before you can also add the optional method methods equals true parameter to get a handy summary of the object's methods with their short dock strings and parameter types the inspect function is quite powerful you can get a comprehensive description of its parameters by by typing inspect inspect as seen on screen the python standard library has its own inspect module that also allows live inspection of code objects it's much more powerful but also much more complex than the rich function you've been using you should check it out if you need to do heavyduty code introspection however Python's inspect module doesn't offer syntax highlighting for many investigations you may find the rich function more convenient in the next section of the course you'll deepen your understanding of Rich looking at the console class and logging the console class and logging Rich has a console class that encapsulates most of the package's capabilities a console instance can format text generate colorized log output or pretty print Json and it can also handle indentation horizontal rules widgets panels and tables as well as interactive prompts and animations you can capture console output and Export it as text SVG or HTML the print function that comes with Rich is a shortcut that supports some of the console features in longer programs you should prefer console and its print method over Rich print as it's more powerful console will interpret console markup to apply colors and attributes to text all of these features are available subject to your terminals capabilities but most modern terminal emulators will handle everything just fine console markup consists of paired tags within square brackets here a color and style are specified with green underlined text and blue italicized text which are then displayed when the command is executed the specified styles are applied to the text within the tags you can find a complete list of the names hex codes and RGB values of the 255 standard text colors in the rich appendix but you can also view them from the command line if your terminal supports true color then you can specify any of the 16 million colors available by their RGB values as a shorthand you can use the forward slash enclosed in Brackets to close the last applied style you can specify the background color by using on between the foreground and background colors as seen here along with a full range of text colors console markup supports attributes such as bold blink reverse underline and metallic a combination of color and attributes is called a style and you can put several Styles together in a dictionary to create a theme in custom theme you've defined styles that you can apply to any console instance using a console object with a theme helps keep your formatting consistent across the application creating good log statements is an important part of writing maintainable code logging helps you during development and testing by confirming that your code is following the expected paths it's invaluable when things go wrong in production code AS well-placed log statements can provide insight into obscure code misbehavior the console class supports formatted logging and uses a syntax that's close to that of Python's standard logging package it can generate nicely formatted tracebacks of any uncaught exceptions in your code while using styles from a defined theme pythons built-in tracebacks and error messages get more informative and useful with each new release but some extra eye candy doesn't hurt and there's no substitute for good log messages to give context for a crash continuing the previous example you can produce some samples of logging output log messages can use the themes you defined previously with console log you automatically add timestamps source file names and Source line numbers to your logging statements while things are running normally you'll just get the clean log output as seen But if there's a crash during development then you'll want to log as much information as possible about the cause try manually throwing a runtime error and see the difference when an exception happens the trace back can optionally display all of your local variables as well as the stack trace of the error your session may contain more local variables than this so the output may look different tools like these can really help to make your development experience more pleasant and productive Rich's colorful and nicely presented error messages are much more readable than Python's default tracebacks you may even look forward to getting an exception but one category of people who will not look forward to exceptions will be your end user users so to keep them happy in the next section of the course you'll look at ways to engage your users with animation
Info
Channel: Real Python
Views: 7,978
Rating: undefined out of 5
Keywords: python, realpython, rich, tui, logging, console, print
Id: NIyljVEcJKw
Channel Id: undefined
Length: 19min 37sec (1177 seconds)
Published: Thu Feb 22 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.