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")