1

I am a big fan of the pretty printing option of rich.

Thus, I want to automatically run the lines

from rich import pretty
pretty.install()

every time I use python (before anything else).

How can I achieve the following behavior:

  1. python -> run the two lines and drop me into interactive python3 shell
  2. python myscript.py -> run the two lines, then run myscript.py

I have already put the two lines into a startup.py file and created an alias in my ~/.bashrc:

alias python='python3 -i /path/to/startup.py'

which works great when I am using the python standard shell by just calling python (case 1). However, I cannot use the alias to run scripts, for example with python myscript.py (case 2).

I am using Python 3.10.6 on Ubuntu 22.04.

  • Could write a script to subprocess python (or whatever), feeds those lines to stdin, and then drops to normal console... – Abel May 10 '23 at 12:38
  • A possible approach would be to modify `site.py`. `site.py` automatically gets imported while initialization (This behaviour can be disabled using the `-S`). Although modifying `site.py` is discouraged, as this can cause some very weird issues with compatibility, portability and maintanability to name a few. So if you wanna do it, do it; but be warned. – Clasherkasten May 10 '23 at 12:51

1 Answers1

2

I have actually found a solution in the meanwhile.

If you only want to achieve case #1, you should make use of the PYTHONSTARTUP environment variable, by setting it in your ~/.bashrc:

export PYTHONSTARTUP="/path/to/startup.py"

To achieve cases #1 and #2, you should name your startup file usercustomize.py and place it in your USER_SITE directory, which you can find with python -m site. This is the recommended way of modifying the behavior of site.py. More details in the accepted answer of this question.

The second approach has one downside: Compared to the PYTHONSTARTUP solution, imports being done in usercustomize.py are forgotten once you are dropped into the interactive shell or your script is being executed. For example, pretty.install() works, while from rich import print would not overwrite the default print function, as it is just an import. If you want to use default imports in the interactive shell (e.g. import numpy as np, because you use it so frequently), you have to use both, usercustomize.py and PYTHONSTARTUP. I have not yet found a solution that preserves imports while executing a script.

Thanks to @pynexj for pointing out a flaw in my previous solution.