0

I need to create an environment variable in python that will out last the life of the process creating it preferably in a non os-dependent way i.e if I ran : create_env_var.py (example non active code )

#/my/path/create_env_var.py
import module_that_fixes_my_problem as easy_fix
easy_fix.create_environment_variable(name_of_var = "ENV_VAR",value_of_var="this was easy")

and then ran read_env_var.py

#/my/path/read_env_var.py
import module_that_fixes_my_problem as easy_fix
my_var = easy_fix.read_environment_variable(name_of_var = "ENV_VAR")
print(my_var) # "this was easy"

I have tried doing this using os.environ like this :

os.environ['ENV_VAR'] = "this was easy"

but on a Windows machine I couldn't create a lasting environment var and on a Linux machine it would not last outside of the life of the process as described here :

os.environ not setting environment variables

https://bugs.python.org/issue16633

amos-baron
  • 87
  • 5
  • 2
    If you need to persist that value why not to do it differently, e.g., store it in a database or a file? – dcg Mar 30 '20 at 13:16
  • @dcg this is a great question, one that I asked myself. but after all the people above me with more experience in the team decided that for now we will use env variables – amos-baron Mar 30 '20 at 13:17
  • Well, I don't think your code is going to be OS agnostic no more. My guess. – dcg Mar 30 '20 at 13:21
  • @dcg do you have an theist code suggestion then ? – amos-baron Mar 30 '20 at 13:39
  • Unfortunely I don't have any. I said that 'cause I guess any OS would have its own way to do it unless you find some module that abstract that from you – dcg Mar 30 '20 at 13:44
  • That's not how environment variables work. The variables are part of *the process'* environment, and will die with it. You can only influence the environment of *new* child processes, but these should die with their parent. If you want to [change the variables of the parent process](https://unix.stackexchange.com/questions/38205/change-environment-of-a-running-process), that's not OS agnostic. – MisterMiyagi Mar 30 '20 at 13:44
  • As @MisterMiyagi said, environment variables are for your process and any new child processes. The only way I can think is by writing to the OS list of default env variables, so dependent greatly on the OS and a really odd way to do it. I'd reconsider environment variables for your problem - they are not the solution you are looking for. – Michael Baldry Mar 30 '20 at 22:33

0 Answers0