简体   繁体   English

如何组织一个python项目

[英]How to organize a python project

I am new to python and trying to figure out how to do things the "right way" and encountered the following problem:我是 python 的新手,并试图弄清楚如何以“正确的方式”做事并遇到以下问题:

My project has a structure that looks a little this:我的项目的结构看起来有点像这样:

├─packageA
│     functions.py
│     __init__.py
│
└─tests
      some_tests.py

packageA/__init__.py is empty. packageA/__init__.py是空的。

packageA/functions.py looks like this: packageA/functions.py看起来像这样:

def some_function(x):
    return x*x

And finally, tests/some_tests.py :最后, tests/some_tests.py

import packageA.functions

if __name__ == '__main__':
    print(packageA.functions.some_function(2))

If I run test.py using pycharm it works fine.如果我使用 pycharm 运行 test.py 它工作正常。 However, when I open up a console and start it by running python.exe ./tests/some_tests.py I get但是,当我打开控制台并通过运行python.exe ./tests/some_tests.py启动它时,我得到

    Traceback (most recent call last):
  File ".\tests\some_tests.py", line 1, in <module>
    import packageA.functions
ModuleNotFoundError: No module named 'packageA'

While writing this, I figured out that pycharm adds source folders to PYTHONPATH - when I turn this off I get the same error.在写这篇文章时,我发现 pycharm 将源文件夹添加到 PYTHONPATH - 当我关闭它时,我得到了同样的错误。 Is the folder structure above a sensible way to structure a python project?上面的文件夹结构是构建python项目的明智方法吗? If not, how should it be organized instead?如果不是,应该如何组织?

There are several options.有几种选择。 However, the accepted answer in a similar SO question isn't ideal.但是,在类似的 SO 问题中接受的答案并不理想。

The below answer addresses your issue by explicitly adding the parent directory path at the start of your sys.path list.以下答案通过在sys.path列表的开头显式添加父目录路径来解决您的问题。

import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir) 

import packageA.functions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM