ipython_directive.py 42 KB

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