This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: os.path.expandvars: expand string without modifying the environment
Type: enhancement Stage: test needed
Components: Library (Lib) Versions: Python 3.1, Python 2.7
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: gjb1002, r.david.murray
Priority: normal Keywords: patch

Created on 2007-07-06 10:06 by gjb1002, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
patch.diff gjb1002, 2007-07-06 15:54 Path for os.path.expandvars
Messages (4)
msg52809 - (view) Author: Geoffrey Bache (gjb1002) Date: 2007-07-06 10:06
I've several times wanted to expand a string in the way that os.path.expandvars does, but without modifying the actual environment.

If for example I have 

inputString = "$ROOT/${SUBDIR}/some/path"

and I want to find expanded versions of this, I have to do something like

os.environ["ROOT"] = "/users/geoff"
os.environ["SUBDIR"] = "subdir"
fullPath = os.path.expandvars(inputString)

The problem is that my program is multithreaded and I don't want to globally change os.environ. All I want is the information "fullPath". I'd like to be able to create a local "env" dictionary and pass it to os.path.expandvars as an optional second argument.

I attach a patch for posixpath.py and ntpath.py, though this is untested and is intended to show what I mean in practice.
msg52810 - (view) Author: Geoffrey Bache (gjb1002) Date: 2007-07-06 15:54
I've now attached a better patch, which is tested at least on UNIX for now. Decided it was better if the optional argument was a function to replace os.getenv, as then it can be called only on demand and there isn't a need to set up information unnecessarily, or call any code more than once.

File Added: patch
msg85641 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2009-04-06 12:45
Python has had a way to do this since python 2.4:

>>> from string import Template
>>> fullPath =
Template("$ROOT/${SUBDIR/some/path").substitute(dict(ROOT='/users/geof',
SUBDIR='subdir'))
>>> fullPath
'/users/geof/subdir/some/path'
msg85662 - (view) Author: Geoffrey Bache (gjb1002) Date: 2009-04-06 18:58
Thanks, didn't know about that feature.
History
Date User Action Args
2022-04-11 14:56:25adminsetgithub: 45153
2009-04-06 18:58:55gjb1002setmessages: + msg85662
2009-04-06 12:45:27r.david.murraysetstatus: open -> closed

nosy: + r.david.murray
messages: + msg85641

components: + Library (Lib), - Extension Modules
resolution: rejected
2009-04-06 10:31:42ajaksu2settitle: Extra optional argument to os.path.expandvars -> os.path.expandvars: expand string without modifying the environment
stage: test needed
type: enhancement
versions: + Python 3.1, Python 2.7
2007-07-06 10:06:20gjb1002create