python 添加系统环境变量
2019-08-30 python 1939
import os import sys import subprocess ''' # 用户环境变量注册表位置 set regPath= HKEY_CURRENT_USER\Environment # 系统环境变量注册表位置 set regPath= HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session" "Manager\Environment reg add %regPath% /v %key% /t REG_EXPAND_SZ /d "%oldValue%;%value%" /f ''' SET_ENV = r''' @echo set %{key}%={value} echo %{key}% if {user}==sys ( setx /M{key} "%{key}%" ) else ( setx {key} "%{key}%" ) ''' ADD_ENV = r''' @echo off if {user}==sys ( set regPath= HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session" "Manager\Environment ) else ( set regPath= HKEY_CURRENT_USER\Environment ) set key={key} set value={value} :: 判断是否存在该路径 reg query %regPath% /v %key% 1>nul 2>nul if %ERRORLEVEL%==0 ( :: 取值 For /f "tokens=3* delims= " %%i in ('Reg Query %regPath% /v %key% ') do ( if "%%j"=="" (Set oldValue=%%i) else (Set oldValue=%%i %%j) ) ) else Set oldValue="." :: 备份注册表 reg export %regPath% %~dp0%~n0.reg :: 写入环境变量 if "%oldValue%"=="." ( reg add %regPath% /v %key% /t REG_EXPAND_SZ /d "%value%" /f ) else ( reg add %regPath% /v %key% /t REG_EXPAND_SZ /d "%oldValue%;%value%" /f ) ''' class WinReg: # 连续运行 bat 命令 def runbat(self, bat): tmp_bat_file = 'tmp.bat' with open(tmp_bat_file, 'w',encoding="utf-8") as f: f.writelines(bat) #print(tmp_bat_file) self.runcmd(tmp_bat_file) # 添加环境变量 def append_env(self, is_sys, key, value): # 运行设置环境变量命令 user = 'sys' if is_sys else 'me' cmds = ADD_ENV.format(user=user, key=key, value=value) #print("cmd: %s" % cmds) self.runbat(cmds) # 设置环境变量 def _set_env(self, is_sys, key, value): user = 'sys' if is_sys else 'me' cmds = SET_ENV.format(user=user, key=key, value=value) self.runbat(cmds) def runcmd(self,file): p = subprocess.Popen(file, shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT) print(p) def append_path(self,path): print("添加") self.append_env(1,"Path",path) winreg = WinReg() winreg.append_path(r"D:\Program Files (x86)\ffmpeg\bin")
很赞哦! (0)
相关文章
文章评论
-
-
-
0条评论