简体   繁体   English

如何使用 Python 将项目添加到 PATH 用户环境变量

[英]How to add items to the PATH User Environment Variable Using Python

I'm working on some software written in Python 3.10 and it needs to be added to PATH in the User's Environment Variables and in the future it might have to add other things to it as well.我正在开发一些用 Python 3.10 编写的软件,它需要添加到用户环境变量中的 PATH 中,并且将来它可能还需要添加其他内容。

I want the software to do it on it's own so that the User (who might not already know how to do it) doesn't have to do it themselves.我希望软件自己做,这样用户(可能还不知道怎么做)就不必自己做。

I know its possible because there are some installers that I've used to download apps that have an 'Add bin to PATH' button that you can check and it does it on its own.我知道这是可能的,因为我曾经使用一些安装程序来下载具有“将 bin 添加到 PATH”按钮的应用程序,您可以检查该按钮,它会自行完成。

How would I implement this using Python?我将如何使用 Python 实现这一点?

If you're referring to User Environment that doesn't persist beyond current script session, you can use os.environ() .如果您指的是在当前脚本 session 之后不会持续存在的用户环境,则可以使用os.environ() For example:例如:

import os

mypath = os.environ['PATH'].split(os.pathsep)
mypath = {*mypath, '/new/path1', '/new/path2'}
# you can remove some dirs from mypath too

os.environ['PATH'] = os.pathsep.join(mypath)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM