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?
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())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.