##// END OF EJS Templates
fix borken demo.py
Moez Bouhlel -
Show More
@@ -1,583 +1,582 b''
1 """Module for interactive demos using IPython.
1 """Module for interactive demos using IPython.
2
2
3 This module implements a few classes for running Python scripts interactively
3 This module implements a few classes for running Python scripts interactively
4 in IPython for demonstrations. With very simple markup (a few tags in
4 in IPython for demonstrations. With very simple markup (a few tags in
5 comments), you can control points where the script stops executing and returns
5 comments), you can control points where the script stops executing and returns
6 control to IPython.
6 control to IPython.
7
7
8
8
9 Provided classes
9 Provided classes
10 ----------------
10 ----------------
11
11
12 The classes are (see their docstrings for further details):
12 The classes are (see their docstrings for further details):
13
13
14 - Demo: pure python demos
14 - Demo: pure python demos
15
15
16 - IPythonDemo: demos with input to be processed by IPython as if it had been
16 - IPythonDemo: demos with input to be processed by IPython as if it had been
17 typed interactively (so magics work, as well as any other special syntax you
17 typed interactively (so magics work, as well as any other special syntax you
18 may have added via input prefilters).
18 may have added via input prefilters).
19
19
20 - LineDemo: single-line version of the Demo class. These demos are executed
20 - LineDemo: single-line version of the Demo class. These demos are executed
21 one line at a time, and require no markup.
21 one line at a time, and require no markup.
22
22
23 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
23 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
24 executed a line at a time, but processed via IPython).
24 executed a line at a time, but processed via IPython).
25
25
26 - ClearMixin: mixin to make Demo classes with less visual clutter. It
26 - ClearMixin: mixin to make Demo classes with less visual clutter. It
27 declares an empty marquee and a pre_cmd that clears the screen before each
27 declares an empty marquee and a pre_cmd that clears the screen before each
28 block (see Subclassing below).
28 block (see Subclassing below).
29
29
30 - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
30 - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
31 classes.
31 classes.
32
32
33 Inheritance diagram:
33 Inheritance diagram:
34
34
35 .. inheritance-diagram:: IPython.lib.demo
35 .. inheritance-diagram:: IPython.lib.demo
36 :parts: 3
36 :parts: 3
37
37
38 Subclassing
38 Subclassing
39 -----------
39 -----------
40
40
41 The classes here all include a few methods meant to make customization by
41 The classes here all include a few methods meant to make customization by
42 subclassing more convenient. Their docstrings below have some more details:
42 subclassing more convenient. Their docstrings below have some more details:
43
43
44 - marquee(): generates a marquee to provide visible on-screen markers at each
44 - marquee(): generates a marquee to provide visible on-screen markers at each
45 block start and end.
45 block start and end.
46
46
47 - pre_cmd(): run right before the execution of each block.
47 - pre_cmd(): run right before the execution of each block.
48
48
49 - post_cmd(): run right after the execution of each block. If the block
49 - post_cmd(): run right after the execution of each block. If the block
50 raises an exception, this is NOT called.
50 raises an exception, this is NOT called.
51
51
52
52
53 Operation
53 Operation
54 ---------
54 ---------
55
55
56 The file is run in its own empty namespace (though you can pass it a string of
56 The file is run in its own empty namespace (though you can pass it a string of
57 arguments as if in a command line environment, and it will see those as
57 arguments as if in a command line environment, and it will see those as
58 sys.argv). But at each stop, the global IPython namespace is updated with the
58 sys.argv). But at each stop, the global IPython namespace is updated with the
59 current internal demo namespace, so you can work interactively with the data
59 current internal demo namespace, so you can work interactively with the data
60 accumulated so far.
60 accumulated so far.
61
61
62 By default, each block of code is printed (with syntax highlighting) before
62 By default, each block of code is printed (with syntax highlighting) before
63 executing it and you have to confirm execution. This is intended to show the
63 executing it and you have to confirm execution. This is intended to show the
64 code to an audience first so you can discuss it, and only proceed with
64 code to an audience first so you can discuss it, and only proceed with
65 execution once you agree. There are a few tags which allow you to modify this
65 execution once you agree. There are a few tags which allow you to modify this
66 behavior.
66 behavior.
67
67
68 The supported tags are:
68 The supported tags are:
69
69
70 # <demo> stop
70 # <demo> stop
71
71
72 Defines block boundaries, the points where IPython stops execution of the
72 Defines block boundaries, the points where IPython stops execution of the
73 file and returns to the interactive prompt.
73 file and returns to the interactive prompt.
74
74
75 You can optionally mark the stop tag with extra dashes before and after the
75 You can optionally mark the stop tag with extra dashes before and after the
76 word 'stop', to help visually distinguish the blocks in a text editor:
76 word 'stop', to help visually distinguish the blocks in a text editor:
77
77
78 # <demo> --- stop ---
78 # <demo> --- stop ---
79
79
80
80
81 # <demo> silent
81 # <demo> silent
82
82
83 Make a block execute silently (and hence automatically). Typically used in
83 Make a block execute silently (and hence automatically). Typically used in
84 cases where you have some boilerplate or initialization code which you need
84 cases where you have some boilerplate or initialization code which you need
85 executed but do not want to be seen in the demo.
85 executed but do not want to be seen in the demo.
86
86
87 # <demo> auto
87 # <demo> auto
88
88
89 Make a block execute automatically, but still being printed. Useful for
89 Make a block execute automatically, but still being printed. Useful for
90 simple code which does not warrant discussion, since it avoids the extra
90 simple code which does not warrant discussion, since it avoids the extra
91 manual confirmation.
91 manual confirmation.
92
92
93 # <demo> auto_all
93 # <demo> auto_all
94
94
95 This tag can _only_ be in the first block, and if given it overrides the
95 This tag can _only_ be in the first block, and if given it overrides the
96 individual auto tags to make the whole demo fully automatic (no block asks
96 individual auto tags to make the whole demo fully automatic (no block asks
97 for confirmation). It can also be given at creation time (or the attribute
97 for confirmation). It can also be given at creation time (or the attribute
98 set later) to override what's in the file.
98 set later) to override what's in the file.
99
99
100 While _any_ python file can be run as a Demo instance, if there are no stop
100 While _any_ python file can be run as a Demo instance, if there are no stop
101 tags the whole file will run in a single block (no different that calling
101 tags the whole file will run in a single block (no different that calling
102 first %pycat and then %run). The minimal markup to make this useful is to
102 first %pycat and then %run). The minimal markup to make this useful is to
103 place a set of stop tags; the other tags are only there to let you fine-tune
103 place a set of stop tags; the other tags are only there to let you fine-tune
104 the execution.
104 the execution.
105
105
106 This is probably best explained with the simple example file below. You can
106 This is probably best explained with the simple example file below. You can
107 copy this into a file named ex_demo.py, and try running it via::
107 copy this into a file named ex_demo.py, and try running it via::
108
108
109 from IPython.demo import Demo
109 from IPython.demo import Demo
110 d = Demo('ex_demo.py')
110 d = Demo('ex_demo.py')
111 d()
111 d()
112
112
113 Each time you call the demo object, it runs the next block. The demo object
113 Each time you call the demo object, it runs the next block. The demo object
114 has a few useful methods for navigation, like again(), edit(), jump(), seek()
114 has a few useful methods for navigation, like again(), edit(), jump(), seek()
115 and back(). It can be reset for a new run via reset() or reloaded from disk
115 and back(). It can be reset for a new run via reset() or reloaded from disk
116 (in case you've edited the source) via reload(). See their docstrings below.
116 (in case you've edited the source) via reload(). See their docstrings below.
117
117
118 Note: To make this simpler to explore, a file called "demo-exercizer.py" has
118 Note: To make this simpler to explore, a file called "demo-exercizer.py" has
119 been added to the "docs/examples/core" directory. Just cd to this directory in
119 been added to the "docs/examples/core" directory. Just cd to this directory in
120 an IPython session, and type::
120 an IPython session, and type::
121
121
122 %run demo-exercizer.py
122 %run demo-exercizer.py
123
123
124 and then follow the directions.
124 and then follow the directions.
125
125
126 Example
126 Example
127 -------
127 -------
128
128
129 The following is a very simple example of a valid demo file.
129 The following is a very simple example of a valid demo file.
130
130
131 ::
131 ::
132
132
133 #################### EXAMPLE DEMO <ex_demo.py> ###############################
133 #################### EXAMPLE DEMO <ex_demo.py> ###############################
134 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
134 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
135
135
136 print 'Hello, welcome to an interactive IPython demo.'
136 print 'Hello, welcome to an interactive IPython demo.'
137
137
138 # The mark below defines a block boundary, which is a point where IPython will
138 # The mark below defines a block boundary, which is a point where IPython will
139 # stop execution and return to the interactive prompt. The dashes are actually
139 # stop execution and return to the interactive prompt. The dashes are actually
140 # optional and used only as a visual aid to clearly separate blocks while
140 # optional and used only as a visual aid to clearly separate blocks while
141 # editing the demo code.
141 # editing the demo code.
142 # <demo> stop
142 # <demo> stop
143
143
144 x = 1
144 x = 1
145 y = 2
145 y = 2
146
146
147 # <demo> stop
147 # <demo> stop
148
148
149 # the mark below makes this block as silent
149 # the mark below makes this block as silent
150 # <demo> silent
150 # <demo> silent
151
151
152 print 'This is a silent block, which gets executed but not printed.'
152 print 'This is a silent block, which gets executed but not printed.'
153
153
154 # <demo> stop
154 # <demo> stop
155 # <demo> auto
155 # <demo> auto
156 print 'This is an automatic block.'
156 print 'This is an automatic block.'
157 print 'It is executed without asking for confirmation, but printed.'
157 print 'It is executed without asking for confirmation, but printed.'
158 z = x+y
158 z = x+y
159
159
160 print 'z=',x
160 print 'z=',x
161
161
162 # <demo> stop
162 # <demo> stop
163 # This is just another normal block.
163 # This is just another normal block.
164 print 'z is now:', z
164 print 'z is now:', z
165
165
166 print 'bye!'
166 print 'bye!'
167 ################### END EXAMPLE DEMO <ex_demo.py> ############################
167 ################### END EXAMPLE DEMO <ex_demo.py> ############################
168 """
168 """
169
169
170 from __future__ import unicode_literals
170 from __future__ import unicode_literals
171
171
172 #*****************************************************************************
172 #*****************************************************************************
173 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
173 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
174 #
174 #
175 # Distributed under the terms of the BSD License. The full license is in
175 # Distributed under the terms of the BSD License. The full license is in
176 # the file COPYING, distributed as part of this software.
176 # the file COPYING, distributed as part of this software.
177 #
177 #
178 #*****************************************************************************
178 #*****************************************************************************
179 from __future__ import print_function
179 from __future__ import print_function
180
180
181 import os
181 import os
182 import re
182 import re
183 import shlex
183 import shlex
184 import sys
184 import sys
185
185
186 from IPython.utils import io
187 from IPython.utils.text import marquee
186 from IPython.utils.text import marquee
188 from IPython.utils import openpy
187 from IPython.utils import openpy
189 from IPython.utils import py3compat
188 from IPython.utils import py3compat
190 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
189 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
191
190
192 class DemoError(Exception): pass
191 class DemoError(Exception): pass
193
192
194 def re_mark(mark):
193 def re_mark(mark):
195 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
194 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
196
195
197 class Demo(object):
196 class Demo(object):
198
197
199 re_stop = re_mark('-*\s?stop\s?-*')
198 re_stop = re_mark('-*\s?stop\s?-*')
200 re_silent = re_mark('silent')
199 re_silent = re_mark('silent')
201 re_auto = re_mark('auto')
200 re_auto = re_mark('auto')
202 re_auto_all = re_mark('auto_all')
201 re_auto_all = re_mark('auto_all')
203
202
204 def __init__(self,src,title='',arg_str='',auto_all=None):
203 def __init__(self,src,title='',arg_str='',auto_all=None):
205 """Make a new demo object. To run the demo, simply call the object.
204 """Make a new demo object. To run the demo, simply call the object.
206
205
207 See the module docstring for full details and an example (you can use
206 See the module docstring for full details and an example (you can use
208 IPython.Demo? in IPython to see it).
207 IPython.Demo? in IPython to see it).
209
208
210 Inputs:
209 Inputs:
211
210
212 - src is either a file, or file-like object, or a
211 - src is either a file, or file-like object, or a
213 string that can be resolved to a filename.
212 string that can be resolved to a filename.
214
213
215 Optional inputs:
214 Optional inputs:
216
215
217 - title: a string to use as the demo name. Of most use when the demo
216 - title: a string to use as the demo name. Of most use when the demo
218 you are making comes from an object that has no filename, or if you
217 you are making comes from an object that has no filename, or if you
219 want an alternate denotation distinct from the filename.
218 want an alternate denotation distinct from the filename.
220
219
221 - arg_str(''): a string of arguments, internally converted to a list
220 - arg_str(''): a string of arguments, internally converted to a list
222 just like sys.argv, so the demo script can see a similar
221 just like sys.argv, so the demo script can see a similar
223 environment.
222 environment.
224
223
225 - auto_all(None): global flag to run all blocks automatically without
224 - auto_all(None): global flag to run all blocks automatically without
226 confirmation. This attribute overrides the block-level tags and
225 confirmation. This attribute overrides the block-level tags and
227 applies to the whole demo. It is an attribute of the object, and
226 applies to the whole demo. It is an attribute of the object, and
228 can be changed at runtime simply by reassigning it to a boolean
227 can be changed at runtime simply by reassigning it to a boolean
229 value.
228 value.
230 """
229 """
231 if hasattr(src, "read"):
230 if hasattr(src, "read"):
232 # It seems to be a file or a file-like object
231 # It seems to be a file or a file-like object
233 self.fname = "from a file-like object"
232 self.fname = "from a file-like object"
234 if title == '':
233 if title == '':
235 self.title = "from a file-like object"
234 self.title = "from a file-like object"
236 else:
235 else:
237 self.title = title
236 self.title = title
238 else:
237 else:
239 # Assume it's a string or something that can be converted to one
238 # Assume it's a string or something that can be converted to one
240 self.fname = src
239 self.fname = src
241 if title == '':
240 if title == '':
242 (filepath, filename) = os.path.split(src)
241 (filepath, filename) = os.path.split(src)
243 self.title = filename
242 self.title = filename
244 else:
243 else:
245 self.title = title
244 self.title = title
246 self.sys_argv = [src] + shlex.split(arg_str)
245 self.sys_argv = [src] + shlex.split(arg_str)
247 self.auto_all = auto_all
246 self.auto_all = auto_all
248 self.src = src
247 self.src = src
249
248
250 # get a few things from ipython. While it's a bit ugly design-wise,
249 # get a few things from ipython. While it's a bit ugly design-wise,
251 # it ensures that things like color scheme and the like are always in
250 # it ensures that things like color scheme and the like are always in
252 # sync with the ipython mode being used. This class is only meant to
251 # sync with the ipython mode being used. This class is only meant to
253 # be used inside ipython anyways, so it's OK.
252 # be used inside ipython anyways, so it's OK.
254 ip = get_ipython() # this is in builtins whenever IPython is running
253 ip = get_ipython() # this is in builtins whenever IPython is running
255 self.ip_ns = ip.user_ns
254 self.ip_ns = ip.user_ns
256 self.ip_colorize = ip.pycolorize
255 self.ip_colorize = ip.pycolorize
257 self.ip_showtb = ip.showtraceback
256 self.ip_showtb = ip.showtraceback
258 self.ip_run_cell = ip.run_cell
257 self.ip_run_cell = ip.run_cell
259 self.shell = ip
258 self.shell = ip
260
259
261 # load user data and initialize data structures
260 # load user data and initialize data structures
262 self.reload()
261 self.reload()
263
262
264 def fload(self):
263 def fload(self):
265 """Load file object."""
264 """Load file object."""
266 # read data and parse into blocks
265 # read data and parse into blocks
267 if hasattr(self, 'fobj') and self.fobj is not None:
266 if hasattr(self, 'fobj') and self.fobj is not None:
268 self.fobj.close()
267 self.fobj.close()
269 if hasattr(self.src, "read"):
268 if hasattr(self.src, "read"):
270 # It seems to be a file or a file-like object
269 # It seems to be a file or a file-like object
271 self.fobj = self.src
270 self.fobj = self.src
272 else:
271 else:
273 # Assume it's a string or something that can be converted to one
272 # Assume it's a string or something that can be converted to one
274 self.fobj = openpy.open(self.fname)
273 self.fobj = openpy.open(self.fname)
275
274
276 def reload(self):
275 def reload(self):
277 """Reload source from disk and initialize state."""
276 """Reload source from disk and initialize state."""
278 self.fload()
277 self.fload()
279
278
280 self.src = "".join(openpy.strip_encoding_cookie(self.fobj))
279 self.src = "".join(openpy.strip_encoding_cookie(self.fobj))
281 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
280 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
282 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
281 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
283 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
282 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
284
283
285 # if auto_all is not given (def. None), we read it from the file
284 # if auto_all is not given (def. None), we read it from the file
286 if self.auto_all is None:
285 if self.auto_all is None:
287 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
286 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
288 else:
287 else:
289 self.auto_all = bool(self.auto_all)
288 self.auto_all = bool(self.auto_all)
290
289
291 # Clean the sources from all markup so it doesn't get displayed when
290 # Clean the sources from all markup so it doesn't get displayed when
292 # running the demo
291 # running the demo
293 src_blocks = []
292 src_blocks = []
294 auto_strip = lambda s: self.re_auto.sub('',s)
293 auto_strip = lambda s: self.re_auto.sub('',s)
295 for i,b in enumerate(src_b):
294 for i,b in enumerate(src_b):
296 if self._auto[i]:
295 if self._auto[i]:
297 src_blocks.append(auto_strip(b))
296 src_blocks.append(auto_strip(b))
298 else:
297 else:
299 src_blocks.append(b)
298 src_blocks.append(b)
300 # remove the auto_all marker
299 # remove the auto_all marker
301 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
300 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
302
301
303 self.nblocks = len(src_blocks)
302 self.nblocks = len(src_blocks)
304 self.src_blocks = src_blocks
303 self.src_blocks = src_blocks
305
304
306 # also build syntax-highlighted source
305 # also build syntax-highlighted source
307 self.src_blocks_colored = list(map(self.ip_colorize,self.src_blocks))
306 self.src_blocks_colored = list(map(self.ip_colorize,self.src_blocks))
308
307
309 # ensure clean namespace and seek offset
308 # ensure clean namespace and seek offset
310 self.reset()
309 self.reset()
311
310
312 def reset(self):
311 def reset(self):
313 """Reset the namespace and seek pointer to restart the demo"""
312 """Reset the namespace and seek pointer to restart the demo"""
314 self.user_ns = {}
313 self.user_ns = {}
315 self.finished = False
314 self.finished = False
316 self.block_index = 0
315 self.block_index = 0
317
316
318 def _validate_index(self,index):
317 def _validate_index(self,index):
319 if index<0 or index>=self.nblocks:
318 if index<0 or index>=self.nblocks:
320 raise ValueError('invalid block index %s' % index)
319 raise ValueError('invalid block index %s' % index)
321
320
322 def _get_index(self,index):
321 def _get_index(self,index):
323 """Get the current block index, validating and checking status.
322 """Get the current block index, validating and checking status.
324
323
325 Returns None if the demo is finished"""
324 Returns None if the demo is finished"""
326
325
327 if index is None:
326 if index is None:
328 if self.finished:
327 if self.finished:
329 print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
328 print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
330 return None
329 return None
331 index = self.block_index
330 index = self.block_index
332 else:
331 else:
333 self._validate_index(index)
332 self._validate_index(index)
334 return index
333 return index
335
334
336 def seek(self,index):
335 def seek(self,index):
337 """Move the current seek pointer to the given block.
336 """Move the current seek pointer to the given block.
338
337
339 You can use negative indices to seek from the end, with identical
338 You can use negative indices to seek from the end, with identical
340 semantics to those of Python lists."""
339 semantics to those of Python lists."""
341 if index<0:
340 if index<0:
342 index = self.nblocks + index
341 index = self.nblocks + index
343 self._validate_index(index)
342 self._validate_index(index)
344 self.block_index = index
343 self.block_index = index
345 self.finished = False
344 self.finished = False
346
345
347 def back(self,num=1):
346 def back(self,num=1):
348 """Move the seek pointer back num blocks (default is 1)."""
347 """Move the seek pointer back num blocks (default is 1)."""
349 self.seek(self.block_index-num)
348 self.seek(self.block_index-num)
350
349
351 def jump(self,num=1):
350 def jump(self,num=1):
352 """Jump a given number of blocks relative to the current one.
351 """Jump a given number of blocks relative to the current one.
353
352
354 The offset can be positive or negative, defaults to 1."""
353 The offset can be positive or negative, defaults to 1."""
355 self.seek(self.block_index+num)
354 self.seek(self.block_index+num)
356
355
357 def again(self):
356 def again(self):
358 """Move the seek pointer back one block and re-execute."""
357 """Move the seek pointer back one block and re-execute."""
359 self.back(1)
358 self.back(1)
360 self()
359 self()
361
360
362 def edit(self,index=None):
361 def edit(self,index=None):
363 """Edit a block.
362 """Edit a block.
364
363
365 If no number is given, use the last block executed.
364 If no number is given, use the last block executed.
366
365
367 This edits the in-memory copy of the demo, it does NOT modify the
366 This edits the in-memory copy of the demo, it does NOT modify the
368 original source file. If you want to do that, simply open the file in
367 original source file. If you want to do that, simply open the file in
369 an editor and use reload() when you make changes to the file. This
368 an editor and use reload() when you make changes to the file. This
370 method is meant to let you change a block during a demonstration for
369 method is meant to let you change a block during a demonstration for
371 explanatory purposes, without damaging your original script."""
370 explanatory purposes, without damaging your original script."""
372
371
373 index = self._get_index(index)
372 index = self._get_index(index)
374 if index is None:
373 if index is None:
375 return
374 return
376 # decrease the index by one (unless we're at the very beginning), so
375 # decrease the index by one (unless we're at the very beginning), so
377 # that the default demo.edit() call opens up the sblock we've last run
376 # that the default demo.edit() call opens up the sblock we've last run
378 if index>0:
377 if index>0:
379 index -= 1
378 index -= 1
380
379
381 filename = self.shell.mktempfile(self.src_blocks[index])
380 filename = self.shell.mktempfile(self.src_blocks[index])
382 self.shell.hooks.editor(filename,1)
381 self.shell.hooks.editor(filename,1)
383 with open(filename, 'r') as f:
382 with open(filename, 'r') as f:
384 new_block = f.read()
383 new_block = f.read()
385 # update the source and colored block
384 # update the source and colored block
386 self.src_blocks[index] = new_block
385 self.src_blocks[index] = new_block
387 self.src_blocks_colored[index] = self.ip_colorize(new_block)
386 self.src_blocks_colored[index] = self.ip_colorize(new_block)
388 self.block_index = index
387 self.block_index = index
389 # call to run with the newly edited index
388 # call to run with the newly edited index
390 self()
389 self()
391
390
392 def show(self,index=None):
391 def show(self,index=None):
393 """Show a single block on screen"""
392 """Show a single block on screen"""
394
393
395 index = self._get_index(index)
394 index = self._get_index(index)
396 if index is None:
395 if index is None:
397 return
396 return
398
397
399 print(self.marquee('<%s> block # %s (%s remaining)' %
398 print(self.marquee('<%s> block # %s (%s remaining)' %
400 (self.title,index,self.nblocks-index-1)))
399 (self.title,index,self.nblocks-index-1)))
401 print(self.src_blocks_colored[index])
400 print(self.src_blocks_colored[index])
402 sys.stdout.flush()
401 sys.stdout.flush()
403
402
404 def show_all(self):
403 def show_all(self):
405 """Show entire demo on screen, block by block"""
404 """Show entire demo on screen, block by block"""
406
405
407 fname = self.title
406 fname = self.title
408 title = self.title
407 title = self.title
409 nblocks = self.nblocks
408 nblocks = self.nblocks
410 silent = self._silent
409 silent = self._silent
411 marquee = self.marquee
410 marquee = self.marquee
412 for index,block in enumerate(self.src_blocks_colored):
411 for index,block in enumerate(self.src_blocks_colored):
413 if silent[index]:
412 if silent[index]:
414 print(marquee('<%s> SILENT block # %s (%s remaining)' %
413 print(marquee('<%s> SILENT block # %s (%s remaining)' %
415 (title,index,nblocks-index-1)))
414 (title,index,nblocks-index-1)))
416 else:
415 else:
417 print(marquee('<%s> block # %s (%s remaining)' %
416 print(marquee('<%s> block # %s (%s remaining)' %
418 (title,index,nblocks-index-1)))
417 (title,index,nblocks-index-1)))
419 print(block, end=' ')
418 print(block, end=' ')
420 sys.stdout.flush()
419 sys.stdout.flush()
421
420
422 def run_cell(self,source):
421 def run_cell(self,source):
423 """Execute a string with one or more lines of code"""
422 """Execute a string with one or more lines of code"""
424
423
425 exec(source, self.user_ns)
424 exec(source, self.user_ns)
426
425
427 def __call__(self,index=None):
426 def __call__(self,index=None):
428 """run a block of the demo.
427 """run a block of the demo.
429
428
430 If index is given, it should be an integer >=1 and <= nblocks. This
429 If index is given, it should be an integer >=1 and <= nblocks. This
431 means that the calling convention is one off from typical Python
430 means that the calling convention is one off from typical Python
432 lists. The reason for the inconsistency is that the demo always
431 lists. The reason for the inconsistency is that the demo always
433 prints 'Block n/N, and N is the total, so it would be very odd to use
432 prints 'Block n/N, and N is the total, so it would be very odd to use
434 zero-indexing here."""
433 zero-indexing here."""
435
434
436 index = self._get_index(index)
435 index = self._get_index(index)
437 if index is None:
436 if index is None:
438 return
437 return
439 try:
438 try:
440 marquee = self.marquee
439 marquee = self.marquee
441 next_block = self.src_blocks[index]
440 next_block = self.src_blocks[index]
442 self.block_index += 1
441 self.block_index += 1
443 if self._silent[index]:
442 if self._silent[index]:
444 print(marquee('Executing silent block # %s (%s remaining)' %
443 print(marquee('Executing silent block # %s (%s remaining)' %
445 (index,self.nblocks-index-1)))
444 (index,self.nblocks-index-1)))
446 else:
445 else:
447 self.pre_cmd()
446 self.pre_cmd()
448 self.show(index)
447 self.show(index)
449 if self.auto_all or self._auto[index]:
448 if self.auto_all or self._auto[index]:
450 print(marquee('output:'))
449 print(marquee('output:'))
451 else:
450 else:
452 print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
451 print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
453 ans = py3compat.input().strip()
452 ans = py3compat.input().strip()
454 if ans:
453 if ans:
455 print(marquee('Block NOT executed'))
454 print(marquee('Block NOT executed'))
456 return
455 return
457 try:
456 try:
458 save_argv = sys.argv
457 save_argv = sys.argv
459 sys.argv = self.sys_argv
458 sys.argv = self.sys_argv
460 self.run_cell(next_block)
459 self.run_cell(next_block)
461 self.post_cmd()
460 self.post_cmd()
462 finally:
461 finally:
463 sys.argv = save_argv
462 sys.argv = save_argv
464
463
465 except:
464 except:
466 self.ip_showtb(filename=self.fname)
465 self.ip_showtb(filename=self.fname)
467 else:
466 else:
468 self.ip_ns.update(self.user_ns)
467 self.ip_ns.update(self.user_ns)
469
468
470 if self.block_index == self.nblocks:
469 if self.block_index == self.nblocks:
471 mq1 = self.marquee('END OF DEMO')
470 mq1 = self.marquee('END OF DEMO')
472 if mq1:
471 if mq1:
473 # avoid spurious print if empty marquees are used
472 # avoid spurious print if empty marquees are used
474 print()
473 print()
475 print(mq1)
474 print(mq1)
476 print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
475 print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
477 self.finished = True
476 self.finished = True
478
477
479 # These methods are meant to be overridden by subclasses who may wish to
478 # These methods are meant to be overridden by subclasses who may wish to
480 # customize the behavior of of their demos.
479 # customize the behavior of of their demos.
481 def marquee(self,txt='',width=78,mark='*'):
480 def marquee(self,txt='',width=78,mark='*'):
482 """Return the input string centered in a 'marquee'."""
481 """Return the input string centered in a 'marquee'."""
483 return marquee(txt,width,mark)
482 return marquee(txt,width,mark)
484
483
485 def pre_cmd(self):
484 def pre_cmd(self):
486 """Method called before executing each block."""
485 """Method called before executing each block."""
487 pass
486 pass
488
487
489 def post_cmd(self):
488 def post_cmd(self):
490 """Method called after executing each block."""
489 """Method called after executing each block."""
491 pass
490 pass
492
491
493
492
494 class IPythonDemo(Demo):
493 class IPythonDemo(Demo):
495 """Class for interactive demos with IPython's input processing applied.
494 """Class for interactive demos with IPython's input processing applied.
496
495
497 This subclasses Demo, but instead of executing each block by the Python
496 This subclasses Demo, but instead of executing each block by the Python
498 interpreter (via exec), it actually calls IPython on it, so that any input
497 interpreter (via exec), it actually calls IPython on it, so that any input
499 filters which may be in place are applied to the input block.
498 filters which may be in place are applied to the input block.
500
499
501 If you have an interactive environment which exposes special input
500 If you have an interactive environment which exposes special input
502 processing, you can use this class instead to write demo scripts which
501 processing, you can use this class instead to write demo scripts which
503 operate exactly as if you had typed them interactively. The default Demo
502 operate exactly as if you had typed them interactively. The default Demo
504 class requires the input to be valid, pure Python code.
503 class requires the input to be valid, pure Python code.
505 """
504 """
506
505
507 def run_cell(self,source):
506 def run_cell(self,source):
508 """Execute a string with one or more lines of code"""
507 """Execute a string with one or more lines of code"""
509
508
510 self.shell.run_cell(source)
509 self.shell.run_cell(source)
511
510
512 class LineDemo(Demo):
511 class LineDemo(Demo):
513 """Demo where each line is executed as a separate block.
512 """Demo where each line is executed as a separate block.
514
513
515 The input script should be valid Python code.
514 The input script should be valid Python code.
516
515
517 This class doesn't require any markup at all, and it's meant for simple
516 This class doesn't require any markup at all, and it's meant for simple
518 scripts (with no nesting or any kind of indentation) which consist of
517 scripts (with no nesting or any kind of indentation) which consist of
519 multiple lines of input to be executed, one at a time, as if they had been
518 multiple lines of input to be executed, one at a time, as if they had been
520 typed in the interactive prompt.
519 typed in the interactive prompt.
521
520
522 Note: the input can not have *any* indentation, which means that only
521 Note: the input can not have *any* indentation, which means that only
523 single-lines of input are accepted, not even function definitions are
522 single-lines of input are accepted, not even function definitions are
524 valid."""
523 valid."""
525
524
526 def reload(self):
525 def reload(self):
527 """Reload source from disk and initialize state."""
526 """Reload source from disk and initialize state."""
528 # read data and parse into blocks
527 # read data and parse into blocks
529 self.fload()
528 self.fload()
530 lines = self.fobj.readlines()
529 lines = self.fobj.readlines()
531 src_b = [l for l in lines if l.strip()]
530 src_b = [l for l in lines if l.strip()]
532 nblocks = len(src_b)
531 nblocks = len(src_b)
533 self.src = ''.join(lines)
532 self.src = ''.join(lines)
534 self._silent = [False]*nblocks
533 self._silent = [False]*nblocks
535 self._auto = [True]*nblocks
534 self._auto = [True]*nblocks
536 self.auto_all = True
535 self.auto_all = True
537 self.nblocks = nblocks
536 self.nblocks = nblocks
538 self.src_blocks = src_b
537 self.src_blocks = src_b
539
538
540 # also build syntax-highlighted source
539 # also build syntax-highlighted source
541 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
540 self.src_blocks_colored = list(map(self.ip_colorize,self.src_blocks))
542
541
543 # ensure clean namespace and seek offset
542 # ensure clean namespace and seek offset
544 self.reset()
543 self.reset()
545
544
546
545
547 class IPythonLineDemo(IPythonDemo,LineDemo):
546 class IPythonLineDemo(IPythonDemo,LineDemo):
548 """Variant of the LineDemo class whose input is processed by IPython."""
547 """Variant of the LineDemo class whose input is processed by IPython."""
549 pass
548 pass
550
549
551
550
552 class ClearMixin(object):
551 class ClearMixin(object):
553 """Use this mixin to make Demo classes with less visual clutter.
552 """Use this mixin to make Demo classes with less visual clutter.
554
553
555 Demos using this mixin will clear the screen before every block and use
554 Demos using this mixin will clear the screen before every block and use
556 blank marquees.
555 blank marquees.
557
556
558 Note that in order for the methods defined here to actually override those
557 Note that in order for the methods defined here to actually override those
559 of the classes it's mixed with, it must go /first/ in the inheritance
558 of the classes it's mixed with, it must go /first/ in the inheritance
560 tree. For example:
559 tree. For example:
561
560
562 class ClearIPDemo(ClearMixin,IPythonDemo): pass
561 class ClearIPDemo(ClearMixin,IPythonDemo): pass
563
562
564 will provide an IPythonDemo class with the mixin's features.
563 will provide an IPythonDemo class with the mixin's features.
565 """
564 """
566
565
567 def marquee(self,txt='',width=78,mark='*'):
566 def marquee(self,txt='',width=78,mark='*'):
568 """Blank marquee that returns '' no matter what the input."""
567 """Blank marquee that returns '' no matter what the input."""
569 return ''
568 return ''
570
569
571 def pre_cmd(self):
570 def pre_cmd(self):
572 """Method called before executing each block.
571 """Method called before executing each block.
573
572
574 This one simply clears the screen."""
573 This one simply clears the screen."""
575 from IPython.utils.terminal import term_clear
574 from IPython.utils.terminal import _term_clear
576 term_clear()
575 _term_clear()
577
576
578 class ClearDemo(ClearMixin,Demo):
577 class ClearDemo(ClearMixin,Demo):
579 pass
578 pass
580
579
581
580
582 class ClearIPDemo(ClearMixin,IPythonDemo):
581 class ClearIPDemo(ClearMixin,IPythonDemo):
583 pass
582 pass
General Comments 0
You need to be logged in to leave comments. Login now