Changing environment variables from Python script

I wrote a script that checks dirs from Path and removes unreachable dirs. Also I used snippet to run my script as administrator. But when I check my Path after executing the script - it's all the same.

import os
import sys
import win32com.shell.shell as shell

if __name__ == "__main__":

    if os.name != 'nt':
        raise RuntimeError("This script is implemented only for Windows")

    ASADMIN = 'asadmin'

    if sys.argv[-1] != ASADMIN:
        script = os.path.abspath(sys.argv[0])
        params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
        shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
        print("I am root now")

    paths = os.environ.get('Path').split(';')
    accessible_paths = []
    for path in paths:
        if os.access(path, os.R_OK):
            accessible_paths.append(path)

    new_path = ';'.join(accessible_paths)
    os.environ['Path'] = new_path

    print(new_path)
    print(new_path == os.environ['Path'])

      

So how can I change my environment variable using a Python script?

+3


source to share


1 answer


According to the documentation , setting environment variables the way you do it calls os.putenv()

, but the description of this function is unclear. Indeed, the following is said:

Such changes to the environment affect subprocesses starting with os.system (), popen () or fork (), and execv ().



So I'm not sure what is os.environ

meant to do what you expect. This is somewhat corroborated by the next question , where the answer only indicates that this change will affect child processes ...

0


source







All Articles