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

PyInstaller加--noconsole打包yfinance代码出现AttributeError错误求助

解决PyInstaller打包yfinance脚本时--noconsole参数引发的AttributeError错误

我编写了以下Python代码用于获取股票数据:

from yfinance import download
result = download(['GM', 'F'], start = '2022-01-01', end = '2022-12-31')

使用命令 pyinstaller [name].py 打包为可执行文件时程序运行正常,但添加 --noconsole 参数去除控制台窗口后,程序抛出如下错误:

Traceback (most recent call last): File "[name].py", line 10, in File "yfinance\multi.py", line 145, in download File "yfinance\utils.py", line 773, in completed AttributeError: 'NoneType' object has no attribute 'flush'

我可以接受显示控制台窗口,但更希望彻底解决这个问题。当前使用的是PyInstaller开发版本,通过命令 pip install https://github.com/pyinstaller/pyinstaller/tarball/develop 安装。


可行解决方法

这个错误的根源是 --noconsole 参数会禁用标准输出流(stdout),而yfinance的内部代码尝试调用 sys.stdout.flush(),此时 sys.stdout 已变为 None,导致触发AttributeError。以下是几种解决思路:

1. 在脚本开头重定向标准流

在你的Python脚本最开头添加代码,手动将stdout和stderr重定向到内存缓冲区,避免yfinance调用不存在的flush方法:

import sys
from io import StringIO

# 当stdout/stderr为None时,重定向到空缓冲区
if sys.stdout is None:
    sys.stdout = StringIO()
if sys.stderr is None:
    sys.stderr = StringIO()

# 原代码放在后面
from yfinance import download
result = download(['GM', 'F'], start = '2022-01-01', end = '2022-12-31')

2. 修改yfinance的utils.py文件(临时方案)

找到yfinance安装目录下的utils.py文件,定位到第773行的completed函数,在调用flush()前先检查sys.stdout是否存在:

# 修改前代码
sys.stdout.flush()

# 修改后代码
if sys.stdout is not None:
    sys.stdout.flush()

注意:该方案会在yfinance版本更新后失效,仅适合临时应急使用。

3. 改用PyInstaller的--windowed参数(Windows系统适用)

如果是Windows平台,可以尝试使用--windowed参数替代--noconsole,部分场景下能避免流的问题,但不如前两种方案直接有效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:40:02