使用imp动态导入模块 [英] Importing a module dynamically using imp
问题描述
我正在尝试从一个不同的目录动态导入一个模块。我正在从这个问题回答。我在名为foo的目录中有一个名为bar的模块。主脚本将在父目录中运行到foo。
以下是我在测试脚本(在父目录中运行到foo)中的代码。
#test.py
import imp
mod = imp.load_source(bar,./ foo)
和bar.py的代码
#bar.py
但是当我运行test.py时,我发现这个错误:
class bar:
def __init __(self):
printHELLO WORLD
追溯(最近的最后一次呼叫):
文件C:\Documents and Settings\user\Desktop\RBR\test.py,第3行,< module>
mod = imp.load_source(bar,./ foo)
IOError:[Errno 13]权限被拒绝
解决方案
imp.load_source
需要导入的模块的路径名+文件名,你应该更改您的源代码:mod = imp.load_source(bar,./ foo / bar。 py)
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
解决方案
imp.load_source
requires the pathname + file name of the module to import, you should change your source for the one below:mod = imp.load_source("bar","./foo/bar.py")
这篇关于使用imp动态导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!