##// END OF EJS Templates
Merge pull request #4229 from jdfreder/clearoutput...
Brian E. Granger -
r12763:696bf695 merge
parent child Browse files
Show More
@@ -0,0 +1,9 b''
1 clear_output changes
2 --------------------
3
4 * There is no longer a 500ms delay when calling ``clear_output``.
5 * The ability to clear stderr and stdout individually was removed.
6 * A new ``wait`` flag that prevents ``clear_output`` from being executed until new
7 output is available. This eliminates animation flickering by allowing the
8 user to double buffer the output.
9 * The output div height is remembered when the ``wait=True`` flag is used.
@@ -657,35 +657,19 b' class Image(DisplayObject):'
657 return unicode(s.split('.')[-1].lower())
657 return unicode(s.split('.')[-1].lower())
658
658
659
659
660 def clear_output(stdout=True, stderr=True, other=True):
660 def clear_output(wait=False):
661 """Clear the output of the current cell receiving output.
661 """Clear the output of the current cell receiving output.
662
662
663 Optionally, each of stdout/stderr or other non-stream data (e.g. anything
664 produced by display()) can be excluded from the clear event.
665
666 By default, everything is cleared.
667
668 Parameters
663 Parameters
669 ----------
664 ----------
670 stdout : bool [default: True]
665 wait : bool [default: false]
671 Whether to clear stdout.
666 Wait to clear the output until new output is available to replace it."""
672 stderr : bool [default: True]
673 Whether to clear stderr.
674 other : bool [default: True]
675 Whether to clear everything else that is not stdout/stderr
676 (e.g. figures,images,HTML, any result of display()).
677 """
678 from IPython.core.interactiveshell import InteractiveShell
667 from IPython.core.interactiveshell import InteractiveShell
679 if InteractiveShell.initialized():
668 if InteractiveShell.initialized():
680 InteractiveShell.instance().display_pub.clear_output(
669 InteractiveShell.instance().display_pub.clear_output(wait)
681 stdout=stdout, stderr=stderr, other=other,
682 )
683 else:
670 else:
684 from IPython.utils import io
671 from IPython.utils import io
685 if stdout:
672 print('\033[2K\r', file=io.stdout, end='')
686 print('\033[2K\r', file=io.stdout, end='')
673 io.stdout.flush()
687 io.stdout.flush()
674 print('\033[2K\r', file=io.stderr, end='')
688 if stderr:
675 io.stderr.flush()
689 print('\033[2K\r', file=io.stderr, end='')
690 io.stderr.flush()
691
@@ -108,14 +108,12 b' class DisplayPublisher(Configurable):'
108 if 'text/plain' in data:
108 if 'text/plain' in data:
109 print(data['text/plain'], file=io.stdout)
109 print(data['text/plain'], file=io.stdout)
110
110
111 def clear_output(self, stdout=True, stderr=True, other=True):
111 def clear_output(self, wait=False):
112 """Clear the output of the cell receiving output."""
112 """Clear the output of the cell receiving output."""
113 if stdout:
113 print('\033[2K\r', file=io.stdout, end='')
114 print('\033[2K\r', file=io.stdout, end='')
114 io.stdout.flush()
115 io.stdout.flush()
115 print('\033[2K\r', file=io.stderr, end='')
116 if stderr:
116 io.stderr.flush()
117 print('\033[2K\r', file=io.stderr, end='')
118 io.stderr.flush()
119
117
120
118
121 class CapturingDisplayPublisher(DisplayPublisher):
119 class CapturingDisplayPublisher(DisplayPublisher):
@@ -125,8 +123,8 b' class CapturingDisplayPublisher(DisplayPublisher):'
125 def publish(self, source, data, metadata=None):
123 def publish(self, source, data, metadata=None):
126 self.outputs.append((source, data, metadata))
124 self.outputs.append((source, data, metadata))
127
125
128 def clear_output(self, stdout=True, stderr=True, other=True):
126 def clear_output(self, wait=False):
129 super(CapturingDisplayPublisher, self).clear_output(stdout, stderr, other)
127 super(CapturingDisplayPublisher, self).clear_output(wait)
130 if other:
128 if other:
131 # empty the list, *do not* reassign a new list
129 # empty the list, *do not* reassign a new list
132 del self.outputs[:]
130 del self.outputs[:]
@@ -241,7 +241,7 b' var IPython = (function (IPython) {'
241 * @method execute
241 * @method execute
242 */
242 */
243 CodeCell.prototype.execute = function () {
243 CodeCell.prototype.execute = function () {
244 this.output_area.clear_output(true, true, true);
244 this.output_area.clear_output();
245 this.set_input_prompt('*');
245 this.set_input_prompt('*');
246 this.element.addClass("running");
246 this.element.addClass("running");
247 if (this.last_msg_id) {
247 if (this.last_msg_id) {
@@ -390,8 +390,8 b' var IPython = (function (IPython) {'
390 };
390 };
391
391
392
392
393 CodeCell.prototype.clear_output = function (stdout, stderr, other) {
393 CodeCell.prototype.clear_output = function (wait) {
394 this.output_area.clear_output(stdout, stderr, other);
394 this.output_area.clear_output(wait);
395 };
395 };
396
396
397
397
@@ -1339,7 +1339,7 b' var IPython = (function (IPython) {'
1339 var cells = this.get_cells();
1339 var cells = this.get_cells();
1340 for (var i=0; i<ncells; i++) {
1340 for (var i=0; i<ncells; i++) {
1341 if (cells[i] instanceof IPython.CodeCell) {
1341 if (cells[i] instanceof IPython.CodeCell) {
1342 cells[i].clear_output(true,true,true);
1342 cells[i].clear_output();
1343 // Make all In[] prompts blank, as well
1343 // Make all In[] prompts blank, as well
1344 // TODO: make this configurable (via checkbox?)
1344 // TODO: make this configurable (via checkbox?)
1345 cells[i].set_input_prompt();
1345 cells[i].set_input_prompt();
@@ -31,7 +31,7 b' var IPython = (function (IPython) {'
31 this.outputs = [];
31 this.outputs = [];
32 this.collapsed = false;
32 this.collapsed = false;
33 this.scrolled = false;
33 this.scrolled = false;
34 this.clear_out_timeout = null;
34 this.clear_queued = null;
35 if (prompt_area === undefined) {
35 if (prompt_area === undefined) {
36 this.prompt_area = true;
36 this.prompt_area = true;
37 } else {
37 } else {
@@ -289,7 +289,12 b' var IPython = (function (IPython) {'
289 OutputArea.prototype.append_output = function (json, dynamic) {
289 OutputArea.prototype.append_output = function (json, dynamic) {
290 // If dynamic is true, javascript output will be eval'd.
290 // If dynamic is true, javascript output will be eval'd.
291 this.expand();
291 this.expand();
292 this.flush_clear_timeout();
292
293 // Clear the output if clear is queued.
294 if (this.clear_queued) {
295 this.clear_output(false);
296 }
297
293 if (json.output_type === 'pyout') {
298 if (json.output_type === 'pyout') {
294 this.append_pyout(json, dynamic);
299 this.append_pyout(json, dynamic);
295 } else if (json.output_type === 'pyerr') {
300 } else if (json.output_type === 'pyerr') {
@@ -300,6 +305,7 b' var IPython = (function (IPython) {'
300 this.append_stream(json);
305 this.append_stream(json);
301 }
306 }
302 this.outputs.push(json);
307 this.outputs.push(json);
308 this.element.height('auto');
303 var that = this;
309 var that = this;
304 setTimeout(function(){that.element.trigger('resize');}, 100);
310 setTimeout(function(){that.element.trigger('resize');}, 100);
305 };
311 };
@@ -553,7 +559,6 b' var IPython = (function (IPython) {'
553 OutputArea.prototype.append_raw_input = function (content) {
559 OutputArea.prototype.append_raw_input = function (content) {
554 var that = this;
560 var that = this;
555 this.expand();
561 this.expand();
556 this.flush_clear_timeout();
557 var area = this.create_output_area();
562 var area = this.create_output_area();
558
563
559 // disable any other raw_inputs, if they are left around
564 // disable any other raw_inputs, if they are left around
@@ -606,81 +611,35 b' var IPython = (function (IPython) {'
606
611
607
612
608 OutputArea.prototype.handle_clear_output = function (content) {
613 OutputArea.prototype.handle_clear_output = function (content) {
609 this.clear_output(content.stdout, content.stderr, content.other);
614 this.clear_output(content.wait);
610 };
615 };
611
616
612
617
613 OutputArea.prototype.clear_output = function (stdout, stderr, other) {
618 OutputArea.prototype.clear_output = function(wait) {
614 var that = this;
619 if (wait) {
615 if (this.clear_out_timeout != null){
616 // fire previous pending clear *immediately*
617 clearTimeout(this.clear_out_timeout);
618 this.clear_out_timeout = null;
619 this.clear_output_callback(this._clear_stdout, this._clear_stderr, this._clear_other);
620 }
621 // store flags for flushing the timeout
622 this._clear_stdout = stdout;
623 this._clear_stderr = stderr;
624 this._clear_other = other;
625 this.clear_out_timeout = setTimeout(function() {
626 // really clear timeout only after a short delay
627 // this reduces flicker in 'clear_output; print' cases
628 that.clear_out_timeout = null;
629 that._clear_stdout = that._clear_stderr = that._clear_other = null;
630 that.clear_output_callback(stdout, stderr, other);
631 }, 500
632 );
633 };
634
620
621 // If a clear is queued, clear before adding another to the queue.
622 if (this.clear_queued) {
623 this.clear_output(false);
624 };
635
625
636 OutputArea.prototype.clear_output_callback = function (stdout, stderr, other) {
626 this.clear_queued = true;
637 var output_div = this.element;
627 } else {
638
628
639 if (stdout && stderr && other){
629 // Fix the output div's height if the clear_output is waiting for
630 // new output (it is being used in an animation).
631 if (this.clear_queued) {
632 var height = this.element.height();
633 this.element.height(height);
634 this.clear_queued = false;
635 }
636
640 // clear all, no need for logic
637 // clear all, no need for logic
641 output_div.html("");
638 this.element.html("");
642 this.outputs = [];
639 this.outputs = [];
643 this.unscroll_area();
640 this.unscroll_area();
644 return;
641 return;
645 }
642 };
646 // remove html output
647 // each output_subarea that has an identifying class is in an output_area
648 // which is the element to be removed.
649 if (stdout) {
650 output_div.find("div.output_stdout").parent().remove();
651 }
652 if (stderr) {
653 output_div.find("div.output_stderr").parent().remove();
654 }
655 if (other) {
656 output_div.find("div.output_subarea").not("div.output_stderr").not("div.output_stdout").parent().remove();
657 }
658 this.unscroll_area();
659
660 // remove cleared outputs from JSON list:
661 for (var i = this.outputs.length - 1; i >= 0; i--) {
662 var out = this.outputs[i];
663 var output_type = out.output_type;
664 if (output_type == "display_data" && other) {
665 this.outputs.splice(i,1);
666 } else if (output_type == "stream") {
667 if (stdout && out.stream == "stdout") {
668 this.outputs.splice(i,1);
669 } else if (stderr && out.stream == "stderr") {
670 this.outputs.splice(i,1);
671 }
672 }
673 }
674 };
675
676
677 OutputArea.prototype.flush_clear_timeout = function() {
678 var output_div = this.element;
679 if (this.clear_out_timeout){
680 clearTimeout(this.clear_out_timeout);
681 this.clear_out_timeout = null;
682 this.clear_output_callback(this._clear_stdout, this._clear_stderr, this._clear_other);
683 }
684 };
643 };
685
644
686
645
@@ -86,14 +86,11 b' class ZMQDisplayPublisher(DisplayPublisher):'
86 parent=self.parent_header, ident=self.topic,
86 parent=self.parent_header, ident=self.topic,
87 )
87 )
88
88
89 def clear_output(self, stdout=True, stderr=True, other=True):
89 def clear_output(self, wait=False):
90 content = dict(stdout=stdout, stderr=stderr, other=other)
90 content = dict(wait=wait)
91
91
92 if stdout:
92 print('\r', file=sys.stdout, end='')
93 print('\r', file=sys.stdout, end='')
93 print('\r', file=sys.stderr, end='')
94 if stderr:
95 print('\r', file=sys.stderr, end='')
96
97 self._flush_streams()
94 self._flush_streams()
98
95
99 self.session.send(
96 self.session.send(
@@ -391,7 +391,7 b' class AsyncResult(object):'
391 tic = time.time()
391 tic = time.time()
392 while not self.ready() and (timeout < 0 or time.time() - tic <= timeout):
392 while not self.ready() and (timeout < 0 or time.time() - tic <= timeout):
393 self.wait(interval)
393 self.wait(interval)
394 clear_output()
394 clear_output(wait=True)
395 print("%4i/%i tasks finished after %4i s" % (self.progress, N, self.elapsed), end="")
395 print("%4i/%i tasks finished after %4i s" % (self.progress, N, self.elapsed), end="")
396 sys.stdout.flush()
396 sys.stdout.flush()
397 print()
397 print()
@@ -984,6 +984,20 b' Message type: ``status``::'
984 execution_state : ('busy', 'idle', 'starting')
984 execution_state : ('busy', 'idle', 'starting')
985 }
985 }
986
986
987 Clear output
988 ------------
989
990 This message type is used to clear the output that is visible on the frontend.
991
992 Message type: ``clear_output``::
993
994 content = {
995
996 # Wait to clear the output until new output is available. Clears the
997 # existing output immediately before the new output is displayed.
998 # Useful for creating simple animations with minimal flickering.
999 'wait' : bool,
1000 }
987
1001
988 Messages on the stdin ROUTER/DEALER sockets
1002 Messages on the stdin ROUTER/DEALER sockets
989 ===========================================
1003 ===========================================
@@ -21,7 +21,7 b''
21 "source": [
21 "source": [
22 "Sometimes you want to clear the output area in the middle of a calculation. This can be useful for doing simple animations. In terminals, there is the carriage-return (`'\\r'`) for overwriting a single line, but the notebook frontend can clear the whole output area, not just a single line.\n",
22 "Sometimes you want to clear the output area in the middle of a calculation. This can be useful for doing simple animations. In terminals, there is the carriage-return (`'\\r'`) for overwriting a single line, but the notebook frontend can clear the whole output area, not just a single line.\n",
23 "\n",
23 "\n",
24 "To clear output in the Notebook you can use the `clear_output` function."
24 "To clear output in the Notebook you can use the `clear_output()` function. If you are clearing the output every frame of an animation, calling `clear_output()` will create noticeable flickering. You can use `clear_output(wait=True)` to add the *clear_output* call to a queue. When data becomes available to replace the existing output, the *clear_output* will be called immediately before the new data is added. This avoids the flickering by not rendering the cleared output to the screen."
25 ]
25 ]
26 },
26 },
27 {
27 {
@@ -58,7 +58,7 b''
58 "from IPython.display import display, clear_output\n",
58 "from IPython.display import display, clear_output\n",
59 "for i in range(10):\n",
59 "for i in range(10):\n",
60 " time.sleep(0.25)\n",
60 " time.sleep(0.25)\n",
61 " clear_output()\n",
61 " clear_output(wait=True)\n",
62 " print(i)\n",
62 " print(i)\n",
63 " sys.stdout.flush()"
63 " sys.stdout.flush()"
64 ],
64 ],
@@ -166,7 +166,7 b''
166 "for n in range(1,10):\n",
166 "for n in range(1,10):\n",
167 " time.sleep(1)\n",
167 " time.sleep(1)\n",
168 " ax.plot(x, jn(x,n))\n",
168 " ax.plot(x, jn(x,n))\n",
169 " clear_output()\n",
169 " clear_output(wait=True)\n",
170 " display(f)\n",
170 " display(f)\n",
171 "\n",
171 "\n",
172 "# close the figure at the end, so we don't get a duplicate\n",
172 "# close the figure at the end, so we don't get a duplicate\n",
@@ -271,7 +271,7 b''
271 " # We clear the notebook output before plotting this if in-place \n",
271 " # We clear the notebook output before plotting this if in-place \n",
272 " # plot updating is requested\n",
272 " # plot updating is requested\n",
273 " if in_place:\n",
273 " if in_place:\n",
274 " clear_output()\n",
274 " clear_output(wait=True)\n",
275 " display(fig)\n",
275 " display(fig)\n",
276 " \n",
276 " \n",
277 " return fig"
277 " return fig"
@@ -333,7 +333,7 b''
333 " msg = 'Simulation completed!'\n",
333 " msg = 'Simulation completed!'\n",
334 " tmon = dt.datetime.now() - t0\n",
334 " tmon = dt.datetime.now() - t0\n",
335 " if plots_in_place and fig is not None:\n",
335 " if plots_in_place and fig is not None:\n",
336 " clear_output()\n",
336 " clear_output(wait=True)\n",
337 " plt.close('all')\n",
337 " plt.close('all')\n",
338 " display(fig)\n",
338 " display(fig)\n",
339 " print msg\n",
339 " print msg\n",
@@ -281,7 +281,7 b''
281 " plt.axis('off')\n",
281 " plt.axis('off')\n",
282 " # We clear the notebook output before plotting this if in-place plot updating is requested\n",
282 " # We clear the notebook output before plotting this if in-place plot updating is requested\n",
283 " if in_place:\n",
283 " if in_place:\n",
284 " clear_output()\n",
284 " clear_output(wait=True)\n",
285 " display(fig)\n",
285 " display(fig)\n",
286 " return fig"
286 " return fig"
287 ],
287 ],
@@ -377,7 +377,7 b''
377 " msg = 'Simulation completed!'\n",
377 " msg = 'Simulation completed!'\n",
378 " tmon = dt.datetime.now() - t0\n",
378 " tmon = dt.datetime.now() - t0\n",
379 " if plots_in_place and fig is not None:\n",
379 " if plots_in_place and fig is not None:\n",
380 " clear_output()\n",
380 " clear_output(wait=True)\n",
381 " plt.close('all')\n",
381 " plt.close('all')\n",
382 " display(fig)\n",
382 " display(fig)\n",
383 " print msg\n",
383 " print msg\n",
@@ -108,7 +108,7 b' DirectViewWidget.prototype.set_kernel = function (kernel) {'
108
108
109
109
110 DirectViewWidget.prototype.execute = function () {
110 DirectViewWidget.prototype.execute = function () {
111 this.output_area.clear_output(true, true, true);
111 this.output_area.clear_output();
112 this.element.addClass("running");
112 this.element.addClass("running");
113 var callbacks = {
113 var callbacks = {
114 'execute_reply': $.proxy(this._handle_execute_reply, this),
114 'execute_reply': $.proxy(this._handle_execute_reply, this),
General Comments 0
You need to be logged in to leave comments. Login now