Python – PYHTONPATH

In my previous blog I explained a How in 5 steps one can setup Python with Visual Studio Code? In this blog I am going to briefly explain PYTHONPATH. Also, I will explain how you can setup a multi directory project and run it in Visual Studio Code using PYTHONPATH.

PYTHONPATH

PYTHONPATH is an Environment Variable for Python. According to official documentation of Python, PYTHONPATH augment the default path for searching module files. The form of this environment variable is same as PATH (the separator varies according to Operating System – Colon for Unix style and semi-colon for Windows). Default search path can be set at the time of installation but, I personally prefer to set it run time. The PYTHONPATH can be manipulated run time within a program by using sys.path variable, which is a list.

By default Python executable can only find the files in the directory where the executable was placed during instalation. So, in nutshell “If you want your Python module file to be visible to Python while running the code, make sure that the directory in which the module file exists, is added to PYTHONPATH

Let’s see how it works. I have created a a directory “MathsFunctions” within my working directory. Now, I will create a function factorial OfNum in factorial.py stored in a specific directory. Then I will try to import this module in my python code. Let’s see what happens..?

What happens when PYTHONPATH doesn’t have directory where Python Module Exists?

Did you see the Error message in the Debug Console? It says – ModuleNotFoundError: No module named ‘factorial’ .. so, simply Python couldn’t find factorial.py!

Now let’s try to Put the directory where factorial.py lies in PYTHONPATH using sys.path (real-time)!

Appending the directory in PYTHONPATH real time using sys.path

Bingo!! It works.. I simply appended “C:/pythonTutorials/MathsFunctions” the directory where factoria.py lies to sys.path. This actually means I added this path in PYTHONPATH. So now, factorial.py was visible to Python.

This is how you can use the PYTHONPATH to make sure your module files are visible to interpreter while debugging/running the code. Now, I explained it using Visual Studio code but, you don’t need VS Code to run your code. You can try it using default command interface.

Also,Please visit Python With Visual Studio Code in 5 Simple Steps to see how to set Visual Studio Code to debug a Python code.

Please leave your comments or questions in comments section.