• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

How to Get and Set Environment Variable in Python?

Aniruddha Chaudhari/30108/0
CodePython

Before checking how to get and set environment variables in Python, let’s see- what is an environment variable, uses, and how to check all the environment variables in Windows and Linux.

If you are already aware of it, you can directly jump to Python code for getting and setting environment variables.

What is Environment Variable?

The environment variable is the object which contains the name-value pair data. And there is a set of environment variables.

These environment variables are set at the Operating System level.

How to find all the Environment Variables?

On Windows

  • Open the command prompt and
  • Run command set

This will list out all the environment variables.

On Linux

  • Open Linux terminal
  • Run command env

This gives a list of all the envelopment variables set on your Linux system.

What is the Use of Environment Variables?

Usually, environment variables are used as configuration variables for other running applications. So, by defining and setting the environment variable, you can change the behavior of your application.

You can create new environment variable and set/get the value of the existing environment variable.

Sometimes, the values of the environment variables are updated by the system applications automatically.

One such example is the “PWD” environment variable. It stands for “Print Working Directory”.

“PWD” variable stores the current directory path. Every time when you change the current directory path in the terminal, this variable value changes.

Get and Set Environment Variable in Python

You can use the “OS” module to get, set, and extract the environment variable in Python. Let’s see the getting and setting environment variable one-by-one.

Get Environment Variable

Use getenv() method which is defined in the OS module.

Syntax

getenv(<env_variable_name>)

Here, env_variable_name is any valid variable name.

Python Code

In this coding example, let’s print the home directory path. Home directory path is stored in the “HOME” variable.

import os
home_path = os.getenv("HOME")
print(home_path)

Output

/home/user

You might get a different output. You can verify by matching the output with the value of that environment variable.

If the given environment variable is not present, getenv() method will return None type value.

Set Environment Variable

You can change the value of the environment variable through your Python code.

Use environ() method which is defined in the OS module.

Syntax

environ[<env_variable_name>] = <value>

You can set any valid value like string, bool or number.

Python Code

Let’s change the “HOME” directory path.

import os
os.environ("HOME") = "/home/user2"

This will change the home directory path.

Before changing the environment variable, check what all other applications are using that environment variable. Make sure, changing the value of the environment variable is not impacting other applications.

Otherwise, if you are changing the environment variable as part of coding practice, export your own environment variable and then get and set the value of that environment variable.

Setting Environment Variable from File

While working on one of the Python projects, I come across setting multiple environment variables before executing the Project file.

For this, you can write all the environment variables in the text file. Read the file, loop over all the environment variables and set them one-by-one

I found this “OS” module very useful while working on the Python project. Apart from dealing with the environment variables, you can do a lot of things with this module, like…

  • Clearing Python interpreter console
  • Checking if given file/directory exists in Python
  • Getting the file size in Python

Any query? Let me know in the comment.

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard