如何编写一个python程序,将目录添加到环境变量中?

t2a7ltrp  于 2023-11-15  发布在  Python
关注(0)|答案(1)|浏览(95)

假设我有一个路径,例如“c:\driver\chromedriver”我怎么能写一个python脚本,可以将此路径添加到“编辑系统环境变量”我尝试了我从chatgbt得到的这段代码,但不幸的是,它没有改变任何东西(我尝试作为管理员的程序,并收到了同样的问题)

import subprocess

# Directory path to be added to the system PATH
directory_to_add = "C:\\driver"

# Command to add the directory to the system PATH using setx command
command = f'setx PATH "%PATH%;{directory_to_add}"'

try:
    # Execute the command using subprocess with shell=True to run in a shell environment
    subprocess.run(command, shell=True, check=True)
    print(f"Directory '{directory_to_add}' added to the system PATH.")
except subprocess.CalledProcessError as e:
    print(f"Failed to add directory to PATH: {e}")

字符串
输出:

WARNING: The data being saved is truncated to 1024 characters.

SUCCESS: Specified value was saved.
Directory 'C:\driver' added to the system PATH.

Process finished with exit code 0

vsmadaxz

vsmadaxz1#

命令“setx”的限制是1024个字符,也许你可以在这篇文章SETX doesn't append path to system path variable上找到更多信息

相关问题