在Windows中通过Python添加到路径

在Windows中通过Python添加到路径,python,path,Python,Path,我想通过python脚本将GeckoDriver exe添加到PATH环境变量中,我在StackOverflow上找到了答案,但这对我不起作用。我的代码显示路径已添加,但当我签入cmd或通过系统设置时,路径不存在: cwd = os.getcwd()+"\\driver\\" if 'geckodriver' not in os.environ: print("Added") os.environ["Path"] = cwd 提供的代码将更新当前shell及其子对象的环境变量

我想通过python脚本将GeckoDriver exe添加到
PATH
环境变量中,我在StackOverflow上找到了答案,但这对我不起作用。我的代码显示路径已添加,但当我签入
cmd
或通过系统设置时,路径不存在:

cwd = os.getcwd()+"\\driver\\"

if 'geckodriver' not in os.environ:
    print("Added")
    os.environ["Path"] = cwd

提供的代码将更新当前shell及其子对象的环境变量。它不会传播到设置系统级设置


更糟糕的是,这不容易做到。您必须这样做,或者可以使用命令行工具。从Python来看,两者都不是特别友好的,而且都有缺点。

给出的代码将更新当前shell及其子对象的环境变量。它不会传播到设置系统级设置


更糟糕的是,这不容易做到。您必须这样做,或者可以使用命令行工具。从Python来看,两者都不是特别友好的,而且都有缺点。

您需要运行
setx
命令在Windows下设置永久环境变量。要从Python运行
setx
,请尝试以下代码:

from subprocess import check_output

cwd = os.getcwd()+"\\driver\\"

if 'geckodriver' not in os.environ:
    print("Added")
    check_output(f'setx Path "{cwd}"', shell=True)

您需要运行
setx
命令来设置Windows下的永久环境变量。要从Python运行
setx
,请尝试以下代码:

from subprocess import check_output

cwd = os.getcwd()+"\\driver\\"

if 'geckodriver' not in os.environ:
    print("Added")
    check_output(f'setx Path "{cwd}"', shell=True)