V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
Te11UA
V2EX  ›  Python

Python 如何优雅地处理子线程异常?

  •  
  •   Te11UA · Sep 9, 2020 · 3409 views
    This topic created in 2056 days ago, the information mentioned may be changed or developed.

    目前比较多的做法还是如下,出于担心未知异常、没有记录日志就退出子线程的情况下,在函数用一个大的 try-except 来进行 handle,或者是将主要逻辑放到 test_sth 中,使用 try-except 来捕获:

    def run():
        try:
            test_sth()
            ...
        except Exception:
            log_exception()
    Thread(target=run).start()
    

    总感觉包裹一大块不太美观的样子,请问这样是最佳实践了吗?

    3 replies    2020-09-09 20:41:24 +08:00
    jdhao
        1
    jdhao  
       Sep 9, 2020 via Android
    线程里面捕获异常,返回运行成功与否的标志?住进程根据这个再做处理
    black11black
        2
    black11black  
       Sep 9, 2020
    异常捕捉你肯定得 try except 啊,包裹一大块是肯定的,唯一不爽写法上的改变你可以用装饰器。

    logging 会自动处理多线程相关,但是你这么搞线程自己处理异常而不是集中到主线程,完全没有控制,没什么意义
    dongxiao
        3
    dongxiao  
       Sep 9, 2020 via Android
    使用装饰器,把捕获逻辑提取出来
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4774 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 56ms · UTC 01:04 · PVG 09:04 · LAX 18:04 · JFK 21:04
    ♥ Do have faith in what you're doing.