You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ThreadPoolExecutor在Python中实现主测试复用副测试结果

解决方案

你的核心问题是主测试中引用了未定义变量,且对Future对象的使用逻辑有误。以下是修正后的实现思路和代码:

关键修改点

  • 主测试函数PruebaPrincipal中,需使用传入的Future对象调用.result()方法,而非未定义的变量
  • 副测试返回的是实际的folio值,调整变量名可避免与Future对象混淆
  • 在主测试需要folio值的步骤前调用.result(),该方法会自动阻塞,直到副测试完成并返回结果

修正后的代码

from concurrent.futures import ThreadPoolExecutor

def PruebaPrincipal(opcion_sistema, opcion_ambiente, opcion_usuario, opcion_especifica, tipo_de_credito, folio_future):
    # 等待副测试完成并获取结果,此时副测试已完成,不会长时间阻塞
    resultado_folio = folio_future.result()
    
    with Flujos_obligatorios_originacion() as bot1:
        limpiar_pantalla()
        bot1.get_url(opcion_sistema, opcion_ambiente)
        bot1.iniciar_sesion(opcion_ambiente, opcion_usuario)
        bot1.Crear_Solicitud(tipo_de_credito)
        resultado_database = bot1.Establecer_base_de_datos(opcion_ambiente)
        curp_cliente = bot1.Llenar_Formulario_Solicitud(opcion_sistema, opcion_especifica, resultado_database, opcion_ambiente)
        bot1.Solicitud_Tipo_de_Credito(tipo_de_credito)
        # 使用获取到的folio值
        bot1.Solicitud_Datos_del_Credito(resultado_folio, resultado_database, curp_cliente, tipo_de_credito)
        bot1.cerrar_sesion()
        bot1.close()

def PruebaSecundaria(opcion_ambiente, opcion_sistema):
    with Flujos_obligatorios_originacion() as bot2:
        # 直接返回folio值,变量名更清晰
        folio = bot2.Obtener_Folio_Nav(opcion_ambiente, opcion_sistema)
        return folio

with ThreadPoolExecutor(max_workers=2) as executor:
    # 提交副测试任务,得到Future对象
    folio_future = executor.submit(PruebaSecundaria, opcion_ambiente, opcion_sistema)
    # 将Future对象传入主测试
    executor.submit(PruebaPrincipal, opcion_sistema, opcion_ambiente, opcion_usuario, opcion_especifica, tipo_de_credito, folio_future)

说明

  • 当主测试执行到folio_future.result()时,会自动等待副测试完成并返回结果,完全匹配你“主测试需要该结果时副测试已完成”的需求
  • 调整变量名是为了区分Future对象和实际返回值,提升代码可读性

内容的提问来源于stack exchange,提问作者ImGodsGamerZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 18:03:26