How do I generate an MD5SUM of the python script I'm running at the moment ?

44 views
Skip to first unread message

joaojeronimo

unread,
Jun 20, 2009, 11:32:33 AM6/20/09
to python
Suppose I'm running a script called md5this.py what code should I have
in md5this.py to tell me the exact md5sum hash of that file,
md5this.py ?

Thanks in advance

Jim Zhan

unread,
Jun 20, 2009, 1:26:02 PM6/20/09
to python
Frankly, I don't quite understand what you mean. If you just wanna get
the md5 sums of a file,
this might be the code you need:

from hashlib import md5, sha1

def sumfile(filename, sumtype='md5'):
if sumtype not in ('md5', 'sha1'):
sumtype = 'md5'
fileobj = open(filename, 'r')
digestor = md5() if sumtype == 'md5' else sha1()
while True:
fragment = fileobj.read(2048)
if not fragment: break
digestor.update(fragment)
fileobj.close()
return digestor.hexdigest()

Or if the file you wanna check is the file itself, you can simply
change the code like this:

def sumfile(sumtype='md5'):
if sumtype not in ('md5', 'sha1'):
sumtype = 'md5'
fileobj = open(__file__, 'r')
digestor = md5() if sumtype == 'md5' else sha1()
while True:
fragment = fileobj.read(2048)
if not fragment: break
digestor.update(fragment)
fileobj.close()
return digestor.hexdigest()

Hope it solve your problem :-)
Reply all
Reply to author
Forward
0 new messages