0

The problem is that I'm not able to fetch the variable I set in any way.

I used

    for var in vars:
        os.putenv(str(f"${var}"), local_config[var])
        print(f"{var} has been set")

I've also tried to use os.environ[var] but the result is always empty. I've also tried to remove the $ character.

When I echo the variable in the shell I get nothing, but from inside the script I have both the variable and the value, which proves that the data is ok.

How can I have something like os.environ["LOL"] = "TEST" and have "TEST" back when I echo $LOL? Just to be clear, the shell is the same I run the script into.

Thanks for the help.

1
  • You definitely shouldn't have $ when you call os.putenv(). That's the shell syntax for reading a variable, it's not part of the variable name. Commented Mar 12 at 17:41

1 Answer 1

0

You can use

import os
os.system("SETX ENV-VAR-NAME VALUE")

This will replace any previous value of the environment variable to value, for example:

import os
os.system("SETX LOL TEST")

However this will change(or add) the user env var not the system. to change a system env var youll need to run as administrator and add /m to the end.

import os
os.system("SETX LOL TEST /m")

NOTE: the environment variable change resulting from both these commands will only occur after you reopen the shell

The reason the shell doesn't print the env var when you run the commands one after another is because os creates it's own environment and any subprocesses run from the python script will get the environment variables.

You might want to consider running the shell command from inside the python script if you can.

answer from How do I make environment variable changes stick in Python?

Sign up to request clarification or add additional context in comments.

2 Comments

SETX is Windows. I think the OP is using Unix, since they mention $LOL.
going down the already answered, here is the answer for linux. stackoverflow.com/questions/235435/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.