[Common] Fix win32 set env issue on Python 3

- On Python 3 find_msvcrt returns None and _wputenv should be used with
unicode strings.
- Removed the alternative msvcrt set env since `cdll.msvcrt` should suffice.
- Removed the broad exception catching.
This commit is contained in:
Calum Lind 2018-11-11 14:56:07 +00:00
parent ab7f19fbb8
commit 10fcbecc04
1 changed files with 9 additions and 33 deletions

View File

@ -1239,50 +1239,26 @@ def set_env_variable(name, value):
if windows_check(): if windows_check():
from ctypes import windll from ctypes import windll
from ctypes import cdll from ctypes import cdll
from ctypes.util import find_msvcrt
# Update the copy maintained by Windows (so SysInternals Process Explorer sees it) # Update the copy maintained by Windows (so SysInternals Process Explorer sees it)
try:
result = windll.kernel32.SetEnvironmentVariableW(name, value) result = windll.kernel32.SetEnvironmentVariableW(name, value)
if result == 0: if result == 0:
raise Warning log.info(
except Exception: "Failed to set Env Var '%s' (kernel32.SetEnvironmentVariableW)", name
log.warning(
'Failed to set Env Var \'%s\' (\'kernel32.SetEnvironmentVariableW\')',
name,
) )
else: else:
log.debug( log.debug(
'Set Env Var \'%s\' to \'%s\' (\'kernel32.SetEnvironmentVariableW\')', "Set Env Var '%s' to '%s' (kernel32.SetEnvironmentVariableW)",
name, name,
value, value,
) )
# Update the copy maintained by msvcrt (used by gtk+ runtime) # Update the copy maintained by msvcrt (used by gtk+ runtime)
try: result = cdll.msvcrt._wputenv('%s=%s' % (name, value))
result = cdll.msvcrt._putenv('%s=%s' % (name, value))
if result != 0: if result != 0:
raise Warning log.info("Failed to set Env Var '%s' (msvcrt._putenv)", name)
except Exception:
log.warning('Failed to set Env Var \'%s\' (\'msvcrt._putenv\')', name)
else: else:
log.debug('Set Env Var \'%s\' to \'%s\' (\'msvcrt._putenv\')', name, value) log.debug("Set Env Var '%s' to '%s' (msvcrt._putenv)", name, value)
# Update the copy maintained by whatever c runtime is used by Python
try:
msvcrt = find_msvcrt()
msvcrtname = str(msvcrt).split('.')[0] if '.' in msvcrt else str(msvcrt)
result = cdll.LoadLibrary(msvcrt)._putenv('%s=%s' % (name, value))
if result != 0:
raise Warning
except Exception:
log.warning(
'Failed to set Env Var \'%s\' (\'%s._putenv\')', name, msvcrtname
)
else:
log.debug(
'Set Env Var \'%s\' to \'%s\' (\'%s._putenv\')', name, value, msvcrtname
)
def unicode_argv(): def unicode_argv():