How to use bash Environment Variables in Python - part 2

Getting the environment variables - part 2

There are times when you need to work with a specific bash environment variable and you will want to know the current value for that environment variables in your session. There are several ways to get it, with the help of os.environ package.

First, as you would get the value from a dictionary - the name of the environment variable is the key of the dictionary, and the result is the value.

If the key is not present, it will raise a KeyError.

print (environ['PATH'])
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin:/usr/lib/jvm/default-java/bin:/root/Android/Sdk/tools:/root/Android/Sdk/platform-tools

Next, you can use the get() method of os.environ package.

Using get() will return `None` if a key is not present rather than raise a KeyError.

print (environ.get('WRONG_PATH'))

You can use the getenv() method from os package.

os.getenv is almost equivalent to os.environ.get(), but it can also give a default value instead of None, in the case of the key not being present.

import os
print (os.getenv('WRONG_PATH', default_value))

You can check if a bash environment variable exists in your current session:

# You can check if a key exists. The statement returns True or False
"HOME" in os.environ

You can also use the following statement, but in my opinion, the previous one is more readable:

os.environ.get('HOME') is None

You can store the value of the environment variables in python variables, for later use inside your scripts:

working_dir = os.environ['PWD']
print ("Your current working directory is: %s"%working_dir)

Other articles:

How to use bash Environment Variables in Python - part 1

How to use bash Environment Variables in Python - part 3

Linux Bash shell variables

Linux Bash shell variables - Local Variables

Linux Bash shell variables - Environment Variables

How to create Linux Bash shell variables

How to remove Linux Bash shell variables