gpt4 book ai didi

python - 使用 imp 动态导入模块

转载 作者:IT老高 更新时间:2023-10-28 20:59:55 26 4
gpt4 key购买 nike

我正在尝试从不同的目录动态导入模块。我正在关注 this question 的回答.我在名为 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

最佳答案

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

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

关于python - 使用 imp 动态导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4970235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com