10

在用户为 中的变量提供了一些值之后,有没有办法机器生成一些值cookiecutter.json

我问的原因是:

  • 我需要提示的值之一是用户很难解决
  • 但我很容易编写一些 Python 代码来生成正确的值

所以我真的很希望能够删除用户提示,而是计算值。

我尝试过的事情:

  • 在线搜索示例pre_gen_project.py文件以显示如何执行此操作
  • 阅读 cookiecutter高级使用页面

我在命令行上使用 cookiecutter:

cookiecutter path_to_template

我错过了任何技巧吗?

4

1 回答 1

5

就在几天前,我需要这种确切的能力。我想出的解决方案是为 cookiecutter 编写一个包装脚本,类似于中提到的:

http://cookiecutter.readthedocs.io/en/latest/advanced_usage.html#calling-cookiecutter-functions-from-python

我的脚本会生成一个随机字符串以在 Django 项目中使用。我称我的脚本为cut-cut:

#! /usr/bin/env python

from cookiecutter.main import cookiecutter

import os

rstring = ''.join([c for c in os.urandom(1024)
                   if c.isalnum()])[:64]

cookiecutter(
    'django-template',     # path/url to cookiecutter template
    extra_context={'secret': rstring},
)

所以现在我只是cut-cut像往常一样简单地运行并逐步完成该过程。唯一的区别是我的文件中名为secretcookiecutter.json的条目预先填充了脚本中生成的rstring值,通过传递的extra_context提供。

您可以修改脚本以通过命令行接受模板,但在我的使用中,我总是使用相同的模板,因此我只需传递一个硬编码值“django-template”,如上面代码中所述。

于 2016-06-06T15:00:23.983 回答