Environmental Variables in Python

igmrrf

Richard Francis

Posted on July 19, 2020

Environmental Variables in Python

Environmental Variables in Python

Before we begin let's look at our little vocabulary

ENV = Environmental Variable

ENVs = Environmental Variables
Enter fullscreen mode Exit fullscreen mode

Haven't really built any major project with Python except writing scripts or solving simple Algorithms. Today I was making changes to my Facebook_autopost_bot when I realized am gonna need to set this up to enable others use the code and also share it openly on Github without letting out my passwords and configurations.

Maybe you're already using ENVs in your Python scripts or applications, but if your haven't started then now is a good time to consider a change. I believe prior to you readint his, you already know what an ENV is so no need to make this post longer.
NOTE: ENVs exist outside of your code as part of your server environment— can help you by both streamlining and making more secure the process of running your scripts and applications. Automation and Security are the major reasons for adopting ENVs

Let's Start

In Python environment variables are implemented using the os package.

Sample Code:

import os

print(environ)
Enter fullscreen mode Exit fullscreen mode

Result: Will show you all the ENVs existing on your machine(object containing a lot of information about your machine, os, services etc.)

Note: This is an edited (shortened) output for the purpose of the blog post length.

>>> environ({'SHELL': '/bin/bash', 'LSCOLORS': 'ExFxBxDxCxegedabagacad', 'SESSION_MANAGER': 'local/igmrrf:@/tmp/.ICE-unix/2554,unix/igmrrf:/tmp/.ICE-unix/2554', 'QT_ACCESSIBILITY': '1', 'APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL': 'true', 'LANGUAGE': 'en_NG:en', 'QT4_IM_MODULE': 'ibus', 'GNOME_SHELL_SESSION_MODE': 'ubuntu', 'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh', 'XMODIFIERS': '@im=ibus', 'DESKTOP_SESSION': 'ubuntu', 'SSH_AGENT_PID': '2467', 'NO_AT_BRIDGE': '1', 'GTK_MODULES': 'gail:atk-bridge', 'DBUS_STARTER_BUS_TYPE': 'session', 'PWD': '/home/igmrrf/Desktop/Writings/ENVs in Python',   'TERM_PROGRAM': 'vscode', '_': '/usr/bin/python3'})
Enter fullscreen mode Exit fullscreen mode

COMMANDS for Reading and Writing environment variables:

READING

os.environ.get('USER')
os.environ['User']
os.getenv('USER')

>>> igmrrf
>>> igmrrf
>>> igmrrf
Enter fullscreen mode Exit fullscreen mode

The commands will print out your current username

Note: If there no environment variable matching the key, it'll return None

WRITING

To change an ENV

os.environ['USER'] = 'tldo'
Enter fullscreen mode Exit fullscreen mode
os.environ['USER']

>>>tldo
Enter fullscreen mode Exit fullscreen mode

To Clear an ENV

os.environ.pop('USER')
Enter fullscreen mode Exit fullscreen mode

When trying to access that ENV, you'll get None

os.environ.get('USER')

>>> None
Enter fullscreen mode Exit fullscreen mode

To Clear All ENV

os.environ.clear()
Enter fullscreen mode Exit fullscreen mode

When trying to access any ENV, you'll get KeyError

os.environ.get('USER')

>>> KeyError: key does not exist.
Enter fullscreen mode Exit fullscreen mode

NOTE: I was scared at first about this clear function but don't worry, the settings you apply in your python projects and scripts don't affect other projects outside that specific process or affect machine wide ENVs.If you wish to affect a machine wide change on your machine you'll need to run these commands from bash with sudo priviledges

Using ENVs

In order to use these variables as we keep on building scripts and as programmers and developers, effeciency, speed and optimization is a major criteria, we need to assign the function of handling these variables to an external file.

A package that does this effortlessly is python-decouple

Open your terminal & Run

pip install python-decouple
Enter fullscreen mode Exit fullscreen mode

if your use Linux ubuntu and install python using sudo apt install python3 then run

pip3 install python-decouple
Enter fullscreen mode Exit fullscreen mode

A useful package for handling ENVs locally instead of us acccessing our os(import os) and manipulating which is a bit complex 😉

If you've already got it installed, you'll get

Requirement already satisfied: python-decouple in /home/your_name/.local/lib/python3.8/site-packages (3.3)
Enter fullscreen mode Exit fullscreen mode

else it will be installed in few seconds

Using Python-decouple

Let's get started by creating and opening our .env file at the root of your project

$ touch .env
$ code .env
Enter fullscreen mode Exit fullscreen mode

Note: code is a command that comes with VsCode. Only run it if you have VsCode install and configured correctly on your machine

Then configure the file as follows

username=igmrrf
PASSWORD=12345
URL=https://api.igmrrf.com
Enter fullscreen mode Exit fullscreen mode

Then import Python-decouple in Your Python script where you need these variables

from decouple import config

print(config('URL'))
print(config('USERNAME'))

>>> your_api_endpoint
>>> igmrrf
Enter fullscreen mode Exit fullscreen mode

Wasn't that easy? 😄

Python provides a package for almost everything, that's one of the reasons Python is so popular and getting more recognition.

If you've got a second, either tweet about this or go check out a python package 😉

💖 💪 🙅 🚩
igmrrf
Richard Francis

Posted on July 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related