问题描述
我正在尝试获取一个 private_key ,因此,我尝试了以下操作:
Im trying to get a private_key so, I tried this:
private_key = os.urandom(32).encode('hex')
但是它抛出了这个错误:
But it throws this error:
AttributeError: 'bytes' object has no attribute 'encode'
所以我检查了问题并解决了,在Python3x字节中只能解码.然后将其更改为:
So I check questions and solved that, in Python3x bytes can be only decode. Then I change it to:
private_key = os.urandom(32).decode('hex')
但是现在它抛出此错误:
But now it throws this error:
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
我真的不明白为什么.当我在上次错误之后尝试此操作时;
And I really didnt understand why. When I tried this after last error;
private_key = os.urandom(32).codecs.decode('hex')
说
所以我被卡住了,该如何解决?我听说这在Python 2x中有效,但是我需要在3x中使用.
So I stuck, what can I do for fixing this? I heard this is working in Python 2x, but I need to use it in 3x.
推荐答案
使用 binascii.hexlify
.它可以在Python 2.x和Python 3.x中使用.
Use binascii.hexlify
. It works both in Python 2.x and Python 3.x.
>>> import binascii
>>> binascii.hexlify(os.urandom(32))
b'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'
如果在Python 3.x中需要字符串对象而不是字节对象,请使用decode()
:
If you need a string object instead of a bytes object in Python 3.x, use decode()
:
>>> binascii.hexlify(os.urandom(32)).decode()
'daae7948824525c1b8b59f9d5a75e9c0404e46259c7b1e17a4654a7e73c91b87'
这篇关于解码os.urandom()字节对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!