• 捕获Pyinstaller 打包后的console异常信息


    Python 使用Pyinstaller 打包UI程序后Console 是隐藏的,而有时会遇到崩溃类似

    "Failed to execute script"

    写一个抓进程异常console信息工具 process_catch_log.py

    import json
    import subprocess
    import logging
    from logging.handlers import RotatingFileHandler
    
    import psutil
    
    handlers = [
        RotatingFileHandler("process_error.log", maxBytes=1024*1024*5, backupCount=200, encoding="gbk"),
        logging.StreamHandler()
    ]
    fmt = '%(asctime)s %(threadName)s %(levelname)s : %(message)s'
    logging.basicConfig(handlers=handlers, format=fmt, level=logging.DEBUG)
    
    logging.info("Start...")
    config_file = "config.json"
    try:
        with open(config_file, encoding="utf-8") as f:
            config = json.load(f)
    except Exception as err:
        logging.error("load config.json error:{}".format(err))
        config = dict(app="./dist/log_package_demo.exe")
        with open(config_file, "w", encoding="utf-8") as f:
            json.dump(config, f, ensure_ascii=False, indent=4)
        logging.warning("use default config:{}".format(config))
    
    process_name = config.get("app")
    logging.info("Open process {}".format(process_name))
    p = subprocess.Popen(process_name, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    p.wait()
    error_info = p.stderr.read()
    if error_info:
        logging.error("Catch error message below:")
        logging.error("-" * 30 + "
    " + error_info.decode("gbk"))
        logging.error("-" * 30)
    
    logging.info("end...")
    

    等等抓起日志的进程log_package_demo.py, 打包: Pyinstaller -w -F

    import logging
    from logging.handlers import RotatingFileHandler
    
    
    file_handler = RotatingFileHandler("log_package_demo.log", maxBytes=1024*1024*5, backupCount=200, encoding="utf-8")
    console_handler = logging.StreamHandler()
    
    log_fmt = r"%(asctime)s %(threadNmae)s %(levelname): %(message)"
    
    logging.basicConfig(level=logging.DEBUG, handlers=[file_handler, console_handler])
    
    
    logging.debug("this a debug log")
    logging.info("this a info log")
    logging.warning("this a warning log 甭哭")
    logging.error("this a error log:{}".format(1/0))
    logging.critical("this a critical log")
    

    参考:

    pyinstaller打包成无控制台程序时运行出错(与popen冲突的解决方法)

  • 相关阅读:
    android面试之怎么把图片变成圆形
    android面试之contentProvider获取联系人
    Android面试之assets和aw文件的使用
    Android设计模式之面试
    Activity、Window、View的关系
    ViewPager的简单用法
    补间动画
    帧动画
    android系统的样式和主题
    C++的三种继承方式简述
  • 原文地址:https://www.cnblogs.com/onsunsl/p/Pyinstaller-console.html
Copyright © 2020-2023  润新知