【问题标题】:Python Multithreading - How to prevent None items from ending up in result - Concurrent FuturesPython 多线程 - 如何防止 None 项目最终出现在结果中 - Concurrent Futures
【发布时间】:2019-02-06 14:14:35
【问题描述】:

我希望从主机名列表中抓取 SSL 数据。一切都按预期工作,除了当 get_cert_data 函数由于缺少 SSL 证书或无法连接到主机而返回 None 时。 None 值以任何一种方式附加到 certs_list 中。我正在使用包含 100 万台主机的大型列表,由于数据的性质,我预计其中大多数都没有 SSL 证书。可以理解的是,我想节省内存,而不是在列表中存储 900K None 值。感谢您抽出宝贵时间阅读本文!奖励:使用域名或主机名来获取这些数据是否更有意义?为什么?

import concurrent.futures
import pandas as pd

df = pd.read_csv('hostnames.csv')
hosts_list = df['Host name'].tolist()

def get_cert_data(hostname):
    try:
        ctx = ssl.create_default_context()
        s = ctx.wrap_socket(socket.socket(), server_hostname=hostname)
        s.connect((hostname, 443))
        cert = s.getpeercert()
        issuer = dict(x[0] for x in cert['issuer'])
        issued_by = issuer['organizationName']
        if not "COMODO" in issued_by.upper():
            pass
        else:
            print(issued_by)
            return cert
    except Exception as e:
        pass

with concurrent.futures.ThreadPoolExecutor(max_workers = 16) as pool:
    certs_list = list(pool.map(get_cert_data, hosts_list))

【问题讨论】:

    标签: python multithreading concurrency threadpool


    【解决方案1】:

    pool.map 不返回结果。它返回一个可迭代的 Future 对象。每一个代表一个要执行的操作。所以,你必须过滤他们的结果。

    valid_certs = [cert.result() for cert in certs if cert.result() is not None]
    

    【讨论】:

    • 那里的小拼写错误,它应该说 valid_certs = [cert.result() for cert in certs if cert.result() is not None]
    • 谢谢@blue_note。 'cert' 是否引用 get_cert_data 的返回值?我不是 100% 清楚
    • @证书正在引用 get_cert_data 的 future(无论何时完成)返回值。见课程concurrent.futures.Future
    • 对不起,我感到困惑的是证书中的证书。什么是证书引用?
    • @ezeekiel: 抱歉,我的意思显然是 certs_list 变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2021-04-14
    相关资源
    最近更新 更多