Skip to content

Commit 56edfc7

Browse files
authored
Fixbug/jupyter (#401)
* Update console.py * fix: buffer * refactor: in notebook * doc: explain
1 parent 099f70a commit 56edfc7

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

swanlab/log/console.py

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,30 @@ def getLevel(self):
105105
return self.__level
106106

107107

108-
class Consoler(sys.stdout.__class__, LeverCtl):
108+
# 检测是否在 notebook 环境中
109+
def in_notebook():
110+
try:
111+
# notebook 中会有 __IPYTHON__,而正常环境没有定义,所以 try
112+
# 'type: ignore': 可以让 pylance 忽略对变量定义的检查
113+
__IPYTHON__ # type: ignore
114+
return True
115+
except NameError:
116+
return False
117+
118+
119+
# Consoler 继承的父类
120+
def __consoler_class():
121+
# 如果在 notebook 中,使用 io.StringIO
122+
if in_notebook():
123+
from io import StringIO
124+
125+
return StringIO
126+
# 正常环境使用标准输出
127+
else:
128+
return sys.stdout.__class__
129+
130+
131+
class Consoler(__consoler_class(), LeverCtl):
109132
# 记录日志行数
110133
__sum = 0
111134

@@ -114,7 +137,11 @@ class Consoler(sys.stdout.__class__, LeverCtl):
114137
__previous_message = None
115138

116139
def __init__(self):
117-
super().__init__(sys.stdout.buffer)
140+
# 根据环境进行不同的初始化
141+
if in_notebook():
142+
super().__init__()
143+
else:
144+
super().__init__(sys.stdout.buffer)
118145
self.original_stdout = sys.stdout # 保存原始的 sys.stdout
119146

120147
def init(self, path, swanlog_level="debug"):

0 commit comments

Comments
 (0)