Sunday, July 08, 2018

Python3 - How To Add Package Path To Sys Path

First of all, let's take a look at how Python finds its modules:

Strictly taken, a module is a single python file, while a package is a folder containing python files, accompanied by a (can be empty) file named __init__.py, to tell python it is a package to import modules from. In both cases, modules need their .py extension. By default, Python looks for its modules and packages in $PYTHONPATH.

To find out what is your $PYTHONPATH:
$ echo $PYTHONPATH

To find out what is included in $PYTHONPATH, run the following code in python:
import sys
print(sys.path)

Now let's talk about how to add a package into your $PYTHONPATH:
There are two ways of doing it, through the python file iteslf, or update the $PYTHONPATH.

Within a Python file:
From within a python file, you can add path(s) incidentally to the default path by adding the following lines in the head section of your python application or script:

import sys
sys.path.insert(0, "/path/to/your/package_or_module")
# Now you can import
And I can simply import the file test.py by:
import test

Update the PYTHONPATH:
Suppose you have a package called my_package in /home/myname/pythonfiles, to add the /home/myname/pythonfiles path to your $PYTHONPATH, you need to:
export PYTHONPATH=$PYTHONPATH:/home/myname/pythonfiles

Now you should be able to import modules from "my_package"

No comments: