When we import a python package in our python script, do you know how to find this package for python? The key is to use sys.path. In this tutorial, we will use some examples to help you understand it.
sys.path is a python list, which contains some directory paths. When you import a pthon library, the python script will find that python package in these paths.
Output sys.path
We will output directory paths in sys.path by code below.
import sys for p in sys.path: print(p)
These directory paths are:
From the result we can find an interesting path: E:\workspace-nlp\Example, which is the path of current python script. It can explain why you can import python libraries that are in the same path with current python.
For example, if there are some python scripts in E:\workspace-nlp\Test
They are: model_1.py, model_2.py, model_3.py
Then you can import model_2 and model_3 in model_1.py
import model_2 import model_3
How to import python packeages in other directory?
As example above, if you plan to import python packages are not in E:\workspace-nlp\Example, for example these packages are in F:\workspace-nlp\Models, how to do?
We can set the path to the sys.path first, then import packages in it, for example:
import sys sys.path.append('F:\workspace-nlp\Models') for p in sys.path: print(p)
The paths are:
We can find F:\workspace-nlp\Models are added to sys.path, then you can load python packages in F:\workspace-nlp\Models.