简体   繁体   中英

Adding to PATH via Python in Windows

I want to add GeckoDriver exe to PATH environment variable via a python script, I found an answer on StackOverflow but this didn't work for me. My code says the path was added, but when I check in cmd or through the system settings, it isn't there:

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

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

The presented code will update the environment variable for the current shell and its children. It won't propagate up to setting the system-level settings.

The worse news, is that this can't be done easily. You either have to edit the registry , or you may be able to use setx command line tool. Neither are particularly friendly from Python, and both have downsides.

You need to run setx command to set permanent environmental variable under Windows. To run setx from Python, try this code:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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