Say I have the following HTML script:
<head>$name</head>
And I have the following shell script which replaces the variable in the HTML script with a name
#/bin/bash
report=$(cat ./a.html)
export name=$(echo aakash)
bash -c "echo \"$report\""
This works.
Now I have to implement the shell script in Python so that I am able to replace the variables in the HTML file and output the replaced contents in a new file. How do I do it?
An example would help. Thanks.
3 Answers 3
It looks like you're after a templating engine, but if you wanted a straight forward, no thrills, built into the standard library, here's an example using string.Template:
from string import Template
with open('a.html') as fin:
template = Template(fin.read())
print template.substitute(name='Bob')
# <head>Bob</head>
I thoroughly recommend you read the docs especially regarding escaping identifier names and using safe_substitute and such...
2 Comments
with open('a.html', 'r') as report:
data = report.read()
data = data.replace('$name', 'aakash')
with open('out.html', 'w') as newf:
newf.write(data)
2 Comments
data.replace('$name', 'aakash') to data.replace('$name', 'aakash', 1).Firstly you could save your html template like:
from string import Template
with open('a.html') as fin:
template = Template(fin.read())
Then if you want to substitute variables one at a time, you need to use safe_substitute and cast the result to a template every time. This wont return a key error even when a key value is not specified.
Something like:
new=Template(template.safe_substitute(name="Bob"))
After this , the new template is new , which needs to be modified again if you would want.
bashyou can convert it topythonand test that... probably should have posted your python attempt first.