5

There are many suggestions on the web what the structure of the Python project can/shall be, e.g. What is the best project structure for a Python application?.

"proj-dir"
+- doc
+- apidoc
+- scripts
+- "src-dir"
+- tests

It seems that many people in the Python world prefer the "src-dir" and "proj-dir" to be equal (or very similar). However, the scripts and tests will surely have to import some modules from src-dir, so either I have to

  • run all scripts and tests when proj-dir as my current working dir, or
  • the PYTHONPATH must contain the proj-dir, right?

Or, is there any other possibility which I overlook now?

Suppose I have such structure and have set up the PYTHONPATH correctly. Now I commit the project into VCS and another developer checks the project out. On his machine the PYTHONPATH will not be set properly and the imports in scripts and in tests will not work.

  1. Is there any possibility to somehow make the PYTHONPATH definition part of the project, so that it can be part of the version control?
  2. Is there a different project structure that would allow me to make checkout and start using the project without modifying the PYTHONPATH?
  3. Is to solution suggested here: Python - How to PYTHONPATH with a complex directory structure? (i.e. to include a short sys.path modifying snippet in every script and test) the right one?
  4. Would a site module http://docs.python.org/2/library/site.html be of any help?
  5. What is your workflow when developing a project with a similar structure?
4

1 回答 1

1

即使项目结构复杂且测试用例在不同的包中使用 src,您也可以在 Windows 的环境变量中添加 PYTHONPATH

我的电脑 --> 属性 --> 系统属性 --> 高级选项卡 --> 环境变量。添加新的系统变量 PYTHONPATH 并将您的项目目录附加到带有分隔符“;”的该变量

我建议您将 readme.txt 保留到您的项目中,其中清楚地说明了如何添加 PYTHONPATH 以运行脚本。类似于添加android-sdk的PATH使adb shell工作,添加Java路径使Java在命令提示符下工作

因此,readme.txt 有助于在不同的机器上下载时运行脚本,只需进行一次更改(添加 PYTHONPATH 变量,值 = 项目路径)

无需添加 src 的所有模块即可使使用 src 的测试用例正常工作

这是一个示例项目结构:

SAMPLEPROJECT
    src
      com
        sample
          example
            utils
              a.py
              b.py

    testcases
      test1.py
      test2.py

    res
    docs

如果 test1.py 测试用例使用 a.py 和 b.py:不要将 utils 模块添加到 PYTHONPATH,因为您已经将项目路径添加到 python 路径,因此您的导入语句在 test1.py 中看起来像这样

from src.com.sample.example.utils import a.py
from src.com.sample.example.utils import b.py 
于 2013-07-08T19:22:44.963 回答