my question is simple:
Is there any way to code in a pythonic way that bash command?
hexdump -e '2/1 "%02x"' file.dat
Obviously, without using os, popen, or any shortcut ;)
EDIT: although I've not explicitly specified, it would be great if the code was functional in Python3.x
Thanks!
If you only care about Python 2.x,
line.encode('hex')
will encode a chunk of binary data into hex. So:(IIRC,
hexdump
by default prints 32 pairs of hex per line; if not, just change that32
to16
or whatever it is…)If the two-argument
iter
looks baffling, click the help link; it's not too complicated once you get the idea.If you care about Python 3.x,
encode
only works for codecs that convert Unicode strings to bytes; any codecs that convert the other way around (or any other combination), you have to usecodecs.encode
to do it explicitly:Or it may be better to use
hexlify
:If you want to do something besides print them out, rather than read the whole file into memory, you probably want to make an iterator. You could just put this in a function and change that
print
to ayield
, and that function returns exactly the iterator you want. Or use a genexpr ormap
call:Simply
read()
the whole file andencode('hex')
. What could be more pythonic?The standard library is your friend. Try binascii.hexlify().