如何添加和删除系统的环境变量“PATH"? [英] How to add to and remove from system's environment variable "PATH"?

查看:29
本文介绍了如何添加和删除系统的环境变量“PATH"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何永久添加系统环境变量PATH"的路径?

How do I permanently add the path to system's environment variable "PATH"?

如果路径不存在,我只想添加它.

I want to only add the path if it does not already exist.

此外,我想删除所有包含文件夹名称的路径,例如 myprogram 是否为:

Also I want to remove all paths that contain a folder name such as myprogram whether it be:

C:path omyprogramdist;D:anotherpath omyprogramdist;

推荐答案

import _winreg as reg
import win32gui
import win32con


# read the value
key = reg.OpenKey(reg.HKEY_CURRENT_USER, 'Environment', 0, reg.KEY_ALL_ACCESS)
# use this if you need to modify the system variable and if you have admin privileges
#key = reg.OpenKey(reg.HKEY_LOCAL_MACHINE, r'SYSTEMCurrentControlSetControlSession ManagerEnvironment', 0, reg.KEY_ALL_ACCESS) 
try
    value, _ = reg.QueryValueEx(key, 'PATH')
except WindowsError:
    # in case the PATH variable is undefined
    value = ''

# modify it
value = ';'.join([s for s in value.split(';') if not r'myprogram' in s])

# write it back
reg.SetValueEx(key, 'PATH', 0, reg.REG_EXPAND_SZ, value)
reg.CloseKey(key)

# notify the system about the changes
win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')

这篇关于如何添加和删除系统的环境变量“PATH"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆