Skip to content

Instantly share code, notes, and snippets.

@eestrada
Last active November 4, 2021 00:20
Show Gist options
  • Save eestrada/af505d551af640eeda272a3c2055a1d1 to your computer and use it in GitHub Desktop.
Save eestrada/af505d551af640eeda272a3c2055a1d1 to your computer and use it in GitHub Desktop.
Pythonic interface to the global and user environment variables on Windows.
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
"""Get global Windows environment variables.
This can be useful for programs that need to spawn subprocesses,
but want to make sure that those subprocess are always spawned
with the latest changes from the global environment variables."""
import os
import winreg
import collections.abc
def _dump_vars(root_key, reg_path, expand_envars=True):
with winreg.OpenKey(root_key, reg_path) as reg_key:
rval = {}
r = range(winreg.QueryInfoKey(reg_key)[1])
for v in (winreg.EnumValue(reg_key, i) for i in r):
if expand_envars and v[2] == winreg.REG_EXPAND_SZ:
rval[v[0]] = winreg.ExpandEnvironmentStrings(v[1])
else:
rval[v[0]] = v[1]
return rval
def dump_win_env(system=True, user=True, expand_envars=True, combine_path=True):
rdict = dict()
sdict = dict()
udict = dict()
if system:
root_key = winreg.HKEY_LOCAL_MACHINE
reg_path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
sdict = _dump_vars(root_key, reg_path, expand_envars=expand_envars)
if user:
root_key = winreg.HKEY_CURRENT_USER
reg_path = r'Environment'
udict = _dump_vars(root_key, reg_path, expand_envars=expand_envars)
rdict.update(sdict)
rdict.update(udict)
path_names = [n for n in rdict.keys() if n.casefold() == 'Path'.casefold()]
path_name = path_names[0] if path_names else 'Path'
if combine_path and system and user and path_name in sdict and path_name in udict:
spath = sdict[path_name].strip(os.pathsep)
upath = udict[path_name].strip(os.pathsep)
rdict[path_name] = os.pathsep.join([spath, upath])
return rdict
# Useful links for how to do certain things related to the Registry in Windows:
#
# Request UAC elevation from within a Python script? This is useful if one
# wants/needs to modify protected registry entries, such as system (not user)
# global variables:
# * https://stackoverflow.com/a/41930586/1733321
#
# How to notify other processes of global environment variable changes. Also,
# how to set key values:
# * https://stackoverflow.com/a/21472285/1733321
#
# How to get environment variables from the registry based on given key. Useful
# for `__getitem__`, `__setitem__`, and `__delitem__` implementations:
# * https://stackoverflow.com/a/37547237/1733321
#
# How to loop thru/enumerate keys/values for a given registry key. Useful for
# `__len__` and `__iter__` implementations of a Mapping class:
# * https://stackoverflow.com/q/3974038/1733321
class WinEnv(collections.abc.Mapping):
def __init__(self, system=False):
if system:
root_key = winreg.HKEY_LOCAL_MACHINE
reg_path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
else:
root_key = winreg.HKEY_CURRENT_USER
reg_path = r'Environment'
self._cache = _dump_vars(root_key, reg_path)
def __getitem__(self, key):
return self._cache[key]
def __iter__(self):
return iter(self._cache)
def __len__(self):
return len(self._cache)
def to_dict(self):
return dict(self)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment