Cookiecutter 模板依赖关系管理

Cookiecutter Template Dependency Management

提问人:Sadra 提问时间:7/29/2023 最后编辑:Sadra 更新时间:7/30/2023 访问量:104

问:

我正在开发一个千篇一律的模板。我的模板有一些依赖项。例如,在“我想使用 ”中显示消息。我怎样才能满足这样的要求?hooks/post_gen_project.pyrich.print

此外,我还看到许多 cookiecutter 模板的根目录中包含 、 或文件。这有什么意义?!起初,我认为这可能是向我的模板添加依赖项的一种方式,但这不起作用,并且想知道这背后的整个想法。不幸的是,cookiecutter 的文档描述所有这些概念和细节都很薄弱!setup.pypyproject.tomlsetup.cfg

谢谢。

python 模板 jinja2 依赖管理 cookiecutter

评论


答:

0赞 Sadra 7/29/2023 #1

解决方案 1

一种做法是在钩子文件中安装依赖项。pre_gen_project.py

try:
    import rich
except ModuleNotFoundError:
    import subprocess

    subprocess.run(
        [
            "pip",
            "install",
            "--disable-pip-version-check",
            "--no-python-version-warning",
            "-q",
            "rich",
        ]
    )

这样,在触发之前,它就会安装,以便您可以毫无问题地使用 in。post_gen_projectrichrich.printpost_gen_project.py

解决方案 2

另一种解决方案是将文件保留在您的(或您保存模板文件的任何地方)中,并将所有依赖项放在那里。cc_requirements.txt{{cookiecutter.project_slug}}/

rich==<desired-version>

然后,在文件中,使用以下指令..post_gen_project.py

  • 首先,安装依赖项。
  • 其次,删除文件。cc_requirements.txt

这是文件的内容。post_gen_project.py

import os

# ...

PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)

def remove_file(filepath: str) -> None:
    """removes a file

    Args:
        filepath (str): path to file
    """
    os.remove(os.path.join(PROJECT_DIRECTORY, filepath))


def install_requirements():
    requirements_file = os.path.join(PROJECT_DIRECTORY, "cc_requirements.txt")
    subprocess.check_call(
        [
            "pip",
            "install",
            "--disable-pip-version-check",
            "--no-python-version-warning",
            "-qUr",
            requirements_file,
        ]
    )
    remove_file(requirements_file)

# ...

if __name__ == "__main__":
    ...
    install_requirements()
    import rich
    # ...

setup.py, ,setup.cfgpyproject.toml

这些文件通常是为了管理与模板对应的元数据而存在的。这些文件中只需要一些特定的元数据关键字,例如而不是全部文件。例如,如果您环顾这些文件中的关键字,它们大部分时间都是空的,这意味着当有人尝试安装它们时,最终,实际上没有任何(功能)被运送!versionpackages