gpt4 book ai didi

python - 对不同目录中的文件使用 exec 会导致模块导入错误

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:12 25 4
gpt4 key购买 nike

我有 3 个非常简单的脚本。结构如下所示:

test.py
test_problem_folder
test_problem_1.py
test_problem_2.py

测试.py:

import os

if __name__ == "__main__":
filename = "./test_problem_folder/test_problem_1.py"
exec(compile(open(filename, "rb").read(), filename, 'exec'), globals(), locals())

test_problem_folder/test_problem_1.py:

import test_problem_2
test_problem_2.test()

test_problem_folder/test_problem_2.py:

def test():
print("Hello")

如果我尝试运行 test.py,我会收到错误:

ModuleNotFoundError:没有名为“test_problem_2”的模块

如果我展平文件夹结构,使 test_problem_* 与 test.py 位于同一目录,则不会出现此问题。我认为路径一定搞砸了,所以我尝试 os.chdir() 到 ./test_problem_folder,但仍然遇到相同的错误。我究竟做错了什么?我的真实场景更复杂,我需要使用 exec 而不是 popen。

最佳答案

我尝试了你的代码,如果我在 test_problem_folder 下运行 python test_problem_1.py,一切正常。显然,Python 路径不了解 test_problem_folder

你可以将test_problem_folder的abs路径附加到你的python路径中,然后就可以找到该模块,你不必在下有__init__.py文件test_problem_folder

import os
import sys

if __name__ == "__main__":
sys.path.append("/path/to/.../test_problem_folder")
filename = "./test_problem_folder/test_problem_1.py"
exec(compile(open(filename, "rb").read(), filename, 'exec'), globals(), locals())

或者,您可以将 test.py 目录附加到 pythonpath,在 test_problem_folder 下创建 __init__.py(这使其成为python 包(目录除外),然后从模块 test_problem_folder

导入 test_problem_1
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
import test_problem_folder.test_problem_1 as problem1

if __name__ == "__main__":
pass

关于python - 对不同目录中的文件使用 exec 会导致模块导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42100723/

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