Home > other >  How to run a python script with temporary environment variable
How to run a python script with temporary environment variable

Time:10-02

If I have a python scripts with simple lines as the following:

import os

name = os.environ.get('BEAR_NAME')
if name != "":
  print("hello, ", name)

I'd like to set a temporary environment variable when running this script. Note that if I do

export BEAR_NAME="sleepybear"
python hello.py

the env var BEAR_NAME will still have value sleepybear once the python program finishes, which is not desired. Take docker's example, we can do docker run -e SOME_VAR=SOME_VAL to set the environment variable SOME_VAR. Is there a similar way when running a python script?

CodePudding user response:

Your shell command can be

BEAR_NAME="sleepybear" python hello.py

CodePudding user response:

Something like this?

hello.py

import os

def hello():
    name = os.environ.get('BEAR_NAME', 'defaultbear')
    print('hello,', name)

hello()
os.environ['BEAR_NAME'] = 'sleepybear'
hello()

Sample run

> python hello.py
hello defaultbear
hello sleepybear

> echo            
  • Related