python -- add environment variables to windows

Method 1 (temporary addition)

import os

# 获取当前用户的环境变量
user_env = os.environ['USERPROFILE'] + '\\AppData\\Roaming\\Python\\Python39\\Scripts'

# 将路径添加到环境变量中
os.environ['PATH'] += ';' + user_env
```

In the above example, we first get the current user's environment variables, and then add the path to the environment variables. Please note that this will only add the environment variable in the current Python process, if you want to add the environment variable permanently, you need to manually add it to the Windows system environment variables.

Method 2 (permanently added)

import winreg
import os

# 获取当前用户的环境变量
user_env = os.environ['USERPROFILE'] + '\\AppData\\Roaming\\Python\\Python39\\Scripts'

# 打开Windows注册表
reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)

# 打开环境变量键
key = winreg.OpenKey(reg, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 0, winreg.KEY_ALL_ACCESS)

# 获取当前环境变量值
value, type = winreg.QueryValueEx(key, 'Path')

# 将路径添加到环境变量中
if user_env not in value:
value += ';' + user_env

# 更新环境变量值
winreg.SetValueEx(key, 'Path', 0, type, value)

# 关闭键和注册表
winreg.CloseKey(key)
winreg.CloseKey(reg)

In the above example, we first get the current user's environment variables, then open the Windows registry and open the environment variables key. Next, we get the current environment variable value and add the path to the environment variable. Finally, we update the environment variable values ​​and close the keys and registry.

Note that this will permanently change Windows system environment variables, so use with caution.

Method 3 (permanently added)

import win32api
import win32con
import os

# 获取当前用户的环境变量
user_env = os.environ['USERPROFILE'] + '\\AppData\\Roaming\\Python\\Python39\\Scripts'

# 打开环境变量键
key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', 0, win32con.KEY_ALL_ACCESS)

# 获取当前环境变量值
value, type = win32api.RegQueryValueEx(key, 'Path')

# 将路径添加到环境变量中
if user_env not in value:
value += ';' + user_env

# 更新环境变量值
win32api.RegSetValueEx(key, 'Path', 0, type, value)

# 关闭键
win32api.RegCloseKey(key)

In the above example, we first get the current user's environment variables, and then open the environment variable key. Next, we get the current environment variable value and add the path to the environment variable. Finally, we update the environment variable value and close the key.

Note that this will also permanently change Windows system environment variables, so use with caution.

Guess you like

Origin blog.csdn.net/weixin_44634704/article/details/130979781