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

PyQt动态调用函数时字符串参数名无法解析为对应变量值怎么办

问题原因

你在checklist中存储的是参数名字符串,调用函数时直接把字符串作为参数传入,没有映射到实际的变量值,所以Telnet收到的是字符串"host"而不是对应的IP地址,才会触发解析错误。

解决步骤

  1. 在connectAndParse方法中把所有需要用到的变量整理成上下文映射字典,key为参数名,value为实际变量值
  2. 调用check系列方法前,先根据参数名字符串从上下文中取出对应的实际值,组成参数列表再传入
  3. 修正原有代码的隐含问题:不需要额外实例化runtask=Worker(),直接用当前self实例即可;同时修正原代码中getattr后重复调用方法、括号缺失的语法错误

修改后的核心代码如下:

def connectAndParse(self, runlist, checklist):
    results = []
    for x in range(len(runlist)):
        laid = str(runlist[x])
        hostlist = pydxt.finder(dxt,int(laid))
        tbs = str(int(laid)-int(hostlist[5])+1)
        host = hostlist[1]
        usr = hostlist[2]
        passwd = hostlist[3]
        sitedown = False
        # 构建参数名到实际值的映射字典
        ctx = {
            "host": host,
            "usr": usr,
            "passwd": passwd,
            "tbs": tbs,
            "laid": laid,
            "sitedown": sitedown
        }
        for y in range(len(checklist)):
            if checklist[y][0]:
                func_name = checklist[y][1]
                param_names = checklist[y][2]
                # 按参数名取出实际值
                args = [ctx[name] for name in param_names]
                # 调用对应方法传入参数
                func = getattr(self, func_name)
                res = func(*args)
                results.append(res)
                # 如果check方法会修改sitedown,执行完后更新ctx里的值即可
                # 例如:ctx["sitedown"] = 最新的sitedown状态
    self.finished.emit()

额外优化建议

  • 建议移除所有不必要的global变量,dxt、runlist、results这类数据尽量通过参数传递或者实例属性存储,避免多线程场景下的变量冲突
  • 后续如果需要新增check方法,只需要在togglebuttons里添加对应配置,同时在ctx中补充用到的参数即可,不需要修改核心执行逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:21:03