将python模块和软件包导入同一项目的不同子目录中

问题描述 投票:1回答:1

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

示例问题如下:

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

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

  1. lib/api.py中,我想在调用或导入data_files/key.txt时正确读取api.py
  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
python structure project project-structure project-structuring
1个回答
0
投票

据我所知,没有一种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),您可以根据需要分为几类。例如。实用程序(通用功能),数据库(读取,写入),视图(用户命令)等。这取决于您的项目。

关于在同一级别调用模块,应在顶层模块的__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

© www.soinside.com 2019 - 2024. All rights reserved.