I've read this answer: How to import a module given the full path? and I am still a little unsure about what the best way to go about solving my problem is and I'd like to see what the community has to say. I learn best by example, sorry if I'm being thick here!
I have a directory tree full of arbitrary directories and files, I am crawling it to find directories as categories and then the .py files inside are each a module. I have no problem crawling the directory tree and finding the files, the problem is importing them properly and using them later. I'm using Python 3.4.
I should mention that I have control over each of the files I want to import and can specify a format or name be available for parsing at import time. edit An example use case would be something like this: > use /parsers/foo
then the module is loaded, and i issue parsers/foo > set filename bar.xml
and then issue the parsers/foo > run
command and the data is parsed and saved into a database.
I guess my questions are:
- How would you set up this import loop,
- How would you use them at a later time
This is a CLI interface that I'm building with prompt_toolkit. The idea is to issue a command like "use category/module" kinda like Metasploit or other similar interfaces.
Here is the directory/module crawling code:
def _load_modules(self, mod_path):
self.modules = {}
# walk through the module tree
for dirpath, subdirs, filenames in os.walk(mod_path):
if len(filenames) > 0:
for filename in [f for f in filenames if f.endswith('.py')]:
# extract the category from the module directory
cat = (re.search('/modules/([^/]*)', dirpath).group(1))
self.modules.setdefault(cat,list()).append(
(dirpath, filename)
)
Thanks for your help.