How to use environment variables in Python

Published on Aug. 22, 2023, 12:15 p.m.

To use environment variables in Python, you can use the os module to access the variables and their values. Here’s an example:

import os

# Access the value of an environment variable
my_var = os.environ.get('MY_VAR')

# Print the value of the variable
print(my_var)

In this example, we use the os.environ.get() function to access the value of an environment variable called MY_VAR. The get() function returns None if the variable is not set, so you should check for this before using the value.

You can also use the os.environ dictionary to access all of the environment variables and their values:

import os

# Access all the environment variables
env_vars = os.environ

# Print the value of a specific variable
print(env_vars.get('MY_VAR'))

In this example, we access all of the environment variables by using the os.environ dictionary, and then use the get() function to access the value of a specific variable.

To set environment variables in Linux

To set environment variables in Linux, you can use the export command in either the command line or a shell script. Environment variables are variables that are available within the current shell session and can also be used by child processes.

Here are some examples of how to set environment variables in Linux:

  1. Set an environment variable in the command line
export MY_VAR="value"

This sets an environment variable called MY_VAR with a value of “value” for the current shell session.
2. Set an environment variable in a shell script

#!/bin/bash
MY_VAR="value"
export MY_VAR

This sets an environment variable called MY_VAR with a value of “value” in the script. Adding export MY_VAR makes the variable available as an environment variable for child processes.

You can add this command to ~/.bashrc or /etc/profile.d to automatically set the environment variable every time a new shell is opened.

Tags:

related content