Python Forum

Full Version: Confusion about Hashlib
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have never used haslib before. If I understand it is a way to encode an object for compression? I have the following line giving an error:

multi_inc_prot = 'MULTI_INC_PROT_%s' % hashlib.md5(sys.argv[0]).hexdigest()
The error is:

Error:
Traceback (most recent call last): File "/home/pace.com/rob/sandbox/branches/first-branch/CodeBase/BMFamily/src1/unittests/make_path0014.py", line 51, in <module> MakeSimulatedPositionsSourceCode(MakeSim, 'path0014', 'Path0014') File "../../../py0/Tools/helpers_make_path.py", line 181, in MakeSimulatedPositionsSourceCode multi_inc_prot = string % hashlib.md5(sys.argv[0]).hexdigest() TypeError: Unicode-objects must be encoded before hashing
I tried:

string = 'MULTI_INC_PROT_%s'.encode('utf-8')
  
  multi_inc_prot = string % hashlib.md5(sys.argv[0]).hexdigest()
which did not work. Apparently, I am misunderstanding the error. Could someone please explain?

Never mind I figured it out. It was the argument that needed encoding:

multi_inc_prot = 'MULTI_INC_PROT_%s' % hashlib.md5(sys.argv[0].encode('utf-8')).hexdigest()
usage instructions here: http://code.krypto.org/python/hashl
also, please When showing code, provide enough to run a stand alone snippet (keep it as short as possible, while still creating the error)
Error:
TypeError: Unicode-objects must be encoded before hashing
You are trying hash a str, hashlib.HASHFUNC expects bytes.
Just use sys.argv[0].encode().
This encodes the unicode str to bytes.