开发者

Unable to pass a variable to function

开发者 https://www.devze.com 2023-02-14 11:24 出处:网络
I\'m trying to build a function that calculates hashed for a file. The function takes to arguments, the file name and the algorithm to generate:

I'm trying to build a function that calculates hashed for a file. The function takes to arguments, the file name and the algorithm to generate:

def getHashValue(fName, Hash):
   f = open(fName, 'rb')
   hashvalue = hashlib.Hash(f.read()).hexdigest
   f.close()
   print(f开发者_开发技巧Name + str(Hash) + hashvalue)

My problem is that I'm unable to get the Hash argument to work. The idea was if I ad md5 I will get this:

hashvalue = hashlib.md5(f.read()).hexdigest

Andy.l


Don't use hashlib inside the function. Just take the function as a parameter and use it.

def getHashValue(fName,Hash):
   f = open(fName,'rb')
   hashvalue = Hash(f.read()).hexdigest
   f.close()
   print(fName + str(Hash) + hashvalue)

Then when you call this function, use:

getHashValue(filename, hashlib.md5)

If you want to get the hash function from a string, use getattr.

hashvalue = getattr(hashlib, Hash)(f.read()).hexdigest

And call this one with:

getHashValue(filename, 'md5')


You're looking for getattr:

hashvalue = getattr(hashlib, Hash)(f.read()).hexdigest


You must pass the hash argument as a string and use getattr.

Like this:

def getHashValue(fName, hash):
    f = open(fName, 'rb')
    hashfun = getattr(hashlib, hash) # Here you assign the function to a variable just to simplify
    hashvalue = hashfun(f.read()).hexdigest
    f.close()

Then you can call: getHashValue("foo.txt", "md5")

And you should get the result you want. Be careful, though, you should handle the cases where the hash algorithm does not exist (for instance you used "xyz" instead of "md5" or something).


Assuming Hash is a str, you will need to use "getattr" to get the function you want:

def getHashValue(fName,Hash):
   f = open(fName,'rb')
   hashvalue = getattr(hashlib,Hash)(f.read()).hexdigest
   f.close()
   print(fName + str(Hash) + hashvalue)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号