python: how to use 'import' on character string variable?
Question: I want to create a function which uses import, like the following:

    
    
        def test_module(module_name):
                try:
                        import module_name
                except ImportError:
                        print 'import '+module_name+' error'
    
    
        test_module('os')
    

however, the function doesn't work because import seems not to recognize the
string variable. are there any workarounds?

thanks!


Answer: `imported = __import__(module_name)` will work.

Or you can use
[`importlib.import_module`](https://docs.python.org/2/library/importlib.html#importlib.import_module).

The difference is in convenience: in case of import like `module_name =
'top.lower'`

`__import__` will return `top`, whereas `importlib.import_module` will return
`lower`:

    
    
    >>> __import__('os.path')
    <module 'os' from nowhere>
    >>> importlib.import_module('os.path')
    <module 'ntpath' from nowhere>
    

