Kamil Kisiel Kamil Kisiel - 2 months ago 10x
Python Question

Dynamic module import in Python

I'm writing a Python application that takes as a command as an argument, for example:

$ python myapp.py command1

I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:


So I want the application to find the available command modules at runtime and execute the appropriate one.

Currently this is implemented something like:

command = sys.argv[1]
command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"])
except ImportError:
# Display error message


This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.

Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.


With Python older than 2.7/3.1, that's pretty much how you do it. For newer versions, see

You can use exec if you want to as well.

Note you can import a list of modules by doing this:

>>> moduleNames = ['sys', 'os', 're', 'unittest'] 
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)

Ripped straight from Dive Into Python.