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.

Kam
  • 5,878
  • 10
  • 53
  • 97
  • You can use `split` and `join` to rip apart the text and stitch it back together with your message. – Waleed Khan Oct 12 '13 at 16:00
  • @WaleedKhan Thanks but how would that solve my issue? – Kam Oct 12 '13 at 16:01
  • @GraemeStuart I have updated my question with what I have tried – Kam Oct 12 '13 at 16:02
  • You need the fileinput module from the standard library. [Here's a simple example of how to use it.][1] [1]: http://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place – ennuikiller Oct 12 '13 at 16:06

1 Answers1

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/

James Robinson
  • 822
  • 6
  • 13