Environment variables - Expand

Alex Martelli aleax at aleax.it
Mon May 12 07:54:43 EDT 2003


<posted & mailed>

Dips wrote:

> Hi All,
> 
> Is it possible to expand environment variable in Windows using
> one-liner python command?

Python is not really about "one-liners", even though in this
case it might be possible.


> For instance, the following command doesn't expand %WINDIR%
> automatically
> file_name = '%WINDIR%\WIN.INI'
> file = os.open(file,'r')

Some problems here (that backslash is likely to cause problems,
and I doubt you really want to use 'file' in EITHER of the two
spots you use it in the last like), but, let's skip those.

%name% is not Python syntax for "expand this", so of course
it won't.  If you can rather use the Python syntax $(WINDIR)s
for the same functionality, then

filename = filename % os.environ

will do it.


> In actual 'file_name' is fed as command-line argument and so can
> contain any environement variables.

If you're stuck with an "alien" (non-Python) syntax, then the
requirement of parsing and expanding it by a "one-liner" becomes
_particularly_ unreasonable.  You could use A FEW lines with
regular expressions, e.g (warning, untested code):

import re
re_env = re.compile(r'%\w+%')

def expander(mo):
    return os.environ.get(mo.group()[1:-1}, 'UNKNOWN')

filename = re_env.sub(expander, filename)

or you might find some existing program or library routine that
does exactly what you want and call it from Pyhton (e.g. with
os.popen if it's an external program).


Alex





More information about the Python-list mailing list