Run a module when module name is in a variable
<p>I'm trying to run modules from a directory. A simplified version of my project tree would be:</p>

<pre><code>main.py
modules/
|_ a/
|  |_ a.py
|  |_ __init__.py
|_ b/
|  |_ b.py
|  |_ __init__.py
|_ __init__.py
</code></pre>

<p>Each module in <code>modules/</code> has an empty <code>__init__.py</code> and a <code>run()</code> method that does some stuff in <code>&lt;module-name&gt;.py</code></p>

<p>From <code>main.py</code> I would like to load all modules, and then run a module by passing it's name as parameter to a function. For example what I would like to do from <code>main.py</code>:</p>

<pre><code>def runModule(module_name):
    # pseudo-codish
    from modules import "module_name"
    "module_name.run()" 

runModule(a)
</code></pre>

<p>I've googled a bit but can't seem to find a way this would work. Is this even possible? I'm working with Python3 but would welcome a Python2 solution for guidance even.</p>

<p>You can do this with <a href="https://docs.python.org/3/library/importlib.html#importlib.import_module" rel="nofollow"><code>importlib</code></a>.</p>

<pre><code>def run_module(module_name):
    mod = importlib.import_module(module_name)
    mod.run()
</code></pre>

python