python-动态导入
在Python2中如何实现类似的功能python-动态导入,python,dynamic,python-import,Python,Dynamic,Python Import,在Python2中如何实现类似的功能 my_variable = something1 imported = False try: import my_variable #something1.py, something2.py, etc... I think I can use __import__(my_variable) imported = True except ImportError: print('Error importing ' + my_variable + '
my_variable = something1
imported = False
try:
import my_variable #something1.py, something2.py, etc... I think I can use __import__(my_variable)
imported = True
except ImportError:
print('Error importing ' + my_variable + '.py')
if imported:
my_variable.function() #where my_variable actually is something1 ???
假设您使用的是Python 2.7或更高版本,您可以使用:
import importlib
module_name = 'sys'
try:
sys = importlib.import_module(module_name, package = None)
except Exception:
print('Error importing:', module_name)
if module_name in locals():
print(sys.argv)