Skip to the content.

Using Environment Variables in your Code

-

Introduction

-

Environment variables

Environment variables…

-

Setting environment variables:

There are a few ways to set an environent variable:

#list of environment variables
DB_URL=jdbc:mysql://localhost:3306/mydatabase
DB_USER=mydbuser
DB_PASSWORD=GimmeTheData2030

-

Using environment variables in Java:

public class AccessEnvironementVars {
    public static void main(String[] args) {
        String dbUrl = System.getenv("DB_URL");
        
        if (dbUrl != null) {
            System.out.println("Database URL: " + dbUrl);
        } else {
            System.out.println("Environment variable DB_URL not found.");
        }
    }
}

-

Using environment variables in Python:

To use environment variables in Python, you can leverage the os module:

Accessing an environment variable:

import os
# Get the value of the environment variable named 'MY_VARIABLE'
my_var = os.environ.get('MY_VARIABLE')

if my_var:
    print(my_var)
else:
    print("Environment variable 'MY_VARIABLE' not found.")

Output:

Environment variable 'MY_VARIABLE' not found.

-

Setting an environment variable:

import os

# Set the value of the environment variable 'MY_VARIABLE'
os.environ['MY_VARIABLE'] = 'Hello, World!'

# Access the newly set variable
print(os.environ.get('MY_VARIABLE'))

Output:

Hello, World!

-

Important considerations:

Security:

-

Process isolation:

Environment variables are specific to each process. If you set an environment variable in one Python script, it won’t be automatically available in another script.

-

Best Practices For Using Environment Variables in Python

Always add . env files to . … While defining variables use descriptive, all UPPERCASE names.

-

Best Practices For Using Environment Variables in Java