如何使用Cookiecutter将单个模板文件夹批量生成多个不同命名子文件夹
核心思路
Cookiecutter原生不支持直接循环生成多份同结构目录,可通过自定义后生成钩子(post_gen_project)+ 多账号参数输入实现需求,步骤如下:
步骤1:修改cookiecutter.json配置
将单值account_name改为多账号输入项,支持逗号分隔传入多个账号名:
{ "client_name": "client", "account_names": "account1,account2,account3" }
步骤2:调整模板目录结构
移除原来的{{cookiecutter.account_name}}动态目录,将账号级别的模板内容单独存为通用模板目录,调整后结构如下:
├── project │ ├── {{cookiecutter.client_name}} │ │ ├── _account_template # 存账号目录的通用模板内容 │ │ │ ├── some-folder │ │ │ ├── account.py.tpl # 模板文件,后续会替换文件名和内容
步骤3:添加post_gen_project钩子
在模板根目录的hooks文件夹中新建post_gen_project.py文件,Cookiecutter生成完基础目录后会自动执行该脚本,实现批量生成账号目录:
import os import shutil # 读取配置的账号列表 account_names = "{{cookiecutter.account_names}}".split(",") client_dir = "{{cookiecutter.client_name}}" template_dir = os.path.join(client_dir, "_account_template") for account in account_names: account = account.strip() # 新建对应账号的目录 account_dir = os.path.join(client_dir, account) shutil.copytree(template_dir, account_dir) # 重命名账号对应的py文件 py_file = os.path.join(account_dir, "account.py.tpl") target_py_file = os.path.join(account_dir, f"{account}.py") os.rename(py_file, target_py_file) # 可选:替换py文件内部的account_name变量 with open(target_py_file, "r", encoding="utf-8") as f: content = f.read() content = content.replace("{{account_name}}", account) with open(target_py_file, "w", encoding="utf-8") as f: f.write(content) # 删除通用模板目录 shutil.rmtree(template_dir)
验证使用
执行生成命令时,直接传入自定义的账号列表即可:
cookiecutter 你的模板路径 --extra-context '{"client_name": "某客户", "account_names": "zhangsan,lisi,wangwu"}'
执行后会自动在客户目录下生成zhangsan、lisi、wangwu三个账号目录,每个目录下的结构和文件都按模板生成完成。
内容的提问来源于stack exchange,提问作者Yaman Ahlawat
相关产品推荐
相关产品推荐

