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

Python 3.10虚拟助手代码未按参数执行 所有指令均触发维基搜索

故障原因

所有指令都触发维基搜索的核心原因是条件判断写法错误,另有一处逻辑无效问题:

  • 维基搜索的触发判断if 'who is' or 'what is' in query:存在语法逻辑错误:Python中or运算符会先计算左侧表达式的值,非空字符串'who is'的布尔值恒为真,因此整个if条件永远成立,后续所有elif分支根本没有执行机会,不管输入什么指令都会直接走维基搜索流程。
  • open google分支只定义了内部函数open()但从未调用,即使修复判断逻辑,触发打开谷歌的指令时也不会产生实际操作。
  • 原代码存在缩进错误:if __name__ == "__main__":块下的wishMe()、while循环体没有按Python语法要求缩进,会导致代码归属逻辑混乱。
修复后代码
if __name__ == "__main__":
    wishMe()
    while True:
        query = takeCommand().lower()

        # 基于指令匹配执行对应任务
        # 修正判断逻辑,两个关键词分别做存在性判断
        if 'who is' in query or 'what is' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak("According to Wikipedia")
            print(f'Astra: {results}')
            speak(results)

        elif 'open youtube' in query:
            webbrowser.open("youtube.com")

        elif 'open google' in query:
            # 移除无效的内部函数定义,直接执行打开操作
            webbrowser.open("google.com")

        elif 'open stackoverflow' in query:
            webbrowser.open("stackoverflow.com")   

        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")    
            speak(f"Sir, the time is {strTime}")

        elif 'open v s code' in query:
            codePath = "C:\\Users\\DELL\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            os.startfile(codePath)

注意:后续新增关键词判断时,所有匹配规则都要写完整的'关键词' in query形式,不要省略in query部分,否则会再次出现条件恒真的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 01:01:14