Setting Environment Variables in Python
Introduction
Environment variables are system-level settings that store configuration values used by applications and operating systems. They allow programs to access important information such as file paths, API keys, database credentials, and system configurations without hardcoding them into the source code.
When working with Python, setting environment variables is an important step because it helps Python locate executables, libraries, and configuration settings. Environment variables are widely used in software development, automation testing, DevOps, and cloud applications.
In this tutorial, you will learn what environment variables are, why they are important, and how to configure them on Windows, macOS, and Linux systems.
What Are Environment Variables?
Environment variables are dynamic values stored by the operating system that can be accessed by applications and scripts during execution.
Examples of common environment variables include:
PATH
HOME
USERNAME
TEMP
JAVA_HOME
PYTHONPATH
These variables help applications determine where files, programs, and configurations are located.
Why Are Environment Variables Important?
Environment variables provide several benefits:
Avoid hardcoding sensitive information
Simplify application configuration
Improve portability across environments
Enable centralized configuration management
Allow programs to locate required files and executables
In Python development and automation testing, environment variables are frequently used to store:
API keys
Database credentials
Application URLs
Browser paths
Test environment settings
Understanding the PATH Variable
The PATH variable is one of the most important environment variables.
It contains a list of directories that the operating system searches when a command is executed.
For example, when you run:
python
the operating system looks through the directories listed in PATH to locate the Python executable.
Without Python being added to PATH, you may receive an error such as:
'python' is not recognized as an internal or external command
What is PYTHONPATH?
PYTHONPATH is an environment variable used by Python to locate additional modules and packages.
When Python starts, it searches for modules in:
Current directory
Standard library directories
Directories specified in PYTHONPATH
This is useful when working with custom modules stored outside the default locations.
Viewing Environment Variables in Windows
To view environment variables in Windows:
Method 1
Open the Start Menu.
Search for “Environment Variables”.
Click Edit the system environment variables.
Click Environment Variables.
You will see:
User Variables
Variables available only to the current user.
System Variables
Variables available to all users on the system.
Viewing Environment Variables Using Command Prompt
Open Command Prompt and run:
set
This displays all currently configured environment variables.
To view a specific variable:
echo %PATH%
Example:
C:\Python313\;C:\Python313\Scripts\
Setting Environment Variables in Windows
Method 1: Using the Environment Variables Window
Step 1
Open:
Environment Variables
Step 2
Select either:
User Variables
System Variables
Step 3
Click:
New
Step 4
Enter:
Variable Name:
MY_VARIABLE
Variable Value:
HelloPython
Step 5
Click:
OK
The variable is now saved.
Verifying the Variable
Open a new Command Prompt window and run:
echo %MY_VARIABLE%
Output:
HelloPython
Adding Python to PATH Manually
Sometimes Python is installed but not added to PATH.
To add Python manually:
Step 1
Locate the Python installation directory.
Example:
C:\Python313\
Step 2
Open Environment Variables.
Step 3
Select:
Path
Step 4
Click:
Edit
Step 5
Add:
C:\Python313\
and
C:\Python313\Scripts\
Step 6
Save the changes.
Step 7
Open Command Prompt and verify:
python --version
Example Output:
Python 3.13.0
Setting Temporary Environment Variables in Windows
You can create variables that exist only for the current Command Prompt session.
Example:
set PROJECT_NAME=PythonTutorial
Verify:
echo %PROJECT_NAME%
Output:
PythonTutorial
Once the Command Prompt window closes, the variable is removed.
Setting Environment Variables in PowerShell
Create a variable:
$env:PROJECT_NAME="PythonTutorial"
Display the value:
$env:PROJECT_NAME
Output:
PythonTutorial
Setting Environment Variables in Linux
Open Terminal and create a temporary variable:
export PROJECT_NAME=PythonTutorial
Verify:
echo $PROJECT_NAME
Output:
PythonTutorial
Creating Permanent Variables in Linux
Open:
~/.bashrc
or
~/.profile
Add:
export PROJECT_NAME=PythonTutorial
Save the file and reload:
source ~/.bashrc
Verify:
echo $PROJECT_NAME
Setting Environment Variables in macOS
Open Terminal and edit:
~/.zshrc
Add:
export PROJECT_NAME=PythonTutorial
Save the file and reload:
source ~/.zshrc
Verify:
echo $PROJECT_NAME
Output:
PythonTutorial
Accessing Environment Variables in Python
Python provides the os module to access environment variables.
Example:
import os
value = os.getenv("PROJECT_NAME")
print(value)
Output:
PythonTutorial
Reading the PATH Variable in Python
Example:
import os
print(os.getenv("PATH"))
This displays all directories stored in the PATH environment variable.
Setting Environment Variables in Python
You can create environment variables during program execution.
Example:
import os
os.environ["PROJECT_NAME"] = "PythonTutorial"
print(os.environ["PROJECT_NAME"])
Output:
PythonTutorial
Note that this variable exists only while the program is running.
Environment Variables in Automation Testing
Environment variables are heavily used in automation testing.
Common examples include:
Application URL
TEST_URL=https://test.example.com
Username
USERNAME=testuser
Password
PASSWORD=SecurePassword
API Key
API_KEY=123456789
Automation frameworks can read these values dynamically instead of hardcoding them.
Advantages of Using Environment Variables
Security
Sensitive information is not stored directly in source code.
Flexibility
Configurations can change without modifying code.
Reusability
The same script can run in multiple environments.
Maintainability
Centralized configuration simplifies updates.
Best Practices
When working with environment variables:
Use meaningful variable names.
Avoid hardcoding passwords.
Store sensitive data securely.
Document required variables.
Separate development and production configurations.
Use environment-specific settings.
Common Mistakes
Forgetting to Restart Terminal
Some changes require reopening the terminal or command prompt.
Typing Errors
Incorrect variable names can cause configuration issues.
Missing PATH Configuration
Python commands may not work if PATH is not configured correctly.
Exposing Sensitive Information
Never store passwords or API keys directly in source code repositories.
Real-World Example
Suppose you have an automation framework that runs against different environments.
Instead of writing:
url = "https://test.example.com"
You can use:
import os
url = os.getenv("TEST_URL")
This allows the same script to run in:
Development
Testing
Staging
Production
without changing the code.
Conclusion
Environment variables play a critical role in Python development and automation testing. They help applications store configuration values securely and make software easier to maintain and deploy across different environments.
Understanding how to create, modify, and access environment variables is an essential skill for Python developers, automation engineers, and DevOps professionals. By using environment variables effectively, you can build more secure, flexible, and scalable applications.
Frequently Asked Questions (FAQs)
What are environment variables?
Environment variables are system-level settings that store configuration values used by applications and operating systems.
Why is PATH important?
The PATH variable helps the operating system locate executable programs such as Python.
What is PYTHONPATH?
PYTHONPATH is an environment variable that tells Python where to look for additional modules and packages.
Can Python read environment variables?
Yes. Python can read environment variables using the os.getenv() function.
Why are environment variables used in automation testing?
They help store configuration values such as URLs, usernames, passwords, and API keys without hardcoding them into scripts.
Key Takeaways
Environment variables store configuration information used by applications.
PATH is the most important variable for locating Python executables.
PYTHONPATH helps Python find custom modules and packages.
Environment variables can be created temporarily or permanently.
Python accesses environment variables using the
osmodule.Automation frameworks commonly use environment variables for configuration management.
Using environment variables improves security, flexibility, and maintainability.
