[英]Can't import module with importlib.import_module
I want to use importlib.import_module
to import modules dynamically. 我想使用
importlib.import_module
动态导入模块。 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. 我可以在Python控制台中成功地做到这一点。 But if I run these code in a file
C:\\Users\\Administrator\\Desktop>python test.py
, it can't work: 但是,如果我在文件
C:\\Users\\Administrator\\Desktop>python test.py
运行这些代码,它将无法工作:
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. 但是,如果我将db.py文件复制到与脚本文件相同的目录中,那么它将起作用。 I can't figure out why.
我不知道为什么。
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: 我将
bsddb
模块直接保留在D drive
,并将代码再次更改为:
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. 结果为
319
,模块list of functions and variables
。 It seems you may need to import module using the dot (.) notation
like above. 似乎您可能需要使用上述的
dot (.) notation
导入模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.