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

Python报SyntaxError: 'yield' outside function错误如何解决

问题复现

你编写的读取密码加密Excel文件的代码如下:

with open('abcd.xlsm', 'rb') as abcd1:
        excel = msoffcrypto.OfficeFile('abcd.xlsm')
        excel.load_key('1234')
        excel.decrypt(temp)
        abcd1.seek(0, os.SEEK_END)
        while True:
            lines = abcd1.readline()
            if not lines:
                time.sleep(0.1)
                continue
            yield lines

代码运行后触发报错:

SyntaxError: 'yield' outside function

错误原因
  1. 核心语法问题:yield是Python生成器的专用关键字,只能在函数定义的内部作用域使用,不能直接写在顶层代码、with代码块这类非函数作用域中,这是触发当前语法错误的直接原因。
  2. 配套逻辑问题:
    • 你打开了原加密文件的句柄abcd1,但解密操作的输出是写入temp对象的,直接读取abcd1完全拿不到解密后的内容
    • 执行abcd1.seek(0, os.SEEK_END)会把文件指针直接移动到文件末尾,后续调用readline()永远读不到有效内容,会进入无意义的死循环空转
    • .xlsm是带宏的二进制格式Excel文件,不是纯文本文件,用readline()按行读取没有实际意义,拿到的二进制片段无法解析为正常表格内容。
修正实现

把解密、读取逻辑封装到函数内部,解密完成后用专门的Excel解析库读取内容,如果需要逐行返回结果再在函数内使用yield即可:

import msoffcrypto
import io
import pandas as pd

def read_encrypted_excel(file_path: str, password: str):
    with open(file_path, "rb") as encrypted_f:
        office_file = msoffcrypto.OfficeFile(encrypted_f)
        office_file.load_key(password)
        # 解密内容写入内存字节流,不需要生成本地临时文件
        decrypted_buffer = io.BytesIO()
        office_file.decrypt(decrypted_buffer)
        # 将流指针重置到起始位置,供解析库读取
        decrypted_buffer.seek(0)
        # 解析Excel内容,可按需指定工作表、表头行等参数
        excel_content = pd.read_excel(decrypted_buffer, engine="openpyxl")
        # 逐行返回结果,不需要生成器的话直接return excel_content即可
        for row in excel_content.itertuples(index=False):
            yield row

# 调用示例
if __name__ == "__main__":
    for row_data in read_encrypted_excel("abcd.xlsm", "1234"):
        print(row_data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 08:03:19