Skip to main content

A (basic) cross-platform python console manager

Project description

Contributors Stars Issues Repo Size MIT License

PyConsole

A (basic) cross-platform python console manager

Table of Contents
  1. About The Project
  2. Installation
  3. Usage
  4. License
  5. Features
  6. Acknowledgements

About The Project

This 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 and rich.

Installation

To install simply use pip:

  • To install run
    pip install python-console
    
  • To uninstall run
    pip uninstall python-console
    

Usage

To begin with, we can import the library with:

import pyconsole

Or you can import specific things like the Console class:

from pyconsole import Console

For more complete examples check the features section or run the test.py file in this repository.

Features

The main features of this library are:

  • The Console class
    • The Keyboard class
    • The Cursor class
  • Colors with the Color class
  • Boxes with the Box and TitleBox class
  • Pretty printing exceptions, warnings and interactive sessions

If 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.

Console

The focus of this library is the Console, it can be used like so:

  from pyconsole import Console


  console = Console()

Or it can be customized with keyword arguments:

  from pyconsole import Console, RGB


  console = Console(indent=4, pass_prompt="#", color_mode=RGB)

The console methods are:

  • print
  • error
  • warn
  • get_key
  • get_pass
  • print_traceback
  • clear
  • command

Other useful attributes are:

  • system
  • color
  • cursor
  • keyboard
  • size

Some examples:

Print colored traceback with print_traceback

  from pyconsole import Console, RGB


  console = Console(color_mode=RGB)

  try:
      invalid = 1 / 0
  except ZeroDivisionError:
      console.print_traceback()

Print the registered key name from a key press

  from pyconsole import Console


  console = 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 name

  from pyconsole import Console


  console = Console()
  console.print("The console dimensions are:", console.size)
  console.print(f"The current system is: '{console.system}'")

Cursor

The cursor key can be used to modify some cursor properties.

Currently, it can only hide or restore its visibility.

It can be used like so:

  import time

  from pyconsole import Console


  console = 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:

  import time

  from pyconsole import Console


  console = Console()
  console.cursor.wrap(time.sleep, 5)

Keyboard

The keyboard is the class that's in charge of registering keys and associating them according to platform.

Registering a new key

  from pyconsole import Console


  console = Console()
  console.keyboard.register_key("TILDE", "~")

The list of registered keys can be found when using intellisense.

Key

The 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 instance

  from pyconsole import Keyboard


  Keyboard.Key.register("TILDE")

Or alternatively

  from pyconsole import Keyboard


  Keyboard.Key.TILDE = Keyboard.Key.next_num

It 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 number

  from pyconsole import Keyboard


  print(Keyboard.Key(1))  # prints 'LEFT' for left arrow

Color

The 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 using colorama for 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:

  from console import Console, RED


  console = Console()
  console.print(f"{RED}This is red text")

Or you can do a manual reset

  from pyconsole import Console, RED, BLUE, RESET


  console = Console()
  console.print(f"{RED}This is red{RESET} and {BLUE}this is blue{RESET}", reset=False)

You can also create simple colors with ColorCodes and ColorMods

  from pyconsole import Console, Color, ColorCode, ColorMod


  console = Console()
  color = Color(ColorCode.CYAN, [ColorMod.UNDERLINE, ColorMod.OVERLINE])
  console.print(f"{color}Hello")

You can even add two colors properties together

  from pyconsole import Color, ColorCode, ColorMod


  color = Color(ColorCode.YELLOW, [ColorMod.BOLD])
  color += Color(mods=[ColorMod.STRIKE])

Or if you want more complex colors, you can create them using rgb values

  from pyconsole import Color


  color = Color.from_rgb(246, 38, 129, bg=True)  # Use bg=True for background color

Additionally, you can add the __color__ method to a custom class and define how you want it to look with color

  from pyconsole import Console, LIME, BLUE, RESET


  class Example:
      def __init__(self, value):
          self.value = value

      def __color__(self):
          return f"{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 Parser

The 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)

  from pyconsole import Console, Color, RGB


  console = Console(color_mode=RGB)
  console.color.set_color(bytearray, Color.from_rgb(48, 25, 52))

And you can parse an object into a colored string

  from pyconsole import Console


  console = 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 passing ignore_str=False

  from pyconsole import Console


  console = 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.

Box

The Box and TitleBox classes surround your text wwith a border making a box or a titled box respectively.

You can create a box with multiple lines and border color

  from pyconsole import Box, LIME


  box = Box("Multiple lines\nin one box\nwith a border color :)", color=LIME)

The TitleBox class works the same way, but with an added title

  from pyconsole import TitleBox, GREEN, LIME, RESET


  box = TitleBox("A Cool Title", f"Just a box\nwith a title\nand {LIME}COLOR{RESET}", color=GREEN)

Other

Some other useful functions include:

  • install_errors for pretty error formatting all the time (no need to call console.print_traceback inside a try-except block)
  • install_warnings for pretty warnings formatting
  • pretty.install for pretty interactive session printing
  • install for installing all of the above
  • get_console to get the global console instance that the functions above use
  • set_console to change the global console properties

License

Distributed under the MIT License. See LICENSE for more information.

Acknowledgements

None 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python-console-1.1.0.tar.gz (26.3 kB view details)

Uploaded Source

Built Distribution

python_console-1.1.0-py3-none-any.whl (25.8 kB view details)

Uploaded Python 3

File details

Details for the file python-console-1.1.0.tar.gz.

File metadata

  • Download URL: python-console-1.1.0.tar.gz
  • Upload date:
  • Size: 26.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.6.4 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.7.9

File hashes

Hashes for python-console-1.1.0.tar.gz
Algorithm Hash digest
SHA256 50014562ac9dda02dbce07b36452fd8b3cb6f12133f83148c82aee2ec8a7ac9c
MD5 a119de88550c8a92ced6f486a49042fb
BLAKE2b-256 84dcfa1e110d3f1bb2ef1d6d76cef6c5cf9654436c0e6742cb5cc8e493244c00

See more details on using hashes here.

File details

Details for the file python_console-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: python_console-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 25.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.6.4 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.7.9

File hashes

Hashes for python_console-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e90bd700307d47cfca395a0e6c117b4d4f662f5e98f7af243a4ae000240f1f4d
MD5 b652b11ffb3ee3f5d389d26506d2f236
BLAKE2b-256 732c0c9ba59168c8338c0705cd885633fa49e54f6c4f9adef90707741dd4e4fc

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page