D
D
Dmitry Temnikov2019-09-05 00:19:59
Python
Dmitry Temnikov, 2019-09-05 00:19:59

How to edit Windows system variables or current user variables in python?

At first it might seem like this:

os.environ['DEBUG']='FALSE'
os.environ.get('DEBUG')
del os.environ.get('DEBUG')

But if you look closely, you can understand that these are all the same Python environment variables. Since through the "Control Panel" --> "System Properties" --> "Environment Variables" they are not visible. So how do you get access to system variables or user variables?
Note: what I want to do is run a script (conditionally test.py), which has CLI commands like:
python test.py --no-debug initdb
python test.py --debug initd

And then the input of the keys "--debug" and "--no-debug" should not be entered according to the terms of reference. It should pick up with a variable.
The CLI itself is something like this (pieces with a variable)
if "DEBUG" not in os.environ:
    os.environ["DEBUG"] = "FALSE"
    print('debug mode is off')
def logging(s):
    if s=='FALSE': return False
    if s=='TRUE': return True

@click.group()
@click.option('--no-debug', is_flag=True)
@click.option('--debug', is_flag=True)
def main(no_debug, debug):
    if no_debug: 
        os.environ["DEBUG"] = "FALSE"
        print('debug mode is off')
    if debug: 
        os.environ["DEBUG"] = "TRUE"
        print('debug mode is on')

@click.command()
@click.option('--name')
def initdb(name):
---------------------------------
    if logging(os.environ.get('DEBUG')): 
        log.write(f'initialization {name} database....\n')

@click.command()
@click.option('--name')
def dropdb(name):
---------------------------------
    if logging(os.environ.get('DEBUG')): 
        log.write(f'dropping {name} database....\n')

But apparently, since the interpreter is restarted for each session, its variables are lost, which is why system variables are needed.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Temnikov, 2019-09-05
@exibit777

The question actually was how to create and edit environment variables at the user or system level at the process level?
update Found the answer myself. Environment variables are keys in the registry:
System variables HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment
Current user variables HKEY_CURRENT_USER\Environment
Example:

key=winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Environment")
winreg.SetValueEx(key, "DEBUG", 0, winreg.REG_SZ, "FALSE")

S
Sergey Gornostaev, 2019-09-05
@sergey-gornostaev

Environment variables have hierarchical scopes:

Система
  Пользователь
    Сеанс
       Процесс

Variables set in parent scopes are visible to child scopes, but not vice versa. In particular, if a process sets an environment variable, it will only have the value set for that process.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question