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

Python 对不同目录中的文件使用exec会导致模块导入错误,python,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(), filen

我有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\u problem\u文件夹/test\u problem\u 1.py:

import test_problem_2
test_problem_2.test()
test\u problem\u文件夹/test\u problem\u 2.py:

def test():
    print("Hello")
如果尝试运行test.py,则会出现以下错误:

ModuleNotFoundError:没有名为“测试问题2”的模块


如果我将文件夹结构展平,使test_problem_*与test.py位于同一目录中,我就不会遇到这个问题。我想路径一定是搞乱了,所以我尝试了os.chdir()到./test\u problem\u文件夹,但仍然得到相同的错误。我做错了什么?我的真实场景更复杂,我需要使用exec而不是popen。

我尝试了你的代码,如果我在
test\u problem\u文件夹下运行
python test\u problem\u 1.py
,一切正常。显然,Python路径对
test\u problem\u文件夹

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())
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
您可以将
test\u problem\u文件夹的abs路径
附加到python路径,然后就可以找到该模块了,您不必在
test\u problem\u文件夹下有
\u init\u.py
文件

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())
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
或者,您可以将
test.py
目录附加到pythonpath,在
test\u problem\u文件夹下创建
\uuuuu init\uuuuuuu.py
(这使它成为一个python包而不是目录),然后从模块
test\u problem\u文件夹导入test\u problem\u 1

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())
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

非常确定您丢失了一个uu init uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu.py没有改变任何内容。还可能是您需要告诉它在同一目录中使用
导入来!这是唯一的办法吗?实际上,我的代码将执行一些作为参数给出的python文件,在运行了很多次之后,我不想太多地污染路径,所以我注意到这是有效的:sys.path.append(os.path.dirname(filename)),而这不是:sys.path.append(os.path.abspath(filename))@user3715648查看我的编辑。第二种方法在python项目中更常用,将项目路径附加到pythonpath