Can't import module with importlib.import_module

邮差的信 提交于 2020-01-25 05:54:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!