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”)

Advertisements

About Divyashree - The GNULINUX Guy

I am a Linux and Opensource enthusiast. I started working on Linux early in 2007 while I was doing my Masters in Computer Science and passed out in 2010. Currently working as a DevOps in in Public/Private cloud domain. my @github : https://github.com/kumarprd my @nagiosexchange : https://exchange.nagios.org/directory/Owner/divyaimca/1 my @linkedin : https://www.linkedin.com/in/priyadarshee-kumar-☁-a9415615
This entry was posted in HOWTO, Programming, TIPS & T RICS and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s