在不同目录中的文件上使用exec会导致模块导入错误

时间:2017-02-07 21:51:56

标签: python

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

test.py
test_problem_folder
     test_problem_1.py
     test_problem_2.py

test.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。

1 个答案:

答案 0 :(得分:1)

我尝试了您的代码,如果我在python test_problem_1.py下运行test_problem_folder,一切正常。显然,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,在__init__.py下创建test_problem_folder(这使得它成为除目录之外的python包)然后从模块{导入test_problem_1 {1}}

test_problem_folder
相关问题