(key, system=True, user=True, fallback=True)
| 329 | |
| 330 | |
| 331 | def win_get_environment_variable(key, system=True, user=True, fallback=True): |
| 332 | if (not system and not user and fallback): |
| 333 | # if no --system or --permanent flag is provided use shell's value |
| 334 | return os.environ[key] |
| 335 | try: |
| 336 | folder = None |
| 337 | try: |
| 338 | if system: |
| 339 | # Read globally from ALL USERS section. |
| 340 | folder = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment') |
| 341 | else: |
| 342 | # Register locally from CURRENT USER section. |
| 343 | folder = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment') |
| 344 | value = str(winreg.QueryValueEx(folder, key)[0]) |
| 345 | except Exception: |
| 346 | # If reading registry fails for some reason - read via os.environ. This has the drawback |
| 347 | # that expansion items such as %PROGRAMFILES% will have been expanded, so |
| 348 | # need to be precise not to set these back to system registry, or |
| 349 | # expansion items would be lost. |
| 350 | if fallback: |
| 351 | return os.environ[key] |
| 352 | return None |
| 353 | finally: |
| 354 | if folder is not None: |
| 355 | folder.Close() |
| 356 | |
| 357 | except Exception as e: |
| 358 | # this catch is if both the registry key threw an exception and the key is not in os.environ |
| 359 | if e.args[0] != 2: |
| 360 | # 'The system cannot find the file specified.' |
| 361 | errlog(f'Failed to read environment variable {key}:') |
| 362 | errlog(str(e)) |
| 363 | return None |
| 364 | return value |
| 365 | |
| 366 | |
| 367 | def win_set_environment_variable(key, value, system, user): |
no test coverage detected