欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

自己亲自做的 用 python 来实现 添加 anaconda 3 anaconda3 的环境变量 有大用 有大大用 有大大大用

import os
import winreg
import ctypes


def read_environment_variable():
    # 获取当前的 PATH 环境变量
    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 0,
                        winreg.KEY_READ) as key:
        current_path, _ = winreg.QueryValueEx(key, 'Path')
    return current_path


def update_system_path(new_paths):
    # 打开注册表以更新
    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 0,
                        winreg.KEY_SET_VALUE) as key:
        current_path = read_environment_variable()

        # 检查路径是否已存在
        if 'C:\\ProgramData\\Anaconda3' not in current_path:
            # 添加新的路径
            if not current_path.endswith(';'):
                current_path += ';'
            new_path = current_path + new_paths

            # 更新 PATH 环境变量
            winreg.SetValueEx(key, 'Path', 0, winreg.REG_EXPAND_SZ, new_path)

            # 触发环境变量变更
            ctypes.windll.user32.SendMessageW(0xffff, 0x1A, 0, None)

            # 提示用户重启电脑
            ctypes.windll.user32.MessageBoxW(0, "请重启电脑以使更改生效!", "提示", 0)
        else:
            ctypes.windll.user32.MessageBoxW(0, "环境变量中已经有了anaconda!", "提示", 0)



if __name__ == "__main__":
    # 设置要添加的路径
    new_paths = r"C:\ProgramData\Anaconda3;C:\ProgramData\Anaconda3\Scripts;C:\ProgramData\Anaconda3\Library\mingw-w64\bin;C:\ProgramData\Anaconda3\Library\usr\bin;C:\ProgramData\Anaconda3\Library\bin"

    # 更新 PATH
    update_system_path(new_paths)



代码说明

  1. winreg 模块:用于读取和写入 Windows 注册表,这里用它来访问和修改系统的环境变量。

  2. ctypes 模块:用于调用 Windows API,以触发系统环境变量的更新。

  3. 检查和更新 PATH:首先获取当前的 PATH,然后检查我们要添加的路径是否已经存在于中。如果不存在,则将新路径添加到现有的 PATH 中。

  4. 权限问题:需要以管理员权限运行这个 Python 脚本,因为它修改系统环境变量。

运行代码

  1. 确保安装 Python(版本 3.x)。

  2. 将代码保存为 .py 文件,例如 update_path.py

  3. 以管理员权限运行该 Python 文件。

确保在对系统环境变量进行更改时,知道您正在做什么,并且可以安全地恢复调整。



普通分类: