Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic module import in Python
    primarykey
    data
    text
    <p>I'm writing a Python application that takes as 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 <strong>__import__</strong> function, which takes a string for a module name:</p> <blockquote> <p>__import__(name, globals=None, locals=None, fromlist=(), level=0)</p> <p>The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. </p> <p>Source: <a href="https://docs.python.org/3/library/functions.html#__import__" rel="noreferrer">https://docs.python.org/3/library/functions.html#<strong>import</strong></a></p> </blockquote> <p>So currently I have something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) 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 "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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload