Skip to content Skip to sidebar Skip to footer

String Variable As Import Module Specifier

I have tried the following: >> modname = 'sys' >> import modname Traceback (most recent call last): File '', line 1, in ImportError: No

Solution 1:

use importlib module if you want to import a module based on a string.

>>> import importlib
>>> mod = importlib.import_module('sys')
>>> mod
<module 'sys' (built-in)>

Solution 2:

>>> modname = 'sys'
>>> sys = __import__(modname)

Post a Comment for "String Variable As Import Module Specifier"