0

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.

1
  • If you can write it in bash you can convert it to python and test that... probably should have posted your python attempt first. Commented Jul 9, 2013 at 4:28

3 Answers 3

2

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...

Sign up to request clarification or add additional context in comments.

2 Comments

But this will require substituting all the variables at once. I want to substitute them one at a time.
@user2359303 to be fair - that wasn't ascertainable from your question and makes no sense - what is the reason you only want to/have to replace one at a time?
0
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

Cool...Even I figured out that this is the only way....templates wont do since they require substitution of all variables at once, while I want them to replace one at a time
@user2359303: And, if you want to change only the first occurence, you can change data.replace('$name', 'aakash') to data.replace('$name', 'aakash', 1).
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.