我想找出最干净,最好是自包含的方式在与包本身位于不同目录的脚本中使用我的包。
示例问题如下:
lib
中的模块都需要导入,并作为脚本运行。
我的项目目录如下,我遇到两个问题:
lib/api.py
中,我想在调用或导入data_files/key.txt
时正确读取api.py
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的方式来构造您的项目。
这是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