1

In terminal (bash) on OSX I can set an environment variable, using the syntax export VARNAME=1 or export VARNAME="hello"; and that persist as long as the session is running, or until the terminal window is closed.

What would be the equivalent form, to do the same via Python3? I would like to avoid to call Popen just to set a global variable.

Also I need this variable only for the purpose to run my python code; once the script is done, I do not need it anymore; so even if it last only for the lifespan of my script running, it is acceptable.

  • 1
    Do you understand that if you set an environment variable in your program, it only applies to your program and its child processes, and *not* to the shell that called your program? – hobbs Dec 13 '17 at 22:51
  • 1
    If you were to write a bash script that _exports_ a variable, the calling terminal would still not get it. It applies only to the current environment and any other shell environment spawned from the current environment. Once you exit your script, be it Bash or Python, all the changes to the environment are gone. The best you can do is update permanent env. variable setting facilities (profile scripts and such) and ask the user politely to re-source them or to restart their Terminal. – zwer Dec 13 '17 at 22:53
  • I see; so how should I act, to be sure that the env variable is present, when I run the python script? As now I am calling Popen exporting the variable, when I run the python code. I do not need to have the variable set all the time; I just need it when the python code is running. –  Dec 13 '17 at 23:09
  • 1
    @rataplan, if that's what you need, just put it in `os.environ`. – Charles Duffy Dec 13 '17 at 23:12
  • Thanks @CharlesDuffy! So that will be the equivalent for Python; trying it now –  Dec 13 '17 at 23:14

0 Answers0