pythonpython-3.xblender

Importing modules from specific folder in Blender python script (MacOS)


In a script within a .blend file, I'm trying to import modules from a folder relative to that blend file.

This is my folder structure:

Models/

  • model.blend
  • _scripts/
    • color-thief-py-master/
      • colorthief.py
    • ...other python module repositories here

model.blend has this code at the top of one of its scripts:

from os.path import dirname as up

packages_path = os.path.join(up(bpy.data.filepath), "_scripts")

if (not packages_path in sys.path):
    sys.path.insert(0, packages_path)

When I try to import colorthief afterwards (from colorthief import ColorThief) I get a ModuleNotFoundError. Same goes for all other modules in the scripts/ folder.

I have checked that the _scripts folder is being successfully added to the path.

What am I doing wrong here? I'm on MacOS but ideally looking for a cross-platform solution.


Solution

  • The problem is that when you use sys.path.insert(0, packages_path) the system file becomes in the folder Models. Try this:

    from _scripts.color-thief-py-master.colorthief import ColorThief
    

    or import ColorThief before using sys.path.insert(0, packages_path)