问题
I want to use importlib.import_module to import modules dynamically. My code like this:
import os
import importlib
os.chdir('D:\\Python27\\Lib\\bsddb')
m = importlib.import_module('db')
print dir(m)
I can to this successfully in the Python console. But if I run these code in a fileC:\Users\Administrator\Desktop>python test.py, it can't work:
Traceback (most recent call last):
File "test.py", line 5, in <module>
m = importlib.import_module("db")
File "D:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named db
But if I copy the db.py file to the directory the same as the script file, it works. I can't figure out why.
回答1:
EDIT: I had tested the earlier code in console and it worked. However, I have modified the code again. I kept the bsddb module directly in D drive and changed the code again to:
import os
os.chdir("D:\\")
import importlib
m = importlib.import_module("bsddb.db")
print len(dir(m))
print dir(m)
This results in 319 and the list of functions and variables exponsed by the module. It seems you may need to import module using the dot (.) notation like above.
来源:https://stackoverflow.com/questions/38410960/cant-import-module-with-importlib-import-module