加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – os.urandom()解码问题

发布时间:2020-12-20 12:07:38 所属栏目:Python 来源:网络整理
导读:我试图得到一个private_key,我试过这个: private_key = os.urandom(32).encode('hex') 但它抛出了这个错误: AttributeError: 'bytes' object has no attribute 'encode' 所以我检查问题并解决了,在Python3x字节中只能解码.然后我将其更改为: private_key
我试图得到一个private_key,我试过这个:

private_key = os.urandom(32).encode('hex')

但它抛出了这个错误:

AttributeError: 'bytes' object has no attribute 'encode'

所以我检查问题并解决了,在Python3x字节中只能解码.然后我将其更改为:

private_key = os.urandom(32).decode('hex')

但现在它抛出了这个错误:

LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

我真的不明白为什么.当我在最后一次错误后尝试这个时;

private_key = os.urandom(32).codecs.decode('hex')

它说

AttributeError: ‘bytes’ object has no attribute ‘codecs’

所以我卡住了,我该怎么做才能解决这个问题?我听说这是在Python 2x中工作,但我需要在3x中使用它.

解决方法

使用 binascii.hexlify.它适用于Python 2.x和Python 3.x.

>>> import binascii
>>> binascii.hexlify(os.urandom(32))
b'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'

如果在Python 3.x中需要字符串对象而不是字节对象,请使用decode():

>>> binascii.hexlify(os.urandom(32)).decode()
'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读