KKO
KKO

Reputation: 1933

Environment variables for the current user with Python

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.

Upvotes: 1

Views: 7358

Answers (3)

Abdelrahman Mahmoud
Abdelrahman Mahmoud

Reputation: 1

this will add environment variables to the system as shown enter image description here

import winreg as reg
import ctypes

# Define the registry key and the variable you want to set
key = reg.HKEY_LOCAL_MACHINE
sub_key = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
variable_name = "abdo"
variable_value = "1"

# Open the registry key
with reg.OpenKey(key, sub_key, 0, reg.KEY_SET_VALUE) as registry_key:
    # Set the new environment variable
    reg.SetValueEx(registry_key, variable_name, 0, reg.REG_SZ, 
    variable_value)

# Notify the system that the environment has changed
# This causes the system to reload the environment variables
ctypes.windll.user32.SendMessageW(0xFFFF, 0x1A, 0, 0)

print(f"Environment variable '{variable_name}' set to 
'{variable_value}'.")

Upvotes: 0

Karthik Kallur
Karthik Kallur

Reputation: 1

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)

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148965

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.

Upvotes: 3

Related Questions