As using Python to change the system variable %PATH% (windows)?

I want to use script on Python to add to the end of this variable your directory, but due to the fact that Python is also necessary to prescribe in path, Google gives the answers I need... Tell me how can do it or Google for providing me with references if I have not learned this over the years (((
September 26th 19 at 11:41
2 answers
September 26th 19 at 11:43
Solution
import os

cmd = 'wmic environment where name="PATH" set variablevalue="C:\Temp;%PATH%'
os.system(cmd)

python 3.4
September 26th 19 at 11:45
A very concise solution that I found much harder, thank you !
# -*- coding: utf-8 -*-
import sys
from subprocess import check_call

if sys.hexversion > 0x03000000:
 import winreg
else:
 import _winreg as winreg


class Win32Environment:
 """Utility class to get/set windows environment variable"""

 def __init__(self, scope):
 assert scope in ('user', 'system')
 self.scope = scope
 if scope == 'user':
 self.root = winreg.HKEY_CURRENT_USER
 self.subkey = 'Environment'
else:
 self.root = winreg.HKEY_LOCAL_MACHINE
 self.subkey = R SYSTEM\CurrentControlSet\Control\Session Manager\Environment'

 def getenv(self, name):
 key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_READ)
try:
 value, _ = winreg.QueryValueEx(key, name)
 except WindowsError:
 value = "
 return value

 def setenv(self, name, value):
 # Note: for 'system' scope, you must run this as Administrator
 key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_ALL_ACCESS)
 winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value)
winreg.CloseKey(key)
 # For some strange reason, calling SendMessage from the current process
 # doesn't propagate environment changes at all.
 # TODO: handle CalledProcessError (for assert)
check_call("'\
%s-c "import win32api, win32con; assert win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')""' % sys.executable)


if __name__ == "__add_to_winpath_":
 e1 = Win32Environment(scope="system")
print(e1.getenv('PATH'))
 name = "d:\workspace\ndk\android-ndk-r9d\"
 e1.setenv('PATH', e1.getenv('PATH') + ';' + name)
 print(e1.getenv('PATH'))

Find more questions by tags Python