Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print python os.urandom output on terminal

Tags:

python

how can i print the output of os.urandom(n) in terminal?

I try to generate a SECRET_KEY with fabfile and will output the 24 bytes.

Example how i implement both variants in the python shell:

>>> import os
>>> out = os.urandom(24)
>>> out
'oS\xf8\xf4\xe2\xc8\xda\xe3\x7f\xc75*\x83\xb1\x06\x8c\x85\xa4\xa7piE\xd6I'
>>> print out
oS�������5*������piE�I
like image 635
danbruegge Avatar asked Aug 15 '13 07:08

danbruegge


2 Answers

If what you want is hex-encoded string, use binascii.a2b_hex (or hexlify):

>>> out = 'oS\xf8\xf4\xe2\xc8\xda\xe3\x7f\xc75*\x83\xb1\x06\x8c\x85\xa4\xa7piE\xd6I'
>>> import binascii
>>> print binascii.hexlify(out)
6f53f8f4e2c8dae37fc7352a83b1068c85a4a7706945d649
like image 164
falsetru Avatar answered Sep 28 '22 13:09

falsetru


To use just built-ins, you can get the integer value with ord and then convert that back to a hex number:

list_of_hex = [str(hex(ord(z)))[2:] for z in out]
print " ".join(list_of_hex)

If you just want the hex list, then the str() and [2:] are unnecessary

The output of this and the hexify() version are both type str and should work fine for the web app.

like image 41
beroe Avatar answered Sep 28 '22 11:09

beroe