0

I am writing a python script and I want this script to write some value to an environment variable which does not exist before the running of this script. The OS which I am running is Ubuntu. So ideally, after execution of the script, I should be able to display the environment variable using the echo command on the terminal. By that I mean the terminal behaviour should be as such:

> echo $NEW_VAR
environmentvarvalue

I want to be able to access this environment variable in a different python script as well. So the following code:

import os
output = "The value of NEW_VAR is " + os.environ.get('NEW_VAR')
print output

when run after running the initial script, should produce the following output when executed:

The value of NEW_VAR is environmentvarvalue

I have tried the following code in my initial script after a bit of research about this:

import os
os.environ['NEW_VAR'] = 'environmentvarvalue'

but the environment variable gets saved only for the scope of the initial scrpt, and when I run the echo command on the terminal after execution of the script, the behaviour is the same as when the variable does not exist. Is there something wrong with my code? Or is there a better way of assigning an environment variable through python? I know that I can probably run the export command from the subprocess python module, but this does not seem like the right way to solve this problem.

  • It is just for the python session, when you set it in python, if you want to set it permanently, you need something like: https://stackoverflow.com/questions/17657686/is-it-possible-to-set-an-environment-variable-from-python-permanently – user1767754 Nov 23 '17 at 05:52
  • Is there no way of doing it without writing to the .bashrc file? Surely python must have a module which can do this in a cleaner way, right? – Naveen Vijay Nov 23 '17 at 05:55
  • You didn't tell why you want to set the environment variable to be permanent. – user1767754 Nov 23 '17 at 06:13

1 Answers1

0

You can't do this using environment variables. Your environment is destroyed when the script finishes. The parent process (your shell) will never see the variable.

You need a different approach. Possibly writing to a file or a database.

viraptor
  • 33,322
  • 10
  • 107
  • 191