【问题标题】:Can I make a file optional based on a variable's value in cookiecutter.json我可以根据 cookiecutter.json 中的变量值使文件成为可选文件吗
【发布时间】:2016-01-26 00:34:07
【问题描述】:

我想在我的 python cookiecutter 项目中添加一个可选的文件。

一个例子是在 cookiecutter.json 中有变量

{"settings_file": true}

这将在我的目录的根目录下创建一个文件settings.py(可能包含一些内容)。

cookiecutter 是否提供执行此操作的选项?或者我应该使用后处理钩子来编写一个创建文件的脚本(我觉得这不是最优雅的解决方案)。

【问题讨论】:

    标签: python cookiecutter


    【解决方案1】:

    根据官方docs,可以使用后生成钩子脚本(hooks/post_gen_project.py

    (此处复制 sn-p 供略过的人使用)

    import os
    import sys
    
    REMOVE_PATHS = [
        '{% if cookiecutter.packaging != "pip" %} requirements.txt {% endif %}',
        '{% if cookiecutter.packaging != "poetry" %} poetry.lock {% endif %}',
    ]
    
    for path in REMOVE_PATHS:
        path = path.strip()
        if path and os.path.exists(path):
            if os.path.isdir(path):
                os.rmdir(path)
            else:
                os.unlink(path)
    

    【讨论】:

      【解决方案2】:

      我将回答我自己的问题,以防有人遇到它:它尚未作为项目的功能实现,请在此处查看增强票:https://github.com/audreyr/cookiecutter/issues/127

      我想出的“最不难看”的解决方案是每次都创建文件,并在 post hook 期间清理它们(您也可以在 post hook 期间创建它们,但会失去 cookiecutter 模板的优势)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-26
        • 1970-01-01
        • 2021-07-09
        • 1970-01-01
        • 2019-02-22
        • 2012-01-11
        • 2022-06-16
        • 2013-02-21
        相关资源
        最近更新 更多