ipython_directive.py 41 KB

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