ちょっとだけ違う似たようなバッチをたくさん作らないといけなくなったので、Node.jsでHandlebars.jsを使えばいいやと思ったけど、どうやらPythonでもpybars3ってのでHandlebarsが使えるみたいなので、そっちでやってみる。
大量に似たようなバッチを作らないといけなくなり、Node.jsでやるかっと思ったら、目の前のPCには入ってない。
WinPythonは入っていて、WinPythonにはpybars3もインストール済みなようなので、日本語の情報がないことに不安を感じつつも使ってみることにした。
入ってなければ
pip install pybars3
WindowsのCMDバッチだから、ファイルのエンコードは「cp932」
settings.json
[ { "file_name": "A.bat", "message": "AAAA", "users": [{"name": "山田"}, {"name": "鈴木"}] }, { "file_name": "B.bat", "message": "BBBB", "users": [{"name": "田中"}, {"name": "佐藤"}, {"name": "山本"}] } ]
template.hbs
@echo off echo. echo message: {{message}} echo. echo users: {{#for users}} echo * {{name}} {{/for}} exit /b
json_to_cmd.py
# -*- coding: utf-8 -*- import json from pybars import Compiler def main(): with open("settings.json", "r", encoding="cp932") as f: settings = json.load(f) with open("template.hbs", "r", encoding="cp932") as f: source = f.read() compiler = Compiler() template = compiler.compile(source) helpers = {"for": _for} for setting in settings: output = template(setting, helpers=helpers) with open(setting["file_name"], "w", encoding="cp932") as f: f.write(output) def _for(this, options, items): result = [] for thing in items: result.extend(options["fn"](thing)) return result if __name__ == "__main__": main()
Handlebarsそのものとは違うような気がしないでもないが、一応できた。
この感じでJSONとテンプレートを用意すれば、ちょっと違うけど別物っていうバッチを簡単に生み出せるから、楽ができそうだ。
やっぱり、退屈なことはPythonにやらせなきゃいけないからね。