(key, value, system, user)
| 365 | |
| 366 | |
| 367 | def win_set_environment_variable(key, value, system, user): |
| 368 | debug_print(f'set {key}={value}, in system={system}') |
| 369 | previous_value = win_get_environment_variable(key, system=system, user=user) |
| 370 | if previous_value == value: |
| 371 | debug_print(' no need to set, since same value already exists.') |
| 372 | # No need to elevate UAC for nothing to set the same value, skip. |
| 373 | return False |
| 374 | |
| 375 | if not value: |
| 376 | try: |
| 377 | if system: |
| 378 | cmd = ['REG', 'DELETE', 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', '/V', key, '/f'] |
| 379 | else: |
| 380 | cmd = ['REG', 'DELETE', 'HKCU\\Environment', '/V', key, '/f'] |
| 381 | debug_print(str(cmd)) |
| 382 | value = subprocess.call(cmd, stdout=subprocess.PIPE) |
| 383 | except Exception: |
| 384 | return False |
| 385 | return True |
| 386 | |
| 387 | try: |
| 388 | if win_set_environment_variable_direct(key, value, system): |
| 389 | return True |
| 390 | # Escape % signs so that we don't expand references to environment variables. |
| 391 | value = value.replace('%', '^%') |
| 392 | if len(value) >= 1024: |
| 393 | exit_with_error(f'the new environment variable {key} is more than 1024 characters long! A value this long cannot be set via command line: please add the environment variable specified above to system environment manually via Control Panel.') |
| 394 | cmd = ['SETX', key, value] |
| 395 | debug_print(str(cmd)) |
| 396 | retcode = subprocess.call(cmd, stdout=subprocess.PIPE) |
| 397 | if retcode != 0: |
| 398 | errlog(f'ERROR! Failed to set environment variable {key}={value}. You may need to set it manually.') |
| 399 | else: |
| 400 | return True |
| 401 | except Exception as e: |
| 402 | errlog(f'ERROR! Failed to set environment variable {key}={value}:') |
| 403 | errlog(str(e)) |
| 404 | errlog('You may need to set it manually.') |
| 405 | |
| 406 | return False |
| 407 | |
| 408 | |
| 409 | def win_set_environment_variables(env_vars_to_add, system, user): |
no test coverage detected