Hi Pythonistas!
Today we will learn about what is PYTHONSTARTUP. and how can we use them. It is an environment variable that points to a python script. This script will be executed when the python interpreter is called. So we can load the required modules during the prototyping stage.
So no need to import every time when we call the interpreter.
How to set PYTHONSTARTUP
1 Create a python file let's say start.py
2 Do the required script in this file
Code
print("startupscript starting")
import os
import math
print("os and math module loaded")
print("startupscript loaded")
3 Set the environment variable
For Unix-like os
export PYTHONSTARTUP=/home/afsal/start.py
For Windows
set PYTHONSTARTUP=<path to file>\file.py
4 start the interpreter
Output
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
startupscript starting
os and math module loaded
startupscript loaded
>>> os.listdir()
['start.py']
>>> math.sin(90)
0.8939966636005579
>>> math.sin(90)
We can use the os and math module in the interpreter without explicitly importing
I hope you have learned something from this post. Please share your valuable feedback with afsal@parseltongue.co.in