Recently, I was trying to migrate my code from Python 2.7 to Python 3.8, and one of the tasks was to replace "imp" with "importlib" since imp is deprecated. Notice that my OS is Windows 10 and my progarm is compiled with PyCharm.
After some surveys, I tried to follow the way according to How do I import a module given full path .
I first tried spec.loader.load_module(), which worked fine for my program. No exception was raised. But because this method is deprecated as well, then I tried spec.loader.exec_module(mod), it would fail to load package xml.sax and some other packages of xml.
spec.loader.load_module()
# NAME = 'xml.sax'
# PATH = 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\xml\\sax\\__init__.py'
spec = importlib.util.spec_from_file_location(name=NAME, location=PATH, loader=importlib.machinery.SourceFileLoader(NAME, PATH))
mod = importlib.util.module_from_spec(spec)
sys.modules[NAME] = mod
mod = spec.loader.load_module() # Works fine
spec.loader.exec_module(mod)
# NAME = 'xml.sax'
# PATH = 'C:Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\xml\\sax\\__init__.py'
spec = importlib.util.spec_from_file_location(name=NAME, location=PATH, loader=importlib.machinery.SourceFileLoader(NAME, PATH))
mod = importlib.util.module_from_spec(spec)
sys.modules[NAME] = mod
spec.loader.load_module(mod) # ModuleNotFoundError: No module named 'xml.sax'
I had checked that xml had been in sys.modules, so it might not because xml.sax was loaded first before xml loaded. I have no idea why load_module() worked but exec_module() failed. I'm not sure the difference between these two methods. Is there something else should I have to check?