If you're making a program (e.g., an email sender) that needs to use sensitive data such as username and passwords, you might be tempted to store those credentials as strings in your Python .py files. That is a bad idea because Python files may be moved around in GitHub accounts and other places, and the credentials will be visible to anyone. You should store them in environment variables instead. Here is how to do it.
On Windows:
1. Create an environment variable with the following steps:
- Search for cmd on the Windows Start menu, right-click over the Command Prompt program and go to Run as Administrator to have administrator access. Then execute the following to create the user_name environment variable with username [email protected]:
setx email [email protected] /M
setx password my_strong_password /M
Close Command Prompt (important). Note that an even more secure method would be to set the environment variables using the Windows graphical interface and set the variables at the user's level. That way, the variables are only available for your specific Windows user account.
2. Now, you can fetch the values of the email and password variables from your Python script with:
import os
my_email = os.getenv('email')
my_password = os.getenv('password')
print(my_email, my_password)
As you see above, we are using os.get_env() to get the value of the email and password environment variables which are securely stored in the computer environment. The code above will output [email protected] and my_strong_password.
On Mac and Linux:
1. Create an environment variable with the following steps:
Open Terminal and run:
touch ~/.zshrc; open ~/.zshrc
A text editor should open a .zshrc file. Insert the following in the file:
export email="[email protected]"
export password="my_strong_password"
Save and close the text editor. Close Terminal (important).
2. Now, you can fetch the values of the email and password variables from your Python script with:
import os
my_email = os.getenv('email')
my_password = os.getenv('password')
print(my_email, my_password)
As you see above, we are using os.get_env() to get the value of the email and password environment variables which are securely stored in the computer environment. The code above will output [email protected] and my_strong_password.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.