简体   繁体   English

如何使用 Python 将文件夹添加到 Windows PATH?

[英]How to add a folder to the Windows PATH with Python?

I want to add a folder to the Windows PATH environment variable with Python.我想用 Python 在 Windows PATH 环境变量中添加一个文件夹。 I tried these three code snippets but none worked:我尝试了这三个代码片段,但都没有奏效:

os.environ['PATH'] += ";C:\my\folder"

and

sys.path.insert(0, os.path.abspath('C:\my\folder'))

and

if sys.platform == 'win32':
    sep = ';'
else:
    sep = ':'

os.environ['PATH'] += sep + r'"C:\my\folder"'

The Windows command for permanently changing the path is 用于永久更改路径的Windows命令是

setx /M path "%path%;C:\my\folder"

You can execute arbitrary shell commands via Python with os.system 您可以使用os.system通过Python执行任意的shell命令

import os
os.system('setx /M path "%path%;C:\my\folder"')

Note: 注意:

You need to run this with elevated privileges. 您需要使用提升的特权来运行它。

References: 参考文献:

你应该使用:

os.environ['PATH'] += R";C:\\my\\folder"

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

相关问题 如何使用Python将文件夹临时添加到Windows PATH? - How to add a folder to the Windows PATH temporarily with Python? 如何将文件夹添加到 Python 路径? - How to add a folder to Python path? (Python,Windows)如何在不进入高级设置的情况下将新文件夹添加到 PATH? 从命令行? - (Python, Windows) How to add a new folder to PATH without going to advanced settings? From command line? 一次为Python库路径添加一个文件夹(Windows) - Add a folder to the Python library path, once for all (Windows) 如何使用python3将路径中的文件夹移动到Windows中的另一个路径? - How to move folder in a path to another path in windows using python3? 将 Python 添加到 Windows 路径 - Add Python to the Windows path 如何使用 python 添加 windows 系统路径? - how to add windows system path with python? 如何在 Windows 10 中为 python 添加 os.environ[“PATH”] 的路径? - How to add path to os.environ[“PATH”] for python in Windows 10? 将脚本的工作文件夹添加到Windows上的Python导入()路径的最佳方法? - Best way to add script's working folder to import() path for Python on Windows? 在python中如何添加到Windows路径变量以查找可执行文件 - in python How to add to the windows path variable to find executables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM