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

PyInstaller打包exe提前终止求助:未到输入环节且无法写入CSV

问题分析与解决方案

一、先捕获具体错误信息

错误弹窗关闭过快无法查看详细traceback,可通过以下方式获取完整错误:

  • 打开命令提示符,导航到exe所在目录,直接运行exe文件,错误信息会保留在命令行窗口中。
  • 或修改代码添加异常捕获,将错误写入日志文件:
import csv
import traceback
import os
from gemini import OpenRouter

api_key = "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"

gemma_client = OpenRouter(api_key=api_key, model="google/gemma-7b-it:free")

data = []
num = 0

try:
    while True:
        num += 1
        article = input("Enter url: ")
        summary = gemma_client.create_chat_completion(
            "Summarise findings of the following paper:"+article+". DONT USE DOTPOINTS, In the first line state of your response state whether it is an original work or not in the form OG:Yes or OG:Noo"
        )
        OG = summary[0:13]
        summary = summary[13:]
        data.append([num, OG, summary])

        # 用exe所在目录写入CSV,避免路径问题
        current_dir = os.path.dirname(os.path.abspath(__file__))
        csv_path = os.path.join(current_dir, 'data.csv')
        with open(csv_path, mode='w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerows(data)

        add_more = input("Do you want to add more data? (yes/no): ")
        if add_more.lower() != 'yes':
            break
except Exception as e:
    error_log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'error.log')
    with open(error_log_path, 'w', encoding='utf-8') as f:
        f.write(traceback.format_exc())
    print(f"错误已记录至error.log,详情:{e}")
    input("按回车键退出...")

二、修复代码中的明显问题

  • 原代码num +1未赋值,需改为num +=1,否则序号始终为0,可能引发逻辑异常。
  • 写入CSV时指定utf-8编码,避免不同环境下的编码冲突。
  • 使用exe所在目录作为CSV写入路径,避免因当前工作目录不一致导致的写入失败。

三、PyInstaller打包优化

针对PyInstaller可能遗漏依赖的问题,调整打包命令:

  1. 添加隐藏导入:gemini库存在动态导入模块,PyInstaller无法自动检测,需手动指定:
python -m PyInstaller --hidden-import gemini --hidden-import requests --hidden-import urllib3 your_script.py

(注:可根据错误日志补充或调整隐藏导入的模块)

  1. 保留控制台窗口:若之前使用--windowed参数导致控制台隐藏,改用--console参数:
python -m PyInstaller --console --hidden-import gemini your_script.py
  1. 禁用过度精简:添加--no-strip参数,避免PyInstaller剥离二进制文件中的必要符号信息:
python -m PyInstaller --console --no-strip --hidden-import gemini your_script.py

四、API调用依赖问题

OpenRouter的API调用需要网络请求与SSL证书支持,若出现SSL相关错误,可临时跳过证书验证(仅用于测试环境):

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 20:35:03