Python: Importing files based on which files the user wants
Question: I have the following directory structure

    
    
    + code
    |
    --+ plugins
      |
      -- __init__.py
      -- test_plugin.py (has a class TestPlugin)
      -- another_test_plugin.py (has a class AnotherTestPlugin)
    --+ load.py
    --+ __init__.py
    

In load.py, I want to be able to initialize only those classes that the user
specifies. For example, lets say I do something like

    
    
    $ python load.py -c test_plugin # Should only import test_plugin.py and initialize an object of the TestPlugin class
    

I am having trouble trying to use the "imp" module to do it. It keeps on
saying "No such file or directory". My understanding is that it is somehow not
understanding the path properly. Can someone help me out with this?


Answer: ok, your problem is a path related problem. You expect that the script is
being run in the same directory as where load.py is, where it is not the case.

what you have to do is something like:

    
    
    import imp, os, plugins
    
    path = os.path.dirname(plugins.__file__)
    imp.load_source('TestPlugin', os.path.join(path, 'test_plugin.py')
    

where plugins is the module containing all your plugins (i.e. just the empty
`__init__.py`), that will help you get the full path to your plugin modules'
files.

