demo.py 20 KB

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