jeudi 16 juin 2016

Protect against null environment variables when using os.path.expandvars

How can I protect against Python's os.path.expandvars() treatment of null/unset environment variables?

From os.path:

Malformed variable names and references to non-existing variables are left unchanged.

>>> os.path.expandvars('$HOME/stuff')
'/home/dennis/stuff'
>>> os.path.expandvars('foo/$UNSET/bar')
'foo/$UNSET/bar'

I could perform this step separately from other path processing (expanduser(), realpath(), normpath(), etc.) instead of chaining them all together and check to see if the result is unchanged, but that is normal when there are no variables present - so I would also have to parse the string to see if it has any variables. I fear that may not be robust enough.

The issue comes into play when creating a file using the result. I end up with a file with the variable name as a literal part of the file's name. I want to instead reject the input with an exception.

Aucun commentaire:

Enregistrer un commentaire