Set & Get environment variables in python

In bash generally we export environment variables like :

export VARIABLE=value

In some cases in our we need to set some environment variables inside our python programme to use it further.

But in Python, the if we try to use the system call to set the variable it never works :

e.g.

import os

os.system(‘export VARIABLE=value’)

It never works as, the python is the child process of bash and it cant change the env variable of Parent bash.

So here we have to use:

import os

os.environ[‘VARIABLE’] = “value”

To get the values of any environment variable :

import os

value=os.getenv(“VARIABLE”)

Leave a Reply