本文介绍了无法使用importlib.import_module导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用importlib.import_module动态导入模块.我的代码是这样的:

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)

我可以在Python控制台中成功地做到这一点.但是,如果我在文件C:\Users\Administrator\Desktop>python test.py中运行这些代码,它将无法正常工作:

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

但是,如果我将db.py文件复制到与脚本文件相同的目录中,那么它将起作用.我不知道为什么.

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.

推荐答案

我已经在控制台中测试了较早的代码,并且可以正常工作.但是,我再次修改了代码.我将bsddb模块直接保留在D drive中,然后再次将代码更改为:

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)

这将导致319list of functions and variables被模块取幂.似乎您可能需要使用dot (.) notation导入模块,如上所述.

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.

这篇关于无法使用importlib.import_module导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 13:12