python:如何使用';导入&x27;关于字符串变量?

python:如何使用';导入&x27;关于字符串变量?,python,import,Python,Import,我想创建一个使用导入的函数,如下所示: def test_module(module_name): try: import module_name except ImportError: print 'import '+module_name+' error' test_module('os') 但是,该函数不起作用,因为import似乎无法识别字

我想创建一个使用导入的函数,如下所示:

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


    test_module('os')
但是,该函数不起作用,因为import似乎无法识别字符串变量。 有什么解决办法吗


谢谢

imported=\uuuuuuuu导入(模块名称)
将起作用

或者你可以使用

不同之处在于方便:如果是进口的话
module\u name='top.lower'

导入
将返回
top
,而
importlib.import\u模块
将返回
lower

>>> __import__('os.path')
<module 'os' from nowhere>
>>> importlib.import_module('os.path')
<module 'ntpath' from nowhere>
>>\uuuuuuuuuuu导入('os.path'))
>>>importlib.import\u模块('os.path')
(我没有投反对票)。你的语法错了。它应该是
imported=\uuuuu import\uuu(模块名称)
。也就是说,首选的方法是使用。