如何组织一个Python项目?

83 投票
8 回答
80240 浏览
提问于 2025-04-16 12:44

我刚开始学习Python,正在做一个小项目,但对如何按照“Python的方式”来组织文件夹有些疑问。

我在开发环境中使用的是PyDev,当我创建一个新项目时,会生成一个叫src的文件夹。

+ src

现在,在PyDev中,我可以创建Pydev ModulePyDev Package

我需要按照以下方式来组织我的项目:

+ Indicators
    - Moving_averages.py
    - Stochastics.py
+ Strategies
    - Moving_averages_cross.py
- example.py

我该如何在模块和包的层面上来组织这些呢?模块和包是什么意思呢?

8 个回答

28

查看 python-package-template

目录结构

    .
    |-- bin
    |   `-- my_program
    |-- docs
    |   `-- doc.txt
    |-- my_program
    |   |-- data
    |   |   `-- some_data.html
    |   |-- __init__.py
    |   |-- submodule
    |   |   `-- __init__.py
    |   |-- helpers.py
    |-- tests
    |   |-- __init__.py
    |   |-- test_helpers.py
    |-- Makefile
    |-- CHANGES.txt
    |-- LICENSE.txt
    |-- README.md
    |-- requirements-dev.txt
    |-- requirements.txt
    `-- setup.py

查看 Makefile 文件

    PYTHON=`which python`
    NAME=`python setup.py --name`


    all: check test source deb

    init:
        pip install -r requirements.txt --use-mirrors

    dist: source deb

    source:
        $(PYTHON) setup.py sdist

    deb:
        $(PYTHON) setup.py --command-packages=stdeb.command bdist_deb

    rpm:
        $(PYTHON) setup.py bdist_rpm --post-install=rpm/postinstall --pre-uninstall=rpm/preuninstall

    test:
        unit2 discover -s tests -t .
        python -mpytest weasyprint

    check:
        find . -name \*.py | grep -v "^test_" | xargs pylint --errors-only --reports=n
        # pep8
        # pyntch
        # pyflakes
        # pychecker
        # pymetrics

    clean:
        $(PYTHON) setup.py clean
        rm -rf build/ MANIFEST dist build my_program.egg-info deb_dist
        find . -name '*.pyc' -delete
43

从文件系统的角度来看,模块就是以 .py 结尾的文件,而包则是一个包含模块和(嵌套)包的文件夹。如果一个文件夹里有一个 __init__.py 文件,Python 就会把这个文件夹认作一个包。

像这样的文件结构

some/
    __init__.py
    foofoo.py
    thing/
        __init__.py
        barbar.py

定义了一个包 some,这个包里有一个模块 foofoo,还有一个嵌套的包 thing,而这个包里又有一个模块 barbar。不过在使用包和模块的时候,其实你并不需要特别区分这两种类型:

import some

some.dothis() # dothis is defined in 'some/__init__.py'

import some.foofoo # <- module
import some.thing # <- package

在给你的包或模块命名时,请遵循 PEP8 的建议(也就是说,使用小写字母命名)。

51

一个包其实就是一个文件夹,里面有一个叫做 __init__.py 的文件,通常还会有一些模块。这里的模块就是指 *.py 文件。包主要是和 import 这个功能有关。如果你在 Indicators 文件夹里加上 __init__.py 文件,你就可以使用:

from Indicators.Stochastics import *

或者

from Indicators import Stochastics

顺便提一下,我建议把模块和包的名字都写成小写字母。这样虽然不会影响功能,但更符合 Python 的风格。

撰写回答