testing for modules?

Fredrik Lundh fredrik at pythonware.com
Tue Oct 25 09:58:28 CEST 2005


Ed Hotchkiss wrote:

> i have a generic script that is using several modules on windows and linux
> boxes. i need to have the scripts test if a module is installed, and then if
> not - then to install the module. can anyone give me a headsup on how to
> test for a module, returning something to indicate whether or not it is
> installed, then after that executing file to install the module.?

if the modules behave nicely, and don't do silly stuff when first imported,
something like

    try:
        import mymodule
    except ImportError:
        install_module("mymodule")
        import mymodule # retry

usually works.

if you have lots of modules, you can use something like

    MODULES = "mymodule", "myothermodule", "sys"

    for module in MODULES:
        try:
            __import__(module)
        except ImportError:
            install_module(module)

    ...

    import mymodule # will fail if installation failed
    import myothermodule, sys

    ....

</F> 






More information about the Python-list mailing list