Reputation: 1029
I have this code that carry module manually
exec("import" + moduleName + " as selectedModule")
importlib.reload(selectedModule)
But this code make
name 'seletedModule' is not defined
It is not happened on python2.x. How to import this on python3?
Upvotes: 1
Views: 118
Reputation: 33724
If you need to import a library dynamically, don't use exec
, its not safe.
Use importlib.import_module
instead.
selected_module = importlib.import_module(module_name)
importlib.reload(selected_module)
As for the error you're getting: you're probably calling exec
within a function scope, thus you'll need you manually set globals
and locals
to be the same in exec
(Using a function defined in an exec'ed string in Python 3). Workaround:
exec("<do-stuff>", globals())
Upvotes: 4