0

How do I load a python module, that is not built in. I'm trying to create a plugin system for a small project im working on. How do I load those "plugins" into python? And, instaed of calling "import module", use a string to reference the module.

Staz_The_Box
  • 21
  • 1
  • 5
  • have a look at this: http://stackoverflow.com/questions/9059699/python-use-a-library-locally-instead-of-installing-it – Felk May 10 '15 at 23:57

1 Answers1

1

Have a look at importlib

Option 1: Import an arbitrary file in an arbiatrary path

Assume there's a module at /path/to/my/custom/module.py containing the following contents:

# /path/to/my/custom/module.py

test_var = 'hello'

def test_func():
    print(test_var)

We can import this module using the following code:

import importlib.machinery
myfile = '/path/to/my/custom/module.py'
sfl = importlib.machinery.SourceFileLoader('mymod', myfile)
mymod = sfl.load_module()

The module is imported and assigned to the variable mymod. We can then access the module's contents as:

mymod.test_var
# prints 'hello' to the console

mymod.test_func()
# also prints 'hello' to the console

Option 2: Import a module from a package

Use importlib.import_module

For example, if you want to import settings from a settings.py file in your application root folder, you could use

_settings = importlib.import_module('settings')

The popular task queue package Celery uses this a lot, rather than giving you code examples here, please check out their git repository

Community
  • 1
  • 1
Haleemur Ali
  • 26,718
  • 5
  • 61
  • 85