python学习笔记-结构化python工程

it2026-09-28  12

最近在系统地重新学习python,推荐一本优秀的python书籍:Python最佳实践指南。 这一篇文章简单介绍一下一个正规的python项目中应该包含哪些内容,从而使你看起来更专业。话不多说先看结构:

README.md 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

下面分别剖析一下

1 项目核心代码

核心代码在示例结构的sample文件夹中,包含一些测试的代码。

2 项目文档

文档保存在docs文件夹中,可以在这里对项目进行详细的描述。

3 测试代码

测试代码保存在test文件夹中

4 setup.py

编写python的第三方库,最终要的一个工作就是编写setup.py了,其实如果我们下载过一些第三库的源代码文件,打开之后一般就会有一个setup.py,执行python setup.py install 就可以安装这个库了。setup.py 如何编写内容很多,可以参考官方文档,一个最基本的setup.py是这样子的:

from distutils.core import setup #This is a list of files to install, and where #(relative to the 'root' dir, where setup.py is) #You could be more specific. files = ["things/*"] setup(name = "appname", version = "100", description = "yadda yadda", author = "myself and I", author_email = "email@someplace.com", url = "whatever", #Name the folder where your packages live: #(If you have other packages (dirs) or modules (py files) then #put them into the package directory - they will be found #recursively.) packages = ['package'], #'package' package must contain files (see list above) #I called the package 'package' thus cleverly confusing the whole issue... #This dict maps the package name =to=> directories #It says, package *needs* these files. package_data = {'package' : files }, #'runner' is in the root. scripts = ["runner"], long_description = """Really long text here.""" # #This next part it for the Cheese Shop, look a little down the page. #classifiers = [] )

5 README.md

这是项目的门面,多参考github上面的项目。

6 requirements.txt

一个 pip requirements file 应该放在仓库的根目录。它应该指明完整工程的所有依赖包: 测试, 编译和文档生成。

如果您的工程没有任何开发依赖,或者您喜欢通过 setup.py 来设置,那么这个文件不是必须的。

6.1 requirements.txt文件的格式

requirements.txt文件中是这样的:

scikit-learn==1.2.0 numpy==1.0 # 格式为:包名==版本号

可以手动填写所需的包及其版本,也可以使用如下指令:

pip freeeze > requirements.txt

直接将当前python环境中的所有包打包,不过这样可能会多很多不是完全需要的包(因此最好配合virtualenv一起食用风味更佳)。

那么如何安装requirements.txt中的包呢?使用如下指令即可:

pip install -r requirements.txt
最新回复(0)