##// END OF EJS Templates
New demo class, very handy for interactive presentations.
fperez -
Show More
@@ -0,0 +1,115 b''
1 """Module for interactive demos using IPython.
2 """
3 #*****************************************************************************
4 # Copyright (C) 2005 Fernando Perez. <Fernando.Perez@colorado.edu>
5 #
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
8 #
9 #*****************************************************************************
10
11 import exceptions
12
13 from IPython.PyColorize import Parser
14 from IPython.genutils import marquee
15
16 class DemoError(exceptions.Exception): pass
17
18 class Demo:
19 def __init__(self,fname,pause_mark='# pause',auto=False):
20
21 self.fname = fname
22 self.pause_mark = pause_mark
23 self.auto = auto
24
25 # get a few things from ipython. While it's a bit ugly design-wise,
26 # it ensures that things like color scheme and the like are always in
27 # sync with the ipython mode being used. This class is only meant to
28 # be used inside ipython anyways, so it's OK.
29 self.ip_showtraceback = __IPYTHON__.showtraceback
30 self.ip_ns = __IPYTHON__.user_ns
31 self.ip_colors = __IPYTHON__.rc['colors']
32
33 # read data and parse into blocks
34 fobj = file(fname,'r')
35 self.src = fobj.read()
36 fobj.close()
37 self.src_blocks = [b.strip() for b in self.src.split(pause_mark) if b]
38 self.nblocks = len(self.src_blocks)
39
40 # try to colorize blocks
41 colorize = Parser().format
42 col_scheme = self.ip_colors
43 self.src_blocks_colored = [colorize(s_blk,'str',col_scheme)
44 for s_blk in self.src_blocks]
45
46 # finish initialization
47 self.reset()
48
49 def reset(self):
50 self.user_ns = {}
51 self.finished = False
52 self.block_index = 0
53
54 def again(self):
55 self.block_index -= 1
56 self()
57
58
59 def _validate_index(self,index):
60 if index<0 or index>=self.nblocks:
61 raise ValueError('invalid block index %s' % index)
62
63 def seek(self,index):
64 self._validate_index(index)
65 self.block_index = index-1
66 self.finished = False
67
68 def show(self,index=None):
69 if index is None:
70 index = self.block_index
71 else:
72 self._validate_index(index)
73 print marquee('<%s> block # %s (%s/%s)' %
74 (self.fname,index,index+1,self.nblocks))
75 print self.src_blocks_colored[index],
76
77 def __call__(self,index=None):
78 """run a block of the demo.
79
80 If index is given, it should be an integer >=1 and <= nblocks. This
81 means that the calling convention is one off from typical Python
82 lists. The reason for the inconsistency is that the demo always
83 prints 'Block n/N, and N is the total, so it would be very odd to use
84 zero-indexing here."""
85
86 if index is None and self.finished:
87 print 'Demo finished. Use reset() if you want to rerun it.'
88 return
89 if index is None:
90 index = self.block_index
91 self._validate_index(index)
92 try:
93 next_block = self.src_blocks[index]
94 self.block_index += 1
95 self.show(index)
96 if not self.auto:
97 print marquee('Press <q> to quit, <Enter> to execute...'),
98 ans = raw_input().strip()
99 if ans:
100 print marquee('Block NOT executed')
101 return
102
103 exec next_block in self.user_ns
104
105 except:
106 self.ip_showtraceback(filename=self.fname)
107 else:
108 self.ip_ns.update(self.user_ns)
109
110 if self.block_index == self.nblocks:
111 print
112 print marquee(' END OF DEMO ')
113 print marquee('Use reset() if you want to rerun it.')
114 self.finished = True
115
@@ -5,7 +5,7 b' General purpose utilities.'
5 5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 6 these things are also convenient when working at the command line.
7 7
8 $Id: genutils.py 874 2005-09-20 20:13:04Z fperez $"""
8 $Id: genutils.py 894 2005-09-22 07:16:18Z fperez $"""
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
@@ -899,6 +899,16 b' def ask_yes_no(prompt,default=None):'
899 899 return answers[ans]
900 900
901 901 #----------------------------------------------------------------------------
902 def marquee(txt='',width=80,mark='*'):
903 """Return the input string centered in a 'marquee'."""
904 if not txt:
905 return (mark*width)[:width]
906 nmark = (width-len(txt)-2)/len(mark)/2
907 if nmark < 0: nmark =0
908 marks = mark*nmark
909 return '%s %s %s' % (marks,txt,marks)
910
911 #----------------------------------------------------------------------------
902 912 class EvalDict:
903 913 """
904 914 Emulate a dict which evaluates its contents in the caller's frame.
@@ -6,7 +6,7 b' Requires Python 2.1 or newer.'
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 874 2005-09-20 20:13:04Z fperez $
9 $Id: iplib.py 894 2005-09-22 07:16:18Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
@@ -1272,7 +1272,7 b' want to merge them back into the new files.""" % locals()'
1272 1272 return
1273 1273 pdb.pm()
1274 1274
1275 def showtraceback(self,exc_tuple = None):
1275 def showtraceback(self,exc_tuple = None,filename=None):
1276 1276 """Display the exception that just occurred."""
1277 1277
1278 1278 # Though this won't be called by syntax errors in the input line,
@@ -1282,7 +1282,7 b' want to merge them back into the new files.""" % locals()'
1282 1282 else:
1283 1283 type, value, tb = exc_tuple
1284 1284 if type is SyntaxError:
1285 self.showsyntaxerror()
1285 self.showsyntaxerror(filename)
1286 1286 else:
1287 1287 sys.last_type = type
1288 1288 sys.last_value = value
@@ -1,9 +1,20 b''
1 2005-09-22 Fernando Perez <Fernando.Perez@colorado.edu>
2
3 * IPython/genutils.py (marquee): little utility used by the demo
4 code, handy in general.
5
6 * IPython/demo.py (Demo.__init__): new class for interactive
7 demos. Not documented yet, I just wrote it in a hurry for
8 scipy'05. Will docstring later.
9
1 10 2005-09-20 Fernando Perez <Fernando.Perez@colorado.edu>
2 11
3 12 * IPython/Shell.py (sigint_handler): Drastic simplification which
4 13 also seems to make Ctrl-C work correctly across threads! This is
5 14 so simple, that I can't beleive I'd missed it before. Needs more
6 15 testing, though.
16 (KBINT): Never mind, revert changes. I'm sure I'd tried something
17 like this before...
7 18
8 19 * IPython/genutils.py (get_home_dir): add protection against
9 20 non-dirs in win32 registry.
General Comments 0
You need to be logged in to leave comments. Login now