This code can be used to generate plain text files from templates.
To install the latest release from PyPI, run:
pip install qr-generateTo install the latest code from GitHub, run:
pip install git+https://github.com/quadraturerules/generate.gitThe following syntax can be used to generate text:
- For loops use the syntax
{{for VARIABLE in LIST}}and{{end for}} - Ifs use the syntax
{{if CONDITION}}and{{end if}}
To generate a file that prints each value in a list, the following template can be written:
template = """{{for v in values}}
print({{v}})
{{end for}}"""A python script can then be used to generate the file:
import generate
t = generate.parse(template)
values = [
generate.substitute.Float(i)
for i in [1.0, 4.0, 6.0]
]
print(t.substitute(loop_targets={"values": values}))The items in the list values passed in as a loop target must be a subclass of
Substitutor.
Alternatively, you could create a folder called input_code and create a file inside it containing the file code.py with contents:
{{for v in values}}
print({{v}})
{{end for}}and create a file in the directory called __gen__.py with contents:
import generate
loop_targets = {"values": [
generate.substitute.Float(i)
for i in [1.0, 4.0, 6.0]
]}You can then run:
python -m generate input_code output_codeThis would create a directory called output_code containing a file code.py with the template replacements having been made.
When templating using a folder, a file for each entry in a list can be created by using a .template file. For example, if a file called
p.template was added to the input_code directory with the contents
--
template: v in values
filename: p-{{v}}.py
--
print({{v}})You can then run:
python -m generate input_code output_codeThis would generate files called p-1.0.py, p-4.0py, and p-6.0.py.
A larger example of the use of this library can be found by looking at the code used to generate the quadraturerules libraries associated with the online encylopedia of quadrature rules.