推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
HITMengbin
V2EX  ›  Python

pyqt 界面崩溃时,能否执行别的动作

  •  
  •   HITMengbin · Dec 4, 2020 · 3262 views
    This topic created in 1991 days ago, the information mentioned may be changed or developed.

    请教各位,因为需要连接一个 com 口读取信息,com 口经常消失,导致 pyqt 的界面存在崩溃的情况,想添加一个功能,在程序出现问题,界面准备崩溃的时候,会执行这个功能,请问这个想法可以实现吗?如何实现呢?

    12 replies    2020-12-08 11:38:41 +08:00
    ByteRan
        1
    ByteRan  
       Dec 4, 2020
    sys.excepthook
    Vegetable
        2
    Vegetable  
       Dec 4, 2020
    https://docs.python.org/zh-cn/3/library/atexit.html
    也许能解决你的问题,这个模块可以注册函数,在程序退出之前自动执行。你描述的场景应该属于一般的 error,在射程之内。
    DoctorCat
        3
    DoctorCat  
       Dec 4, 2020   ❤️ 1
    崩溃了怕是不行,Qt native 库是非托管的,已经进入系统管辖的异常链了。Python VM 层面无法 catch 到的。Qt 的动态库里看看有没有什么方法能捕获。

    @tanranran
    @Vegetable
    HITMengbin
        4
    HITMengbin  
    OP
       Dec 4, 2020
    @tanranran 我现在只是在每个查询端口那里加 try 判断,总感觉这样太不方便了
    HITMengbin
        5
    HITMengbin  
    OP
       Dec 4, 2020
    @Vegetable 好的,我看看,谢谢
    HITMengbin
        6
    HITMengbin  
    OP
       Dec 4, 2020
    @DoctorCat QT 本身有 event 判定,但是就是崩溃了,对事件判定不知道还能不能行
    gainsurier
        7
    gainsurier  
       Dec 4, 2020 via iPhone
    breakpad ?
    HITMengbin
        8
    HITMengbin  
    OP
       Dec 4, 2020
    @gainsurier 只是抓取崩溃报告吧
    wuwukai007
        9
    wuwukai007  
       Dec 4, 2020
    def excepthook(exc_type, exc_value, exc_tb):
    tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
    logging.info("error message:\n%s", tb)
    # QtWidgets.QApplication.quit()

    sys.excepthook = excepthook
    ret = app.exec_()
    sys.exit(ret)
    andthen255
        10
    andthen255  
       Dec 4, 2020
    虽然我用的是 qt 不是 pyqt,崩溃了是主线程阻塞卡死了吧? exec 本质是一个循环一直拿事件队列里的事件处理,卡死就不会处理事件了,当然也不会执行什么功能。我都是开个线程处理 COM,每次操作的时候判断状态
    RealMadrid
        11
    RealMadrid  
       Dec 4, 2020
    如果是 qt 的话,qtcreator 源码中有一个 qtcrashhandler 的工具。当 qtcreator 崩溃时,会弹出一个窗口,打印奔溃的 back trace.
    具体实现原理,就是注册 sigaction, 当软件发生错误时,进入注册的函数。在函数里 fork 个进程,对原进程进行 gdb 分析,再启动另一个 dialog, 显示出来
    HITMengbin
        12
    HITMengbin  
    OP
       Dec 8, 2020
    @andthen255
    @RealMadrid
    @wuwukai007 谢谢各位,我多试试看,有结果反馈出来
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1414 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 64ms · UTC 17:07 · PVG 01:07 · LAX 10:07 · JFK 13:07
    ♥ Do have faith in what you're doing.