python – os.urandom()解码问题

我试图得到一个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'

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...