In this post, I’ll show you how to create an environment variable so that you don’t have to write your passwords directly into your code. This will keep your passwords safe and prevent you from accidentally sharing your credentials with others.
Your Bash Profile
Your bash_profile
is found in the Terminal and contains preferences for your Terminal interface among other things. This is where your passwords, usernames, and other credentials will be secured stored.
Accessing Your Bash Profile
To access your bash_profile
, launch your Terminal and run this command:
nano .bash_profile
This will launch a new Terminal view. I store my passwords right at the top and press Enter a few times to make space for them. The format to use looks like this:
export user_name=“paul”
export password=“hello123”
Export is the function to set up the environment variable. What comes after export is the variable name. In my example above, password
is what I can use to retrieve what comes after the equal sign. Here are some things to keep in mind:
- Do not put spaces around the equal sign
- Use double quotes
Once you have entered passwords and or usernames, follow these shortcuts to save your changes:
- Control + X key
- Y key (to save changes)
- Enter key
Retrieve your Passwords in Python
Here is some example code you can use to retrieve the environment variable and pass it into your Python code.
import os
password = os.environ.get('password')
print(password)
Summary
Creating environmental variables in your bash_profile
is a more secure way of writing your Python code. Now when you share your code, you don’t have to worry about accidentally sharing your credentials.