Customize Python Shell

When you load your bash shell, .profile or .bashrc provides initialization script for the shell. It’s possible to achieve the same functionality for the Python shell.

Let’s say, I’d like to modify the Python shell to pretty print all variables and TraceBack(subjective!) using rich library.

  • Create a new file .pythonrc.py in the home directory.
# Install rich specific things for console pretty printing
from rich.pretty import install
install()
from rich.traceback import install
install()
#from rich.console import Console
#console = Console()
#old_print = print
#print=console.print

  • Then while starting the shell pass the file as PYTHONSTARTUP environment variable like PYTHONSTARTUP="/Users/user/.pythonrc.py" poetry run ipython .

  • Now the output of the variable looks different from the usual ipython output(note the indentation).

  • The same Output without Python shell customization.

References

  1. Python docs on customization: https://docs.python.org/3/tutorial/appendix.html#the-interactive-startup-file
  2. Rich library: https://rich.readthedocs.io/en/stable/console.html