1

I have the following file "template.txt"

function FA()
{
    if(){...}
    message=[msg]
    message=[msg]
}
function FB()
{
    if(){...}
    message=[msg]
    message=[msg]
}
function FC()
{
    if(){...}
    message=[msg]
    message=[msg]
}

I would like to do this:

./script.py --function FB --message TEST

and get this result:

function FA()
{
    if(){...}
    message=[msg]
    message=[msg]
}
function FB()
{
    if(){...}
    message=TEST
    message=TEST
}
function FC()
{
    if(){...}
    message=[msg]
    message=[msg]
}

I can now using getopt retrieve all the options and arguments properly but I can't figure out how to achieve the above behavior elegantly. Any ideas? Are there any libraries that can help me with this?

I was able to achieve this behavior using AWK but now I need it in python. In AWK you can go to a specific line (e.g. function FC()) and start replacing from there until you hit another function. I can't seem to figure this out in python.

I am also wondering if there's a better approach to this problem.

4
  • You can use split and join to rip apart the text and stitch it back together with your message. Commented Oct 12, 2013 at 16:00
  • @WaleedKhan Thanks but how would that solve my issue? Commented Oct 12, 2013 at 16:01
  • @GraemeStuart I have updated my question with what I have tried Commented Oct 12, 2013 at 16:02
  • You need the fileinput module from the standard library. [Here's a simple example of how to use it.][1] [1]: stackoverflow.com/questions/5453267/… Commented Oct 12, 2013 at 16:06

1 Answer 1

1

Once you get your variables, and have them sanitized properly you can do something like this.

def templater(template,function,message):
    template = template.split('function')
    for i,f in enumerate(template):
        if function in f:
            template[i] = f.replace('[msg]',message)
    return 'function'.join(template)

Edit: As far as a better approach, you should consider creating your template using the formatting mini language http://docs.python.org/2/library/string.html#formatspec or an actual templating language such as jinja2 http://jinja.pocoo.org/docs/

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

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.