resolve environment variables in string - regular expression

Paul McGuire ptmcg at austin.rr.com
Fri Feb 9 19:53:27 EST 2007


On Feb 9, 6:47 am, "bruno.desthuilli... at gmail.com"
<bruno.desthuilli... at gmail.com> wrote:
> On 9 fév, 12:30, "Kai Rosenthal" <kairosent... at tiscali.de> wrote:
>
> > Hello,
>
> > how can I resolve envionment variables in a string.
> > e.g.
>
> > strVar = /myVar
> > resolve in
>
> nothing. This raises a SyntaxError. Python is *not* a shell script
> language.
>
> > str1 = /mytest02/$MYVAR/mytest02     --> /mytest02//myVar/mytest02
> > (unix)
> > str2 =$MYVAR/mytest03     --> /myVar/mytest03 (unix)
> > str3 =%MYVAR%/mytest03     --> /myVar/mytest03 (windows)
> > I would not set the variables in this time.
>
> > I think I need a little regular expression code snippet,
>
> Nope.
>
> my_var = "/myVar"
> str1 = "/mytest02/%s/mytest02" % my_var
> str2 = "%(my_var)s/mytest03" % {'my_var': my_var}
> import os
> str3=os.path.join(my_var, "mytest03")
>
> hth


Here's a pyparsing snippet to maybe do what you want.

-- Paul


from pyparsing import Word,alphas
import os

substitutionVar = Word("$",alphas+"_")
substitutionVar.setParseAction( lambda t: os.getenv(t[0][1:],t[0]) )

envsub = lambda s : substitutionVar.transformString(s)

test = "$TEMP/mytest03"
print envsub(test)

prints:
C:\DOCUME~1\Paul\LOCALS~1\Temp/mytest03




More information about the Python-list mailing list