Change %PATH% from Python Script (Windows)

我的未来我决定 提交于 2020-05-14 10:17:06

问题


As part of a project, I need to ensure that a few paths are included in the user's %PATH% variable, which I am going to do at the beginning of the script. What's the best way to do this from a python script?

My first thought was to just use something like the following:

subprocess.call('path = %PATH%;c:\path1;c:\path2;c:\path3')

To add each of the paths, as this is how you would do it from the Windows command line, though my fear is that after a reboot these settings would not carry over (this is what seems to happen when I run it from the command line regularly - in order for it to stick, I actually have to go in through the GUI and change it).

Anyone have a better idea, or will this work as I'd like it to? (Ideally, the user will only have to execute this portion of the script once, at which point the 'setup' will be complete and not need to be run again)

Thanks!


回答1:


path = os.environ.get('PATH')
subprocess.call('setx /M PATH "' + path + ';c:\path1;c:\path2;c:\path3"')

...or use _winreg. Example from another question here: How to add to and remove from system's environment variable "PATH"?



来源:https://stackoverflow.com/questions/28951885/change-path-from-python-script-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!