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_environvalue is set toTrue, which means native operating system, type of environment isbytes.
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 asbytes.default: If a key does not exist, it returns a default value. Thedefaultparameter is set toNoneif 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 programimport os# defining Env variable key in byteskey = bytes('HOME', 'utf-8')# invoking getenv() methodvalue = os.getenvb(key, default=None)# show value on consoleprint(f"Value of env variable when key=HOME: {value}")
Explanation
- Line 5: We use the
bytes()function to convertHOMEstring 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 programimport os# defining Env variable key in byteskey = bytes('usr', 'utf-8')# invoking getenv() methodvalue = os.getenvb(key)# show value on consoleprint(f"Value of env variable when key=usr: {value}")
Explanation
- Line 5: We invoke the
bytes()function to convertusrstring 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 returnsNone. - Line 9: If the value exists, we get a value parallel to the key on the console.