繁体   English   中英

Python UnicodeDecodeError:'utf8'编解码器无法解码位置74的字节0x80:无效的起始字节

[英]Python UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 74: invalid start byte

我在hbase中有一些数据存储为以\\ x00填充定界的字节和字符串组合。

所以我的hbase中的行看起来像:-

00:00:00:00:00:00\x00\x80\x00\x00\x00U\xEF\xA0\xB00\x002\x0040.0.2.1\x00

该行(键)对应的值为100。

行说明:-

00:00:00:00:00:00 - This is mac address and is a string 
\x80\x00\x00\x00U\xEF\xA0\xB00 - This is the time which is saved as bytes
2 - this is customer id number stored as string
40.0.2.1 - this is store ID stored as string

我已经使用star base模块将python连接到它的stargate服务器。

这是我的代码片段,用于连接starbase和hbase表,并尝试获取该行的值:

from starbase import Connection
import starbase

C = Connection(host='10.10.5.2', port='60010')
get_table =  C.table('dummy_table')
mac_address = "00:00:00:00:00:00"
time_start = "\x80\x00\x00\x00U\xEF\xA0\xB00"
cus_id = "2"
store_id = "40.0.2.1"

create_query = "%s\x00%s\x00%s\x00%s\x00" % (mac,time_start,cus_id,store_id)

fetch_result = get_table.fetch(create_query)
print fetch_result

预期输出为:-

100

您不必担心starbase连接及其方法。 如果所有内容都是字符串,它们就可以正常工作,但是由于时间已转换为字节,这给了我错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 74: invalid start byte

以防万一我打印时需要查看create_query的输出:-

00:00:1E:00:C8:36▒U▒v▒130.0.2.6

我非常感谢您的帮助。 谢谢

我的猜测是您的数据库不支持在这些字段中存储字节。 也许您必须存储字符串。

一种方法是将字节转换为base64字符串,然后再将其存储在数据库中。 例如:

>>> from base64 import b64encode, b64decode
>>> b64encode("\x80\x00\x00\x00U\xEF\xA0\xB00")
'gAAAAFXvoLAw'
>>> b64decode(_)
'\x80\x00\x00\x00U\xef\xa0\xb00'

尝试这个

time_start = "\\x80\\x00\\x00\\x00U\\xEF\\xA0\\xB00"

\\ x是十六进制值的转义序列,

create_query = "%s\x00%s\x00%s\x00%s\x00" % (mac,time_start,cus_id,store_id)

正在将time_start转换为字符串。 由于x80不是有效的utf-8,因此它引发了错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM