创建新文件并将其包含到 python 包中

Create and include new file into python package

我想根据 git describe 命令为我的包使用版本。为此,我用函数 get_version() 创建了 setup.py。此函数从 .version 文件中检索版本(如果存在),否则计算新的包版本并将其写入新的 .version 文件。但是,当我调用 python setup.py sdist 时,.version 并未在 .tar 存档中进行复制。当我尝试从 PyPi 存储库安装包时,这会导致错误。如何正确地将我的 .version 文件 "on the fly" 包含到包中?

setup.py:

import pathlib
from subprocess import check_output
from setuptools import find_packages, setup


_VERSION_FILE = pathlib.Path(".version")  # Add it to .gitignore!
_GIT_COMMAND = "git describe --tags --long --dirty"
_VERSION_FORMAT = "{tag}.dev{commit_count}+{commit_hash}"


def get_version() -> str:
    """ Return version from git, write commit to file
    """
    if _VERSION_FILE.is_file():
        with _VERSION_FILE.open() as f:
            return f.readline().strip()
    output = check_output(_GIT_COMMAND.split()).decode("utf-8").strip().split("-")

    tag, count, commit = output[:3]
    dirty = len(output) == 4

    if count == "0" and not dirty:
        return tag

    version = _VERSION_FORMAT.format(tag=tag, commit_count=count, commit_hash=commit)

    with _VERSION_FILE.open("w") as f:
        print(version, file=f, end="")

    return version


_version = get_version()

setup(
    name="mypackage",
    package_data={
        "": [str(_VERSION_FILE)]
    },
    version=_version,
    packages=find_packages(exclude=["tests"]),
)

如果您将名为 MANIFEST.in 的文件包含在与 setup.py 相同的目录中,其中包含 include .version,这应该会获取该文件。

这是 setup.py 中的一个错误。我忘了在 if count == "0" and not dirty: 中添加文件转储。现在它适用于 MANIFEST.in.