【问题标题】:importing python modules and packages in different sub-directories of the same project在同一项目的不同子目录中导入 python 模块和包
【发布时间】:2020-04-29 03:03:35
【问题描述】:

我想找出最干净且最好是自包含的方式,以便在与包本身不同的目录中的脚本中使用我的包。

示例问题如下:

lib 中的模块都需要导入,并作为脚本运行。

我的项目目录如下,我有两个问题:

  1. lib/api.py 中,我想在调用或导入api.py 时正确读取data_files/key.txt
  2. testing_script.py我要导入使用lib/get_data.py

我似乎找不到一个干净的方法来做到这一点,这是否意味着我的项目是以非 Python 方式构建的?

感谢您的帮助。

my-project-git
├── LICENSE
├── README.md
├─── my_project
│   ├── data_files
│   │   ├── key.txt
│   │   ├── mappings.csv
│   ├── lib
│   │   ├── __init__.py
│   │   ├── api.py
│   │   └── get_data.py
│   └── test
│       ├── __init__.py
│       └── testing_script.py
├── requirements.txt
└── setup.py

【问题讨论】:

  • 我提出了一个答案。只是一个 PS:lib 通常用于第三方库或 C(或其他)语言库。

标签: python structure project project-structure project-structuring


【解决方案1】:

据我所知,没有一种 Python 的方式来构建您的项目。

这是 Kenneth Reitz 在 2013 年推荐的,也是我使用它的方式:https://www.kennethreitz.org/essays/repository-structure-and-python

README.rst
LICENSE
setup.py
requirements.txt
sample/__init__.py
sample/core.py
sample/helpers.py
docs/conf.py
docs/index.rst
tests/test_basic.py
tests/test_advanced.py

sample(在您的情况下为my_project)内,您可以根据需要划分类别。例如。 Utils(常用函数)、Database(读、写)、View(用户命令)等。这取决于你的项目。

至于调用同级模块,你应该在顶层模块的__init__文件中定义它们,在这种情况下是sample

例如:

__init__ in _my_project

from sample.core import a_Class
from sample.core import a_function
from sample.core import anything

然后从/test/test_basic.py 你做:

from sample import a_Class
# or import sample

a = a_Class()  # use the class from core.py
# or a = sample.a_Class()

查看示例模块存储库:https://github.com/navdeep-G/samplemod

【讨论】:

    猜你喜欢
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2014-11-16
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多