捕獲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 + "\n" + 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衝突的解決方法)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章