V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
V2EX  ›  hiyoi  ›  全部回复第 7 页 / 共 7 页
回复总数  125
1  2  3  4  5  6  7  
2020 年 5 月 19 日
回复了 wuwukai007 创建的主题 Python Python 捕获多进程 OR 多线程 error 的最佳实现是什么?
最近刚好碰到这个情况,我是这么解决的,把要子线程和日志对象封装到一起,使用 logger.exception()来 traceback 错误


```
from concurrent.futures import ThreadPoolExecutor
import logging


class Main(object):
def __init__(self, logger=None):
self.pool = ThreadPoolExecutor
self.logger = logger or self._get_logger(__name__)

def _get_logger(self, name):
logger = logging.getLogger(name)
handler = logging.StreamHandler()
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s - %(threadName)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger

def do_something(self):
try:
a = 1 / 0
except Exception as e:
self.logger.exception(e)

def async_task(self):
with self.pool() as p:
for i in range(3):
p.submit(self.do_something)


if __name__ == '__main__':
m = Main()
m.async_task()
```

日志:
```
2020-05-19 16:23:38,378 - ERROR - ThreadPoolExecutor-0_0 - division by zero
Traceback (most recent call last):
File "thread.py", line 22, in do_something
a = 1 / 0
ZeroDivisionError: division by zero
2020-05-19 16:23:38,378 - ERROR - ThreadPoolExecutor-0_0 - division by zero
Traceback (most recent call last):
File "thread.py", line 22, in do_something
a = 1 / 0
ZeroDivisionError: division by zero
2020-05-19 16:23:38,378 - ERROR - ThreadPoolExecutor-0_2 - division by zero
Traceback (most recent call last):
File "thread.py", line 22, in do_something
a = 1 / 0
ZeroDivisionError: division by zero
```
2019 年 7 月 11 日
回复了 rizon 创建的主题 程序员 腾讯云服务器 https 连接不上了
原来是这原因,debug 好几天都找不到问题再哪里。腾讯云这孙子也没发个通知公告一下。
2018 年 7 月 28 日
回复了 Alice0T0 创建的主题 程序员 求推荐免费图床
@cairnechen 这个 uid 貌似是小贱贱图床的,不知道用什么什么手段隐藏了信息
2018 年 7 月 25 日
回复了 gaocc 创建的主题 问与答 求漫画和小说 api,最好是免费的
😂之前为了自己看漫画方便,动手做了一个
https://www.kumaodm.com
厉害啊。
1  2  3  4  5  6  7  
About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1066 Online   Highest 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 14ms · UTC 23:28 · PVG 07:28 · LAX 16:28 · JFK 19:28
♥ Do have faith in what you're doing.