Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evaluate environment variables into a string in Python?

I have a string representing a path. Because this application is used on Windows, OSX and Linux, we've defined environment variables to properly map volumes from the different file systems. The result is:

"$C/test/testing" 

What I want to do is evaluate the environment variables in the string so that they're replaced by their respective volume names. Is there a specific command I'm missing, or do I have to take os.environ.keys() and manually replace the strings?

like image 362
Soviut Avatar asked Dec 22 '08 18:12

Soviut


People also ask

How do I find the value of an environment variable?

To display the values of environment variables, use the printenv command. If you specify the Name parameter, the system only prints the value associated with the variable you requested.

How do you expand an environment variable in Python?

path. expandvars() method in Python is used to expand the environment variables in the given path. It replaces substrings of the form $name or ${name} in the given path with the value of environment variable name.


2 Answers

Use os.path.expandvars to expand the environment variables in the string, for example:

>>> os.path.expandvars('$C/test/testing') '/stackoverflow/test/testing' 
like image 102
jblocksom Avatar answered Oct 21 '22 22:10

jblocksom


In Python 3 you can do:

'{VAR}'.format(**os.environ)) 

for example

>>> 'hello from {PWD}'.format(**os.environ)) hello from /Users/william 
like image 25
grisaitis Avatar answered Oct 21 '22 23:10

grisaitis