Here is how to store Python passwords securely on Windows, Mac, and Linux in Python.


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.



Output

 


Explanation

 


Related HowTos
Extract extension from filename
Print to stderr in Python
Generate random integers between 0 and 9
Use a pythonic way to create a long multi-line string
Measure elapsed time in Python
Install specific package versions with pip
Read from stdin (standard input)
Get the class name of an instance
Check if a string is empty
Pad zeroes to a string
Delete an element from a dictionary
Check if a string is a float
Count the occurrences of an item in a list
Remove an element from a list by index
Use static methods
Remove a trailing newline
Print literal curly-brace characters in a string and also use .format on it
Exit/deactivate a virtualenv
Determine the type of an object
Limit floats to two decimal points
Know if an object has an attribute
Select an item from a list randomly
Read a file line-by-line into a list
Call a function of a module by using its name
Get the number of elements in a list
Print without a newline or space
Sort a list of dictionaries by a value of the dictionary
Remove a key from dictionary
Rename column names with Pandas
Lowercase a string
Upgrade all Python packages with pip
Get a substring of a string
Get the last element of a list
Parse a string to a float or integer
Convert a string into datetime format
Access environment variable values
Print coloured text on the terminal
Find current directory of a file
Change the size of figures drawn with Matplotlib
Manually raise an exception
Delete a file or folder
Split a list into evenly sized parts
Select rows from a DataFrame based on column values with Pandas
Install pip on Windows
Check if a given key already exists in a dictionary
Iterate over rows in a DataFrame for Pandas
Make function decorators and chain them together
Pass a variable by reference
Make a time delay
Convert bytes to a string
Copy a file
Concatenate two lists
Add new keys to a dictionary
Catch multiple exceptions in a single 'except' block
Check if a list is empty
Get the current time
Sort a dictionary by value
Use global variables in a function
List all files of a directory
Iterate over dictionaries using for loops
Check if a string contains a substring
Find the index of an item in a list
Understand how slice notation works
Make a flat list out of a list of lists
Accesses the index in for loops
Safely create a nested directory
Merge two dictionaries in a single expression
Check whether a file exists without exceptions
Convert a dictionary into a list
Convert a list into a dictionary
Duplicate a file
Append text in a text file
Use for loops
Deploy a web app to Heroku
Schedule a Python script for execution at a specific time every day
Do dictionary comprehension
Do list comprehension
Create a virtual environment
Create a new file
Merge two lists
Extract items from two different lists into one list
Check if a text file is empty
Randomly select an item from a list
Generate a random integer
Break a while loop
Create a pandas DataFrame from a dictionary
Create a pandas DataFrame from a list
Get the last item of a list
Delete a column from a pandas dataframe
Access a column of a pandas dataframe
Create a class
Make a webpage request
Get the first two characters of a string
Loop through two lists at the same time
Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.


Subscribe to be the first to know when a new Python course is released.