从 Python 脚本 (Windows) 更改 %PATH% [英] Change %PATH% from Python Script (Windows)

查看:60
本文介绍了从 Python 脚本 (Windows) 更改 %PATH%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为项目的一部分,我需要确保在用户的 %PATH% 变量中包含一些路径,这将在脚本的开头进行.从 python 脚本执行此操作的最佳方法是什么?

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')

添加每个路径,因为这是您从 Windows 命令行执行的操作,尽管我担心重新启动后这些设置不会继续(这似乎是我从 Windows 命令行运行时发生的情况)命令行 - 为了让它坚持下去,我实际上必须通过 GUI 进行更改).

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)

谢谢!

推荐答案

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

...或使用 _winreg.此处另一个问题的示例:如何添加到并从系统的环境变量PATH"中删除?

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

这篇关于从 Python 脚本 (Windows) 更改 %PATH%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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