title: How to import a module given its name as string?
body: <p>I'm writing a Python application that takes a command as an argument, for example:</p>
  <pre><code>$ python myapp.py command1
  </code></pre>
  <p>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:</p>
  <pre><code>myapp/
      __init__.py
      commands/
          __init__.py
          command1.py
          command2.py
      foo.py
      bar.py
  </code></pre>
  <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p>
  <p>Python defines an <code>__import__()</code> function, which takes a string for a module name:</p>
  <blockquote>
  <p><code>__import__(name, globals=None, locals=None, fromlist=(), level=0)</code></p>
  <p>The function imports the module <code>name</code>, potentially using the given <code>globals</code> and <code>locals</code> to determine how to interpret the name in a package context. The <code>fromlist</code> gives the names of objects or submodules that should be imported from the module given by <code>name</code>.</p>
  <p>Source: <a href="https://docs.python.org/3/library/functions.html#__import_" rel="noreferrer">https://docs.python.org/3/library/functions.html#__import_</a>_</p>
  </blockquote>
  <p>So currently I have something like:</p>
  <pre><code>command = sys.argv[1]
  try:
      command_module = __import__(&quot;myapp.commands.%s&quot; % command, fromlist=[&quot;myapp.commands&quot;])
  except ImportError:
      # Display error message
  
  command_module.run()
  </code></pre>
  <p>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.</p>
  <p>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 &quot;plugins&quot;. The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>