首页 > 解决方案 > 文件夹结构和导入

问题描述

所以我有一个我目前正在做的小项目,但我正在努力进口。最初我有一个这样的结构:

root -> python
     -> tests  -> testscripts

我从 python 文件夹运行我的测试,并且我在该文件夹中有一个名为 pertest_resources 的类,其中包含指向其他文件夹(如根目录和脚本文件夹)的路径。

python_folder = os.path.realpath(os.curdir)
perf_root_folder = os.path.realpath(python_folder + "/../")
test_root_folder = os.path.realpath(python_folder + "/../tests")
script_folder = os.path.realpath(test_root_folder + "/scripts")
network_folder = os.path.realpath(test_root_folder + "/networks")
output_folder = os.path.realpath(test_root_folder + "/output")
input_folder = os.path.realpath(test_root_folder + "/input")
kit_folder = os.path.realpath(perf_root_folder + "/kit")
sys.path.append(python_folder)
sys.path.append(script_folder)
sys.path.append(network_folder)

现在,当所有核心文件都在 python 文件夹中时,这工作正常,但现在它变得有点混乱,我被要求将一些 python 脚本分支到一个名为“networks”的新文件夹,其结构如下:

root -> python -> perftest_resources.py
     -> tests  -> testscripts
               -> networks -> standard_network.py

现在我想从 python 文件夹中运行一个名为 test 的文件,该文件使用 standard_network ,然后从 python 文件夹中导入 perftest_resources 。

我试过了:

sys.path.append('..' + os.sep + '..') 
from python.perftest_resources import PerfTestResources as pr

但是当它最初从 python 文件夹中的 test.py 运行时,这不起作用。我需要将 init 添加到两个文件夹吗?

标签: pythonimport

解决方案


是包裹吗?如果为真,您应该使用intra-package references, 比如

from . import echo
from .. import formats
from ..filters import equalizer

如果没有,把它变成包)

阅读更多:https ://docs.python.org/3/tutorial/modules.html


推荐阅读