Skip to content

Instantly share code, notes, and snippets.

@Rurik
Last active March 6, 2024 21:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rurik/6556041 to your computer and use it in GitHub Desktop.
Save Rurik/6556041 to your computer and use it in GitHub Desktop.
Python functions to compress folder paths to include their environment variable. This is the opposite of os.path.expandvars(). For example, "C:\Windows\system32\cmd.exe" would resolve to "%WINDIR%\system32\cmd.exe".
#@bbaskin
import os
import re
# Thanks to Andrew Havens of Cipher Tech for figuring out how to escape the paranthesis to work with
# both expandvars and regex
def generalize_vars_init():
"""
Initialize a dictionary with the local system's environment variables.
Returns:
path_generalize_list: A Python dictionary of path:variable.
"""
envvar_list = [r'%ALLUSERSPROFILE%',
r'%LOCALAPPDATA%',
r'%APPDATA%',
r'%COMMONPROGRAMFILES%',
r'%PROGRAMDATA%',
r'%PROGRAMFILES%',
r'%PROGRAMFILES(x86)%',
r'%PUBLIC%',
r'%TEMP%',
r'%USERPROFILE%',
r'%WINDIR%']
path_generalize_list = {}
for env in envvar_list:
resolved = os.path.expandvars(env).encode('unicode_escape')
resolved = resolved.replace('(', '\\(').replace(')', '\\)')
if not resolved == env:
path_generalize_list[resolved] = env
return path_generalize_list
def generalize_var(d, string):
"""
Performs a multiple find/replace on a string based on a given dictionary.
Args:
d: Python dictionary of text as: search:replace
string: string to perform replacement on
Returns:
A string value with replacements made.
"""
search = '(?i)' + '|'.join('(%s)' % key for key in d.iterkeys())
regex = re.compile(search)
lookup = dict((index + 1, value) for index, value in enumerate(d.itervalues()))
return regex.sub(lambda match: match.expand(lookup[match.lastindex]), string)
if __name__ == '__main__':
lookup = generalize_vars_init()
strings = [r'C:\Windows\System32\cmd.exe', r'C:\Program Files\testing123', r'C:\ProgramData\Folder\File']
for s in strings:
print ('%s => %s' % (s, generalize_var(lookup, s)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment