Skip to content Skip to sidebar Skip to footer

Python - Import A Module Directory Given Full Path

I have a python module here /root/python/foo.py. I have a bunch of other modules here in the folder /root/lib/ which looks like this lib/ | ├─ module1/ | ├�

Solution 1:

try:

from importlib.machinery importSourceFileLoaderproblem_module= SourceFileLoader('test_mod', '/root/lib/module1/__init__.py').load_module()

the __init__.py should take care about the modules in the same package:

add from . import bar to make bar.py part of the package.

Some corrections:

  • module1 is a package not a module.
  • bar.py is a module part of the package module1

Solution 2:

Python does not give us an easy way to load files that cannot be referenced by sys.path, most usual solution will do one of the following things:

  1. Add desired paths to sys.path or
  2. Restructure your modules so that the correct path is already on sys.path

Nearly all other solutions that does not do either will be work arounds (using non-intended methods to get the job done) and some can cause quite a headache.

However python does give us a mechanic that lets us simulate a package that is spread out across folders that are not held on sys.path, you can do this by specifying a __path__ special name in a module:

__path__ = ["/root/lib"]

Put this line in a file called lib.py and place it in the same folder as foo.py to be imported by it (so in root/python/ in your case) then from foo.py you can do this as you would expect:

import lib.module1
#orfrom lib import module1

This indicates to python that the .module1 subpackage is located somewhere on the specified __path__ and will be loaded from that directory (or multiple directories) using the intended import mechanisms and keeping your sys.path unaltered.

Post a Comment for "Python - Import A Module Directory Given Full Path"