ipython_directive.py 44 KB

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