Environment variables for the current user with Python

6.5k views Asked by At

How can you get a list of the environment variables for the current user ("user variables") using Python?

os.environ() returns the system variables, and changing those requires admin access.

I want to have it change the user variables for PATH, as that can be done without any restrictions.

2

There are 2 answers

0
Serge Ballesta On

That's wrong. os.environ returns the environment of current process. At this level, there is no notion of user or system variables.

You can of course change any of these environment variables. For PATH just do :

os.environ['PATH'] = new_path

But you are only changing the current process environment. That means that this new environment will be used by current process and all its childs, but will vanish at the end of the process.

There is no portable way to modify the environment of the calling shell

Anyway in windows, you can modify the permanent environment variables with the command setx. For example if you want to set on change the user environment variable FOO to bar, you could do in a python script :

import os
os.system("setx FOO bar")

But this change will only be used by processes started from Windows explorer after the command has been executed. In particular neither the environment of the python script nor the one of the calling cmd.exe if any will be changed.

0
Karthik Kallur On

Yes it is possible

import subprocess
raw_path = subprocess.run(["powershell", "-Command","[Environment]::GetEnvironmentVariable('Path','User')"], capture_output=True) 
user_path = raw_path.stdout.decode('ascii').split(';') print(user_path)