Show More
@@ -1,635 +1,813 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Sphinx directive to support embedded IPython code. |
|
2 | """Sphinx directive to support embedded IPython code. | |
3 |
|
3 | |||
4 | This directive allows pasting of entire interactive IPython sessions, prompts |
|
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 |
|
5 | and all, and their code will actually get re-executed at doc build time, with | |
6 | all prompts renumbered sequentially. |
|
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. | |||
7 |
|
9 | |||
8 | To enable this directive, simply list it in your Sphinx ``conf.py`` file |
|
10 | To enable this directive, simply list it in your Sphinx ``conf.py`` file | |
9 | (making sure the directory where you placed it is visible to sphinx, as is |
|
11 | (making sure the directory where you placed it is visible to sphinx, as is | |
10 | needed for all Sphinx directives). |
|
12 | needed for all Sphinx directives). | |
11 |
|
13 | |||
12 | By default this directive assumes that your prompts are unchanged IPython ones, |
|
14 | By default this directive assumes that your prompts are unchanged IPython ones, | |
13 |
but this can be customized. |
|
15 | but this can be customized. The configurable options that can be placed in | |
14 | config file will configure this directive for the following input/output |
|
16 | conf.py are | |
15 | prompts ``Yade [1]:`` and ``-> [1]:``:: |
|
17 | ||
16 |
|
18 | ipython_savefig_dir: | ||
17 | import ipython_directive as id |
|
19 | The directory in which to save the figures. This is relative to the | |
18 | id.rgxin =re.compile(r'(?:In |Yade )\[(\d+)\]:\s?(.*)\s*') |
|
20 | Sphinx source directory. The default is `html_static_path`. | |
19 | id.rgxout=re.compile(r'(?:Out| -> )\[(\d+)\]:\s?(.*)\s*') |
|
21 | ipython_rgxin: | |
20 | id.fmtin ='Yade [%d]:' |
|
22 | The compiled regular expression to denote the start of IPython input | |
21 | id.fmtout=' -> [%d]:' |
|
23 | lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You | |
22 |
|
24 | shouldn't need to change this. | ||
23 | from IPython import Config |
|
25 | ipython_rgxout: | |
24 | id.CONFIG = Config( |
|
26 | The compiled regular expression to denote the start of IPython output | |
25 | prompt_in1="Yade [\#]:", |
|
27 | lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You | |
26 | prompt_in2=" .\D..", |
|
28 | shouldn't need to change this. | |
27 | prompt_out=" -> [\#]:" |
|
29 | ipython_promptin: | |
28 | ) |
|
30 | The string to represent the IPython input prompt in the generated ReST. | |
29 | id.reconfig_shell() |
|
31 | The default is 'In [%d]:'. This expects that the line numbers are used | |
30 |
|
32 | in the prompt. | ||
31 | import ipython_console_highlighting as ich |
|
33 | ipython_promptout: | |
32 | ich.IPythonConsoleLexer.input_prompt= |
|
34 | ||
33 | re.compile("(Yade \[[0-9]+\]: )|( \.\.\.+:)") |
|
35 | The string to represent the IPython prompt in the generated ReST. The | |
34 | ich.IPythonConsoleLexer.output_prompt= |
|
36 | default is 'Out [%d]:'. This expects that the line numbers are used | |
35 | re.compile("(( -> )|(Out)\[[0-9]+\]: )|( \.\.\.+:)") |
|
37 | in the prompt. | |
36 | ich.IPythonConsoleLexer.continue_prompt=re.compile(" \.\.\.+:") |
|
|||
37 |
|
||||
38 |
|
38 | |||
39 | ToDo |
|
39 | ToDo | |
40 | ---- |
|
40 | ---- | |
41 |
|
41 | |||
42 | - Turn the ad-hoc test() function into a real test suite. |
|
42 | - Turn the ad-hoc test() function into a real test suite. | |
43 | - Break up ipython-specific functionality from matplotlib stuff into better |
|
43 | - Break up ipython-specific functionality from matplotlib stuff into better | |
44 | separated code. |
|
44 | separated code. | |
45 | - Make sure %bookmarks used internally are removed on exit. |
|
|||
46 |
|
||||
47 |
|
45 | |||
48 | Authors |
|
46 | Authors | |
49 | ------- |
|
47 | ------- | |
50 |
|
48 | |||
51 | - John D Hunter: orignal author. |
|
49 | - John D Hunter: orignal author. | |
52 | - Fernando Perez: refactoring, documentation, cleanups, port to 0.11. |
|
50 | - Fernando Perez: refactoring, documentation, cleanups, port to 0.11. | |
53 | - VΓ‘clavΕ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations. |
|
51 | - VΓ‘clavΕ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations. | |
|
52 | - Skipper Seabold, refactoring, cleanups, pure python addition | |||
54 | """ |
|
53 | """ | |
55 |
|
54 | |||
56 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
57 | # Imports |
|
56 | # Imports | |
58 | #----------------------------------------------------------------------------- |
|
57 | #----------------------------------------------------------------------------- | |
59 |
|
58 | |||
60 | # Stdlib |
|
59 | # Stdlib | |
61 | import cStringIO |
|
60 | import cStringIO | |
62 | import os |
|
61 | import os | |
63 | import re |
|
62 | import re | |
64 | import sys |
|
63 | import sys | |
|
64 | import tempfile | |||
65 |
|
65 | |||
66 | # To keep compatibility with various python versions |
|
66 | # To keep compatibility with various python versions | |
67 | try: |
|
67 | try: | |
68 | from hashlib import md5 |
|
68 | from hashlib import md5 | |
69 | except ImportError: |
|
69 | except ImportError: | |
70 | from md5 import md5 |
|
70 | from md5 import md5 | |
71 |
|
71 | |||
72 | # Third-party |
|
72 | # Third-party | |
73 | import matplotlib |
|
73 | import matplotlib | |
74 | import sphinx |
|
74 | import sphinx | |
75 | from docutils.parsers.rst import directives |
|
75 | from docutils.parsers.rst import directives | |
|
76 | from docutils import nodes | |||
|
77 | from sphinx.util.compat import Directive | |||
76 |
|
78 | |||
77 | matplotlib.use('Agg') |
|
79 | matplotlib.use('Agg') | |
78 |
|
80 | |||
79 | # Our own |
|
81 | # Our own | |
80 | from IPython import Config, InteractiveShell |
|
82 | from IPython import Config, InteractiveShell | |
81 |
from IPython. |
|
83 | from IPython.core.profiledir import ProfileDir | |
|
84 | from IPython.utils import io | |||
82 |
|
85 | |||
83 | #----------------------------------------------------------------------------- |
|
86 | #----------------------------------------------------------------------------- | |
84 | # Globals |
|
87 | # Globals | |
85 | #----------------------------------------------------------------------------- |
|
88 | #----------------------------------------------------------------------------- | |
86 |
|
89 | # for tokenizing blocks | ||
87 | sphinx_version = sphinx.__version__.split(".") |
|
|||
88 | # The split is necessary for sphinx beta versions where the string is |
|
|||
89 | # '6b1' |
|
|||
90 | sphinx_version = tuple([int(re.split('[a-z]', x)[0]) |
|
|||
91 | for x in sphinx_version[:2]]) |
|
|||
92 |
|
||||
93 | COMMENT, INPUT, OUTPUT = range(3) |
|
90 | COMMENT, INPUT, OUTPUT = range(3) | |
94 | CONFIG = Config() |
|
|||
95 | rgxin = re.compile('In \[(\d+)\]:\s?(.*)\s*') |
|
|||
96 | rgxout = re.compile('Out\[(\d+)\]:\s?(.*)\s*') |
|
|||
97 | fmtin = 'In [%d]:' |
|
|||
98 | fmtout = 'Out[%d]:' |
|
|||
99 |
|
91 | |||
100 | #----------------------------------------------------------------------------- |
|
92 | #----------------------------------------------------------------------------- | |
101 | # Functions and class declarations |
|
93 | # Functions and class declarations | |
102 | #----------------------------------------------------------------------------- |
|
94 | #----------------------------------------------------------------------------- | |
103 | def block_parser(part): |
|
95 | def block_parser(part, rgxin, rgxout, fmtin, fmtout): | |
104 | """ |
|
96 | """ | |
105 | part is a string of ipython text, comprised of at most one |
|
97 | part is a string of ipython text, comprised of at most one | |
106 | input, one ouput, comments, and blank lines. The block parser |
|
98 | input, one ouput, comments, and blank lines. The block parser | |
107 | parses the text into a list of:: |
|
99 | parses the text into a list of:: | |
108 |
|
100 | |||
109 | blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] |
|
101 | blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] | |
110 |
|
102 | |||
111 | where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and |
|
103 | where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and | |
112 | data is, depending on the type of token:: |
|
104 | data is, depending on the type of token:: | |
113 |
|
105 | |||
114 | COMMENT : the comment string |
|
106 | COMMENT : the comment string | |
115 |
|
107 | |||
116 | INPUT: the (DECORATOR, INPUT_LINE, REST) where |
|
108 | INPUT: the (DECORATOR, INPUT_LINE, REST) where | |
117 | DECORATOR: the input decorator (or None) |
|
109 | DECORATOR: the input decorator (or None) | |
118 | INPUT_LINE: the input as string (possibly multi-line) |
|
110 | INPUT_LINE: the input as string (possibly multi-line) | |
119 | REST : any stdout generated by the input line (not OUTPUT) |
|
111 | REST : any stdout generated by the input line (not OUTPUT) | |
120 |
|
112 | |||
121 |
|
113 | |||
122 | OUTPUT: the output string, possibly multi-line |
|
114 | OUTPUT: the output string, possibly multi-line | |
123 | """ |
|
115 | """ | |
124 |
|
116 | |||
125 | block = [] |
|
117 | block = [] | |
126 | lines = part.split('\n') |
|
118 | lines = part.split('\n') | |
127 | N = len(lines) |
|
119 | N = len(lines) | |
128 | i = 0 |
|
120 | i = 0 | |
129 | decorator = None |
|
121 | decorator = None | |
130 | while 1: |
|
122 | while 1: | |
131 |
|
123 | |||
132 | if i==N: |
|
124 | if i==N: | |
133 | # nothing left to parse -- the last line |
|
125 | # nothing left to parse -- the last line | |
134 | break |
|
126 | break | |
135 |
|
127 | |||
136 | line = lines[i] |
|
128 | line = lines[i] | |
137 | i += 1 |
|
129 | i += 1 | |
138 | line_stripped = line.strip() |
|
130 | line_stripped = line.strip() | |
139 | if line_stripped.startswith('#'): |
|
131 | if line_stripped.startswith('#'): | |
140 | block.append((COMMENT, line)) |
|
132 | block.append((COMMENT, line)) | |
141 | continue |
|
133 | continue | |
142 |
|
134 | |||
143 | if line_stripped.startswith('@'): |
|
135 | if line_stripped.startswith('@'): | |
144 | # we're assuming at most one decorator -- may need to |
|
136 | # we're assuming at most one decorator -- may need to | |
145 | # rethink |
|
137 | # rethink | |
146 | decorator = line_stripped |
|
138 | decorator = line_stripped | |
147 | continue |
|
139 | continue | |
148 |
|
140 | |||
149 | # does this look like an input line? |
|
141 | # does this look like an input line? | |
150 | matchin = rgxin.match(line) |
|
142 | matchin = rgxin.match(line) | |
151 | if matchin: |
|
143 | if matchin: | |
152 | lineno, inputline = int(matchin.group(1)), matchin.group(2) |
|
144 | lineno, inputline = int(matchin.group(1)), matchin.group(2) | |
153 |
|
145 | |||
154 | # the ....: continuation string |
|
146 | # the ....: continuation string | |
155 | continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) |
|
147 | continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) | |
156 | Nc = len(continuation) |
|
148 | Nc = len(continuation) | |
157 | # input lines can continue on for more than one line, if |
|
149 | # input lines can continue on for more than one line, if | |
158 | # we have a '\' line continuation char or a function call |
|
150 | # we have a '\' line continuation char or a function call | |
159 | # echo line 'print'. The input line can only be |
|
151 | # echo line 'print'. The input line can only be | |
160 | # terminated by the end of the block or an output line, so |
|
152 | # terminated by the end of the block or an output line, so | |
161 | # we parse out the rest of the input line if it is |
|
153 | # we parse out the rest of the input line if it is | |
162 | # multiline as well as any echo text |
|
154 | # multiline as well as any echo text | |
163 |
|
155 | |||
164 | rest = [] |
|
156 | rest = [] | |
165 | while i<N: |
|
157 | while i<N: | |
166 |
|
158 | |||
167 | # look ahead; if the next line is blank, or a comment, or |
|
159 | # look ahead; if the next line is blank, or a comment, or | |
168 | # an output line, we're done |
|
160 | # an output line, we're done | |
169 |
|
161 | |||
170 | nextline = lines[i] |
|
162 | nextline = lines[i] | |
171 | matchout = rgxout.match(nextline) |
|
163 | matchout = rgxout.match(nextline) | |
172 | #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation)) |
|
164 | #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation)) | |
173 | if matchout or nextline.startswith('#'): |
|
165 | if matchout or nextline.startswith('#'): | |
174 | break |
|
166 | break | |
175 | elif nextline.startswith(continuation): |
|
167 | elif nextline.startswith(continuation): | |
176 | inputline += '\n' + nextline[Nc:] |
|
168 | inputline += '\n' + nextline[Nc:] | |
177 | else: |
|
169 | else: | |
178 | rest.append(nextline) |
|
170 | rest.append(nextline) | |
179 | i+= 1 |
|
171 | i+= 1 | |
180 |
|
172 | |||
181 | block.append((INPUT, (decorator, inputline, '\n'.join(rest)))) |
|
173 | block.append((INPUT, (decorator, inputline, '\n'.join(rest)))) | |
182 | continue |
|
174 | continue | |
183 |
|
175 | |||
184 | # if it looks like an output line grab all the text to the end |
|
176 | # if it looks like an output line grab all the text to the end | |
185 | # of the block |
|
177 | # of the block | |
186 | matchout = rgxout.match(line) |
|
178 | matchout = rgxout.match(line) | |
187 | if matchout: |
|
179 | if matchout: | |
188 | lineno, output = int(matchout.group(1)), matchout.group(2) |
|
180 | lineno, output = int(matchout.group(1)), matchout.group(2) | |
189 | if i<N-1: |
|
181 | if i<N-1: | |
190 | output = '\n'.join([output] + lines[i:]) |
|
182 | output = '\n'.join([output] + lines[i:]) | |
191 |
|
183 | |||
192 | block.append((OUTPUT, output)) |
|
184 | block.append((OUTPUT, output)) | |
193 | break |
|
185 | break | |
194 |
|
186 | |||
195 | return block |
|
187 | return block | |
196 |
|
188 | |||
197 |
|
||||
198 | class EmbeddedSphinxShell(object): |
|
189 | class EmbeddedSphinxShell(object): | |
199 | """An embedded IPython instance to run inside Sphinx""" |
|
190 | """An embedded IPython instance to run inside Sphinx""" | |
200 |
|
191 | |||
201 | def __init__(self): |
|
192 | def __init__(self): | |
202 |
|
193 | |||
203 | self.cout = cStringIO.StringIO() |
|
194 | self.cout = cStringIO.StringIO() | |
204 | Term.cout = self.cout |
|
|||
205 | Term.cerr = self.cout |
|
|||
206 |
|
195 | |||
207 | # For debugging, so we can see normal output, use this: |
|
|||
208 | # from IPython.utils.io import Tee |
|
|||
209 | #Term.cout = Tee(self.cout, channel='stdout') # dbg |
|
|||
210 | #Term.cerr = Tee(self.cout, channel='stderr') # dbg |
|
|||
211 |
|
196 | |||
212 | # Create config object for IPython |
|
197 | # Create config object for IPython | |
213 | config = Config() |
|
198 | config = Config() | |
214 | config.Global.display_banner = False |
|
199 | config.Global.display_banner = False | |
215 | config.Global.exec_lines = ['import numpy as np', |
|
200 | config.Global.exec_lines = ['import numpy as np', | |
216 | 'from pylab import *' |
|
201 | 'from pylab import *' | |
217 | ] |
|
202 | ] | |
218 | config.InteractiveShell.autocall = False |
|
203 | config.InteractiveShell.autocall = False | |
219 | config.InteractiveShell.autoindent = False |
|
204 | config.InteractiveShell.autoindent = False | |
220 | config.InteractiveShell.colors = 'NoColor' |
|
205 | config.InteractiveShell.colors = 'NoColor' | |
221 |
|
206 | |||
|
207 | # create a profile so instance history isn't saved | |||
|
208 | tmp_profile_dir = tempfile.mkdtemp(prefix='profile_') | |||
|
209 | profname = 'auto_profile_sphinx_build' | |||
|
210 | pdir = os.path.join(tmp_profile_dir,profname) | |||
|
211 | profile = ProfileDir.create_profile_dir(pdir) | |||
|
212 | ||||
222 | # Create and initialize ipython, but don't start its mainloop |
|
213 | # Create and initialize ipython, but don't start its mainloop | |
223 | IP = InteractiveShell.instance(config=config) |
|
214 | IP = InteractiveShell.instance(config=config, profile_dir=profile) | |
|
215 | # io.stdout redirect must be done *after* instantiating InteractiveShell | |||
|
216 | io.stdout = self.cout | |||
|
217 | io.stderr = self.cout | |||
|
218 | ||||
|
219 | # For debugging, so we can see normal output, use this: | |||
|
220 | #from IPython.utils.io import Tee | |||
|
221 | #io.stdout = Tee(self.cout, channel='stdout') # dbg | |||
|
222 | #io.stderr = Tee(self.cout, channel='stderr') # dbg | |||
224 |
|
223 | |||
225 | # Store a few parts of IPython we'll need. |
|
224 | # Store a few parts of IPython we'll need. | |
226 | self.IP = IP |
|
225 | self.IP = IP | |
227 | self.user_ns = self.IP.user_ns |
|
226 | self.user_ns = self.IP.user_ns | |
228 | self.user_global_ns = self.IP.user_global_ns |
|
227 | self.user_global_ns = self.IP.user_global_ns | |
229 |
|
228 | |||
230 | self.input = '' |
|
229 | self.input = '' | |
231 | self.output = '' |
|
230 | self.output = '' | |
232 |
|
231 | |||
233 | self.is_verbatim = False |
|
232 | self.is_verbatim = False | |
234 | self.is_doctest = False |
|
233 | self.is_doctest = False | |
235 | self.is_suppress = False |
|
234 | self.is_suppress = False | |
236 |
|
235 | |||
237 | # on the first call to the savefig decorator, we'll import |
|
236 | # on the first call to the savefig decorator, we'll import | |
238 | # pyplot as plt so we can make a call to the plt.gcf().savefig |
|
237 | # pyplot as plt so we can make a call to the plt.gcf().savefig | |
239 | self._pyplot_imported = False |
|
238 | self._pyplot_imported = False | |
240 |
|
239 | |||
241 | # we need bookmark the current dir first so we can save |
|
240 | def clear_cout(self): | |
242 | # relative to it |
|
|||
243 | self.process_input_line('bookmark ipy_basedir') |
|
|||
244 | self.cout.seek(0) |
|
241 | self.cout.seek(0) | |
245 | self.cout.truncate(0) |
|
242 | self.cout.truncate(0) | |
246 |
|
243 | |||
247 | def process_input_line(self, line): |
|
244 | def process_input_line(self, line, store_history=True): | |
248 | """process the input, capturing stdout""" |
|
245 | """process the input, capturing stdout""" | |
249 | #print "input='%s'"%self.input |
|
246 | #print "input='%s'"%self.input | |
250 | stdout = sys.stdout |
|
247 | stdout = sys.stdout | |
|
248 | splitter = self.IP.input_splitter | |||
251 | try: |
|
249 | try: | |
252 | sys.stdout = self.cout |
|
250 | sys.stdout = self.cout | |
253 |
s |
|
251 | splitter.push(line) | |
|
252 | more = splitter.push_accepts_more() | |||
|
253 | if not more: | |||
|
254 | source_raw = splitter.source_raw_reset()[1] | |||
|
255 | self.IP.run_cell(source_raw, store_history=store_history) | |||
254 | finally: |
|
256 | finally: | |
255 | sys.stdout = stdout |
|
257 | sys.stdout = stdout | |
256 |
|
258 | |||
|
259 | def process_image(self, decorator): | |||
|
260 | """ | |||
|
261 | # build out an image directive like | |||
|
262 | # .. image:: somefile.png | |||
|
263 | # :width 4in | |||
|
264 | # | |||
|
265 | # from an input like | |||
|
266 | # savefig somefile.png width=4in | |||
|
267 | """ | |||
|
268 | savefig_dir = self.savefig_dir | |||
|
269 | source_dir = self.source_dir | |||
|
270 | saveargs = decorator.split(' ') | |||
|
271 | filename = saveargs[1] | |||
|
272 | # insert relative path to image file in source | |||
|
273 | outfile = os.path.relpath(os.path.join(savefig_dir,filename), | |||
|
274 | source_dir) | |||
|
275 | ||||
|
276 | imagerows = ['.. image:: %s'%outfile] | |||
|
277 | ||||
|
278 | for kwarg in saveargs[2:]: | |||
|
279 | arg, val = kwarg.split('=') | |||
|
280 | arg = arg.strip() | |||
|
281 | val = val.strip() | |||
|
282 | imagerows.append(' :%s: %s'%(arg, val)) | |||
|
283 | ||||
|
284 | image_file = os.path.basename(outfile) # only return file name | |||
|
285 | image_directive = '\n'.join(imagerows) | |||
|
286 | return image_file, image_directive | |||
|
287 | ||||
|
288 | ||||
257 | # Callbacks for each type of token |
|
289 | # Callbacks for each type of token | |
258 | def process_input(self, data, input_prompt, lineno): |
|
290 | def process_input(self, data, input_prompt, lineno): | |
259 | """Process data block for INPUT token.""" |
|
291 | """Process data block for INPUT token.""" | |
260 | decorator, input, rest = data |
|
292 | decorator, input, rest = data | |
261 | image_file = None |
|
293 | image_file = None | |
|
294 | image_directive = None | |||
262 | #print 'INPUT:', data # dbg |
|
295 | #print 'INPUT:', data # dbg | |
263 | is_verbatim = decorator=='@verbatim' or self.is_verbatim |
|
296 | is_verbatim = decorator=='@verbatim' or self.is_verbatim | |
264 | is_doctest = decorator=='@doctest' or self.is_doctest |
|
297 | is_doctest = decorator=='@doctest' or self.is_doctest | |
265 | is_suppress = decorator=='@suppress' or self.is_suppress |
|
298 | is_suppress = decorator=='@suppress' or self.is_suppress | |
266 | is_savefig = decorator is not None and \ |
|
299 | is_savefig = decorator is not None and \ | |
267 | decorator.startswith('@savefig') |
|
300 | decorator.startswith('@savefig') | |
268 |
|
301 | |||
269 | input_lines = input.split('\n') |
|
302 | input_lines = input.split('\n') | |
270 |
|
303 | |||
271 | continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) |
|
304 | continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) | |
272 | Nc = len(continuation) |
|
305 | Nc = len(continuation) | |
273 |
|
306 | |||
274 | if is_savefig: |
|
307 | if is_savefig: | |
275 | saveargs = decorator.split(' ') |
|
308 | image_file, image_directive = self.process_image(decorator) | |
276 | filename = saveargs[1] |
|
|||
277 | outfile = os.path.join('_static/%s'%filename) |
|
|||
278 | # build out an image directive like |
|
|||
279 | # .. image:: somefile.png |
|
|||
280 | # :width 4in |
|
|||
281 | # |
|
|||
282 | # from an input like |
|
|||
283 | # savefig somefile.png width=4in |
|
|||
284 | imagerows = ['.. image:: %s'%outfile] |
|
|||
285 |
|
||||
286 | for kwarg in saveargs[2:]: |
|
|||
287 | arg, val = kwarg.split('=') |
|
|||
288 | arg = arg.strip() |
|
|||
289 | val = val.strip() |
|
|||
290 | imagerows.append(' :%s: %s'%(arg, val)) |
|
|||
291 |
|
||||
292 | image_file = outfile |
|
|||
293 | image_directive = '\n'.join(imagerows) |
|
|||
294 |
|
||||
295 | # TODO: can we get "rest" from ipython |
|
|||
296 | #self.process_input_line('\n'.join(input_lines)) |
|
|||
297 |
|
309 | |||
298 | ret = [] |
|
310 | ret = [] | |
299 | is_semicolon = False |
|
311 | is_semicolon = False | |
|
312 | store_history = True | |||
300 |
|
313 | |||
301 | for i, line in enumerate(input_lines): |
|
314 | for i, line in enumerate(input_lines): | |
302 | if line.endswith(';'): |
|
315 | if line.endswith(';'): | |
303 | is_semicolon = True |
|
316 | is_semicolon = True | |
|
317 | if is_semicolon or is_suppress: | |||
|
318 | store_history = False | |||
304 |
|
319 | |||
305 | if i==0: |
|
320 | if i==0: | |
306 | # process the first input line |
|
321 | # process the first input line | |
307 | if is_verbatim: |
|
322 | if is_verbatim: | |
308 | self.process_input_line('') |
|
323 | self.process_input_line('') | |
|
324 | self.IP.execution_count += 1 # increment it anyway | |||
309 | else: |
|
325 | else: | |
310 | # only submit the line in non-verbatim mode |
|
326 | # only submit the line in non-verbatim mode | |
311 | self.process_input_line(line) |
|
327 | self.process_input_line(line, store_history=store_history) | |
312 | formatted_line = '%s %s'%(input_prompt, line) |
|
328 | formatted_line = '%s %s'%(input_prompt, line) | |
313 | else: |
|
329 | else: | |
314 | # process a continuation line |
|
330 | # process a continuation line | |
315 | if not is_verbatim: |
|
331 | if not is_verbatim: | |
316 | self.process_input_line(line) |
|
332 | self.process_input_line(line, store_history=store_history) | |
317 |
|
333 | |||
318 | formatted_line = '%s %s'%(continuation, line) |
|
334 | formatted_line = '%s %s'%(continuation, line) | |
319 |
|
335 | |||
320 | if not is_suppress: |
|
336 | if not is_suppress: | |
321 | ret.append(formatted_line) |
|
337 | ret.append(formatted_line) | |
322 |
|
338 | |||
323 | if not is_suppress: |
|
339 | if not is_suppress: | |
324 | if len(rest.strip()): |
|
340 | if len(rest.strip()): | |
325 | if is_verbatim: |
|
341 | if is_verbatim: | |
326 | # the "rest" is the standard output of the |
|
342 | # the "rest" is the standard output of the | |
327 | # input, which needs to be added in |
|
343 | # input, which needs to be added in | |
328 | # verbatim mode |
|
344 | # verbatim mode | |
329 | ret.append(rest) |
|
345 | ret.append(rest) | |
330 |
|
346 | |||
331 | self.cout.seek(0) |
|
347 | self.cout.seek(0) | |
332 | output = self.cout.read() |
|
348 | output = self.cout.read() | |
333 | if not is_suppress and not is_semicolon: |
|
349 | if not is_suppress and not is_semicolon: | |
334 | ret.append(output) |
|
350 | ret.append(output) | |
335 |
|
351 | |||
336 | self.cout.truncate(0) |
|
352 | self.cout.truncate(0) | |
337 | return ret, input_lines, output, is_doctest, image_file |
|
353 | return (ret, input_lines, output, is_doctest, image_file, | |
|
354 | image_directive) | |||
338 | #print 'OUTPUT', output # dbg |
|
355 | #print 'OUTPUT', output # dbg | |
339 |
|
356 | |||
340 | def process_output(self, data, output_prompt, |
|
357 | def process_output(self, data, output_prompt, | |
341 | input_lines, output, is_doctest, image_file): |
|
358 | input_lines, output, is_doctest, image_file): | |
342 | """Process data block for OUTPUT token.""" |
|
359 | """Process data block for OUTPUT token.""" | |
343 | if is_doctest: |
|
360 | if is_doctest: | |
344 | submitted = data.strip() |
|
361 | submitted = data.strip() | |
345 | found = output |
|
362 | found = output | |
346 | if found is not None: |
|
363 | if found is not None: | |
347 | found = found.strip() |
|
364 | found = found.strip() | |
348 |
|
365 | |||
349 | # XXX - fperez: in 0.11, 'output' never comes with the prompt |
|
366 | # XXX - fperez: in 0.11, 'output' never comes with the prompt | |
350 | # in it, just the actual output text. So I think all this code |
|
367 | # in it, just the actual output text. So I think all this code | |
351 | # can be nuked... |
|
368 | # can be nuked... | |
352 | ## ind = found.find(output_prompt) |
|
369 | ||
353 | ## if ind<0: |
|
370 | # the above comment does not appear to be accurate... (minrk) | |
354 | ## e='output prompt="%s" does not match out line=%s' % \ |
|
371 | ||
355 |
|
|
372 | ind = found.find(output_prompt) | |
356 | ## raise RuntimeError(e) |
|
373 | if ind<0: | |
357 | ## found = found[len(output_prompt):].strip() |
|
374 | e='output prompt="%s" does not match out line=%s' % \ | |
|
375 | (output_prompt, found) | |||
|
376 | raise RuntimeError(e) | |||
|
377 | found = found[len(output_prompt):].strip() | |||
358 |
|
378 | |||
359 | if found!=submitted: |
|
379 | if found!=submitted: | |
360 | e = ('doctest failure for input_lines="%s" with ' |
|
380 | e = ('doctest failure for input_lines="%s" with ' | |
361 | 'found_output="%s" and submitted output="%s"' % |
|
381 | 'found_output="%s" and submitted output="%s"' % | |
362 | (input_lines, found, submitted) ) |
|
382 | (input_lines, found, submitted) ) | |
363 | raise RuntimeError(e) |
|
383 | raise RuntimeError(e) | |
364 | #print 'doctest PASSED for input_lines="%s" with found_output="%s" and submitted output="%s"'%(input_lines, found, submitted) |
|
384 | #print 'doctest PASSED for input_lines="%s" with found_output="%s" and submitted output="%s"'%(input_lines, found, submitted) | |
365 |
|
385 | |||
366 | def process_comment(self, data): |
|
386 | def process_comment(self, data): | |
367 | """Process data block for COMMENT token.""" |
|
387 | """Process data fPblock for COMMENT token.""" | |
368 | if not self.is_suppress: |
|
388 | if not self.is_suppress: | |
369 | return [data] |
|
389 | return [data] | |
370 |
|
390 | |||
|
391 | def save_image(self, image_file): | |||
|
392 | """ | |||
|
393 | Saves the image file to disk. | |||
|
394 | """ | |||
|
395 | self.ensure_pyplot() | |||
|
396 | command = 'plt.gcf().savefig("%s")'%image_file | |||
|
397 | #print 'SAVEFIG', command # dbg | |||
|
398 | self.process_input_line('bookmark ipy_thisdir', store_history=False) | |||
|
399 | self.process_input_line('cd -b ipy_savedir', store_history=False) | |||
|
400 | self.process_input_line(command, store_history=False) | |||
|
401 | self.process_input_line('cd -b ipy_thisdir', store_history=False) | |||
|
402 | self.process_input_line('bookmark -d ipy_thisdir', store_history=False) | |||
|
403 | self.clear_cout() | |||
|
404 | ||||
|
405 | ||||
371 | def process_block(self, block): |
|
406 | def process_block(self, block): | |
372 | """ |
|
407 | """ | |
373 | process block from the block_parser and return a list of processed lines |
|
408 | process block from the block_parser and return a list of processed lines | |
374 | """ |
|
409 | """ | |
375 |
|
||||
376 | ret = [] |
|
410 | ret = [] | |
377 | output = None |
|
411 | output = None | |
378 | input_lines = None |
|
412 | input_lines = None | |
|
413 | lineno = self.IP.execution_count | |||
379 |
|
414 | |||
380 | m = rgxin.match(str(self.IP.outputcache.prompt1).strip()) |
|
415 | input_prompt = self.promptin%lineno | |
381 | lineno = int(m.group(1)) |
|
416 | output_prompt = self.promptout%lineno | |
382 |
|
||||
383 | input_prompt = fmtin%lineno |
|
|||
384 | output_prompt = fmtout%lineno |
|
|||
385 | image_file = None |
|
417 | image_file = None | |
386 | image_directive = None |
|
418 | image_directive = None | |
387 | # XXX - This needs a second refactor. There's too much state being |
|
419 | ||
388 | # held globally, which makes for a very awkward interface and large, |
|
|||
389 | # hard to test functions. I've already broken this up at least into |
|
|||
390 | # three separate processors to isolate the logic better, but this only |
|
|||
391 | # serves to highlight the coupling. Next we need to clean it up... |
|
|||
392 | for token, data in block: |
|
420 | for token, data in block: | |
393 | if token==COMMENT: |
|
421 | if token==COMMENT: | |
394 | out_data = self.process_comment(data) |
|
422 | out_data = self.process_comment(data) | |
395 | elif token==INPUT: |
|
423 | elif token==INPUT: | |
396 |
out_data, input_lines, output, is_doctest, image_file |
|
424 | (out_data, input_lines, output, is_doctest, image_file, | |
|
425 | image_directive) = \ | |||
397 | self.process_input(data, input_prompt, lineno) |
|
426 | self.process_input(data, input_prompt, lineno) | |
398 | elif token==OUTPUT: |
|
427 | elif token==OUTPUT: | |
399 | out_data = \ |
|
428 | out_data = \ | |
400 | self.process_output(data, output_prompt, |
|
429 | self.process_output(data, output_prompt, | |
401 | input_lines, output, is_doctest, |
|
430 | input_lines, output, is_doctest, | |
402 | image_file) |
|
431 | image_file) | |
403 | if out_data: |
|
432 | if out_data: | |
404 | ret.extend(out_data) |
|
433 | ret.extend(out_data) | |
405 |
|
434 | |||
|
435 | # save the image files | |||
406 | if image_file is not None: |
|
436 | if image_file is not None: | |
407 |
self. |
|
437 | self.save_image(image_file) | |
408 | command = 'plt.gcf().savefig("%s")'%image_file |
|
438 | ||
409 | print 'SAVEFIG', command # dbg |
|
|||
410 | self.process_input_line('bookmark ipy_thisdir') |
|
|||
411 | self.process_input_line('cd -b ipy_basedir') |
|
|||
412 | self.process_input_line(command) |
|
|||
413 | self.process_input_line('cd -b ipy_thisdir') |
|
|||
414 | self.cout.seek(0) |
|
|||
415 | self.cout.truncate(0) |
|
|||
416 | return ret, image_directive |
|
439 | return ret, image_directive | |
417 |
|
440 | |||
418 | def ensure_pyplot(self): |
|
441 | def ensure_pyplot(self): | |
419 | if self._pyplot_imported: |
|
442 | if self._pyplot_imported: | |
420 | return |
|
443 | return | |
421 |
self.process_input_line('import matplotlib.pyplot as plt' |
|
444 | self.process_input_line('import matplotlib.pyplot as plt', | |
|
445 | store_history=False) | |||
422 |
|
446 | |||
423 | # A global instance used below. XXX: not sure why this can't be created inside |
|
447 | def process_pure_python(self, content): | |
424 | # ipython_directive itself. |
|
448 | """ | |
425 | shell = EmbeddedSphinxShell() |
|
449 | content is a list of strings. it is unedited directive conent | |
|
450 | ||||
|
451 | This runs it line by line in the InteractiveShell, prepends | |||
|
452 | prompts as needed capturing stderr and stdout, then returns | |||
|
453 | the content as a list as if it were ipython code | |||
|
454 | """ | |||
|
455 | output = [] | |||
|
456 | savefig = False # keep up with this to clear figure | |||
|
457 | multiline = False # to handle line continuation | |||
|
458 | fmtin = self.promptin | |||
|
459 | ||||
|
460 | for lineno, line in enumerate(content): | |||
|
461 | ||||
|
462 | line_stripped = line.strip() | |||
|
463 | ||||
|
464 | if not len(line): | |||
|
465 | output.append(line) # preserve empty lines in output | |||
|
466 | continue | |||
|
467 | ||||
|
468 | # handle decorators | |||
|
469 | if line_stripped.startswith('@'): | |||
|
470 | output.extend([line]) | |||
|
471 | if 'savefig' in line: | |||
|
472 | savefig = True # and need to clear figure | |||
|
473 | continue | |||
|
474 | ||||
|
475 | # handle comments | |||
|
476 | if line_stripped.startswith('#'): | |||
|
477 | output.extend([line]) | |||
|
478 | continue | |||
|
479 | ||||
|
480 | # deal with multilines | |||
|
481 | if not multiline: # not currently on a multiline | |||
|
482 | ||||
|
483 | if line_stripped.endswith('\\'): # now we are | |||
|
484 | multiline = True | |||
|
485 | cont_len = len(str(lineno)) + 2 | |||
|
486 | line_to_process = line.strip('\\') | |||
|
487 | output.extend([u"%s %s" % (fmtin%lineno,line)]) | |||
|
488 | continue | |||
|
489 | else: # no we're still not | |||
|
490 | line_to_process = line.strip('\\') | |||
|
491 | else: # we are currently on a multiline | |||
|
492 | line_to_process += line.strip('\\') | |||
|
493 | if line_stripped.endswith('\\'): # and we still are | |||
|
494 | continuation = '.' * cont_len | |||
|
495 | output.extend([(u' %s: '+line_stripped) % continuation]) | |||
|
496 | continue | |||
|
497 | # else go ahead and run this multiline then carry on | |||
|
498 | ||||
|
499 | # get output of line | |||
|
500 | self.process_input_line(unicode(line_to_process.strip()), | |||
|
501 | store_history=False) | |||
|
502 | out_line = self.cout.getvalue() | |||
|
503 | self.clear_cout() | |||
|
504 | ||||
|
505 | # clear current figure if plotted | |||
|
506 | if savefig: | |||
|
507 | self.ensure_pyplot() | |||
|
508 | self.process_input_line('plt.clf()', store_history=False) | |||
|
509 | self.clear_cout() | |||
|
510 | savefig = False | |||
|
511 | ||||
|
512 | # line numbers don't actually matter, they're replaced later | |||
|
513 | if not multiline: | |||
|
514 | in_line = u"%s %s" % (fmtin%lineno,line) | |||
|
515 | ||||
|
516 | output.extend([in_line]) | |||
|
517 | else: | |||
|
518 | output.extend([(u' %s: '+line_stripped) % continuation]) | |||
|
519 | multiline = False | |||
|
520 | if len(out_line): | |||
|
521 | output.extend([out_line]) | |||
|
522 | output.extend([u'']) | |||
|
523 | ||||
|
524 | return output | |||
|
525 | ||||
|
526 | class IpythonDirective(Directive): | |||
|
527 | ||||
|
528 | has_content = True | |||
|
529 | required_arguments = 0 | |||
|
530 | optional_arguments = 4 # python, suppress, verbatim, doctest | |||
|
531 | final_argumuent_whitespace = True | |||
|
532 | option_spec = { 'python': directives.unchanged, | |||
|
533 | 'suppress' : directives.flag, | |||
|
534 | 'verbatim' : directives.flag, | |||
|
535 | 'doctest' : directives.flag, | |||
|
536 | } | |||
426 |
|
537 | |||
427 | def reconfig_shell(): |
|
|||
428 | """Called after setting module-level variables to re-instantiate |
|
|||
429 | with the set values (since shell is instantiated first at import-time |
|
|||
430 | when module variables have default values)""" |
|
|||
431 | global shell |
|
|||
432 | shell = EmbeddedSphinxShell() |
|
538 | shell = EmbeddedSphinxShell() | |
433 |
|
539 | |||
|
540 | def get_config_options(self): | |||
|
541 | # contains sphinx configuration variables | |||
|
542 | config = self.state.document.settings.env.config | |||
|
543 | ||||
|
544 | # get config variables to set figure output directory | |||
|
545 | confdir = self.state.document.settings.env.app.confdir | |||
|
546 | savefig_dir = config.ipython_savefig_dir | |||
|
547 | source_dir = os.path.dirname(self.state.document.current_source) | |||
|
548 | if savefig_dir is None: | |||
|
549 | savefig_dir = config.html_static_path | |||
|
550 | if isinstance(savefig_dir, list): | |||
|
551 | savefig_dir = savefig_dir[0] # safe to assume only one path? | |||
|
552 | savefig_dir = os.path.join(confdir, savefig_dir) | |||
|
553 | ||||
|
554 | # get regex and prompt stuff | |||
|
555 | rgxin = config.ipython_rgxin | |||
|
556 | rgxout = config.ipython_rgxout | |||
|
557 | promptin = config.ipython_promptin | |||
|
558 | promptout = config.ipython_promptout | |||
|
559 | ||||
|
560 | return savefig_dir, source_dir, rgxin, rgxout, promptin, promptout | |||
|
561 | ||||
|
562 | def setup(self): | |||
|
563 | # get config values | |||
|
564 | (savefig_dir, source_dir, rgxin, | |||
|
565 | rgxout, promptin, promptout) = self.get_config_options() | |||
|
566 | ||||
|
567 | # and attach to shell so we don't have to pass them around | |||
|
568 | self.shell.rgxin = rgxin | |||
|
569 | self.shell.rgxout = rgxout | |||
|
570 | self.shell.promptin = promptin | |||
|
571 | self.shell.promptout = promptout | |||
|
572 | self.shell.savefig_dir = savefig_dir | |||
|
573 | self.shell.source_dir = source_dir | |||
|
574 | ||||
|
575 | # setup bookmark for saving figures directory | |||
434 |
|
576 | |||
435 | def ipython_directive(name, arguments, options, content, lineno, |
|
577 | self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir, | |
436 | content_offset, block_text, state, state_machine, |
|
578 | store_history=False) | |
437 | ): |
|
579 | self.shell.clear_cout() | |
438 |
|
580 | |||
439 | debug = ipython_directive.DEBUG |
|
581 | return rgxin, rgxout, promptin, promptout | |
440 | shell.is_suppress = options.has_key('suppress') |
|
|||
441 | shell.is_doctest = options.has_key('doctest') |
|
|||
442 | shell.is_verbatim = options.has_key('verbatim') |
|
|||
443 |
|
582 | |||
444 | #print 'ipy', shell.is_suppress, options |
|
|||
445 | parts = '\n'.join(content).split('\n\n') |
|
|||
446 | lines = ['.. sourcecode:: ipython', ''] |
|
|||
447 |
|
583 | |||
|
584 | def teardown(self): | |||
|
585 | # delete last bookmark | |||
|
586 | self.shell.process_input_line('bookmark -d ipy_savedir', | |||
|
587 | store_history=False) | |||
|
588 | self.shell.clear_cout() | |||
|
589 | ||||
|
590 | def run(self): | |||
|
591 | debug = False | |||
|
592 | ||||
|
593 | #TODO, any reason block_parser can't be a method of embeddable shell | |||
|
594 | # then we wouldn't have to carry these around | |||
|
595 | rgxin, rgxout, promptin, promptout = self.setup() | |||
|
596 | ||||
|
597 | options = self.options | |||
|
598 | self.shell.is_suppress = 'suppress' in options | |||
|
599 | self.shell.is_doctest = 'doctest' in options | |||
|
600 | self.shell.is_verbatim = 'verbatim' in options | |||
|
601 | ||||
|
602 | ||||
|
603 | # handle pure python code | |||
|
604 | if 'python' in self.arguments: | |||
|
605 | content = self.content | |||
|
606 | self.content = self.shell.process_pure_python(content) | |||
|
607 | ||||
|
608 | parts = '\n'.join(self.content).split('\n\n') | |||
|
609 | ||||
|
610 | lines = ['.. code-block:: ipython',''] | |||
448 | figures = [] |
|
611 | figures = [] | |
|
612 | ||||
449 | for part in parts: |
|
613 | for part in parts: | |
450 | block = block_parser(part) |
|
614 | ||
|
615 | block = block_parser(part, rgxin, rgxout, promptin, promptout) | |||
451 |
|
616 | |||
452 | if len(block): |
|
617 | if len(block): | |
453 | rows, figure = shell.process_block(block) |
|
618 | rows, figure = self.shell.process_block(block) | |
454 | for row in rows: |
|
619 | for row in rows: | |
455 |
lines.extend([' |
|
620 | lines.extend([' %s'%line for line in row.split('\n')]) | |
456 |
|
621 | |||
457 | if figure is not None: |
|
622 | if figure is not None: | |
458 | figures.append(figure) |
|
623 | figures.append(figure) | |
459 |
|
624 | |||
|
625 | #text = '\n'.join(lines) | |||
|
626 | #figs = '\n'.join(figures) | |||
|
627 | ||||
460 | for figure in figures: |
|
628 | for figure in figures: | |
461 | lines.append('') |
|
629 | lines.append('') | |
462 | lines.extend(figure.split('\n')) |
|
630 | lines.extend(figure.split('\n')) | |
463 | lines.append('') |
|
631 | lines.append('') | |
464 |
|
632 | |||
465 | #print lines |
|
633 | #print lines | |
466 | if len(lines)>2: |
|
634 | if len(lines)>2: | |
467 | if debug: |
|
635 | if debug: | |
468 | print '\n'.join(lines) |
|
636 | print '\n'.join(lines) | |
469 | else: |
|
637 | else: #NOTE: this raises some errors, what's it for? | |
470 | #print 'INSERTING %d lines'%len(lines) |
|
638 | #print 'INSERTING %d lines'%len(lines) | |
471 | state_machine.insert_input( |
|
639 | self.state_machine.insert_input( | |
472 | lines, state_machine.input_lines.source(0)) |
|
640 | lines, self.state_machine.input_lines.source(0)) | |
|
641 | ||||
|
642 | text = '\n'.join(lines) | |||
|
643 | txtnode = nodes.literal_block(text, text) | |||
|
644 | txtnode['language'] = 'ipython' | |||
|
645 | #imgnode = nodes.image(figs) | |||
473 |
|
646 | |||
474 | return [] |
|
647 | # cleanup | |
|
648 | self.teardown() | |||
475 |
|
649 | |||
476 | ipython_directive.DEBUG = False |
|
650 | return []#, imgnode] | |
477 | ipython_directive.DEBUG = True # dbg |
|
|||
478 |
|
651 | |||
479 | # Enable as a proper Sphinx directive |
|
652 | # Enable as a proper Sphinx directive | |
480 | def setup(app): |
|
653 | def setup(app): | |
481 | setup.app = app |
|
654 | setup.app = app | |
482 | options = {'suppress': directives.flag, |
|
|||
483 | 'doctest': directives.flag, |
|
|||
484 | 'verbatim': directives.flag, |
|
|||
485 | } |
|
|||
486 |
|
655 | |||
487 |
app.add_directive('ipython', |
|
656 | app.add_directive('ipython', IpythonDirective) | |
|
657 | app.add_config_value('ipython_savefig_dir', None, True) | |||
|
658 | app.add_config_value('ipython_rgxin', | |||
|
659 | re.compile('In \[(\d+)\]:\s?(.*)\s*'), True) | |||
|
660 | app.add_config_value('ipython_rgxout', | |||
|
661 | re.compile('Out\[(\d+)\]:\s?(.*)\s*'), True) | |||
|
662 | app.add_config_value('ipython_promptin', 'In [%d]:', True) | |||
|
663 | app.add_config_value('ipython_promptout', 'Out[%d]:', True) | |||
488 |
|
664 | |||
489 |
|
665 | |||
490 | # Simple smoke test, needs to be converted to a proper automatic test. |
|
666 | # Simple smoke test, needs to be converted to a proper automatic test. | |
491 | def test(): |
|
667 | def test(): | |
492 |
|
668 | |||
493 | examples = [ |
|
669 | examples = [ | |
494 | r""" |
|
670 | r""" | |
495 | In [9]: pwd |
|
671 | In [9]: pwd | |
496 | Out[9]: '/home/jdhunter/py4science/book' |
|
672 | Out[9]: '/home/jdhunter/py4science/book' | |
497 |
|
673 | |||
498 | In [10]: cd bookdata/ |
|
674 | In [10]: cd bookdata/ | |
499 | /home/jdhunter/py4science/book/bookdata |
|
675 | /home/jdhunter/py4science/book/bookdata | |
500 |
|
676 | |||
501 | In [2]: from pylab import * |
|
677 | In [2]: from pylab import * | |
502 |
|
678 | |||
503 | In [2]: ion() |
|
679 | In [2]: ion() | |
504 |
|
680 | |||
505 | In [3]: im = imread('stinkbug.png') |
|
681 | In [3]: im = imread('stinkbug.png') | |
506 |
|
682 | |||
507 | @savefig mystinkbug.png width=4in |
|
683 | @savefig mystinkbug.png width=4in | |
508 | In [4]: imshow(im) |
|
684 | In [4]: imshow(im) | |
509 | Out[4]: <matplotlib.image.AxesImage object at 0x39ea850> |
|
685 | Out[4]: <matplotlib.image.AxesImage object at 0x39ea850> | |
510 |
|
686 | |||
511 | """, |
|
687 | """, | |
512 | r""" |
|
688 | r""" | |
513 |
|
689 | |||
514 | In [1]: x = 'hello world' |
|
690 | In [1]: x = 'hello world' | |
515 |
|
691 | |||
516 | # string methods can be |
|
692 | # string methods can be | |
517 | # used to alter the string |
|
693 | # used to alter the string | |
518 | @doctest |
|
694 | @doctest | |
519 | In [2]: x.upper() |
|
695 | In [2]: x.upper() | |
520 | Out[2]: 'HELLO WORLD' |
|
696 | Out[2]: 'HELLO WORLD' | |
521 |
|
697 | |||
522 | @verbatim |
|
698 | @verbatim | |
523 | In [3]: x.st<TAB> |
|
699 | In [3]: x.st<TAB> | |
524 | x.startswith x.strip |
|
700 | x.startswith x.strip | |
525 | """, |
|
701 | """, | |
526 | r""" |
|
702 | r""" | |
527 |
|
703 | |||
528 | In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\ |
|
704 | In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\ | |
529 | .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv' |
|
705 | .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv' | |
530 |
|
706 | |||
531 | In [131]: print url.split('&') |
|
707 | In [131]: print url.split('&') | |
532 | ['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'] |
|
708 | ['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'] | |
533 |
|
709 | |||
534 | In [60]: import urllib |
|
710 | In [60]: import urllib | |
535 |
|
711 | |||
536 | """, |
|
712 | """, | |
537 | r"""\ |
|
713 | r"""\ | |
538 |
|
714 | |||
539 | In [133]: import numpy.random |
|
715 | In [133]: import numpy.random | |
540 |
|
716 | |||
541 | @suppress |
|
717 | @suppress | |
542 | In [134]: numpy.random.seed(2358) |
|
718 | In [134]: numpy.random.seed(2358) | |
543 |
|
719 | |||
544 | @doctest |
|
720 | @doctest | |
545 | In [135]: np.random.rand(10,2) |
|
721 | In [135]: numpy.random.rand(10,2) | |
546 | Out[135]: |
|
722 | Out[135]: | |
547 | array([[ 0.64524308, 0.59943846], |
|
723 | array([[ 0.64524308, 0.59943846], | |
548 | [ 0.47102322, 0.8715456 ], |
|
724 | [ 0.47102322, 0.8715456 ], | |
549 | [ 0.29370834, 0.74776844], |
|
725 | [ 0.29370834, 0.74776844], | |
550 | [ 0.99539577, 0.1313423 ], |
|
726 | [ 0.99539577, 0.1313423 ], | |
551 | [ 0.16250302, 0.21103583], |
|
727 | [ 0.16250302, 0.21103583], | |
552 | [ 0.81626524, 0.1312433 ], |
|
728 | [ 0.81626524, 0.1312433 ], | |
553 | [ 0.67338089, 0.72302393], |
|
729 | [ 0.67338089, 0.72302393], | |
554 | [ 0.7566368 , 0.07033696], |
|
730 | [ 0.7566368 , 0.07033696], | |
555 | [ 0.22591016, 0.77731835], |
|
731 | [ 0.22591016, 0.77731835], | |
556 | [ 0.0072729 , 0.34273127]]) |
|
732 | [ 0.0072729 , 0.34273127]]) | |
557 |
|
733 | |||
558 | """, |
|
734 | """, | |
559 |
|
735 | |||
560 | r""" |
|
736 | r""" | |
561 | In [106]: print x |
|
737 | In [106]: print x | |
562 | jdh |
|
738 | jdh | |
563 |
|
739 | |||
564 | In [109]: for i in range(10): |
|
740 | In [109]: for i in range(10): | |
565 | .....: print i |
|
741 | .....: print i | |
566 | .....: |
|
742 | .....: | |
567 | .....: |
|
743 | .....: | |
568 | 0 |
|
744 | 0 | |
569 | 1 |
|
745 | 1 | |
570 | 2 |
|
746 | 2 | |
571 | 3 |
|
747 | 3 | |
572 | 4 |
|
748 | 4 | |
573 | 5 |
|
749 | 5 | |
574 | 6 |
|
750 | 6 | |
575 | 7 |
|
751 | 7 | |
576 | 8 |
|
752 | 8 | |
577 | 9 |
|
753 | 9 | |
578 | """, |
|
754 | """, | |
579 |
|
755 | |||
580 | r""" |
|
756 | r""" | |
581 |
|
757 | |||
582 | In [144]: from pylab import * |
|
758 | In [144]: from pylab import * | |
583 |
|
759 | |||
584 | In [145]: ion() |
|
760 | In [145]: ion() | |
585 |
|
761 | |||
586 | # use a semicolon to suppress the output |
|
762 | # use a semicolon to suppress the output | |
587 | @savefig test_hist.png width=4in |
|
763 | @savefig test_hist.png width=4in | |
588 | In [151]: hist(np.random.randn(10000), 100); |
|
764 | In [151]: hist(np.random.randn(10000), 100); | |
589 |
|
765 | |||
590 |
|
766 | |||
591 | @savefig test_plot.png width=4in |
|
767 | @savefig test_plot.png width=4in | |
592 | In [151]: plot(np.random.randn(10000), 'o'); |
|
768 | In [151]: plot(np.random.randn(10000), 'o'); | |
593 | """, |
|
769 | """, | |
594 |
|
770 | |||
595 | r""" |
|
771 | r""" | |
596 | # use a semicolon to suppress the output |
|
772 | # use a semicolon to suppress the output | |
597 | In [151]: plt.clf() |
|
773 | In [151]: plt.clf() | |
598 |
|
774 | |||
599 | @savefig plot_simple.png width=4in |
|
775 | @savefig plot_simple.png width=4in | |
600 | In [151]: plot([1,2,3]) |
|
776 | In [151]: plot([1,2,3]) | |
601 |
|
777 | |||
602 | @savefig hist_simple.png width=4in |
|
778 | @savefig hist_simple.png width=4in | |
603 | In [151]: hist(np.random.randn(10000), 100); |
|
779 | In [151]: hist(np.random.randn(10000), 100); | |
604 |
|
780 | |||
605 | """, |
|
781 | """, | |
606 | r""" |
|
782 | r""" | |
607 | # update the current fig |
|
783 | # update the current fig | |
608 | In [151]: ylabel('number') |
|
784 | In [151]: ylabel('number') | |
609 |
|
785 | |||
610 | In [152]: title('normal distribution') |
|
786 | In [152]: title('normal distribution') | |
611 |
|
787 | |||
612 |
|
788 | |||
613 | @savefig hist_with_text.png |
|
789 | @savefig hist_with_text.png | |
614 | In [153]: grid(True) |
|
790 | In [153]: grid(True) | |
615 |
|
791 | |||
616 | """, |
|
792 | """, | |
617 | ] |
|
793 | ] | |
|
794 | # skip local-file depending first example: | |||
|
795 | examples = examples[1:] | |||
618 |
|
796 | |||
619 | #ipython_directive.DEBUG = True # dbg |
|
797 | #ipython_directive.DEBUG = True # dbg | |
620 | #options = dict(suppress=True) # dbg |
|
798 | #options = dict(suppress=True) # dbg | |
621 | options = dict() |
|
799 | options = dict() | |
622 | for example in examples: |
|
800 | for example in examples: | |
623 | content = example.split('\n') |
|
801 | content = example.split('\n') | |
624 | ipython_directive('debug', arguments=None, options=options, |
|
802 | ipython_directive('debug', arguments=None, options=options, | |
625 | content=content, lineno=0, |
|
803 | content=content, lineno=0, | |
626 | content_offset=None, block_text=None, |
|
804 | content_offset=None, block_text=None, | |
627 | state=None, state_machine=None, |
|
805 | state=None, state_machine=None, | |
628 | ) |
|
806 | ) | |
629 |
|
807 | |||
630 | # Run test suite as a script |
|
808 | # Run test suite as a script | |
631 | if __name__=='__main__': |
|
809 | if __name__=='__main__': | |
632 | if not os.path.isdir('_static'): |
|
810 | if not os.path.isdir('_static'): | |
633 | os.mkdir('_static') |
|
811 | os.mkdir('_static') | |
634 | test() |
|
812 | test() | |
635 | print 'All OK? Check figures in _static/' |
|
813 | print 'All OK? Check figures in _static/' |
General Comments 0
You need to be logged in to leave comments.
Login now