Customize Python Shell with PYTHONSTARTUP

Jan. 19, 2021

Pythonstartup as Environment Variables


Most of us know how to customize our Linux shell when we need to work in the terminal. For example, to change the Bash prompt, we can simply edit the hidden (via the dot format) .bash_profile or .bashrc file in our home directory:

PS1="MyPrompt> "

Then the next time we log in to the Bash shell, our prompt is changed to 'MyPrompt'.

Customize Python Shell

We can do the same thing with our Python shell via a Python file and export it into the PYTHONSTARTUP environmental variable. For example, if I want to have the 'random' module always available when I start my Python shell (don't ask me why), I can create a Python file named 'myPythonstartup.py':

$ cat myPythonstartup.py

import random

Then export this file as an environmental variable PYTHONSTARTUP:

$ export PYTHONSTARTUP=myPythonstartup.py

When I start my Python shell, I will automatically have the random module available without needing to import it:

$ python3

Python 3.8.1 (v3.8.1:1b293b6006, Dec 18 2019, 14:08:53)

[Clang 6.0 (clang-600.0.57)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> random.random()

0.48845685016683704

Neat, right? We can this format for commonly used modules, variables, functions, and anything you can put into a Python file.

Conclusion

In short, PYTHONSTARTUP environmental variable allows users to customize the python shell for commonly used variables and libraries. To find more information about it: PYTHONSTARTUP.

Happy Coding!

Eric

Return to blog