CX_FREEZE窗口-AttributeError:“ NoneType”对象没有属性写入

问题描述

我目前正在使用cx_freeze 6.1(6.2和6.3有一些不同的问题)来为OpenCV python应用程序生成MSI Windows安装程序。编译成功,并生成了MSI安装程序。 当base设置为“ None”或“ Console”时,安装程​​序运行正常。但是,它为base =“ win32gui”引发错误。 我将基础设置为win32gui,因为我不希望用户看到提示窗口或让他们意外关闭应用程序。 请参阅附件以查看完整的错误。我尝试了其他帖子中提到的一些旧解决方案,但没有任何帮助。我试图在排除中包括“单击”,但它也没有帮助。感谢任何相关的答复。

Error in Windows GUI

解决方法

经过两天的挣扎,我找到了自己的答案。分享,这样可以帮助他人。 base =“ Win32GUI”-尝试将所有strrr和stdout消息写入Windows GUI。但是,由于内存有限,大多数情况下它将失败,因为它将尝试将这些错误重定向到某些文件。

最佳方法如下:

将所有stderr和stdout消息重定向到任何文件,例如日志文件。我遵循了How to redirect stdout and stderr to logger in Python的指示,并创建了记录器编写器:

import sys

class LoggerWriter:
def __init__(self,level):
    # self.level is really like using log.debug(message)
    # at least in my case
    self.level = level

def write(self,message):
    # if statement reduces the amount of newlines that are
    # printed to the logger
    if message != '\n':
        self.level(message)

def flush(self):
    # create a flush method so things can be flushed when
    # the system wants to. Not sure if simply 'printing'
    # sys.stderr is the correct way to do it,but it seemed
    # to work properly for me.
    self.level(sys.stderr)

然后在app.py或主烧瓶文件中,创建日志和/或错误文件。下面的示例创建error.log

import configparser
import logging
import sys
from LoggerWriter import LoggerWriter
from pathlib import Path
from logging.handlers import TimedRotatingFileHandler
from threading import Timer

# Create Logger if doesn't exist
Path("log").mkdir(parents=True,exist_ok=True)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
handler = TimedRotatingFileHandler('log/error.log',when="midnight",interval=1,encoding='utf8')
handler.suffix = "%Y-%m-%d"
handler.setFormatter(formatter)
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
logger.addHandler(handler)
sys.stdout = LoggerWriter(logging.debug)
sys.stderr = LoggerWriter(logging.warning)

if __name__ == '__main__':
   app.run()