Skip to main content
 首页 » 编程设计

python之如何在 unicode 中读取 oslo 配置值

2025年05月04日7rubylouvre

我的 nova.conf 文件中有一些日文字符。

kura

从配置文件中读取后,我必须将其解码为 utf-8

my_data = CONF.test.test 
my_data = my_data.decode('utf-8') 

当我在没有解码的情况下使用变量时,它给出 UnicodeDecodeError

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128) 

有什么方法可以直接从配置中读取解码后的数据吗?

请您参考如下方法:

Is there any way to read data from config directly in decoded form?

不在 python 2.7 中。因为在 python 3 之前的 python 中,字符串默认为 ASCII 字符串,而在 python 3 中,字符串默认为 unicode 字符串。所以基本上:

>>> mydata = "クラ" 
>>> print mydata.decode('utf-8') 
クラ 
>>> print mydata 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128) 

而在 python 3 中:

>>> mydata = "クラ" 
>>> print(mydata) 
クラ 

因此,如果您想轻松处理 unicode 字符串,是时候进行转换了。