3

I wrote script that checks dirs from Path and remove inaccessible dirs. Also i used snippet to run my script as admin. But when i check my Path after script execution - 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 actually change environment variable by Python script ?

sharl
  • 1,257
  • 1
  • 12
  • 17
  • The initial system environment variables are loaded by the session manager (smss.exe) from the registry key `HKLM\System\CurrentControlSet\Control\Session Manager\Environment`. winlogon.exe also merges a per-user `PATH` that's loaded from the user's `HKCU\Environment` key. – Eryk Sun Jan 19 '15 at 08:24

1 Answers1

0

According to documentation, setting environment variables the way you do it calls os.putenv(), but description of this function is not clear. Indeed, it is said the following:

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

So I'm not sure that os.environ is designed to do what you expect. This is somewhat confirmed by the following question, where answer only indicates that child processes will be affected by this change...

Community
  • 1
  • 1
Joël
  • 2,723
  • 18
  • 36