【问题标题】:How can I pass a function parameter as an attribute of a module in python?如何在 python 中将函数参数作为模块的属性传递?
【发布时间】:2021-12-06 11:49:46
【问题描述】:
def hash(malware, hash):

        h = hashlib.hash()
        with open(malware,'rb') as f:
            chunk = 0
            while chunk != b'':
                chunk = f.read(1024)
                h.update(chunk)
        return h.hexdigest()

hash(file, 'sha1')
hash(file, 'sha256')

我要做的是使用 hashlib 模块的属性“sha1”和“sha256”作为函数参数。

这是否可能,或者有办法做到这一点?

【问题讨论】:

    标签: python hashlib


    【解决方案1】:

    让我们改变这种方式:

    def hash(malware, h):
        with open(malware,'rb') as f:
            chunk = 0
            while chunk != b'':
                chunk = f.read(1024)
                h.update(chunk)
        return h.hexdigest()
    
    hash1 = hashlib.sha1()
    hash256 = hashlib.sha256()
    hash(file, hash1)
    hash(file, hash256)
    

    所以,您只需通过函数参数传递_hashlib.HASH(即hash1hash256)。下面是输出示例:

    >>> # test.txt --> hello world
    >>> hash('test.txt', hash1) 
    '2aae6c35c94fcfb415dbe95f408b9ce91ee846ed'
    >>> hash('test.txt', hash256) 
    '524857d0148721c24e3e7795e19ade0cdcf49f2a4dfbef2f1575d1208fa8c54f'
    

    【讨论】:

      【解决方案2】:

      首先,不要使用hash 作为函数的名称,因为它是标准库的内置函数。 关于您的问题 - 从 hashlib 导入您想要的哈希函数并将它们作为对象传递,而不是 str

      from hashlib import sha1, sha256
      
      
      def myhash(malware, hashfunc):
      
              h = hashfunc()
              with open(malware,'rb') as f:
                  chunk = 0
                  while chunk != b'':
                      chunk = f.read(1024)
                      h.update(chunk)
              return h.hexdigest()
      
      myhash(file, sha1)
      myhash(file, sha256)
      

      如果您坚持使用str,请使用getattr()

      import hashlib
      
      def myhash(malware, hashfunc):
      
              h = getattr(hashlib, hashfunc)()
              with open(malware,'rb') as f:
                  chunk = 0
                  while chunk != b'':
                      chunk = f.read(1024)
                      h.update(chunk)
              return h.hexdigest()
      
      myhash(file, 'sha1')
      myhash(file, 'sha256')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        • 2017-07-29
        • 1970-01-01
        • 1970-01-01
        • 2017-08-02
        • 2017-06-04
        相关资源
        最近更新 更多