PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/IPython/sphinxext/ipython_directive.py

http://github.com/ipython/ipython
Python | 1251 lines | 1124 code | 46 blank | 81 comment | 34 complexity | 0bf6dec523472c181d0edf55a166df69 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, Apache-2.0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Sphinx directive to support embedded IPython code.
  4. IPython provides an extension for `Sphinx <http://www.sphinx-doc.org/>`_ to
  5. highlight and run code.
  6. This directive allows pasting of entire interactive IPython sessions, prompts
  7. and all, and their code will actually get re-executed at doc build time, with
  8. all prompts renumbered sequentially. It also allows you to input code as a pure
  9. python input by giving the argument python to the directive. The output looks
  10. like an interactive ipython section.
  11. Here is an example of how the IPython directive can
  12. **run** python code, at build time.
  13. .. ipython::
  14. In [1]: 1+1
  15. In [1]: import datetime
  16. ...: datetime.datetime.now()
  17. It supports IPython construct that plain
  18. Python does not understand (like magics):
  19. .. ipython::
  20. In [0]: import time
  21. In [0]: %timeit time.sleep(0.05)
  22. This will also support top-level async when using IPython 7.0+
  23. .. ipython::
  24. In [2]: import asyncio
  25. ...: print('before')
  26. ...: await asyncio.sleep(1)
  27. ...: print('after')
  28. The namespace will persist across multiple code chucks, Let's define a variable:
  29. .. ipython::
  30. In [0]: who = "World"
  31. And now say hello:
  32. .. ipython::
  33. In [0]: print('Hello,', who)
  34. If the current section raises an exception, you can add the ``:okexcept:`` flag
  35. to the current block, otherwise the build will fail.
  36. .. ipython::
  37. :okexcept:
  38. In [1]: 1/0
  39. IPython Sphinx directive module
  40. ===============================
  41. To enable this directive, simply list it in your Sphinx ``conf.py`` file
  42. (making sure the directory where you placed it is visible to sphinx, as is
  43. needed for all Sphinx directives). For example, to enable syntax highlighting
  44. and the IPython directive::
  45. extensions = ['IPython.sphinxext.ipython_console_highlighting',
  46. 'IPython.sphinxext.ipython_directive']
  47. The IPython directive outputs code-blocks with the language 'ipython'. So
  48. if you do not have the syntax highlighting extension enabled as well, then
  49. all rendered code-blocks will be uncolored. By default this directive assumes
  50. that your prompts are unchanged IPython ones, but this can be customized.
  51. The configurable options that can be placed in conf.py are:
  52. ipython_savefig_dir:
  53. The directory in which to save the figures. This is relative to the
  54. Sphinx source directory. The default is `html_static_path`.
  55. ipython_rgxin:
  56. The compiled regular expression to denote the start of IPython input
  57. lines. The default is ``re.compile('In \\[(\\d+)\\]:\\s?(.*)\\s*')``. You
  58. shouldn't need to change this.
  59. ipython_warning_is_error: [default to True]
  60. Fail the build if something unexpected happen, for example if a block raise
  61. an exception but does not have the `:okexcept:` flag. The exact behavior of
  62. what is considered strict, may change between the sphinx directive version.
  63. ipython_rgxout:
  64. The compiled regular expression to denote the start of IPython output
  65. lines. The default is ``re.compile('Out\\[(\\d+)\\]:\\s?(.*)\\s*')``. You
  66. shouldn't need to change this.
  67. ipython_promptin:
  68. The string to represent the IPython input prompt in the generated ReST.
  69. The default is ``'In [%d]:'``. This expects that the line numbers are used
  70. in the prompt.
  71. ipython_promptout:
  72. The string to represent the IPython prompt in the generated ReST. The
  73. default is ``'Out [%d]:'``. This expects that the line numbers are used
  74. in the prompt.
  75. ipython_mplbackend:
  76. The string which specifies if the embedded Sphinx shell should import
  77. Matplotlib and set the backend. The value specifies a backend that is
  78. passed to `matplotlib.use()` before any lines in `ipython_execlines` are
  79. executed. If not specified in conf.py, then the default value of 'agg' is
  80. used. To use the IPython directive without matplotlib as a dependency, set
  81. the value to `None`. It may end up that matplotlib is still imported
  82. if the user specifies so in `ipython_execlines` or makes use of the
  83. @savefig pseudo decorator.
  84. ipython_execlines:
  85. A list of strings to be exec'd in the embedded Sphinx shell. Typical
  86. usage is to make certain packages always available. Set this to an empty
  87. list if you wish to have no imports always available. If specified in
  88. ``conf.py`` as `None`, then it has the effect of making no imports available.
  89. If omitted from conf.py altogether, then the default value of
  90. ['import numpy as np', 'import matplotlib.pyplot as plt'] is used.
  91. ipython_holdcount
  92. When the @suppress pseudo-decorator is used, the execution count can be
  93. incremented or not. The default behavior is to hold the execution count,
  94. corresponding to a value of `True`. Set this to `False` to increment
  95. the execution count after each suppressed command.
  96. As an example, to use the IPython directive when `matplotlib` is not available,
  97. one sets the backend to `None`::
  98. ipython_mplbackend = None
  99. An example usage of the directive is:
  100. .. code-block:: rst
  101. .. ipython::
  102. In [1]: x = 1
  103. In [2]: y = x**2
  104. In [3]: print(y)
  105. See http://matplotlib.org/sampledoc/ipython_directive.html for additional
  106. documentation.
  107. Pseudo-Decorators
  108. =================
  109. Note: Only one decorator is supported per input. If more than one decorator
  110. is specified, then only the last one is used.
  111. In addition to the Pseudo-Decorators/options described at the above link,
  112. several enhancements have been made. The directive will emit a message to the
  113. console at build-time if code-execution resulted in an exception or warning.
  114. You can suppress these on a per-block basis by specifying the :okexcept:
  115. or :okwarning: options:
  116. .. code-block:: rst
  117. .. ipython::
  118. :okexcept:
  119. :okwarning:
  120. In [1]: 1/0
  121. In [2]: # raise warning.
  122. To Do
  123. =====
  124. - Turn the ad-hoc test() function into a real test suite.
  125. - Break up ipython-specific functionality from matplotlib stuff into better
  126. separated code.
  127. """
  128. # Authors
  129. # =======
  130. #
  131. # - John D Hunter: original author.
  132. # - Fernando Perez: refactoring, documentation, cleanups, port to 0.11.
  133. # - VáclavŠmilauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
  134. # - Skipper Seabold, refactoring, cleanups, pure python addition
  135. #-----------------------------------------------------------------------------
  136. # Imports
  137. #-----------------------------------------------------------------------------
  138. # Stdlib
  139. import atexit
  140. import errno
  141. import os
  142. import pathlib
  143. import re
  144. import sys
  145. import tempfile
  146. import ast
  147. import warnings
  148. import shutil
  149. from io import StringIO
  150. # Third-party
  151. from docutils.parsers.rst import directives
  152. from docutils.parsers.rst import Directive
  153. # Our own
  154. from traitlets.config import Config
  155. from IPython import InteractiveShell
  156. from IPython.core.profiledir import ProfileDir
  157. use_matplotlib = False
  158. try:
  159. import matplotlib
  160. use_matplotlib = True
  161. except Exception:
  162. pass
  163. #-----------------------------------------------------------------------------
  164. # Globals
  165. #-----------------------------------------------------------------------------
  166. # for tokenizing blocks
  167. COMMENT, INPUT, OUTPUT = range(3)
  168. #-----------------------------------------------------------------------------
  169. # Functions and class declarations
  170. #-----------------------------------------------------------------------------
  171. def block_parser(part, rgxin, rgxout, fmtin, fmtout):
  172. """
  173. part is a string of ipython text, comprised of at most one
  174. input, one output, comments, and blank lines. The block parser
  175. parses the text into a list of::
  176. blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]
  177. where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
  178. data is, depending on the type of token::
  179. COMMENT : the comment string
  180. INPUT: the (DECORATOR, INPUT_LINE, REST) where
  181. DECORATOR: the input decorator (or None)
  182. INPUT_LINE: the input as string (possibly multi-line)
  183. REST : any stdout generated by the input line (not OUTPUT)
  184. OUTPUT: the output string, possibly multi-line
  185. """
  186. block = []
  187. lines = part.split('\n')
  188. N = len(lines)
  189. i = 0
  190. decorator = None
  191. while 1:
  192. if i==N:
  193. # nothing left to parse -- the last line
  194. break
  195. line = lines[i]
  196. i += 1
  197. line_stripped = line.strip()
  198. if line_stripped.startswith('#'):
  199. block.append((COMMENT, line))
  200. continue
  201. if line_stripped.startswith('@'):
  202. # Here is where we assume there is, at most, one decorator.
  203. # Might need to rethink this.
  204. decorator = line_stripped
  205. continue
  206. # does this look like an input line?
  207. matchin = rgxin.match(line)
  208. if matchin:
  209. lineno, inputline = int(matchin.group(1)), matchin.group(2)
  210. # the ....: continuation string
  211. continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
  212. Nc = len(continuation)
  213. # input lines can continue on for more than one line, if
  214. # we have a '\' line continuation char or a function call
  215. # echo line 'print'. The input line can only be
  216. # terminated by the end of the block or an output line, so
  217. # we parse out the rest of the input line if it is
  218. # multiline as well as any echo text
  219. rest = []
  220. while i<N:
  221. # look ahead; if the next line is blank, or a comment, or
  222. # an output line, we're done
  223. nextline = lines[i]
  224. matchout = rgxout.match(nextline)
  225. #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation))
  226. if matchout or nextline.startswith('#'):
  227. break
  228. elif nextline.startswith(continuation):
  229. # The default ipython_rgx* treat the space following the colon as optional.
  230. # However, If the space is there we must consume it or code
  231. # employing the cython_magic extension will fail to execute.
  232. #
  233. # This works with the default ipython_rgx* patterns,
  234. # If you modify them, YMMV.
  235. nextline = nextline[Nc:]
  236. if nextline and nextline[0] == ' ':
  237. nextline = nextline[1:]
  238. inputline += '\n' + nextline
  239. else:
  240. rest.append(nextline)
  241. i+= 1
  242. block.append((INPUT, (decorator, inputline, '\n'.join(rest))))
  243. continue
  244. # if it looks like an output line grab all the text to the end
  245. # of the block
  246. matchout = rgxout.match(line)
  247. if matchout:
  248. lineno, output = int(matchout.group(1)), matchout.group(2)
  249. if i<N-1:
  250. output = '\n'.join([output] + lines[i:])
  251. block.append((OUTPUT, output))
  252. break
  253. return block
  254. class EmbeddedSphinxShell(object):
  255. """An embedded IPython instance to run inside Sphinx"""
  256. def __init__(self, exec_lines=None):
  257. self.cout = StringIO()
  258. if exec_lines is None:
  259. exec_lines = []
  260. # Create config object for IPython
  261. config = Config()
  262. config.HistoryManager.hist_file = ':memory:'
  263. config.InteractiveShell.autocall = False
  264. config.InteractiveShell.autoindent = False
  265. config.InteractiveShell.colors = 'NoColor'
  266. # create a profile so instance history isn't saved
  267. tmp_profile_dir = tempfile.mkdtemp(prefix='profile_')
  268. profname = 'auto_profile_sphinx_build'
  269. pdir = os.path.join(tmp_profile_dir,profname)
  270. profile = ProfileDir.create_profile_dir(pdir)
  271. # Create and initialize global ipython, but don't start its mainloop.
  272. # This will persist across different EmbeddedSphinxShell instances.
  273. IP = InteractiveShell.instance(config=config, profile_dir=profile)
  274. atexit.register(self.cleanup)
  275. # Store a few parts of IPython we'll need.
  276. self.IP = IP
  277. self.user_ns = self.IP.user_ns
  278. self.user_global_ns = self.IP.user_global_ns
  279. self.input = ''
  280. self.output = ''
  281. self.tmp_profile_dir = tmp_profile_dir
  282. self.is_verbatim = False
  283. self.is_doctest = False
  284. self.is_suppress = False
  285. # Optionally, provide more detailed information to shell.
  286. # this is assigned by the SetUp method of IPythonDirective
  287. # to point at itself.
  288. #
  289. # So, you can access handy things at self.directive.state
  290. self.directive = None
  291. # on the first call to the savefig decorator, we'll import
  292. # pyplot as plt so we can make a call to the plt.gcf().savefig
  293. self._pyplot_imported = False
  294. # Prepopulate the namespace.
  295. for line in exec_lines:
  296. self.process_input_line(line, store_history=False)
  297. def cleanup(self):
  298. shutil.rmtree(self.tmp_profile_dir, ignore_errors=True)
  299. def clear_cout(self):
  300. self.cout.seek(0)
  301. self.cout.truncate(0)
  302. def process_input_line(self, line, store_history):
  303. return self.process_input_lines([line], store_history=store_history)
  304. def process_input_lines(self, lines, store_history=True):
  305. """process the input, capturing stdout"""
  306. stdout = sys.stdout
  307. source_raw = '\n'.join(lines)
  308. try:
  309. sys.stdout = self.cout
  310. self.IP.run_cell(source_raw, store_history=store_history)
  311. finally:
  312. sys.stdout = stdout
  313. def process_image(self, decorator):
  314. """
  315. # build out an image directive like
  316. # .. image:: somefile.png
  317. # :width 4in
  318. #
  319. # from an input like
  320. # savefig somefile.png width=4in
  321. """
  322. savefig_dir = self.savefig_dir
  323. source_dir = self.source_dir
  324. saveargs = decorator.split(' ')
  325. filename = saveargs[1]
  326. # insert relative path to image file in source
  327. # as absolute path for Sphinx
  328. # sphinx expects a posix path, even on Windows
  329. posix_path = pathlib.Path(savefig_dir,filename).as_posix()
  330. outfile = '/' + os.path.relpath(posix_path, source_dir)
  331. imagerows = ['.. image:: %s' % outfile]
  332. for kwarg in saveargs[2:]:
  333. arg, val = kwarg.split('=')
  334. arg = arg.strip()
  335. val = val.strip()
  336. imagerows.append(' :%s: %s'%(arg, val))
  337. image_file = os.path.basename(outfile) # only return file name
  338. image_directive = '\n'.join(imagerows)
  339. return image_file, image_directive
  340. # Callbacks for each type of token
  341. def process_input(self, data, input_prompt, lineno):
  342. """
  343. Process data block for INPUT token.
  344. """
  345. decorator, input, rest = data
  346. image_file = None
  347. image_directive = None
  348. is_verbatim = decorator=='@verbatim' or self.is_verbatim
  349. is_doctest = (decorator is not None and \
  350. decorator.startswith('@doctest')) or self.is_doctest
  351. is_suppress = decorator=='@suppress' or self.is_suppress
  352. is_okexcept = decorator=='@okexcept' or self.is_okexcept
  353. is_okwarning = decorator=='@okwarning' or self.is_okwarning
  354. is_savefig = decorator is not None and \
  355. decorator.startswith('@savefig')
  356. input_lines = input.split('\n')
  357. if len(input_lines) > 1:
  358. if input_lines[-1] != "":
  359. input_lines.append('') # make sure there's a blank line
  360. # so splitter buffer gets reset
  361. continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
  362. if is_savefig:
  363. image_file, image_directive = self.process_image(decorator)
  364. ret = []
  365. is_semicolon = False
  366. # Hold the execution count, if requested to do so.
  367. if is_suppress and self.hold_count:
  368. store_history = False
  369. else:
  370. store_history = True
  371. # Note: catch_warnings is not thread safe
  372. with warnings.catch_warnings(record=True) as ws:
  373. if input_lines[0].endswith(';'):
  374. is_semicolon = True
  375. #for i, line in enumerate(input_lines):
  376. # process the first input line
  377. if is_verbatim:
  378. self.process_input_lines([''])
  379. self.IP.execution_count += 1 # increment it anyway
  380. else:
  381. # only submit the line in non-verbatim mode
  382. self.process_input_lines(input_lines, store_history=store_history)
  383. if not is_suppress:
  384. for i, line in enumerate(input_lines):
  385. if i == 0:
  386. formatted_line = '%s %s'%(input_prompt, line)
  387. else:
  388. formatted_line = '%s %s'%(continuation, line)
  389. ret.append(formatted_line)
  390. if not is_suppress and len(rest.strip()) and is_verbatim:
  391. # The "rest" is the standard output of the input. This needs to be
  392. # added when in verbatim mode. If there is no "rest", then we don't
  393. # add it, as the new line will be added by the processed output.
  394. ret.append(rest)
  395. # Fetch the processed output. (This is not the submitted output.)
  396. self.cout.seek(0)
  397. processed_output = self.cout.read()
  398. if not is_suppress and not is_semicolon:
  399. #
  400. # In IPythonDirective.run, the elements of `ret` are eventually
  401. # combined such that '' entries correspond to newlines. So if
  402. # `processed_output` is equal to '', then the adding it to `ret`
  403. # ensures that there is a blank line between consecutive inputs
  404. # that have no outputs, as in:
  405. #
  406. # In [1]: x = 4
  407. #
  408. # In [2]: x = 5
  409. #
  410. # When there is processed output, it has a '\n' at the tail end. So
  411. # adding the output to `ret` will provide the necessary spacing
  412. # between consecutive input/output blocks, as in:
  413. #
  414. # In [1]: x
  415. # Out[1]: 5
  416. #
  417. # In [2]: x
  418. # Out[2]: 5
  419. #
  420. # When there is stdout from the input, it also has a '\n' at the
  421. # tail end, and so this ensures proper spacing as well. E.g.:
  422. #
  423. # In [1]: print x
  424. # 5
  425. #
  426. # In [2]: x = 5
  427. #
  428. # When in verbatim mode, `processed_output` is empty (because
  429. # nothing was passed to IP. Sometimes the submitted code block has
  430. # an Out[] portion and sometimes it does not. When it does not, we
  431. # need to ensure proper spacing, so we have to add '' to `ret`.
  432. # However, if there is an Out[] in the submitted code, then we do
  433. # not want to add a newline as `process_output` has stuff to add.
  434. # The difficulty is that `process_input` doesn't know if
  435. # `process_output` will be called---so it doesn't know if there is
  436. # Out[] in the code block. The requires that we include a hack in
  437. # `process_block`. See the comments there.
  438. #
  439. ret.append(processed_output)
  440. elif is_semicolon:
  441. # Make sure there is a newline after the semicolon.
  442. ret.append('')
  443. # context information
  444. filename = "Unknown"
  445. lineno = 0
  446. if self.directive.state:
  447. filename = self.directive.state.document.current_source
  448. lineno = self.directive.state.document.current_line
  449. # output any exceptions raised during execution to stdout
  450. # unless :okexcept: has been specified.
  451. if not is_okexcept and (("Traceback" in processed_output) or ("SyntaxError" in processed_output)):
  452. s = "\nException in %s at block ending on line %s\n" % (filename, lineno)
  453. s += "Specify :okexcept: as an option in the ipython:: block to suppress this message\n"
  454. sys.stdout.write('\n\n>>>' + ('-' * 73))
  455. sys.stdout.write(s)
  456. sys.stdout.write(processed_output)
  457. sys.stdout.write('<<<' + ('-' * 73) + '\n\n')
  458. if self.warning_is_error:
  459. raise RuntimeError('Non Expected exception in `{}` line {}'.format(filename, lineno))
  460. # output any warning raised during execution to stdout
  461. # unless :okwarning: has been specified.
  462. if not is_okwarning:
  463. for w in ws:
  464. s = "\nWarning in %s at block ending on line %s\n" % (filename, lineno)
  465. s += "Specify :okwarning: as an option in the ipython:: block to suppress this message\n"
  466. sys.stdout.write('\n\n>>>' + ('-' * 73))
  467. sys.stdout.write(s)
  468. sys.stdout.write(('-' * 76) + '\n')
  469. s=warnings.formatwarning(w.message, w.category,
  470. w.filename, w.lineno, w.line)
  471. sys.stdout.write(s)
  472. sys.stdout.write('<<<' + ('-' * 73) + '\n')
  473. if self.warning_is_error:
  474. raise RuntimeError('Non Expected warning in `{}` line {}'.format(filename, lineno))
  475. self.clear_cout()
  476. return (ret, input_lines, processed_output,
  477. is_doctest, decorator, image_file, image_directive)
  478. def process_output(self, data, output_prompt, input_lines, output,
  479. is_doctest, decorator, image_file):
  480. """
  481. Process data block for OUTPUT token.
  482. """
  483. # Recall: `data` is the submitted output, and `output` is the processed
  484. # output from `input_lines`.
  485. TAB = ' ' * 4
  486. if is_doctest and output is not None:
  487. found = output # This is the processed output
  488. found = found.strip()
  489. submitted = data.strip()
  490. if self.directive is None:
  491. source = 'Unavailable'
  492. content = 'Unavailable'
  493. else:
  494. source = self.directive.state.document.current_source
  495. content = self.directive.content
  496. # Add tabs and join into a single string.
  497. content = '\n'.join([TAB + line for line in content])
  498. # Make sure the output contains the output prompt.
  499. ind = found.find(output_prompt)
  500. if ind < 0:
  501. e = ('output does not contain output prompt\n\n'
  502. 'Document source: {0}\n\n'
  503. 'Raw content: \n{1}\n\n'
  504. 'Input line(s):\n{TAB}{2}\n\n'
  505. 'Output line(s):\n{TAB}{3}\n\n')
  506. e = e.format(source, content, '\n'.join(input_lines),
  507. repr(found), TAB=TAB)
  508. raise RuntimeError(e)
  509. found = found[len(output_prompt):].strip()
  510. # Handle the actual doctest comparison.
  511. if decorator.strip() == '@doctest':
  512. # Standard doctest
  513. if found != submitted:
  514. e = ('doctest failure\n\n'
  515. 'Document source: {0}\n\n'
  516. 'Raw content: \n{1}\n\n'
  517. 'On input line(s):\n{TAB}{2}\n\n'
  518. 'we found output:\n{TAB}{3}\n\n'
  519. 'instead of the expected:\n{TAB}{4}\n\n')
  520. e = e.format(source, content, '\n'.join(input_lines),
  521. repr(found), repr(submitted), TAB=TAB)
  522. raise RuntimeError(e)
  523. else:
  524. self.custom_doctest(decorator, input_lines, found, submitted)
  525. # When in verbatim mode, this holds additional submitted output
  526. # to be written in the final Sphinx output.
  527. # https://github.com/ipython/ipython/issues/5776
  528. out_data = []
  529. is_verbatim = decorator=='@verbatim' or self.is_verbatim
  530. if is_verbatim and data.strip():
  531. # Note that `ret` in `process_block` has '' as its last element if
  532. # the code block was in verbatim mode. So if there is no submitted
  533. # output, then we will have proper spacing only if we do not add
  534. # an additional '' to `out_data`. This is why we condition on
  535. # `and data.strip()`.
  536. # The submitted output has no output prompt. If we want the
  537. # prompt and the code to appear, we need to join them now
  538. # instead of adding them separately---as this would create an
  539. # undesired newline. How we do this ultimately depends on the
  540. # format of the output regex. I'll do what works for the default
  541. # prompt for now, and we might have to adjust if it doesn't work
  542. # in other cases. Finally, the submitted output does not have
  543. # a trailing newline, so we must add it manually.
  544. out_data.append("{0} {1}\n".format(output_prompt, data))
  545. return out_data
  546. def process_comment(self, data):
  547. """Process data fPblock for COMMENT token."""
  548. if not self.is_suppress:
  549. return [data]
  550. def save_image(self, image_file):
  551. """
  552. Saves the image file to disk.
  553. """
  554. self.ensure_pyplot()
  555. command = 'plt.gcf().savefig("%s")'%image_file
  556. #print 'SAVEFIG', command # dbg
  557. self.process_input_line('bookmark ipy_thisdir', store_history=False)
  558. self.process_input_line('cd -b ipy_savedir', store_history=False)
  559. self.process_input_line(command, store_history=False)
  560. self.process_input_line('cd -b ipy_thisdir', store_history=False)
  561. self.process_input_line('bookmark -d ipy_thisdir', store_history=False)
  562. self.clear_cout()
  563. def process_block(self, block):
  564. """
  565. process block from the block_parser and return a list of processed lines
  566. """
  567. ret = []
  568. output = None
  569. input_lines = None
  570. lineno = self.IP.execution_count
  571. input_prompt = self.promptin % lineno
  572. output_prompt = self.promptout % lineno
  573. image_file = None
  574. image_directive = None
  575. found_input = False
  576. for token, data in block:
  577. if token == COMMENT:
  578. out_data = self.process_comment(data)
  579. elif token == INPUT:
  580. found_input = True
  581. (out_data, input_lines, output, is_doctest,
  582. decorator, image_file, image_directive) = \
  583. self.process_input(data, input_prompt, lineno)
  584. elif token == OUTPUT:
  585. if not found_input:
  586. TAB = ' ' * 4
  587. linenumber = 0
  588. source = 'Unavailable'
  589. content = 'Unavailable'
  590. if self.directive:
  591. linenumber = self.directive.state.document.current_line
  592. source = self.directive.state.document.current_source
  593. content = self.directive.content
  594. # Add tabs and join into a single string.
  595. content = '\n'.join([TAB + line for line in content])
  596. e = ('\n\nInvalid block: Block contains an output prompt '
  597. 'without an input prompt.\n\n'
  598. 'Document source: {0}\n\n'
  599. 'Content begins at line {1}: \n\n{2}\n\n'
  600. 'Problematic block within content: \n\n{TAB}{3}\n\n')
  601. e = e.format(source, linenumber, content, block, TAB=TAB)
  602. # Write, rather than include in exception, since Sphinx
  603. # will truncate tracebacks.
  604. sys.stdout.write(e)
  605. raise RuntimeError('An invalid block was detected.')
  606. out_data = \
  607. self.process_output(data, output_prompt, input_lines,
  608. output, is_doctest, decorator,
  609. image_file)
  610. if out_data:
  611. # Then there was user submitted output in verbatim mode.
  612. # We need to remove the last element of `ret` that was
  613. # added in `process_input`, as it is '' and would introduce
  614. # an undesirable newline.
  615. assert(ret[-1] == '')
  616. del ret[-1]
  617. if out_data:
  618. ret.extend(out_data)
  619. # save the image files
  620. if image_file is not None:
  621. self.save_image(image_file)
  622. return ret, image_directive
  623. def ensure_pyplot(self):
  624. """
  625. Ensures that pyplot has been imported into the embedded IPython shell.
  626. Also, makes sure to set the backend appropriately if not set already.
  627. """
  628. # We are here if the @figure pseudo decorator was used. Thus, it's
  629. # possible that we could be here even if python_mplbackend were set to
  630. # `None`. That's also strange and perhaps worthy of raising an
  631. # exception, but for now, we just set the backend to 'agg'.
  632. if not self._pyplot_imported:
  633. if 'matplotlib.backends' not in sys.modules:
  634. # Then ipython_matplotlib was set to None but there was a
  635. # call to the @figure decorator (and ipython_execlines did
  636. # not set a backend).
  637. #raise Exception("No backend was set, but @figure was used!")
  638. import matplotlib
  639. matplotlib.use('agg')
  640. # Always import pyplot into embedded shell.
  641. self.process_input_line('import matplotlib.pyplot as plt',
  642. store_history=False)
  643. self._pyplot_imported = True
  644. def process_pure_python(self, content):
  645. """
  646. content is a list of strings. it is unedited directive content
  647. This runs it line by line in the InteractiveShell, prepends
  648. prompts as needed capturing stderr and stdout, then returns
  649. the content as a list as if it were ipython code
  650. """
  651. output = []
  652. savefig = False # keep up with this to clear figure
  653. multiline = False # to handle line continuation
  654. multiline_start = None
  655. fmtin = self.promptin
  656. ct = 0
  657. for lineno, line in enumerate(content):
  658. line_stripped = line.strip()
  659. if not len(line):
  660. output.append(line)
  661. continue
  662. # handle decorators
  663. if line_stripped.startswith('@'):
  664. output.extend([line])
  665. if 'savefig' in line:
  666. savefig = True # and need to clear figure
  667. continue
  668. # handle comments
  669. if line_stripped.startswith('#'):
  670. output.extend([line])
  671. continue
  672. # deal with lines checking for multiline
  673. continuation = u' %s:'% ''.join(['.']*(len(str(ct))+2))
  674. if not multiline:
  675. modified = u"%s %s" % (fmtin % ct, line_stripped)
  676. output.append(modified)
  677. ct += 1
  678. try:
  679. ast.parse(line_stripped)
  680. output.append(u'')
  681. except Exception: # on a multiline
  682. multiline = True
  683. multiline_start = lineno
  684. else: # still on a multiline
  685. modified = u'%s %s' % (continuation, line)
  686. output.append(modified)
  687. # if the next line is indented, it should be part of multiline
  688. if len(content) > lineno + 1:
  689. nextline = content[lineno + 1]
  690. if len(nextline) - len(nextline.lstrip()) > 3:
  691. continue
  692. try:
  693. mod = ast.parse(
  694. '\n'.join(content[multiline_start:lineno+1]))
  695. if isinstance(mod.body[0], ast.FunctionDef):
  696. # check to see if we have the whole function
  697. for element in mod.body[0].body:
  698. if isinstance(element, ast.Return):
  699. multiline = False
  700. else:
  701. output.append(u'')
  702. multiline = False
  703. except Exception:
  704. pass
  705. if savefig: # clear figure if plotted
  706. self.ensure_pyplot()
  707. self.process_input_line('plt.clf()', store_history=False)
  708. self.clear_cout()
  709. savefig = False
  710. return output
  711. def custom_doctest(self, decorator, input_lines, found, submitted):
  712. """
  713. Perform a specialized doctest.
  714. """
  715. from .custom_doctests import doctests
  716. args = decorator.split()
  717. doctest_type = args[1]
  718. if doctest_type in doctests:
  719. doctests[doctest_type](self, args, input_lines, found, submitted)
  720. else:
  721. e = "Invalid option to @doctest: {0}".format(doctest_type)
  722. raise Exception(e)
  723. class IPythonDirective(Directive):
  724. has_content = True
  725. required_arguments = 0
  726. optional_arguments = 4 # python, suppress, verbatim, doctest
  727. final_argumuent_whitespace = True
  728. option_spec = { 'python': directives.unchanged,
  729. 'suppress' : directives.flag,
  730. 'verbatim' : directives.flag,
  731. 'doctest' : directives.flag,
  732. 'okexcept': directives.flag,
  733. 'okwarning': directives.flag
  734. }
  735. shell = None
  736. seen_docs = set()
  737. def get_config_options(self):
  738. # contains sphinx configuration variables
  739. config = self.state.document.settings.env.config
  740. # get config variables to set figure output directory
  741. savefig_dir = config.ipython_savefig_dir
  742. source_dir = self.state.document.settings.env.srcdir
  743. savefig_dir = os.path.join(source_dir, savefig_dir)
  744. # get regex and prompt stuff
  745. rgxin = config.ipython_rgxin
  746. rgxout = config.ipython_rgxout
  747. warning_is_error= config.ipython_warning_is_error
  748. promptin = config.ipython_promptin
  749. promptout = config.ipython_promptout
  750. mplbackend = config.ipython_mplbackend
  751. exec_lines = config.ipython_execlines
  752. hold_count = config.ipython_holdcount
  753. return (savefig_dir, source_dir, rgxin, rgxout,
  754. promptin, promptout, mplbackend, exec_lines, hold_count, warning_is_error)
  755. def setup(self):
  756. # Get configuration values.
  757. (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout,
  758. mplbackend, exec_lines, hold_count, warning_is_error) = self.get_config_options()
  759. try:
  760. os.makedirs(savefig_dir)
  761. except OSError as e:
  762. if e.errno != errno.EEXIST:
  763. raise
  764. if self.shell is None:
  765. # We will be here many times. However, when the
  766. # EmbeddedSphinxShell is created, its interactive shell member
  767. # is the same for each instance.
  768. if mplbackend and 'matplotlib.backends' not in sys.modules and use_matplotlib:
  769. import matplotlib
  770. matplotlib.use(mplbackend)
  771. # Must be called after (potentially) importing matplotlib and
  772. # setting its backend since exec_lines might import pylab.
  773. self.shell = EmbeddedSphinxShell(exec_lines)
  774. # Store IPython directive to enable better error messages
  775. self.shell.directive = self
  776. # reset the execution count if we haven't processed this doc
  777. #NOTE: this may be borked if there are multiple seen_doc tmp files
  778. #check time stamp?
  779. if not self.state.document.current_source in self.seen_docs:
  780. self.shell.IP.history_manager.reset()
  781. self.shell.IP.execution_count = 1
  782. self.seen_docs.add(self.state.document.current_source)
  783. # and attach to shell so we don't have to pass them around
  784. self.shell.rgxin = rgxin
  785. self.shell.rgxout = rgxout
  786. self.shell.promptin = promptin
  787. self.shell.promptout = promptout
  788. self.shell.savefig_dir = savefig_dir
  789. self.shell.source_dir = source_dir
  790. self.shell.hold_count = hold_count
  791. self.shell.warning_is_error = warning_is_error
  792. # setup bookmark for saving figures directory
  793. self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir,
  794. store_history=False)
  795. self.shell.clear_cout()
  796. return rgxin, rgxout, promptin, promptout
  797. def teardown(self):
  798. # delete last bookmark
  799. self.shell.process_input_line('bookmark -d ipy_savedir',
  800. store_history=False)
  801. self.shell.clear_cout()
  802. def run(self):
  803. debug = False
  804. #TODO, any reason block_parser can't be a method of embeddable shell
  805. # then we wouldn't have to carry these around
  806. rgxin, rgxout, promptin, promptout = self.setup()
  807. options = self.options
  808. self.shell.is_suppress = 'suppress' in options
  809. self.shell.is_doctest = 'doctest' in options
  810. self.shell.is_verbatim = 'verbatim' in options
  811. self.shell.is_okexcept = 'okexcept' in options
  812. self.shell.is_okwarning = 'okwarning' in options
  813. # handle pure python code
  814. if 'python' in self.arguments:
  815. content = self.content
  816. self.content = self.shell.process_pure_python(content)
  817. # parts consists of all text within the ipython-block.
  818. # Each part is an input/output block.
  819. parts = '\n'.join(self.content).split('\n\n')
  820. lines = ['.. code-block:: ipython', '']
  821. figures = []
  822. for part in parts:
  823. block = block_parser(part, rgxin, rgxout, promptin, promptout)
  824. if len(block):
  825. rows, figure = self.shell.process_block(block)
  826. for row in rows:
  827. lines.extend([' {0}'.format(line)
  828. for line in row.split('\n')])
  829. if figure is not None:
  830. figures.append(figure)
  831. else:
  832. message = 'Code input with no code at {}, line {}'\
  833. .format(
  834. self.state.document.current_source,
  835. self.state.document.current_line)
  836. if self.shell.warning_is_error:
  837. raise RuntimeError(message)
  838. else:
  839. warnings.warn(message)
  840. for figure in figures:
  841. lines.append('')
  842. lines.extend(figure.split('\n'))
  843. lines.append('')
  844. if len(lines) > 2:
  845. if debug:
  846. print('\n'.join(lines))
  847. else:
  848. # This has to do with input, not output. But if we comment
  849. # these lines out, then no IPython code will appear in the
  850. # final output.
  851. self.state_machine.insert_input(
  852. lines, self.state_machine.input_lines.source(0))
  853. # cleanup
  854. self.teardown()
  855. return []
  856. # Enable as a proper Sphinx directive
  857. def setup(app):
  858. setup.app = app
  859. app.add_directive('ipython', IPythonDirective)
  860. app.add_config_value('ipython_savefig_dir', 'savefig', 'env')
  861. app.add_config_value('ipython_warning_is_error', True, 'env')
  862. app.add_config_value('ipython_rgxin',
  863. re.compile(r'In \[(\d+)\]:\s?(.*)\s*'), 'env')
  864. app.add_config_value('ipython_rgxout',
  865. re.compile(r'Out\[(\d+)\]:\s?(.*)\s*'), 'env')
  866. app.add_config_value('ipython_promptin', 'In [%d]:', 'env')
  867. app.add_config_value('ipython_promptout', 'Out[%d]:', 'env')
  868. # We could just let matplotlib pick whatever is specified as the default
  869. # backend in the matplotlibrc file, but this would cause issues if the
  870. # backend didn't work in headless environments. For this reason, 'agg'
  871. # is a good default backend choice.
  872. app.add_config_value('ipython_mplbackend', 'agg', 'env')
  873. # If the user sets this config value to `None`, then EmbeddedSphinxShell's
  874. # __init__ method will treat it as [].
  875. execlines = ['import numpy as np']
  876. if use_matplotlib:
  877. execlines.append('import matplotlib.pyplot as plt')
  878. app.add_config_value('ipython_execlines', execlines, 'env')
  879. app.add_config_value('ipython_holdcount', True, 'env')
  880. metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
  881. return metadata
  882. # Simple smoke test, needs to be converted to a proper automatic test.
  883. def test():
  884. examples = [
  885. r"""
  886. In [9]: pwd
  887. Out[9]: '/home/jdhunter/py4science/book'
  888. In [10]: cd bookdata/
  889. /home/jdhunter/py4science/book/bookdata
  890. In [2]: from pylab import *
  891. In [2]: ion()
  892. In [3]: im = imread('stinkbug.png')
  893. @savefig mystinkbug.png width=4in
  894. In [4]: imshow(im)
  895. Out[4]: <matplotlib.image.AxesImage object at 0x39ea850>
  896. """,
  897. r"""
  898. In [1]: x = 'hello world'
  899. # string methods can be
  900. # used to alter the string
  901. @doctest
  902. In [2]: x.upper()
  903. Out[2]: 'HELLO WORLD'
  904. @verbatim
  905. In [3]: x.st<TAB>
  906. x.startswith x.strip
  907. """,
  908. r"""
  909. In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
  910. .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
  911. In [131]: print url.split('&')
  912. ['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']
  913. In [60]: import urllib
  914. """,
  915. r"""\
  916. In [133]: import numpy.random
  917. @suppress
  918. In [134]: numpy.random.seed(2358)
  919. @doctest
  920. In [135]: numpy.random.rand(10,2)
  921. Out[135]:
  922. array([[ 0.64524308, 0.59943846],
  923. [ 0.47102322, 0.8715456 ],
  924. [ 0.29370834, 0.74776844],
  925. [ 0.99539577, 0.1313423 ],
  926. [ 0.16250302, 0.21103583],
  927. [ 0.81626524, 0.1312433 ],
  928. [ 0.67338089, 0.72302393],
  929. [ 0.7566368 , 0.07033696],
  930. [ 0.22591016, 0.77731835],
  931. [ 0.0072729 , 0.34273127]])
  932. """,
  933. r"""
  934. In [106]: print x
  935. jdh
  936. In [109]: for i in range(10):
  937. .....: print i
  938. .....:
  939. .....:
  940. 0
  941. 1
  942. 2
  943. 3
  944. 4
  945. 5
  946. 6
  947. 7
  948. 8
  949. 9
  950. """,
  951. r"""
  952. In [144]: from pylab import *
  953. In [145]: ion()
  954. # use a semicolon to suppress the output
  955. @savefig test_hist.png width=4in
  956. In [151]: hist(np.random.randn(10000), 100);
  957. @savefig test_plot.png width=4in
  958. In [151]: plot(np.random.randn(10000), 'o');
  959. """,
  960. r"""
  961. # use a semicolon to suppress the output
  962. In [151]: plt.clf()
  963. @savefig plot_simple.png width=4in
  964. In [151]: plot([1,2,3])
  965. @savefig hist_simple.png width=4in
  966. In [151]: hist(np.random.randn(10000), 100);
  967. """,
  968. r"""
  969. # update the current fig
  970. In [151]: ylabel('number')
  971. In [152]: title('normal distribution')
  972. @savefig hist_with_text.png
  973. In [153]: grid(True)
  974. @doctest float
  975. In [154]: 0.1 + 0.2
  976. Out[154]: 0.3
  977. @doctest float
  978. In [155]: np.arange(16).reshape(4,4)
  979. Out[155]:
  980. array([[ 0, 1, 2, 3],
  981. [ 4, 5, 6, 7],
  982. [ 8, 9, 10, 11],
  983. [12, 13, 14, 15]])
  984. In [1]: x = np.arange(16, dtype=float).reshape(4,4)
  985. In [2]: x[0,0] = np.inf
  986. In [3]: x[0,1] = np.nan
  987. @doctest float
  988. In [4]: x
  989. Out[4]:
  990. array([[ inf, nan, 2., 3.],
  991. [ 4., 5., 6., 7.],
  992. [ 8., 9., 10., 11.],
  993. [ 12., 13., 14., 15.]])
  994. """,
  995. ]
  996. # skip local-file depending first example:
  997. examples = examples[1:]
  998. #ipython_directive.DEBUG = True # dbg
  999. #options = dict(suppress=True) # dbg
  1000. options = {}
  1001. for example in examples:
  1002. content = example.split('\n')
  1003. IPythonDirective('debug', arguments=None, options=options,
  1004. content=content, lineno=0,
  1005. content_offset=None, block_text=None,
  1006. state=None, state_machine=None,
  1007. )
  1008. # Run test suite as a script
  1009. if __name__=='__main__':
  1010. if not os.path.isdir('_static'):
  1011. os.mkdir('_static')
  1012. test()
  1013. print('All OK? Check figures in _static/')