##// END OF EJS Templates
rollback to working
Tom Fetherston -
r1939:c31442ed merge
parent child Browse files
Show More
@@ -0,0 +1,68 b''
1 from IPython.demo import Demo,IPythonDemo,LineDemo,IPythonLineDemo,ClearDemo,ClearIPDemo
2 import tempfile, os, StringIO, shutil
3
4 example1 = """
5 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
6
7 print 'Hello, welcome to an interactive IPython demo.'
8
9 # The mark below defines a block boundary, which is a point where IPython will
10 # stop execution and return to the interactive prompt. The dashes are actually
11 # optional and used only as a visual aid to clearly separate blocks while
12 # editing the demo code.
13 # <demo> stop
14
15 x = 1
16 y = 2
17
18 # <demo> stop
19
20 # the mark below makes this block as silent
21 # <demo> silent
22
23 print 'This is a silent block, which gets executed but not printed.'
24
25 # <demo> stop
26 # <demo> auto
27 print 'This is an automatic block.'
28 print 'It is executed without asking for confirmation, but printed.'
29 z = x+y
30
31 print 'z=',x
32
33 # <demo> stop
34 # This is just another normal block.
35 print 'z is now:', z
36
37 print 'bye!'
38 """
39 fp = tempfile.mkdtemp(prefix = 'DemoTmp')
40 fd, filename = tempfile.mkstemp(prefix = 'demoExample1File', suffix = '.py', dir = fp)
41 f = os.fdopen(fd, 'wt')
42
43 f.write(example1)
44 f.close()
45
46 my_d = Demo(filename)
47 my_cd = ClearDemo(filename)
48
49 fobj = StringIO.StringIO(example1)
50 str_d = Demo(fobj, title='via stringio')
51 #~ def tmpcleanup():
52 #~ global my_d, my_cd, fp
53 #~ del my_d
54 #~ del my_cd
55 #~ shutil.rmtree(fp, False)
56
57 print '''
58 The example that is embeded in demo.py file has been used to create
59 the following 3 demos, and should now be available to use:
60 my_d() -- created from a file
61 my_cd() -- created from a file, a ClearDemo
62 str_d() -- same as above, but created via a stringi\o object
63 Call by typing their name, (with parentheses), at the
64 ipython prompt, interact with the block, then call again
65 to run the next block.
66 '''
67 # call tmpcleanup to delete the temporary files created. -not implemented
68
@@ -111,7 +111,11 b' has a few useful methods for navigation, like again(), edit(), jump(), seek()'
111 and back(). It can be reset for a new run via reset() or reloaded from disk
111 and back(). It can be reset for a new run via reset() or reloaded from disk
112 (in case you've edited the source) via reload(). See their docstrings below.
112 (in case you've edited the source) via reload(). See their docstrings below.
113
113
114
114 Note: To make this simpler to explore, a file called "demoExercizer.py" has
115 been added to the \ipython\docs\examples\core. Just cd to this directory in
116 an IPython session, and type:
117 run demoExercizer.py
118 and then follow the directions.
115 Example
119 Example
116 =======
120 =======
117
121
@@ -125,7 +129,7 b" print 'Hello, welcome to an interactive IPython demo.'"
125 # The mark below defines a block boundary, which is a point where IPython will
129 # The mark below defines a block boundary, which is a point where IPython will
126 # stop execution and return to the interactive prompt. The dashes are actually
130 # stop execution and return to the interactive prompt. The dashes are actually
127 # optional and used only as a visual aid to clearly separate blocks while
131 # optional and used only as a visual aid to clearly separate blocks while
128 editing the demo code.
132 # editing the demo code.
129 # <demo> stop
133 # <demo> stop
130
134
131 x = 1
135 x = 1
@@ -170,6 +174,7 b' import sys'
170
174
171 from IPython.PyColorize import Parser
175 from IPython.PyColorize import Parser
172 from IPython.genutils import marquee, file_read, file_readlines
176 from IPython.genutils import marquee, file_read, file_readlines
177 from genutils import Term
173
178
174 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
179 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
175
180
@@ -185,7 +190,7 b' class Demo(object):'
185 re_auto = re_mark('auto')
190 re_auto = re_mark('auto')
186 re_auto_all = re_mark('auto_all')
191 re_auto_all = re_mark('auto_all')
187
192
188 def __init__(self,fname,arg_str='',auto_all=None):
193 def __init__(self,src,title='',arg_str='',auto_all=None):
189 """Make a new demo object. To run the demo, simply call the object.
194 """Make a new demo object. To run the demo, simply call the object.
190
195
191 See the module docstring for full details and an example (you can use
196 See the module docstring for full details and an example (you can use
@@ -193,9 +198,14 b' class Demo(object):'
193
198
194 Inputs:
199 Inputs:
195
200
196 - fname = filename.
201 - src is either a file, or file-like object, or a
202 string that can be resolved to a filename.
197
203
198 Optional inputs:
204 Optional inputs:
205
206 - title: a string to use as the demo name. Of most use when the demo
207 you are making comes from an object that has no filename, or if you
208 want an alternate denotation distinct from the filename.
199
209
200 - arg_str(''): a string of arguments, internally converted to a list
210 - arg_str(''): a string of arguments, internally converted to a list
201 just like sys.argv, so the demo script can see a similar
211 just like sys.argv, so the demo script can see a similar
@@ -207,9 +217,24 b' class Demo(object):'
207 can be changed at runtime simply by reassigning it to a boolean
217 can be changed at runtime simply by reassigning it to a boolean
208 value.
218 value.
209 """
219 """
210
220 if hasattr(src, "read"):
211 self.fname = fname
221 # It seems to be a file or a file-like object
212 self.sys_argv = [fname] + shlex.split(arg_str)
222 self.fobj = src
223 self.fname = "from a file-like object"
224 if title == '':
225 self.title = "from a file-like object"
226 else:
227 self.title = title
228 else:
229 # Assume it's a string or something that can be converted to one
230 self.fobj = open(src)
231 self.fname = src
232 if title == '':
233 (filepath, filename) = os.path.split(src)
234 self.title = filename
235 else:
236 self.title = title
237 self.sys_argv = [src] + shlex.split(arg_str)
213 self.auto_all = auto_all
238 self.auto_all = auto_all
214
239
215 # get a few things from ipython. While it's a bit ugly design-wise,
240 # get a few things from ipython. While it's a bit ugly design-wise,
@@ -228,7 +253,7 b' class Demo(object):'
228 def reload(self):
253 def reload(self):
229 """Reload source from disk and initialize state."""
254 """Reload source from disk and initialize state."""
230 # read data and parse into blocks
255 # read data and parse into blocks
231 self.src = file_read(self.fname)
256 self.src = self.fobj.read()
232 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
257 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
233 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
258 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
234 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
259 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
@@ -277,7 +302,7 b' class Demo(object):'
277
302
278 if index is None:
303 if index is None:
279 if self.finished:
304 if self.finished:
280 print 'Demo finished. Use reset() if you want to rerun it.'
305 print >>Term.cout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.'
281 return None
306 return None
282 index = self.block_index
307 index = self.block_index
283 else:
308 else:
@@ -346,26 +371,27 b' class Demo(object):'
346 if index is None:
371 if index is None:
347 return
372 return
348
373
349 print self.marquee('<%s> block # %s (%s remaining)' %
374 print >>Term.cout, self.marquee('<%s> block # %s (%s remaining)' %
350 (self.fname,index,self.nblocks-index-1))
375 (self.title,index,self.nblocks-index-1))
351 sys.stdout.write(self.src_blocks_colored[index])
376 print >>Term.cout,(self.src_blocks_colored[index])
352 sys.stdout.flush()
377 sys.stdout.flush()
353
378
354 def show_all(self):
379 def show_all(self):
355 """Show entire demo on screen, block by block"""
380 """Show entire demo on screen, block by block"""
356
381
357 fname = self.fname
382 fname = self.title
383 title = self.title
358 nblocks = self.nblocks
384 nblocks = self.nblocks
359 silent = self._silent
385 silent = self._silent
360 marquee = self.marquee
386 marquee = self.marquee
361 for index,block in enumerate(self.src_blocks_colored):
387 for index,block in enumerate(self.src_blocks_colored):
362 if silent[index]:
388 if silent[index]:
363 print marquee('<%s> SILENT block # %s (%s remaining)' %
389 print >>Term.cout, marquee('<%s> SILENT block # %s (%s remaining)' %
364 (fname,index,nblocks-index-1))
390 (title,index,nblocks-index-1))
365 else:
391 else:
366 print marquee('<%s> block # %s (%s remaining)' %
392 print >>Term.cout, marquee('<%s> block # %s (%s remaining)' %
367 (fname,index,nblocks-index-1))
393 (title,index,nblocks-index-1))
368 print block,
394 print >>Term.cout, block,
369 sys.stdout.flush()
395 sys.stdout.flush()
370
396
371 def runlines(self,source):
397 def runlines(self,source):
@@ -390,18 +416,18 b' class Demo(object):'
390 next_block = self.src_blocks[index]
416 next_block = self.src_blocks[index]
391 self.block_index += 1
417 self.block_index += 1
392 if self._silent[index]:
418 if self._silent[index]:
393 print marquee('Executing silent block # %s (%s remaining)' %
419 print >>Term.cout, marquee('Executing silent block # %s (%s remaining)' %
394 (index,self.nblocks-index-1))
420 (index,self.nblocks-index-1))
395 else:
421 else:
396 self.pre_cmd()
422 self.pre_cmd()
397 self.show(index)
423 self.show(index)
398 if self.auto_all or self._auto[index]:
424 if self.auto_all or self._auto[index]:
399 print marquee('output:')
425 print >>Term.cout, marquee('output:')
400 else:
426 else:
401 print marquee('Press <q> to quit, <Enter> to execute...'),
427 print >>Term.cout, marquee('Press <q> to quit, <Enter> to execute...'),
402 ans = raw_input().strip()
428 ans = raw_input().strip()
403 if ans:
429 if ans:
404 print marquee('Block NOT executed')
430 print >>Term.cout, marquee('Block NOT executed')
405 return
431 return
406 try:
432 try:
407 save_argv = sys.argv
433 save_argv = sys.argv
@@ -419,10 +445,10 b' class Demo(object):'
419 if self.block_index == self.nblocks:
445 if self.block_index == self.nblocks:
420 mq1 = self.marquee('END OF DEMO')
446 mq1 = self.marquee('END OF DEMO')
421 if mq1:
447 if mq1:
422 # avoid spurious prints if empty marquees are used
448 # avoid spurious print >>Term.cout,s if empty marquees are used
423 print
449 print >>Term.cout
424 print mq1
450 print >>Term.cout, mq1
425 print self.marquee('Use reset() if you want to rerun it.')
451 print >>Term.cout, self.marquee('Use <demo_name>.reset() if you want to rerun it.')
426 self.finished = True
452 self.finished = True
427
453
428 # These methods are meant to be overridden by subclasses who may wish to
454 # These methods are meant to be overridden by subclasses who may wish to
@@ -471,9 +497,9 b' class LineDemo(Demo):'
471 def reload(self):
497 def reload(self):
472 """Reload source from disk and initialize state."""
498 """Reload source from disk and initialize state."""
473 # read data and parse into blocks
499 # read data and parse into blocks
474 src_b = [l for l in file_readlines(self.fname) if l.strip()]
500 src_b = [l for l in self.fobj.readline() if l.strip()]
475 nblocks = len(src_b)
501 nblocks = len(src_b)
476 self.src = os.linesep.join(file_readlines(self.fname))
502 self.src = os.linesep.join(self.fobj.readlines())
477 self._silent = [False]*nblocks
503 self._silent = [False]*nblocks
478 self._auto = [True]*nblocks
504 self._auto = [True]*nblocks
479 self.auto_all = True
505 self.auto_all = True
@@ -494,29 +520,29 b' class IPythonLineDemo(IPythonDemo,LineDemo):'
494
520
495 class ClearMixin(object):
521 class ClearMixin(object):
496 """Use this mixin to make Demo classes with less visual clutter.
522 """Use this mixin to make Demo classes with less visual clutter.
497
523
498 Demos using this mixin will clear the screen before every block and use
524 Demos using this mixin will clear the screen before every block and use
499 blank marquees.
525 blank marquees.
500
526
501 Note that in order for the methods defined here to actually override those
527 Note that in order for the methods defined here to actually override those
502 of the classes it's mixed with, it must go /first/ in the inheritance
528 of the classes it's mixed with, it must go /first/ in the inheritance
503 tree. For example:
529 tree. For example:
504
530
505 class ClearIPDemo(ClearMixin,IPythonDemo): pass
531 class ClearIPDemo(ClearMixin,IPythonDemo): pass
506
532
507 will provide an IPythonDemo class with the mixin's features.
533 will provide an IPythonDemo class with the mixin's features.
508 """
534 """
509
535
510 def marquee(self,txt='',width=78,mark='*'):
536 def marquee(self,txt='',width=78,mark='*'):
511 """Blank marquee that returns '' no matter what the input."""
537 """Blank marquee that returns '' no matter what the input."""
512 return ''
538 return ''
513
539
514 def pre_cmd(self):
540 def pre_cmd(self):
515 """Method called before executing each block.
541 """Method called before executing each block.
516
542
517 This one simply clears the screen."""
543 This one simply clears the screen."""
518 os.system('clear')
544 import IPython.platutils
519
545 IPython.platutils.term_clear()
520
546
521 class ClearDemo(ClearMixin,Demo):
547 class ClearDemo(ClearMixin,Demo):
522 pass
548 pass
@@ -35,6 +35,9 b' else:'
35 # there is a public, cross-platform way of toggling the term title control on
35 # there is a public, cross-platform way of toggling the term title control on
36 # and off. We should make this a stateful object later on so that each user
36 # and off. We should make this a stateful object later on so that each user
37 # can have its own instance if needed.
37 # can have its own instance if needed.
38 def term_clear():
39 _platutils.term_clear()
40
38 def toggle_set_term_title(val):
41 def toggle_set_term_title(val):
39 """Control whether set_term_title is active or not.
42 """Control whether set_term_title is active or not.
40
43
@@ -65,6 +68,8 b' def set_term_title(title):'
65 # Deprecated functions
68 # Deprecated functions
66 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
67 def freeze_term_title():
70 def freeze_term_title():
71 import warnings
68 warnings.warn("This function is deprecated, use toggle_set_term_title()")
72 warnings.warn("This function is deprecated, use toggle_set_term_title()")
69 _platutils.ignore_termtitle = True
73 _platutils.ignore_termtitle = True
74 del warnings
70
75
@@ -30,3 +30,5 b" if os.environ.get('TERM','') == 'xterm':"
30 set_term_title = _set_term_title_xterm
30 set_term_title = _set_term_title_xterm
31 else:
31 else:
32 set_term_title = _dummy_op
32 set_term_title = _dummy_op
33 def term_clear():
34 os.system('clear')
@@ -41,3 +41,7 b' except ImportError:'
41 if ret:
41 if ret:
42 # non-zero return code signals error, don't try again
42 # non-zero return code signals error, don't try again
43 ignore_termtitle = True
43 ignore_termtitle = True
44
45 def term_clear():
46 os.system('cls')
47
General Comments 0
You need to be logged in to leave comments. Login now