What is the os.getenvb() method in Python?

Overview

In Python, the os.getenvb() method is used to extract the value of the environment variable key bytes, if it exists. Otherwise, it returns the default value.

Note: It’s only available when os.supports_bytes_environ value is set to True, which means native operating system, type of environment is bytes.

Syntax

os.getenvb(key, default=None)

New in Python 3.2.

Parameters

It takes the following values as argument:

  • key: The name of an environment variable as bytes.
  • default: If a key does not exist, it returns a default value. The default parameter is set to None if not provided. This is an optional parameter.

Return Value

This method returns bytes denoting the value of the environment variable. If it does not exist, it returns the default value.

Exception

ValueError: This error is raised when the wrong data type of the key argument is provided.

Example 1

# Example Program to show os.getenvb() function
# include os module in this program
import os
# defining Env variable key in bytes
key = bytes('HOME', 'utf-8')
# invoking getenv() method
value = os.getenvb(key, default=None)
# show value on console
print(f"Value of env variable when key=HOME: {value}")

Explanation

  • Line 5: We use the bytes() function to convert HOME string to bytes.
  • Line 7: We extract the environment variable value of the provided key argument.
  • Line 9: We print value parallel to key on the console.

Example 2

# Example Program to show os.getenvb() function
# include os module in this program
import os
# defining Env variable key in bytes
key = bytes('usr', 'utf-8')
# invoking getenv() method
value = os.getenvb(key)
# show value on console
print(f"Value of env variable when key=usr: {value}")

Explanation

  • Line 5: We invoke the bytes() function to convert usr string to bytes.
  • Line 7: We extract the environment variable value of the provided key='usr' argument. It returns the environment variable if it exists, otherwise, the function returns None.
  • Line 9: If the value exists, we get a value parallel to the key on the console.

Free Resources