sys.path list#
You can add any elements to the sys.path
. Following cells are examples of this feature.
Let’s save a module that just prints something, so that every time it is imported, this message appears in the terminal.
%%writefile imports_files/test_module.py
print("this file was imported")
Writing imports_files/test_module.py
Module from the previous cell is saved in a package that is not in sys.path
. Therefore, when trying to import it, an error is raised, as shown in the next cell:
try:
import test_module
except ModuleNotFoundError:
print("ModuleNotFoundError was rised")
ModuleNotFoundError was rised
But if you’ve added a folder that contains the module in question, it will be imported just fine:
sys.path.append("imports_files")
import test_module
sys.path.remove("imports_files")
Environment variable#
You can define the environment variable PYTHONPATH
and list the paths with “:” - they will automatically appear in the sys.path
of python running in that environment.
In the following cell we have run some code that defines PYTHONPATH
as two paths separated by “:”, then run a script that prints out sys.path
. As a result you can see that the mentioned paths have been added to the sys.path
list.
%%bash
export PYTHONPATH="example/path1:example/path2"
echo $PYTHONPATH
echo
echo "=====python output====="
python3 path_settings_files/print_sys_folder.py
example/path1:example/path2
=====python output=====
/home/f.kobak@maxbit.local/Documents/knowledge/python/basics/path_settings_files
/home/f.kobak@maxbit.local/Documents/knowledge/python/basics/example/path1
/home/f.kobak@maxbit.local/Documents/knowledge/python/basics/example/path2
/usr/lib/python310.zip
/usr/lib/python3.10
/usr/lib/python3.10/lib-dynload
/home/f.kobak@maxbit.local/.local/lib/python3.10/site-packages
/usr/local/lib/python3.10/dist-packages
/usr/lib/python3/dist-packages