Jens
Jens

Reputation: 9130

Use custom environment vars for os.path.expandpath in Python

It seems as if Python's os.path.expandvars() function operates on the calling process environment. Is there a way to add my own new variables into the mix without polluting the process environment?

Best I can come up with ad hoc is:

>>> env = os.environ
>>> env["FOO"] = "VAL"
>>> os.path.expandvars("variable FOO=$FOO")
'variable FOO=VAL'
>>> del env["FOO"] 

Ideally I'd like to pass an env argument like the one for subprocess.Popen(). It seems that I'd have to write such a wrapper myself?

Upvotes: 5

Views: 535

Answers (1)

Lucas Wolfgang
Lucas Wolfgang

Reputation: 11

It may seem silly but try doing the following:

# Crete a new env and modify it
new_env = os.environ.copy()
new_env["FOO_VAR"] = "FOO_VALUE" 

# Replace the env e use expandvars
tmp_env = os.environ
os.environ = new_env
print(os.path.expandvars("variable FOO=$FOO_VAR"))

# Return to the old env
os.environ = tmp_env

By the way, I initially was using regex to identify both %(?.+)% and $\{?(?.+)\}?[/\\\n], but doing the above seems better.

Upvotes: 1

Related Questions