ipython_directive.py 44 KB

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