Python – Adding paths to external modules

Software:
Python 3.9.2

To import an external Python module,
Add its folder path to the sys.path list,
Then import the wanted code.

In this example, there is a Python file:
C:\Oded\GoogleDrive\CGL_Studio\CGL_Python\py\cgl_pixel_utils.py
Containing a function:
cgl_fill_int_range

The following Python code checks the path isn’t already found in sys.path, and if so adds the module path to sys.path,
Imports the cgl_fill_int_range function for the cgl_pixel_utils module,
And calls the cgl_fill_int_range function:

import sys

modulepath = r"C:\Oded\GoogleDrive\CGL_Studio\CGL_Python\py"

if modulepath not in sys.path:
    sys.path.append(modulepath)

from cgl_pixel_utils import cgl_fill_int_range

print(cgl_fill_int_range(-3, 3))

To force reloading of an external module,
Use the reload function from the built-in imp module.
Note that this works with importing full modules and not just specific functions:

import sys
import imp

modulepath = r"C:\Oded\GoogleDrive\CGL_Studio\CGL_Python\py"

if modulepath not in sys.path:
    sys.path.append(modulepath)

import cgl_pixel_utils

# Force reload of cgl_pixel_utils:
imp.reload(cgl_pixel_utils)

print(cgl_pixel_utils.cgl_fill_int_range(-3, 3))

Leave a Reply