How to evaluate environment variables into a string in Python?

PythonFilesystemsEnvironment Variables

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

>>> os.path.expandvars('$C/test/testing')
'/stackoverflow/test/testing'

Solution 2 - Python

In Python 3 you can do:

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

for example

>>> 'hello from {PWD}'.format(**os.environ))
hello from /Users/william

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSoviutView Question on Stackoverflow
Solution 1 - PythonjblocksomView Answer on Stackoverflow
Solution 2 - Pythonwilliam_grisaitisView Answer on Stackoverflow