Mainly Tech projects on Python and Electronic Design Automation.

Saturday, March 24, 2007

Bash style environment variable expander in Python

At work we have a certain config file that has bash/tcsh style embedded environment variable references of two styles:
${VARNAME}
and
$VARNAME

I thought I would try my hand at a concise python expander for the syntax and came up with:


bash$ python -c '
import sys,os,re
s=sys.stdin.read()
s1 = re.subn(r"\$([a-z_A-Z][A-Za-z_0-9\-]*)", r"%(\1)s", s)[0]
s2 = re.subn(r"\${([^}]+)}", r"%(\1)s", s1)[0]
print s2 % os.environ ' < in_file > expanded_file

2 comments:

  1. Isn't this reinventing
    string.Template.substitute?

    ReplyDelete
  2. Now that I've looked it up: it is. Wonderful.

    Thanks steven.

    it now boils down to


    bash$ cat xx.caf
    +defeine+default_ca_nr=${DEFAULT_CA_NR}/abc/def.v
    +loadpli1+$HOMEDRIVE/Progs/hello:bye
    +loadpli2+${HOMEDRIVE}/go/for/it:baby

    bash$ python -c 'from string import Template
    import os,sys
    print Template(sys.stdin.read()).safe_substitute(os.environ)' < xx.caf
    +defeine+default_ca_nr=CA6/abc/def.v
    +loadpli1+C:/Progs/hello:bye
    +loadpli2+C:/go/for/it:baby

    bash$


    I guess I got confused over debates on web templating systems and forgot what was available in the standard library.

    - Paddy.

    ReplyDelete

Followers

Subscribe Now: google

Add to Google Reader or Homepage

Go deh too!

whos.amung.us

Blog Archive