问题

在分析代码时使用到os模块的getenv()方法。奇怪的是,在PyCharm中语法不显示错误提示,但运行时出现如图所示错误:

Windows上不可用Python的os.getenvb方法_第1张图片

进一步分析发现,Python中的os模块提供了与操作系统进行交互的功能。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的功能的便携式方法。

os.getenvb()是Python中的方法os.getenv()的字节版本。此方法还返回与指定键关联的环境变量的值。但是不像os.getenv()方法,它接受字节对象作为键,并返回字节对象作为与指定键关联的环境变量的值。

函数os.getenvb()仅当环境的本机OS类型为字节时,该方法才可用。例如,Windows没有字节作为环境的本机OS类型,因此Windows的功能os.getenvb()该方法在Windows上不可用。

语法

os.getenvb(key, default = None)
参数:
key:一个字节对象,表示环境变量的名称
默认值(可选):表示 key 不存在时默认值的字符串。如果省略,则默认设置为“无”。

返回类型:此方法返回一个字节对象,该对象表示与指定键关联的环境变量的值。如果 key 不存在,则返回默认参数的值。

代码1:使用os.getenvb()方法

# Python program to explain os.getenvb() method  

# importing os module  
import os 

# Get the value of 'HOME' 
# environment variable 
key = b'HOME'
value = os.getenvb(key) 

# Print the value of 'HOME' 
# environment variable 
print("Value of 'HOME' environment variable :", value)  

# Get the value of 'JAVA_HOME' 
# environment variable 
key = b'JAVA_HOME'
value = os.getenvb(key) 

# Print the value of 'JAVA_HOME' 
# environment variable 
print("Value of 'JAVA_HOME' environment variable :", value) 

输出:
Value of 'HOME' environment variable : b'/home/ihritik'
Value of 'JAVA_HOME' environment variable : b'/opt/jdk-10.0.1'

代码2:如果 key 不存在

# Python program to explain os.getenvb() method  

# importing os module  
import os 

# Get the value of 'home' 
# environment variable 
key = b'home'
value = os.getenvb(key) 

# Print the value of 'home' 
# environment variable 
print("Value of 'home' environment variable :", value)

输出:
Value of 'home' environment variable : None

代码3:明确指定默认参数

# Python program to explain os.getenvb() method  

# importing os module  
import os 

# Get the value of 'home' 
# environment variable 
key = b'home'
value = os.getenvb(key, default = "value does not exist") 

# Print the value of 'home' 
# environment variable 
print("Value of 'home' environment variable :", value) 

输出:
Value of 'home' environment variable : value does not exist

原文:

https://www.geeksforgeeks.org/python-os-getenvb-method/

中文译文:

https://vimsky.com/examples/usage/python-os-getenvb-method.html