22import sys
33from io import StringIO
44from threading import Lock , local
5+ from time import sleep
56
67from ._reprs import display_repr
78
@@ -16,7 +17,7 @@ def __call__(self, *args, **kwargs):
1617 return self .printer (* args , ** kwargs )
1718
1819
19- class RecordPrint :
20+ class PrintRecorder :
2021 n = 0
2122 local_print = LocalPrint ()
2223 print_lock = Lock ()
@@ -27,17 +28,17 @@ def __init__(self):
2728
2829 def __enter__ (self ):
2930 with self .print_lock :
30- if RecordPrint .n == 0 :
31+ if PrintRecorder .n == 0 :
3132 LocalPrint .printer = builtins .print
3233 builtins .print = self .local_print
33- RecordPrint .n += 1
34+ PrintRecorder .n += 1
3435 self .local_print .printer = self
3536 return self
3637
3738 def __exit__ (self , exc_type , exc_value , exc_traceback ):
3839 with self .print_lock :
39- RecordPrint .n -= 1
40- if RecordPrint .n == 0 :
40+ PrintRecorder .n -= 1
41+ if PrintRecorder .n == 0 :
4142 builtins .print = LocalPrint .printer
4243 self .local_print .printer = LocalPrint .printer
4344 return False
@@ -72,18 +73,30 @@ def print_outputs_async(out, stderr_future, repr_future, stdout_future):
7273
7374 This is used as a callback to `stdout_future`.
7475 """
75- stdout_val = stdout_future .result ()
76- stderr_val = stderr_future .result ()
77- if repr_future is not None :
78- repr_val = repr_future .result ()
79- else :
80- repr_val = None
81- out .clear_output ()
82- if stdout_val or stderr_val or repr_val is not None :
83- with out :
84- if stdout_val :
85- print (stdout_val , end = "" )
86- if stderr_val :
87- print (stderr_val , end = "" , file = sys .stderr )
76+ try :
77+ stdout_val = stdout_future .result ()
78+ out .clear_output ()
79+ count = 0
80+ while out .outputs :
81+ # See: https://github.com/jupyter-widgets/ipywidgets/issues/3260
82+ count += 1
83+ if count == 100 : # 0.5 seconds
84+ # This doesn't appear to always clear correctly in JupyterLab.
85+ # I don't know why. I'm still investigating.
86+ out .outputs = type (out .outputs )() # is this safe?
87+ break
88+ sleep (0.005 )
89+ if stdout_val :
90+ out .append_stdout (stdout_val )
91+
92+ stderr_val = stderr_future .result ()
93+ if stderr_val :
94+ out .append_stderr (stderr_val )
95+
96+ if repr_future is not None :
97+ repr_val = repr_future .result ()
8898 if repr_val is not None :
89- display_repr (repr_val )
99+ display_repr (repr_val , out = out )
100+ except Exception as exc :
101+ print (exc , file = sys .stderr )
102+ raise
0 commit comments