0

I am writing a CLI-based web server control panel to which I am adding plugin support. I will need to import Python code files with arbitrary names from a /plugins directory. How does one dynamically import code files from a particular directory?

Consider the common situation in which we have the files application.py and foobar.py. In application.py we add the following code to run a method in foobar.py:

import foobar

foobar.main()

How might I generalize this so that all files in the plugins directory get imported?

Additionally, I will need to add a menu item "Run foobar plugin" so I will need a list of the plugin names to iterate over. How is this done in Python?

I am targeting Python 3 on Linux servers if that matters.

dotancohen
  • 30,064
  • 36
  • 138
  • 197
  • have you taken a look at [importlib](https://docs.python.org/3/reference/import.html) ? – David K-J Feb 19 '15 at 11:38
  • @DavidK-J: Thank you. I've tried using `importlib.import_module()` and `importlib.__import__()` directly, but I could not figure out how to import a file in a subdirectory and scope its methods methods. I tried using a known filename in the directory, with the plan of getting the filenames via `os.walk()`. Can you post an example of imorting a Python file **in a subdirectory**? Thanks. – dotancohen Feb 19 '15 at 12:50
  • Take a look at [PluginBase](http://pluginbase.pocoo.org/) or the Stack Overflow [thread](http://stackoverflow.com/questions/932069/building-a-minimal-plugin-architecture-in-python). – David K-J Feb 19 '15 at 22:28
  • Thanks for that link to the SO thread. I'm surprised that I did not find that either in the SO search or from Google. – dotancohen Feb 20 '15 at 17:48

0 Answers0