I'm writing a Python application that takes as a command as an argument, for example:
$ python myapp.py command1
command = sys.argv
command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"])
# Display error message
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.