如何显示在我的代码正确的字,我的代码是:os.urandom(64)

问题描述:

我的代码是:如何显示在我的代码正确的字,我的代码是:os.urandom(64)

print os.urandom(64) 

,其输出:

> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py" 
\xd0\xc8=<\xdbD' 
\xdf\xf0\xb3>\xfc\xf2\x99\x93 
=S\xb2\xcd'\xdbD\x8d\xd0\\xbc{&YkD[\xdd\x8b\xbd\x82\x9e\xad\xd5\x90\x90\xdcD9\xbf9.\xeb\x9b>\xef#n\x84 

这是不可读的,所以我想这:

print os.urandom(64).decode("utf-8") 

但后来我得到:

> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py" 
Traceback (most recent call last): 
    File "D:\zjm_code\a.py", line 17, in <module> 
    print os.urandom(64).decode("utf-8") 
    File "D:\Python25\lib\encodings\utf_8.py", line 16, in decode 
    return codecs.utf_8_decode(input, errors, True) 
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-3: invalid data 

我应该怎么做才能获得人类可读的输出?

不缺少选择。这里有一对夫妇:

>>> os.urandom(64).encode('hex') 
'0bf760072ea10140d57261d2cd16bf7af1747e964c2e117700bd84b7acee331ee39fae5cff6f3f3fc3ee3f9501c9fa38ecda4385d40f10faeb75eb3a8f557909' 
>>> os.urandom(64).encode('base64') 
'ZuYDN1BiB0ln73+9P8eoQ3qn3Q74QzCXSViu8lqueKAOUYchMXYgmz6WDmgJm1DyTX598zE2lClX\n4iEXXYZfRA==\n' 
+0

这些不要在python3中工作。 – mbarkhau 2015-11-13 12:49:09

+0

in python 3 use binascii.hexlify(os.urandom(64)) – 2017-02-19 21:48:03

os.urandom给你一个64字节的字符串。使用十六进制进行编码可能是在某种程度上使其“人类可读”的最佳方式。例如:

>>> s = os.urandom(64) 
>>> s.encode('hex') 
'4c28351a834d80674df3b6eb5f59a2fd0df2ed2a708d14548e4a88c7139e91ef4445a8b88db28ceb3727851c02ce1822b3c7b55a977fa4f4c4f2a0e278ca569e' 

当然,这会给你128个字符的结果,这可能是太长的一条线来阅读舒适;很容易将其分裂,虽然 - 例如为:对单独的行,每行示出可以在眼睛上更容易64个字符

>>> print s[:32].encode('hex') 
4c28351a834d80674df3b6eb5f59a2fd0df2ed2a708d14548e4a88c7139e91ef 
>>> print s[32:].encode('hex') 
4445a8b88db28ceb3727851c02ce1822b3c7b55a977fa4f4c4f2a0e278ca569e 

2块。

随机字节不可能是unicode字符,所以我不惊讶你会得到编码错误。相反,你需要以某种方式转换它们。如果你正在试图做的一切都看它们是什么,然后是这样的:

print [ord(o) for o in os.urandom(64)] 

或者,如果你愿意把它作为十六进制0-9A-F:

print ''.join([hex(ord(o))[2:] for o in os.urandom(64)])