使用 imp 动态导入模块
我正在尝试动态地从不同的目录导入模块。我正在关注这个问题的答案。我在名为 foo 的目录中有一个名为 bar 的模块。主脚本将在 foo 的父目录中运行。
这是我迄今为止在测试脚本中的代码(在 foo 的父目录中运行)
#test.py
import imp
mod = imp.load_source("bar","./foo")
和 bar.py 的代码
#bar.py
class bar:
def __init__(self):
print "HELLO WORLD"
但是当我运行 test.py 时,我收到此错误:
Traceback (most recent call last):
File "C:\Documents and Settings\user\Desktop\RBR\test.py", line 3, in <module>
mod = imp.load_source("bar","./foo")
IOError: [Errno 13] Permission denied
I am trying to import a module from a different directory dynamically. I am following an answer from this question. I have a module named bar in a directory named foo. The main script will be running in the parent directory to foo.
Here is the code i have thus far in my test script (which is running in the parent directory to foo)
#test.py
import imp
mod = imp.load_source("bar","./foo")
and code for bar.py
#bar.py
class bar:
def __init__(self):
print "HELLO WORLD"
But when i run test.py I get this error:
Traceback (most recent call last):
File "C:\Documents and Settings\user\Desktop\RBR\test.py", line 3, in <module>
mod = imp.load_source("bar","./foo")
IOError: [Errno 13] Permission denied
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
imp.load_source
需要要导入的模块的路径名+文件名,您应该将源更改为以下源:imp.load_source
requires the pathname + file name of the module to import, you should change your source for the one below:似乎是一个简单的路径问题 - 检查
__file__
或 cwd...也许首先尝试绝对文件路径? - 这个 imp 示例可能会有所帮助。Appears to be a simple pathing problem - check
__file__
or cwd... Maybe try an absolute file path first? - This imp example may help.