【Python真的很强大】md5sum in Python

''' 
    md5sum in Python 
'''  
  
try:  
  from hashlib import md5        #Python2.5 or later version  
except:  
  from md5 import md5                  #Python2.4 or before version  
  
import sys  
import urllib 
import os.path
  
def sumFile(fobj):  
  m = md5()  
  while True:  
    d = fobj.read()  
    if not d:  
      break  
    m.update(d)  
    del(d)  
  return m.hexdigest()


  
def sumStr(str):  
  m = md5()  
  m.update(str.encode('utf-8'))  
  return m.hexdigest()

'''def sumStr(str):  
  m = md5()  
  for c in str:
    m.update(c)  
  return m.hexdigest()''' 

def md5SumLocalFile(fname):
  try:  
      f = open(fname, 'rb')
  except:  
    return None  
  ret = sumFile(f)  
  f.close()    
  return ret  
  
def md5SumRemoteFile(fname):       
  try:  
    f = urllib.urlopen(fname, 'rb')  
    #f = open(fname, 'rb')  
  except:  
    return None  
  ret = sumFile(f)  
  f.close()    
  return ret


def  md5sum(obj,objType='str'):
    if isinstance(obj, basestring):
      if obj.startswith('http') or obj.startswith('HTTP')  or  obj.startswith('ftp') or  obj.startswith('FTP') :
	return md5SumRemoteFile(obj)
      elif os.path.isfile(obj):
	return md5SumLocalFile(obj)
      elif os.path.isfile(obj)==False and  objType=='file':
	return None
      else:
	return sumStr(obj)
    elif isinstance(obj,object):
      return  sumFile(obj)
    else:
      return None
    
      
    
res=sumStr('1;2;3;4;5\n')  
print res
res=md5sum('/tmp/x.txt','file')  
print res
#测试发现把为文本存入文件,对比md5sum发现一样,但要注意文件结束符以及行结束符!

 

你可能感兴趣的:(md5sum)