Python os.putenv() Method

Python os.putenv() Method

  1. Syntax of Python os.putenv() Method
  2. Example 1: Use the os.putenv() Method in Python
  3. Example 2: Understanding the os.putenv() Method in Python

Python os.putenv() method is an efficient way of changing the environment variable and its subprocesses. All the assignments to items in os.environ are directly translated into corresponding calls to os.putenv().

Syntax of Python os.putenv() Method

os.putenv(key, value)

Parameters

key It is the environment variable to be set.
value The string value to which the environment variable is translated.

Return

There is no return type for this method.

Example 1: Use the os.putenv() Method in Python

import os

os.putenv("key","value")

print("Environment variable set successfully.")

Output:

Environment variable set successfully.

Note that the changes made to the environment affect subprocesses, including the following: os.system(), popen() and execv(), etc.

Example 2: Understanding the os.putenv() Method in Python

import os

os.putenv('PATH', 'C:\\WINNT\\system32')

print("Environment variable set successfully.")

Output:

Environment variable set successfully.

On some platforms, like FreeBSD and macOS, setting the environment using the os.putenv() may cause memory leaks.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method