ipython_directive.py 44 KB

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