Search code examples
pythonimportnuke

Import modules from a list or dict in Python?


Im fairly versed in Python, however this has been an issue for quite some time for me.

I have a folder full of scripts that the artists in my studio use within Nuke. In order for them to be accessible from within, I need to import them via and init.py file that Nuke reads on load.

I would like to be able to make a list of these values, either via a glob search to find everything applicable, or a declared list like:

my_list = ['mod_1', 'mod_2', 'mod_3']

Yet I have been unable to find a method that can handle this. I know I can use variable names to find the modules and import them via:

module = getattr(__import__(package, fromlist=[name]), name)

or

module = __import__(var)

but both of these methods require me to assign a name for the module I am importing.

I am looking for a way to do something along these lines:

capture = glob.glob('/scriptLocation/*.py')
for i in capture:
    import i

or

my_list = ['mod_1', 'mod_2', 'mod_3']
for i in capture:
    import i

TIA!


Solution

  • Try this:

    modules = map(__import__, moduleNames)
    

    Verify this link for more: (Example 16.15)

    >>> moduleNames = ['sys', 'os', 're', 'unittest'] 1
    >>> moduleNames
    ['sys', 'os', 're', 'unittest']
    >>> modules = map(__import__, moduleNames)        2
    >>> modules                                       3
    [<module 'sys' (built-in)>,
    <module 'os' from 'c:\Python22\lib\os.pyc'>,
    <module 're' from 'c:\Python22\lib\re.pyc'>,
    <module 'unittest' from 'c:\Python22\lib\unittest.pyc'>]
    >>> modules[0].version                            4
    '2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)]'
    >>> import sys
    >>> sys.version
    '2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)]'