Python 使用imp动态导入模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4970235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:24:00  来源:igfitidea点击:

Importing a module dynamically using imp

pythondynamicimport

提问by Richard

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.

我正在尝试从不同的目录动态导入模块。我正在关注这个问题的答案。我在名为 foo 的目录中有一个名为 bar 的模块。主脚本将在 foo 的父目录中运行。

Here is the code i have thus far in my test script (which is running in the parent directory to foo)

这是我迄今为止在我的测试脚本中的代码(它在父目录中运行到 foo)

#test.py
import imp

mod = imp.load_source("bar","./foo")

and code for bar.py

和 bar.py 的代码

#bar.py
class bar:

    def __init__(self):
          print "HELLO WORLD"

But when i run test.py I get this error:

但是当我运行 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

采纳答案by Lucas S.

imp.load_sourcerequires the pathname + file name of the module to import, you should change your source for the one below:

imp.load_source需要导入模块的路径名 + 文件名,您应该更改以下源代码:

mod = imp.load_source("bar","./foo/bar.py")

回答by Petriborg

Appears to be a simple pathing problem - check __file__or cwd... Maybe try an absolute file path first? - This imp examplemay help.

似乎是一个简单的路径问题 - 检查__file__或 cwd ... 也许先尝试绝对文件路径?- 这个小鬼例子可能会有所帮助。