Dynamic submodule import failing in __main__
<p>I have a module that I want to run with <code>python -m modulename command</code> with commands referring to submodules launched by importing them. The file layout is as follows:</p>

<pre><code>mainmodule/:
  __init__.py (empty)
  submodule1.py
  submodule2.py
  __main__.py
</code></pre>

<p>with <code>__main__.py</code> as follows:</p>

<pre><code>import sys, importlib


commands = {"cmd1": "submodule1", "cmd2": "submodule2"}
try:
  cmd = modules[sys.argv[1]]
except IndexError:
  cmd = "cmd1"
except Error:
  pass
module = importlib.import_module("."+cmd, "mainmodule")
</code></pre>

<ul>
<li><code>python -m mainmodule</code> launches <code>submodule1</code> as expected;</li>
<li><code>python -m mainmodule cmd1</code> works;</li>
<li><code>python -m mainmodule.submodule1</code> works;</li>
<li><code>python -m mainmodule.submodule2</code> <strong>works too;</strong></li>
</ul>

<p><strong>BUT</strong> <code>python -m mainmodule cmd2</code> fails:</p>

<pre><code>ImportError: No module named mainmodule.submodule2
</code></pre>

<p>Why? I've tried changing the <code>import</code> value expression in many ways, it always fails in the same way.</p>

<p>Change;</p>

<pre><code>  cmd = modules[sys.argv[1]]
</code></pre>

<p>to</p>

<pre><code>  cmd = commands[sys.argv[1]]
</code></pre>

<p>Other than one typo fix, I can't get the same error. Are you maybe not running python from the directory above <code>mainmodule</code>? Or do you maybe not have <code>mainmodule</code> installed properly?</p>

python python-2.7