##// END OF EJS Templates
Update docs for automatic API building.
Fernando Perez -
Show More
@@ -0,0 +1,33 b''
1 #!/usr/bin/env python
2 """Script to auto-generate our API docs.
3 """
4 # stdlib imports
5 import os
6 import sys
7
8 # local imports
9 sys.path.append(os.path.abspath('sphinxext'))
10 from apigen import ApiDocWriter
11
12 #*****************************************************************************
13 if __name__ == '__main__':
14 pjoin = os.path.join
15 package = 'IPython'
16 outdir = pjoin('source','api','generated')
17 docwriter = ApiDocWriter(package,rst_extension='.txt')
18 docwriter.package_skip_patterns += [r'\.fixes$',
19 r'\.externals$',
20 r'\.Extensions',
21 r'\.kernel.config',
22 r'\.attic',
23 ]
24 docwriter.module_skip_patterns += [ r'\.FakeModule',
25 r'\.cocoa',
26 r'\.ipdoctest',
27 r'\.Gnuplot',
28 ]
29 docwriter.write_api_docs(outdir)
30 docwriter.write_index(outdir, 'gen',
31 relative_to = pjoin('source','api')
32 )
33 print '%d files written' % len(docwriter.written_modules)
@@ -0,0 +1,12 b''
1 .. _api-index:
2
3 ###################
4 The IPython API
5 ###################
6
7 .. htmlonly::
8
9 :Release: |version|
10 :Date: |today|
11
12 .. include:: generated/gen.txt
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
@@ -0,0 +1,246 b''
1 ==================================
2 IPython/Vision Beam Pattern Demo
3 ==================================
4
5
6 Installing and testing IPython at OSC systems
7 =============================================
8
9 All components were installed from source and I have my environment set up to
10 include ~/usr/local in my various necessary paths ($PATH, $PYTHONPATH, etc).
11 Other than a slow filesystem for unpacking tarballs, the install went without a
12 hitch. For each needed component, I just downloaded the source tarball,
13 unpacked it via::
14
15 tar xzf (or xjf if it's bz2) filename.tar.{gz,bz2}
16
17 and then installed them (including IPython itself) with::
18
19 cd dirname/ # path to unpacked tarball
20 python setup.py install --prefix=~/usr/local/
21
22 The components I installed are listed below. For each one I give the main
23 project link as well as a direct one to the file I actually dowloaded and used.
24
25 - nose, used for testing:
26 http://somethingaboutorange.com/mrl/projects/nose/
27 http://somethingaboutorange.com/mrl/projects/nose/nose-0.10.3.tar.gz
28
29 - Zope interface, used to declare interfaces in twisted and ipython. Note:
30 you must get this from the page linked below and not fro the defaul
31 one(http://www.zope.org/Products/ZopeInterface) because the latter has an
32 older version, it hasn't been updated in a long time. This pypi link has
33 the current release (3.4.1 as of this writing):
34 http://pypi.python.org/pypi/zope.interface
35 http://pypi.python.org/packages/source/z/zope.interface/zope.interface-3.4.1.tar.gz
36
37 - pyopenssl, security layer used by foolscap. Note: version 0.7 *must* be
38 used:
39 http://sourceforge.net/projects/pyopenssl/
40 http://downloads.sourceforge.net/pyopenssl/pyOpenSSL-0.6.tar.gz?modtime=1212595285&big_mirror=0
41
42
43 - Twisted, used for all networking:
44 http://twistedmatrix.com/trac/wiki/Downloads
45 http://tmrc.mit.edu/mirror/twisted/Twisted/8.1/Twisted-8.1.0.tar.bz2
46
47 - Foolscap, used for managing connections securely:
48 http://foolscap.lothar.com/trac
49 http://foolscap.lothar.com/releases/foolscap-0.3.1.tar.gz
50
51
52 - IPython itself:
53 http://ipython.scipy.org/
54 http://ipython.scipy.org/dist/ipython-0.9.1.tar.gz
55
56
57 I then ran the ipython test suite via::
58
59 iptest -vv
60
61 and it passed with only::
62
63 ======================================================================
64 ERROR: testGetResult_2
65 ----------------------------------------------------------------------
66 DirtyReactorAggregateError: Reactor was unclean.
67 Selectables:
68 <Negotiation #0 on 10105>
69
70 ----------------------------------------------------------------------
71 Ran 419 tests in 33.971s
72
73 FAILED (SKIP=4, errors=1)
74
75 In three more runs of the test suite I was able to reproduce this error
76 sometimes but not always; for now I think we can move on but we need to
77 investigate further. Especially if we start seeing problems in real use (the
78 test suite stresses the networking layer in particular ways that aren't
79 necessarily typical of normal use).
80
81 Next, I started an 8-engine cluster via::
82
83 perez@opt-login01[~]> ipcluster -n 8
84 Starting controller: Controller PID: 30845
85 ^X Starting engines: Engines PIDs: [30846, 30847, 30848, 30849,
86 30850, 30851, 30852, 30853]
87 Log files: /home/perez/.ipython/log/ipcluster-30845-*
88
89 Your cluster is up and running.
90
91 [... etc]
92
93 and in a separate ipython session checked that the cluster is running and I can
94 access all the engines::
95
96 In [1]: from IPython.kernel import client
97
98 In [2]: mec = client.MultiEngineClient()
99
100 In [3]: mec.get_ids()
101 Out[3]: [0, 1, 2, 3, 4, 5, 6, 7]
102
103 and run trivial code in them (after importing the ``random`` module in all
104 engines)::
105
106 In [11]: mec.execute("x=random.randint(0,10)")
107 Out[11]:
108 <Results List>
109 [0] In [3]: x=random.randint(0,10)
110 [1] In [3]: x=random.randint(0,10)
111 [2] In [3]: x=random.randint(0,10)
112 [3] In [3]: x=random.randint(0,10)
113 [4] In [3]: x=random.randint(0,10)
114 [5] In [3]: x=random.randint(0,10)
115 [6] In [3]: x=random.randint(0,10)
116 [7] In [3]: x=random.randint(0,10)
117
118 In [12]: mec.pull('x')
119 Out[12]: [10, 0, 8, 10, 2, 9, 10, 7]
120
121
122 We'll continue conducting more complex tests later, including instaling Vision
123 locally and running the beam demo.
124
125
126 Michel's original instructions
127 ==============================
128
129 I got a Vision network that reproduces the beam pattern demo working:
130
131 .. image:: vision_beam_pattern.png
132 :width: 400
133 :target: vision_beam_pattern.png
134 :align: center
135
136
137 I created a package called beamPattern that provides the function run() in its
138 __init__.py file.
139
140 A subpackage beamPattern/VisionInterface provides Vision nodes for:
141
142 - computing Elevation and Azimuth from a 3D vector
143
144 - Reading .mat files
145
146 - taking the results gathered from the engines and creating the output that a
147 single engine would have had produced
148
149 The Mec node connect to a controller. In my network it was local but an furl
150 can be specified to connect to a remote controller.
151
152 The PRun Func node is from the IPython library of nodes. the import statement
153 is used to get the run function from the beamPattern package and bu puting
154 "run" in the function entry of this node we push this function to the engines.
155 In addition to the node will create input ports for all arguments of the
156 function being pushed (i.e. the run function)
157
158 The second input port on PRun Fun take an integer specifying the rank of the
159 argument we want to scatter. All other arguments will be pushed to the engines.
160
161 The ElevAzim node has a 3D vector widget and computes the El And Az values
162 which are passed into the PRun Fun node through the ports created
163 automatically. The Mat node allows to select the .mat file, reads it and passed
164 the data to the locdata port created automatically on PRun Func
165
166 The calculation is executed in parallel, and the results are gathered and
167 output. Instead of having a list of 3 vectors we nd up with a list of n*3
168 vectors where n is the number of engines. unpackDectorResults will turn it into
169 a list of 3. We then plot x, y, and 10*log10(z)
170
171
172 Installation
173 ------------
174
175 - inflate beamPattern into the site-packages directory for the MGL tools.
176
177 - place the appended IPythonNodes.py and StandardNodes.py into the Vision
178 package of the MGL tools.
179
180 - place the appended items.py in the NetworkEditor package of the MGL tools
181
182 - run vision for the network beamPat5_net.py::
183
184 vision beamPat5_net.py
185
186 Once the network is running, you can:
187
188 - double click on the MEC node and either use an emptty string for the furl to
189 connect to a local engine or cut and paste the furl to the engine you want to
190 use
191
192 - click on the yellow lighting bold to run the network.
193
194 - Try modifying the MAT file or change the Vector used top compute elevation
195 and Azimut.
196
197
198 Fernando's notes
199 ================
200
201 - I had to install IPython and all its dependencies for the python used by the
202 MGL tools.
203
204 - Then I had to install scipy 0.6.0 for it, since the nodes needed Scipy. To
205 do this I sourced the mglenv.sh script and then ran::
206
207 python setup.py install --prefix=~/usr/opt/mgl
208
209
210 Using PBS
211 =========
212
213 The following PBS script can be used to start the engines::
214
215 #PBS -N bgranger-ipython
216 #PBS -j oe
217 #PBS -l walltime=00:10:00
218 #PBS -l nodes=4:ppn=4
219
220 cd $PBS_O_WORKDIR
221 export PATH=$HOME/usr/local/bin
222 export PYTHONPATH=$HOME/usr/local/lib/python2.4/site-packages
223 /usr/local/bin/mpiexec -n 16 ipengine
224
225
226 If this file is called ``ipython_pbs.sh``, then the in one login windows
227 (i.e. on the head-node -- ``opt-login01.osc.edu``), run ``ipcontroller``. In
228 another login window on the same node, run the above script::
229
230 qsub ipython_pbs.sh
231
232 If you look at the first window, you will see some diagnostic output
233 from ipcontroller. You can then get the furl from your own
234 ``~/.ipython/security`` directory and then connect to it remotely.
235
236 You might need to set up an SSH tunnel, however; if this doesn't work as
237 advertised::
238
239 ssh -L 10115:localhost:10105 bic
240
241
242 Links to other resources
243 ========================
244
245 - http://www.osc.edu/~unpingco/glenn_NewLynx2_Demo.avi
246
@@ -0,0 +1,497 b''
1 """Extract reference documentation from the NumPy source tree.
2
3 """
4
5 import inspect
6 import textwrap
7 import re
8 import pydoc
9 from StringIO import StringIO
10 from warnings import warn
11 4
12 class Reader(object):
13 """A line-based string reader.
14
15 """
16 def __init__(self, data):
17 """
18 Parameters
19 ----------
20 data : str
21 String with lines separated by '\n'.
22
23 """
24 if isinstance(data,list):
25 self._str = data
26 else:
27 self._str = data.split('\n') # store string as list of lines
28
29 self.reset()
30
31 def __getitem__(self, n):
32 return self._str[n]
33
34 def reset(self):
35 self._l = 0 # current line nr
36
37 def read(self):
38 if not self.eof():
39 out = self[self._l]
40 self._l += 1
41 return out
42 else:
43 return ''
44
45 def seek_next_non_empty_line(self):
46 for l in self[self._l:]:
47 if l.strip():
48 break
49 else:
50 self._l += 1
51
52 def eof(self):
53 return self._l >= len(self._str)
54
55 def read_to_condition(self, condition_func):
56 start = self._l
57 for line in self[start:]:
58 if condition_func(line):
59 return self[start:self._l]
60 self._l += 1
61 if self.eof():
62 return self[start:self._l+1]
63 return []
64
65 def read_to_next_empty_line(self):
66 self.seek_next_non_empty_line()
67 def is_empty(line):
68 return not line.strip()
69 return self.read_to_condition(is_empty)
70
71 def read_to_next_unindented_line(self):
72 def is_unindented(line):
73 return (line.strip() and (len(line.lstrip()) == len(line)))
74 return self.read_to_condition(is_unindented)
75
76 def peek(self,n=0):
77 if self._l + n < len(self._str):
78 return self[self._l + n]
79 else:
80 return ''
81
82 def is_empty(self):
83 return not ''.join(self._str).strip()
84
85
86 class NumpyDocString(object):
87 def __init__(self,docstring):
88 docstring = textwrap.dedent(docstring).split('\n')
89
90 self._doc = Reader(docstring)
91 self._parsed_data = {
92 'Signature': '',
93 'Summary': [''],
94 'Extended Summary': [],
95 'Parameters': [],
96 'Returns': [],
97 'Raises': [],
98 'Warns': [],
99 'Other Parameters': [],
100 'Attributes': [],
101 'Methods': [],
102 'See Also': [],
103 'Notes': [],
104 'Warnings': [],
105 'References': '',
106 'Examples': '',
107 'index': {}
108 }
109
110 self._parse()
111
112 def __getitem__(self,key):
113 return self._parsed_data[key]
114
115 def __setitem__(self,key,val):
116 if not self._parsed_data.has_key(key):
117 warn("Unknown section %s" % key)
118 else:
119 self._parsed_data[key] = val
120
121 def _is_at_section(self):
122 self._doc.seek_next_non_empty_line()
123
124 if self._doc.eof():
125 return False
126
127 l1 = self._doc.peek().strip() # e.g. Parameters
128
129 if l1.startswith('.. index::'):
130 return True
131
132 l2 = self._doc.peek(1).strip() # ---------- or ==========
133 return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1))
134
135 def _strip(self,doc):
136 i = 0
137 j = 0
138 for i,line in enumerate(doc):
139 if line.strip(): break
140
141 for j,line in enumerate(doc[::-1]):
142 if line.strip(): break
143
144 return doc[i:len(doc)-j]
145
146 def _read_to_next_section(self):
147 section = self._doc.read_to_next_empty_line()
148
149 while not self._is_at_section() and not self._doc.eof():
150 if not self._doc.peek(-1).strip(): # previous line was empty
151 section += ['']
152
153 section += self._doc.read_to_next_empty_line()
154
155 return section
156
157 def _read_sections(self):
158 while not self._doc.eof():
159 data = self._read_to_next_section()
160 name = data[0].strip()
161
162 if name.startswith('..'): # index section
163 yield name, data[1:]
164 elif len(data) < 2:
165 yield StopIteration
166 else:
167 yield name, self._strip(data[2:])
168
169 def _parse_param_list(self,content):
170 r = Reader(content)
171 params = []
172 while not r.eof():
173 header = r.read().strip()
174 if ' : ' in header:
175 arg_name, arg_type = header.split(' : ')[:2]
176 else:
177 arg_name, arg_type = header, ''
178
179 desc = r.read_to_next_unindented_line()
180 desc = dedent_lines(desc)
181
182 params.append((arg_name,arg_type,desc))
183
184 return params
185
186
187 _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|"
188 r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X)
189 def _parse_see_also(self, content):
190 """
191 func_name : Descriptive text
192 continued text
193 another_func_name : Descriptive text
194 func_name1, func_name2, :meth:`func_name`, func_name3
195
196 """
197 items = []
198
199 def parse_item_name(text):
200 """Match ':role:`name`' or 'name'"""
201 m = self._name_rgx.match(text)
202 if m:
203 g = m.groups()
204 if g[1] is None:
205 return g[3], None
206 else:
207 return g[2], g[1]
208 raise ValueError("%s is not a item name" % text)
209
210 def push_item(name, rest):
211 if not name:
212 return
213 name, role = parse_item_name(name)
214 items.append((name, list(rest), role))
215 del rest[:]
216
217 current_func = None
218 rest = []
219
220 for line in content:
221 if not line.strip(): continue
222
223 m = self._name_rgx.match(line)
224 if m and line[m.end():].strip().startswith(':'):
225 push_item(current_func, rest)
226 current_func, line = line[:m.end()], line[m.end():]
227 rest = [line.split(':', 1)[1].strip()]
228 if not rest[0]:
229 rest = []
230 elif not line.startswith(' '):
231 push_item(current_func, rest)
232 current_func = None
233 if ',' in line:
234 for func in line.split(','):
235 push_item(func, [])
236 elif line.strip():
237 current_func = line
238 elif current_func is not None:
239 rest.append(line.strip())
240 push_item(current_func, rest)
241 return items
242
243 def _parse_index(self, section, content):
244 """
245 .. index: default
246 :refguide: something, else, and more
247
248 """
249 def strip_each_in(lst):
250 return [s.strip() for s in lst]
251
252 out = {}
253 section = section.split('::')
254 if len(section) > 1:
255 out['default'] = strip_each_in(section[1].split(','))[0]
256 for line in content:
257 line = line.split(':')
258 if len(line) > 2:
259 out[line[1]] = strip_each_in(line[2].split(','))
260 return out
261
262 def _parse_summary(self):
263 """Grab signature (if given) and summary"""
264 if self._is_at_section():
265 return
266
267 summary = self._doc.read_to_next_empty_line()
268 summary_str = " ".join([s.strip() for s in summary]).strip()
269 if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str):
270 self['Signature'] = summary_str
271 if not self._is_at_section():
272 self['Summary'] = self._doc.read_to_next_empty_line()
273 else:
274 self['Summary'] = summary
275
276 if not self._is_at_section():
277 self['Extended Summary'] = self._read_to_next_section()
278
279 def _parse(self):
280 self._doc.reset()
281 self._parse_summary()
282
283 for (section,content) in self._read_sections():
284 if not section.startswith('..'):
285 section = ' '.join([s.capitalize() for s in section.split(' ')])
286 if section in ('Parameters', 'Attributes', 'Methods',
287 'Returns', 'Raises', 'Warns'):
288 self[section] = self._parse_param_list(content)
289 elif section.startswith('.. index::'):
290 self['index'] = self._parse_index(section, content)
291 elif section == 'See Also':
292 self['See Also'] = self._parse_see_also(content)
293 else:
294 self[section] = content
295
296 # string conversion routines
297
298 def _str_header(self, name, symbol='-'):
299 return [name, len(name)*symbol]
300
301 def _str_indent(self, doc, indent=4):
302 out = []
303 for line in doc:
304 out += [' '*indent + line]
305 return out
306
307 def _str_signature(self):
308 if self['Signature']:
309 return [self['Signature'].replace('*','\*')] + ['']
310 else:
311 return ['']
312
313 def _str_summary(self):
314 if self['Summary']:
315 return self['Summary'] + ['']
316 else:
317 return []
318
319 def _str_extended_summary(self):
320 if self['Extended Summary']:
321 return self['Extended Summary'] + ['']
322 else:
323 return []
324
325 def _str_param_list(self, name):
326 out = []
327 if self[name]:
328 out += self._str_header(name)
329 for param,param_type,desc in self[name]:
330 out += ['%s : %s' % (param, param_type)]
331 out += self._str_indent(desc)
332 out += ['']
333 return out
334
335 def _str_section(self, name):
336 out = []
337 if self[name]:
338 out += self._str_header(name)
339 out += self[name]
340 out += ['']
341 return out
342
343 def _str_see_also(self, func_role):
344 if not self['See Also']: return []
345 out = []
346 out += self._str_header("See Also")
347 last_had_desc = True
348 for func, desc, role in self['See Also']:
349 if role:
350 link = ':%s:`%s`' % (role, func)
351 elif func_role:
352 link = ':%s:`%s`' % (func_role, func)
353 else:
354 link = "`%s`_" % func
355 if desc or last_had_desc:
356 out += ['']
357 out += [link]
358 else:
359 out[-1] += ", %s" % link
360 if desc:
361 out += self._str_indent([' '.join(desc)])
362 last_had_desc = True
363 else:
364 last_had_desc = False
365 out += ['']
366 return out
367
368 def _str_index(self):
369 idx = self['index']
370 out = []
371 out += ['.. index:: %s' % idx.get('default','')]
372 for section, references in idx.iteritems():
373 if section == 'default':
374 continue
375 out += [' :%s: %s' % (section, ', '.join(references))]
376 return out
377
378 def __str__(self, func_role=''):
379 out = []
380 out += self._str_signature()
381 out += self._str_summary()
382 out += self._str_extended_summary()
383 for param_list in ('Parameters','Returns','Raises'):
384 out += self._str_param_list(param_list)
385 out += self._str_section('Warnings')
386 out += self._str_see_also(func_role)
387 for s in ('Notes','References','Examples'):
388 out += self._str_section(s)
389 out += self._str_index()
390 return '\n'.join(out)
391
392
393 def indent(str,indent=4):
394 indent_str = ' '*indent
395 if str is None:
396 return indent_str
397 lines = str.split('\n')
398 return '\n'.join(indent_str + l for l in lines)
399
400 def dedent_lines(lines):
401 """Deindent a list of lines maximally"""
402 return textwrap.dedent("\n".join(lines)).split("\n")
403
404 def header(text, style='-'):
405 return text + '\n' + style*len(text) + '\n'
406
407
408 class FunctionDoc(NumpyDocString):
409 def __init__(self, func, role='func', doc=None):
410 self._f = func
411 self._role = role # e.g. "func" or "meth"
412 if doc is None:
413 doc = inspect.getdoc(func) or ''
414 try:
415 NumpyDocString.__init__(self, doc)
416 except ValueError, e:
417 print '*'*78
418 print "ERROR: '%s' while parsing `%s`" % (e, self._f)
419 print '*'*78
420 #print "Docstring follows:"
421 #print doclines
422 #print '='*78
423
424 if not self['Signature']:
425 func, func_name = self.get_func()
426 try:
427 # try to read signature
428 argspec = inspect.getargspec(func)
429 argspec = inspect.formatargspec(*argspec)
430 argspec = argspec.replace('*','\*')
431 signature = '%s%s' % (func_name, argspec)
432 except TypeError, e:
433 signature = '%s()' % func_name
434 self['Signature'] = signature
435
436 def get_func(self):
437 func_name = getattr(self._f, '__name__', self.__class__.__name__)
438 if inspect.isclass(self._f):
439 func = getattr(self._f, '__call__', self._f.__init__)
440 else:
441 func = self._f
442 return func, func_name
443
444 def __str__(self):
445 out = ''
446
447 func, func_name = self.get_func()
448 signature = self['Signature'].replace('*', '\*')
449
450 roles = {'func': 'function',
451 'meth': 'method'}
452
453 if self._role:
454 if not roles.has_key(self._role):
455 print "Warning: invalid role %s" % self._role
456 out += '.. %s:: %s\n \n\n' % (roles.get(self._role,''),
457 func_name)
458
459 out += super(FunctionDoc, self).__str__(func_role=self._role)
460 return out
461
462
463 class ClassDoc(NumpyDocString):
464 def __init__(self,cls,modulename='',func_doc=FunctionDoc,doc=None):
465 if not inspect.isclass(cls):
466 raise ValueError("Initialise using a class. Got %r" % cls)
467 self._cls = cls
468
469 if modulename and not modulename.endswith('.'):
470 modulename += '.'
471 self._mod = modulename
472 self._name = cls.__name__
473 self._func_doc = func_doc
474
475 if doc is None:
476 doc = pydoc.getdoc(cls)
477
478 NumpyDocString.__init__(self, doc)
479
480 @property
481 def methods(self):
482 return [name for name,func in inspect.getmembers(self._cls)
483 if not name.startswith('_') and callable(func)]
484
485 def __str__(self):
486 out = ''
487 out += super(ClassDoc, self).__str__()
488 out += "\n\n"
489
490 #for m in self.methods:
491 # print "Parsing `%s`" % m
492 # out += str(self._func_doc(getattr(self._cls,m), 'meth')) + '\n\n'
493 # out += '.. index::\n single: %s; %s\n\n' % (self._name, m)
494
495 return out
496
497
@@ -0,0 +1,136 b''
1 import re, inspect, textwrap, pydoc
2 from docscrape import NumpyDocString, FunctionDoc, ClassDoc
3
4 class SphinxDocString(NumpyDocString):
5 # string conversion routines
6 def _str_header(self, name, symbol='`'):
7 return ['.. rubric:: ' + name, '']
8
9 def _str_field_list(self, name):
10 return [':' + name + ':']
11
12 def _str_indent(self, doc, indent=4):
13 out = []
14 for line in doc:
15 out += [' '*indent + line]
16 return out
17
18 def _str_signature(self):
19 return ['']
20 if self['Signature']:
21 return ['``%s``' % self['Signature']] + ['']
22 else:
23 return ['']
24
25 def _str_summary(self):
26 return self['Summary'] + ['']
27
28 def _str_extended_summary(self):
29 return self['Extended Summary'] + ['']
30
31 def _str_param_list(self, name):
32 out = []
33 if self[name]:
34 out += self._str_field_list(name)
35 out += ['']
36 for param,param_type,desc in self[name]:
37 out += self._str_indent(['**%s** : %s' % (param.strip(),
38 param_type)])
39 out += ['']
40 out += self._str_indent(desc,8)
41 out += ['']
42 return out
43
44 def _str_section(self, name):
45 out = []
46 if self[name]:
47 out += self._str_header(name)
48 out += ['']
49 content = textwrap.dedent("\n".join(self[name])).split("\n")
50 out += content
51 out += ['']
52 return out
53
54 def _str_see_also(self, func_role):
55 out = []
56 if self['See Also']:
57 see_also = super(SphinxDocString, self)._str_see_also(func_role)
58 out = ['.. seealso::', '']
59 out += self._str_indent(see_also[2:])
60 return out
61
62 def _str_warnings(self):
63 out = []
64 if self['Warnings']:
65 out = ['.. warning::', '']
66 out += self._str_indent(self['Warnings'])
67 return out
68
69 def _str_index(self):
70 idx = self['index']
71 out = []
72 if len(idx) == 0:
73 return out
74
75 out += ['.. index:: %s' % idx.get('default','')]
76 for section, references in idx.iteritems():
77 if section == 'default':
78 continue
79 elif section == 'refguide':
80 out += [' single: %s' % (', '.join(references))]
81 else:
82 out += [' %s: %s' % (section, ','.join(references))]
83 return out
84
85 def _str_references(self):
86 out = []
87 if self['References']:
88 out += self._str_header('References')
89 if isinstance(self['References'], str):
90 self['References'] = [self['References']]
91 out.extend(self['References'])
92 out += ['']
93 return out
94
95 def __str__(self, indent=0, func_role="obj"):
96 out = []
97 out += self._str_signature()
98 out += self._str_index() + ['']
99 out += self._str_summary()
100 out += self._str_extended_summary()
101 for param_list in ('Parameters', 'Attributes', 'Methods',
102 'Returns','Raises'):
103 out += self._str_param_list(param_list)
104 out += self._str_warnings()
105 out += self._str_see_also(func_role)
106 out += self._str_section('Notes')
107 out += self._str_references()
108 out += self._str_section('Examples')
109 out = self._str_indent(out,indent)
110 return '\n'.join(out)
111
112 class SphinxFunctionDoc(SphinxDocString, FunctionDoc):
113 pass
114
115 class SphinxClassDoc(SphinxDocString, ClassDoc):
116 pass
117
118 def get_doc_object(obj, what=None, doc=None):
119 if what is None:
120 if inspect.isclass(obj):
121 what = 'class'
122 elif inspect.ismodule(obj):
123 what = 'module'
124 elif callable(obj):
125 what = 'function'
126 else:
127 what = 'object'
128 if what == 'class':
129 return SphinxClassDoc(obj, '', func_doc=SphinxFunctionDoc, doc=doc)
130 elif what in ('function', 'method'):
131 return SphinxFunctionDoc(obj, '', doc=doc)
132 else:
133 if doc is None:
134 doc = pydoc.getdoc(obj)
135 return SphinxDocString(doc)
136
@@ -0,0 +1,116 b''
1 """
2 ========
3 numpydoc
4 ========
5
6 Sphinx extension that handles docstrings in the Numpy standard format. [1]
7
8 It will:
9
10 - Convert Parameters etc. sections to field lists.
11 - Convert See Also section to a See also entry.
12 - Renumber references.
13 - Extract the signature from the docstring, if it can't be determined otherwise.
14
15 .. [1] http://projects.scipy.org/scipy/numpy/wiki/CodingStyleGuidelines#docstring-standard
16
17 """
18
19 import os, re, pydoc
20 from docscrape_sphinx import get_doc_object, SphinxDocString
21 import inspect
22
23 def mangle_docstrings(app, what, name, obj, options, lines,
24 reference_offset=[0]):
25 if what == 'module':
26 # Strip top title
27 title_re = re.compile(r'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*',
28 re.I|re.S)
29 lines[:] = title_re.sub('', "\n".join(lines)).split("\n")
30 else:
31 doc = get_doc_object(obj, what, "\n".join(lines))
32 lines[:] = str(doc).split("\n")
33
34 if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \
35 obj.__name__:
36 if hasattr(obj, '__module__'):
37 v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__))
38 else:
39 v = dict(full_name=obj.__name__)
40 lines += ['', '.. htmlonly::', '']
41 lines += [' %s' % x for x in
42 (app.config.numpydoc_edit_link % v).split("\n")]
43
44 # replace reference numbers so that there are no duplicates
45 references = []
46 for l in lines:
47 l = l.strip()
48 if l.startswith('.. ['):
49 try:
50 references.append(int(l[len('.. ['):l.index(']')]))
51 except ValueError:
52 print "WARNING: invalid reference in %s docstring" % name
53
54 # Start renaming from the biggest number, otherwise we may
55 # overwrite references.
56 references.sort()
57 if references:
58 for i, line in enumerate(lines):
59 for r in references:
60 new_r = reference_offset[0] + r
61 lines[i] = lines[i].replace('[%d]_' % r,
62 '[%d]_' % new_r)
63 lines[i] = lines[i].replace('.. [%d]' % r,
64 '.. [%d]' % new_r)
65
66 reference_offset[0] += len(references)
67
68 def mangle_signature(app, what, name, obj, options, sig, retann):
69 # Do not try to inspect classes that don't define `__init__`
70 if (inspect.isclass(obj) and
71 'initializes x; see ' in pydoc.getdoc(obj.__init__)):
72 return '', ''
73
74 if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')): return
75 if not hasattr(obj, '__doc__'): return
76
77 doc = SphinxDocString(pydoc.getdoc(obj))
78 if doc['Signature']:
79 sig = re.sub("^[^(]*", "", doc['Signature'])
80 return sig, ''
81
82 def initialize(app):
83 try:
84 app.connect('autodoc-process-signature', mangle_signature)
85 except:
86 monkeypatch_sphinx_ext_autodoc()
87
88 def setup(app, get_doc_object_=get_doc_object):
89 global get_doc_object
90 get_doc_object = get_doc_object_
91
92 app.connect('autodoc-process-docstring', mangle_docstrings)
93 app.connect('builder-inited', initialize)
94 app.add_config_value('numpydoc_edit_link', None, True)
95
96 #------------------------------------------------------------------------------
97 # Monkeypatch sphinx.ext.autodoc to accept argspecless autodocs (Sphinx < 0.5)
98 #------------------------------------------------------------------------------
99
100 def monkeypatch_sphinx_ext_autodoc():
101 global _original_format_signature
102 import sphinx.ext.autodoc
103
104 if sphinx.ext.autodoc.format_signature is our_format_signature:
105 return
106
107 print "[numpydoc] Monkeypatching sphinx.ext.autodoc ..."
108 _original_format_signature = sphinx.ext.autodoc.format_signature
109 sphinx.ext.autodoc.format_signature = our_format_signature
110
111 def our_format_signature(what, obj):
112 r = mangle_signature(None, what, None, obj, None, None, None)
113 if r is not None:
114 return r[0]
115 else:
116 return _original_format_signature(what, obj)
@@ -6,7 +6,6 b' upstream and were accepted as of Python 2.3, but we need a lot more'
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 ---------------------------------------------------------------------------
10 Original rlcompleter documentation:
9 Original rlcompleter documentation:
11
10
12 This requires the latest extension to the readline module (the
11 This requires the latest extension to the readline module (the
@@ -1234,11 +1234,11 b' def esc_quotes(strng):'
1234 def make_quoted_expr(s):
1234 def make_quoted_expr(s):
1235 """Return string s in appropriate quotes, using raw string if possible.
1235 """Return string s in appropriate quotes, using raw string if possible.
1236
1236
1237 Effectively this turns string: cd \ao\ao\
1237 XXX - example removed because it caused encoding errors in documentation
1238 to: r"cd \ao\ao\_"[:-1]
1238 generation. We need a new example that doesn't contain invalid chars.
1239
1240 Note the use of raw string and padding at the end to allow trailing backslash.
1241
1239
1240 Note the use of raw string and padding at the end to allow trailing
1241 backslash.
1242 """
1242 """
1243
1243
1244 tail = ''
1244 tail = ''
@@ -24,7 +24,6 b' That way the module is imported at startup and you can have all your'
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
28 import IPython.ipapi
27 import IPython.ipapi
29 ip = IPython.ipapi.get()
28 ip = IPython.ipapi.get()
30
29
@@ -70,8 +70,8 b' def esc_quotes(strng):'
70 def make_quoted_expr(s):
70 def make_quoted_expr(s):
71 """Return string s in appropriate quotes, using raw string if possible.
71 """Return string s in appropriate quotes, using raw string if possible.
72
72
73 Effectively this turns string: cd \ao\ao\
73 XXX - example removed because it caused encoding errors in documentation
74 to: r"cd \ao\ao\_"[:-1]
74 generation. We need a new example that doesn't contain invalid chars.
75
75
76 Note the use of raw string and padding at the end to allow trailing
76 Note the use of raw string and padding at the end to allow trailing
77 backslash.
77 backslash.
@@ -121,7 +121,7 b' def skipif(skip_condition, msg=None):'
121 ''' Make function raise SkipTest exception if skip_condition is true
121 ''' Make function raise SkipTest exception if skip_condition is true
122
122
123 Parameters
123 Parameters
124 ---------
124 ----------
125 skip_condition : bool or callable.
125 skip_condition : bool or callable.
126 Flag to determine whether to skip test. If the condition is a
126 Flag to determine whether to skip test. If the condition is a
127 callable, it is used at runtime to dynamically make the decision. This
127 callable, it is used at runtime to dynamically make the decision. This
@@ -50,7 +50,7 b' def skipif(skip_condition=True, msg=None):'
50 ''' Make function raise SkipTest exception if skip_condition is true
50 ''' Make function raise SkipTest exception if skip_condition is true
51
51
52 Parameters
52 Parameters
53 ---------
53 ----------
54 skip_condition : bool or callable.
54 skip_condition : bool or callable.
55 Flag to determine whether to skip test. If the condition is a
55 Flag to determine whether to skip test. If the condition is a
56 callable, it is used at runtime to dynamically make the decision. This
56 callable, it is used at runtime to dynamically make the decision. This
@@ -5,13 +5,14 b''
5 SPHINXOPTS =
5 SPHINXOPTS =
6 SPHINXBUILD = sphinx-build
6 SPHINXBUILD = sphinx-build
7 PAPER =
7 PAPER =
8 SRCDIR = source
8
9
9 # Internal variables.
10 # Internal variables.
10 PAPEROPT_a4 = -D latex_paper_size=a4
11 PAPEROPT_a4 = -D latex_paper_size=a4
11 PAPEROPT_letter = -D latex_paper_size=letter
12 PAPEROPT_letter = -D latex_paper_size=letter
12 ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
13 ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) $(SRCDIR)
13
14
14 .PHONY: help clean html web pickle htmlhelp latex changes linkcheck
15 .PHONY: help clean html web pickle htmlhelp latex changes linkcheck api
15
16
16 help:
17 help:
17 @echo "Please use \`make <target>' where <target> is one of"
18 @echo "Please use \`make <target>' where <target> is one of"
@@ -28,7 +29,7 b' help:'
28 @echo "dist all, and then puts the results in dist/"
29 @echo "dist all, and then puts the results in dist/"
29
30
30 clean:
31 clean:
31 -rm -rf build/* dist/*
32 -rm -rf build/* dist/* $(SRCDIR)/api/generated
32
33
33 pdf: latex
34 pdf: latex
34 cd build/latex && make all-pdf
35 cd build/latex && make all-pdf
@@ -41,12 +42,16 b' dist: clean all'
41 cp -al build/html dist/
42 cp -al build/html dist/
42 @echo "Build finished. Final docs are in dist/"
43 @echo "Build finished. Final docs are in dist/"
43
44
44 html:
45 html: api
45 mkdir -p build/html build/doctrees
46 mkdir -p build/html build/doctrees
46 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html
47 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html
47 @echo
48 @echo
48 @echo "Build finished. The HTML pages are in build/html."
49 @echo "Build finished. The HTML pages are in build/html."
49
50
51 api:
52 python autogen_api.py
53 @echo "Build API docs finished."
54
50 pickle:
55 pickle:
51 mkdir -p build/pickle build/doctrees
56 mkdir -p build/pickle build/doctrees
52 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle
57 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle
@@ -36,9 +36,13 b" execfile('../../IPython/Release.py',iprelease)"
36 # Add any Sphinx extension module names here, as strings. They can be extensions
36 # Add any Sphinx extension module names here, as strings. They can be extensions
37 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
37 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
38 extensions = ['sphinx.ext.autodoc',
38 extensions = ['sphinx.ext.autodoc',
39 'inheritance_diagram', 'only_directives',
39 'sphinx.ext.doctest',
40
41 'only_directives',
42 'inheritance_diagram',
40 'ipython_console_highlighting',
43 'ipython_console_highlighting',
41 # 'plot_directive', # disabled for now, needs matplotlib
44 # 'plot_directive', # disabled for now, needs matplotlib
45 'numpydoc', # to preprocess docstrings
42 ]
46 ]
43
47
44 # Add any paths that contain templates here, relative to this directory.
48 # Add any paths that contain templates here, relative to this directory.
@@ -17,10 +17,11 b' IPython Documentation'
17 interactive/index.txt
17 interactive/index.txt
18 parallel/index.txt
18 parallel/index.txt
19 config/index.txt
19 config/index.txt
20 changes.txt
21 development/index.txt
22 faq.txt
20 faq.txt
23 history.txt
21 history.txt
22 changes.txt
23 development/index.txt
24 api/index.txt
24 license_and_copyright.txt
25 license_and_copyright.txt
25 credits.txt
26 credits.txt
26
27
This diff has been collapsed as it changes many lines, (1571 lines changed) Show them Hide them
@@ -496,9 +496,9 b' following example defines a new magic command, %impall::'
496 ip.expose_magic('impall', doimp)
496 ip.expose_magic('impall', doimp)
497
497
498 You can also define your own aliased names for magic functions. In your
498 You can also define your own aliased names for magic functions. In your
499 ipythonrc file, placing a line like:
499 ipythonrc file, placing a line like::
500
500
501 execute __IP.magic_cl = __IP.magic_clear
501 execute __IP.magic_cl = __IP.magic_clear
502
502
503 will define %cl as a new name for %clear.
503 will define %cl as a new name for %clear.
504
504
@@ -508,1572 +508,9 b' magic functions at any time and their docstrings. You can also type'
508 information on the '?' system) to get information about any particular
508 information on the '?' system) to get information about any particular
509 magic function you are interested in.
509 magic function you are interested in.
510
510
511 The API documentation for the :mod:`IPython.Magic` module contains the full
512 docstrings of all currently available magic commands.
511
513
512 Magic commands
513 --------------
514
515 The rest of this section is automatically generated for each release
516 from the docstrings in the IPython code. Therefore the formatting is
517 somewhat minimal, but this method has the advantage of having
518 information always in sync with the code.
519
520 A list of all the magic commands available in IPython's default
521 installation follows. This is similar to what you'll see by simply
522 typing %magic at the prompt, but that will also give you information
523 about magic commands you may have added as part of your personal
524 customizations.
525
526 .. magic_start
527
528 **%Exit**::
529
530 Exit IPython without confirmation.
531
532 **%Pprint**::
533
534 Toggle pretty printing on/off.
535
536 **%alias**::
537
538 Define an alias for a system command.
539
540 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
541
542 Then, typing 'alias_name params' will execute the system command 'cmd
543 params' (from your underlying operating system).
544
545 Aliases have lower precedence than magic functions and Python normal
546 variables, so if 'foo' is both a Python variable and an alias, the
547 alias can not be executed until 'del foo' removes the Python variable.
548
549 You can use the %l specifier in an alias definition to represent the
550 whole line when the alias is called. For example:
551
552 In [2]: alias all echo "Input in brackets: <%l>"\
553 In [3]: all hello world\
554 Input in brackets: <hello world>
555
556 You can also define aliases with parameters using %s specifiers (one
557 per parameter):
558
559 In [1]: alias parts echo first %s second %s\
560 In [2]: %parts A B\
561 first A second B\
562 In [3]: %parts A\
563 Incorrect number of arguments: 2 expected.\
564 parts is an alias to: 'echo first %s second %s'
565
566 Note that %l and %s are mutually exclusive. You can only use one or
567 the other in your aliases.
568
569 Aliases expand Python variables just like system calls using ! or !!
570 do: all expressions prefixed with '$' get expanded. For details of
571 the semantic rules, see PEP-215:
572 http://www.python.org/peps/pep-0215.html. This is the library used by
573 IPython for variable expansion. If you want to access a true shell
574 variable, an extra $ is necessary to prevent its expansion by IPython:
575
576 In [6]: alias show echo\
577 In [7]: PATH='A Python string'\
578 In [8]: show $PATH\
579 A Python string\
580 In [9]: show $$PATH\
581 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
582
583 You can use the alias facility to acess all of $PATH. See the %rehash
584 and %rehashx functions, which automatically create aliases for the
585 contents of your $PATH.
586
587 If called with no parameters, %alias prints the current alias table.
588
589 **%autocall**::
590
591 Make functions callable without having to type parentheses.
592
593 Usage:
594
595 %autocall [mode]
596
597 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
598 value is toggled on and off (remembering the previous state).
599
600 In more detail, these values mean:
601
602 0 -> fully disabled
603
604 1 -> active, but do not apply if there are no arguments on the line.
605
606 In this mode, you get:
607
608 In [1]: callable
609 Out[1]: <built-in function callable>
610
611 In [2]: callable 'hello'
612 ------> callable('hello')
613 Out[2]: False
614
615 2 -> Active always. Even if no arguments are present, the callable
616 object is called:
617
618 In [4]: callable
619 ------> callable()
620
621 Note that even with autocall off, you can still use '/' at the start of
622 a line to treat the first argument on the command line as a function
623 and add parentheses to it:
624
625 In [8]: /str 43
626 ------> str(43)
627 Out[8]: '43'
628
629 **%autoindent**::
630
631 Toggle autoindent on/off (if available).
632
633 **%automagic**::
634
635 Make magic functions callable without having to type the initial %.
636
637 Without argumentsl toggles on/off (when off, you must call it as
638 %automagic, of course). With arguments it sets the value, and you can
639 use any of (case insensitive):
640
641 - on,1,True: to activate
642
643 - off,0,False: to deactivate.
644
645 Note that magic functions have lowest priority, so if there's a
646 variable whose name collides with that of a magic fn, automagic won't
647 work for that function (you get the variable instead). However, if you
648 delete the variable (del var), the previously shadowed magic function
649 becomes visible to automagic again.
650
651 **%bg**::
652
653 Run a job in the background, in a separate thread.
654
655 For example,
656
657 %bg myfunc(x,y,z=1)
658
659 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
660 execution starts, a message will be printed indicating the job
661 number. If your job number is 5, you can use
662
663 myvar = jobs.result(5) or myvar = jobs[5].result
664
665 to assign this result to variable 'myvar'.
666
667 IPython has a job manager, accessible via the 'jobs' object. You can
668 type jobs? to get more information about it, and use jobs.<TAB> to see
669 its attributes. All attributes not starting with an underscore are
670 meant for public use.
671
672 In particular, look at the jobs.new() method, which is used to create
673 new jobs. This magic %bg function is just a convenience wrapper
674 around jobs.new(), for expression-based jobs. If you want to create a
675 new job with an explicit function object and arguments, you must call
676 jobs.new() directly.
677
678 The jobs.new docstring also describes in detail several important
679 caveats associated with a thread-based model for background job
680 execution. Type jobs.new? for details.
681
682 You can check the status of all jobs with jobs.status().
683
684 The jobs variable is set by IPython into the Python builtin namespace.
685 If you ever declare a variable named 'jobs', you will shadow this
686 name. You can either delete your global jobs variable to regain
687 access to the job manager, or make a new name and assign it manually
688 to the manager (stored in IPython's namespace). For example, to
689 assign the job manager to the Jobs name, use:
690
691 Jobs = __builtins__.jobs
692
693 **%bookmark**::
694
695 Manage IPython's bookmark system.
696
697 %bookmark <name> - set bookmark to current dir
698 %bookmark <name> <dir> - set bookmark to <dir>
699 %bookmark -l - list all bookmarks
700 %bookmark -d <name> - remove bookmark
701 %bookmark -r - remove all bookmarks
702
703 You can later on access a bookmarked folder with:
704 %cd -b <name>
705 or simply '%cd <name>' if there is no directory called <name> AND
706 there is such a bookmark defined.
707
708 Your bookmarks persist through IPython sessions, but they are
709 associated with each profile.
710
711 **%cd**::
712
713 Change the current working directory.
714
715 This command automatically maintains an internal list of directories
716 you visit during your IPython session, in the variable _dh. The
717 command %dhist shows this history nicely formatted. You can also
718 do 'cd -<tab>' to see directory history conveniently.
719
720 Usage:
721
722 cd 'dir': changes to directory 'dir'.
723
724 cd -: changes to the last visited directory.
725
726 cd -<n>: changes to the n-th directory in the directory history.
727
728 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
729 (note: cd <bookmark_name> is enough if there is no
730 directory <bookmark_name>, but a bookmark with the name exists.)
731 'cd -b <tab>' allows you to tab-complete bookmark names.
732
733 Options:
734
735 -q: quiet. Do not print the working directory after the cd command is
736 executed. By default IPython's cd command does print this directory,
737 since the default prompts do not display path information.
738
739 Note that !cd doesn't work for this purpose because the shell where
740 !command runs is immediately discarded after executing 'command'.
741
742 **%clear**::
743
744 Clear various data (e.g. stored history data)
745
746 %clear out - clear output history
747 %clear in - clear input history
748 %clear shadow_compress - Compresses shadow history (to speed up ipython)
749 %clear shadow_nuke - permanently erase all entries in shadow history
750 %clear dhist - clear dir history
751
752 **%color_info**::
753
754 Toggle color_info.
755
756 The color_info configuration parameter controls whether colors are
757 used for displaying object details (by things like %psource, %pfile or
758 the '?' system). This function toggles this value with each call.
759
760 Note that unless you have a fairly recent pager (less works better
761 than more) in your system, using colored object information displays
762 will not work properly. Test it and see.
763
764 **%colors**::
765
766 Switch color scheme for prompts, info system and exception handlers.
767
768 Currently implemented schemes: NoColor, Linux, LightBG.
769
770 Color scheme names are not case-sensitive.
771
772 **%cpaste**::
773
774 Allows you to paste & execute a pre-formatted code block from clipboard
775
776 You must terminate the block with '--' (two minus-signs) alone on the
777 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
778 is the new sentinel for this operation)
779
780 The block is dedented prior to execution to enable execution of method
781 definitions. '>' and '+' characters at the beginning of a line are
782 ignored, to allow pasting directly from e-mails or diff files. The
783 executed block is also assigned to variable named 'pasted_block' for
784 later editing with '%edit pasted_block'.
785
786 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
787 This assigns the pasted block to variable 'foo' as string, without
788 dedenting or executing it.
789
790 Do not be alarmed by garbled output on Windows (it's a readline bug).
791 Just press enter and type -- (and press enter again) and the block
792 will be what was just pasted.
793
794 IPython statements (magics, shell escapes) are not supported (yet).
795
796 **%debug**::
797
798 Activate the interactive debugger in post-mortem mode.
799
800 If an exception has just occurred, this lets you inspect its stack
801 frames interactively. Note that this will always work only on the last
802 traceback that occurred, so you must call this quickly after an
803 exception that you wish to inspect has fired, because if another one
804 occurs, it clobbers the previous one.
805
806 If you want IPython to automatically do this on every exception, see
807 the %pdb magic for more details.
808
809 **%dhist**::
810
811 Print your history of visited directories.
812
813 %dhist -> print full history\
814 %dhist n -> print last n entries only\
815 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\
816
817 This history is automatically maintained by the %cd command, and
818 always available as the global list variable _dh. You can use %cd -<n>
819 to go to directory number <n>.
820
821 Note that most of time, you should view directory history by entering
822 cd -<TAB>.
823
824 **%dirs**::
825
826 Return the current directory stack.
827
828 **%doctest_mode**::
829
830 Toggle doctest mode on and off.
831
832 This mode allows you to toggle the prompt behavior between normal
833 IPython prompts and ones that are as similar to the default IPython
834 interpreter as possible.
835
836 It also supports the pasting of code snippets that have leading '>>>'
837 and '...' prompts in them. This means that you can paste doctests from
838 files or docstrings (even if they have leading whitespace), and the
839 code will execute correctly. You can then use '%history -tn' to see
840 the translated history without line numbers; this will give you the
841 input after removal of all the leading prompts and whitespace, which
842 can be pasted back into an editor.
843
844 With these features, you can switch into this mode easily whenever you
845 need to do testing and changes to doctests, without having to leave
846 your existing IPython session.
847
848 **%ed**::
849
850 Alias to %edit.
851
852 **%edit**::
853
854 Bring up an editor and execute the resulting code.
855
856 Usage:
857 %edit [options] [args]
858
859 %edit runs IPython's editor hook. The default version of this hook is
860 set to call the __IPYTHON__.rc.editor command. This is read from your
861 environment variable $EDITOR. If this isn't found, it will default to
862 vi under Linux/Unix and to notepad under Windows. See the end of this
863 docstring for how to change the editor hook.
864
865 You can also set the value of this editor via the command line option
866 '-editor' or in your ipythonrc file. This is useful if you wish to use
867 specifically for IPython an editor different from your typical default
868 (and for Windows users who typically don't set environment variables).
869
870 This command allows you to conveniently edit multi-line code right in
871 your IPython session.
872
873 If called without arguments, %edit opens up an empty editor with a
874 temporary file and will execute the contents of this file when you
875 close it (don't forget to save it!).
876
877
878 Options:
879
880 -n <number>: open the editor at a specified line number. By default,
881 the IPython editor hook uses the unix syntax 'editor +N filename', but
882 you can configure this by providing your own modified hook if your
883 favorite editor supports line-number specifications with a different
884 syntax.
885
886 -p: this will call the editor with the same data as the previous time
887 it was used, regardless of how long ago (in your current session) it
888 was.
889
890 -r: use 'raw' input. This option only applies to input taken from the
891 user's history. By default, the 'processed' history is used, so that
892 magics are loaded in their transformed version to valid Python. If
893 this option is given, the raw input as typed as the command line is
894 used instead. When you exit the editor, it will be executed by
895 IPython's own processor.
896
897 -x: do not execute the edited code immediately upon exit. This is
898 mainly useful if you are editing programs which need to be called with
899 command line arguments, which you can then do using %run.
900
901
902 Arguments:
903
904 If arguments are given, the following possibilites exist:
905
906 - The arguments are numbers or pairs of colon-separated numbers (like
907 1 4:8 9). These are interpreted as lines of previous input to be
908 loaded into the editor. The syntax is the same of the %macro command.
909
910 - If the argument doesn't start with a number, it is evaluated as a
911 variable and its contents loaded into the editor. You can thus edit
912 any string which contains python code (including the result of
913 previous edits).
914
915 - If the argument is the name of an object (other than a string),
916 IPython will try to locate the file where it was defined and open the
917 editor at the point where it is defined. You can use `%edit function`
918 to load an editor exactly at the point where 'function' is defined,
919 edit it and have the file be executed automatically.
920
921 If the object is a macro (see %macro for details), this opens up your
922 specified editor with a temporary file containing the macro's data.
923 Upon exit, the macro is reloaded with the contents of the file.
924
925 Note: opening at an exact line is only supported under Unix, and some
926 editors (like kedit and gedit up to Gnome 2.8) do not understand the
927 '+NUMBER' parameter necessary for this feature. Good editors like
928 (X)Emacs, vi, jed, pico and joe all do.
929
930 - If the argument is not found as a variable, IPython will look for a
931 file with that name (adding .py if necessary) and load it into the
932 editor. It will execute its contents with execfile() when you exit,
933 loading any code in the file into your interactive namespace.
934
935 After executing your code, %edit will return as output the code you
936 typed in the editor (except when it was an existing file). This way
937 you can reload the code in further invocations of %edit as a variable,
938 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
939 the output.
940
941 Note that %edit is also available through the alias %ed.
942
943 This is an example of creating a simple function inside the editor and
944 then modifying it. First, start up the editor:
945
946 In [1]: ed\
947 Editing... done. Executing edited code...\
948 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
949
950 We can then call the function foo():
951
952 In [2]: foo()\
953 foo() was defined in an editing session
954
955 Now we edit foo. IPython automatically loads the editor with the
956 (temporary) file where foo() was previously defined:
957
958 In [3]: ed foo\
959 Editing... done. Executing edited code...
960
961 And if we call foo() again we get the modified version:
962
963 In [4]: foo()\
964 foo() has now been changed!
965
966 Here is an example of how to edit a code snippet successive
967 times. First we call the editor:
968
969 In [8]: ed\
970 Editing... done. Executing edited code...\
971 hello\
972 Out[8]: "print 'hello'\n"
973
974 Now we call it again with the previous output (stored in _):
975
976 In [9]: ed _\
977 Editing... done. Executing edited code...\
978 hello world\
979 Out[9]: "print 'hello world'\n"
980
981 Now we call it with the output #8 (stored in _8, also as Out[8]):
982
983 In [10]: ed _8\
984 Editing... done. Executing edited code...\
985 hello again\
986 Out[10]: "print 'hello again'\n"
987
988
989 Changing the default editor hook:
990
991 If you wish to write your own editor hook, you can put it in a
992 configuration file which you load at startup time. The default hook
993 is defined in the IPython.hooks module, and you can use that as a
994 starting example for further modifications. That file also has
995 general instructions on how to set a new hook for use once you've
996 defined it.
997
998 **%env**::
999
1000 List environment variables.
1001
1002 **%exit**::
1003
1004 Exit IPython, confirming if configured to do so.
1005
1006 You can configure whether IPython asks for confirmation upon exit by
1007 setting the confirm_exit flag in the ipythonrc file.
1008
1009 **%hist**::
1010
1011 Alternate name for %history.
1012
1013 **%history**::
1014
1015 Print input history (_i<n> variables), with most recent last.
1016
1017 %history -> print at most 40 inputs (some may be multi-line)\
1018 %history n -> print at most n inputs\
1019 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\
1020
1021 Each input's number <n> is shown, and is accessible as the
1022 automatically generated variable _i<n>. Multi-line statements are
1023 printed starting at a new line for easy copy/paste.
1024
1025
1026 Options:
1027
1028 -n: do NOT print line numbers. This is useful if you want to get a
1029 printout of many lines which can be directly pasted into a text
1030 editor.
1031
1032 This feature is only available if numbered prompts are in use.
1033
1034 -t: (default) print the 'translated' history, as IPython understands it.
1035 IPython filters your input and converts it all into valid Python source
1036 before executing it (things like magics or aliases are turned into
1037 function calls, for example). With this option, you'll see the native
1038 history instead of the user-entered version: '%cd /' will be seen as
1039 '_ip.magic("%cd /")' instead of '%cd /'.
1040
1041 -r: print the 'raw' history, i.e. the actual commands you typed.
1042
1043 -g: treat the arg as a pattern to grep for in (full) history.
1044 This includes the "shadow history" (almost all commands ever written).
1045 Use '%hist -g' to show full shadow history (may be very long).
1046 In shadow history, every index nuwber starts with 0.
1047
1048 -f FILENAME: instead of printing the output to the screen, redirect it to
1049 the given file. The file is always overwritten, though IPython asks for
1050 confirmation first if it already exists.
1051
1052 **%logoff**::
1053
1054 Temporarily stop logging.
1055
1056 You must have previously started logging.
1057
1058 **%logon**::
1059
1060 Restart logging.
1061
1062 This function is for restarting logging which you've temporarily
1063 stopped with %logoff. For starting logging for the first time, you
1064 must use the %logstart function, which allows you to specify an
1065 optional log filename.
1066
1067 **%logstart**::
1068
1069 Start logging anywhere in a session.
1070
1071 %logstart [-o|-r|-t] [log_name [log_mode]]
1072
1073 If no name is given, it defaults to a file named 'ipython_log.py' in your
1074 current directory, in 'rotate' mode (see below).
1075
1076 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1077 history up to that point and then continues logging.
1078
1079 %logstart takes a second optional parameter: logging mode. This can be one
1080 of (note that the modes are given unquoted):\
1081 append: well, that says it.\
1082 backup: rename (if exists) to name~ and start name.\
1083 global: single logfile in your home dir, appended to.\
1084 over : overwrite existing log.\
1085 rotate: create rotating logs name.1~, name.2~, etc.
1086
1087 Options:
1088
1089 -o: log also IPython's output. In this mode, all commands which
1090 generate an Out[NN] prompt are recorded to the logfile, right after
1091 their corresponding input line. The output lines are always
1092 prepended with a '#[Out]# ' marker, so that the log remains valid
1093 Python code.
1094
1095 Since this marker is always the same, filtering only the output from
1096 a log is very easy, using for example a simple awk call:
1097
1098 awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py
1099
1100 -r: log 'raw' input. Normally, IPython's logs contain the processed
1101 input, so that user lines are logged in their final form, converted
1102 into valid Python. For example, %Exit is logged as
1103 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1104 exactly as typed, with no transformations applied.
1105
1106 -t: put timestamps before each input line logged (these are put in
1107 comments).
1108
1109 **%logstate**::
1110
1111 Print the status of the logging system.
1112
1113 **%logstop**::
1114
1115 Fully stop logging and close log file.
1116
1117 In order to start logging again, a new %logstart call needs to be made,
1118 possibly (though not necessarily) with a new filename, mode and other
1119 options.
1120
1121 **%lsmagic**::
1122
1123 List currently available magic functions.
1124
1125 **%macro**::
1126
1127 Define a set of input lines as a macro for future re-execution.
1128
1129 Usage:\
1130 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1131
1132 Options:
1133
1134 -r: use 'raw' input. By default, the 'processed' history is used,
1135 so that magics are loaded in their transformed version to valid
1136 Python. If this option is given, the raw input as typed as the
1137 command line is used instead.
1138
1139 This will define a global variable called `name` which is a string
1140 made of joining the slices and lines you specify (n1,n2,... numbers
1141 above) from your input history into a single string. This variable
1142 acts like an automatic function which re-executes those lines as if
1143 you had typed them. You just type 'name' at the prompt and the code
1144 executes.
1145
1146 The notation for indicating number ranges is: n1-n2 means 'use line
1147 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1148 using the lines numbered 5,6 and 7.
1149
1150 Note: as a 'hidden' feature, you can also use traditional python slice
1151 notation, where N:M means numbers N through M-1.
1152
1153 For example, if your history contains (%hist prints it):
1154
1155 44: x=1\
1156 45: y=3\
1157 46: z=x+y\
1158 47: print x\
1159 48: a=5\
1160 49: print 'x',x,'y',y\
1161
1162 you can create a macro with lines 44 through 47 (included) and line 49
1163 called my_macro with:
1164
1165 In [51]: %macro my_macro 44-47 49
1166
1167 Now, typing `my_macro` (without quotes) will re-execute all this code
1168 in one pass.
1169
1170 You don't need to give the line-numbers in order, and any given line
1171 number can appear multiple times. You can assemble macros with any
1172 lines from your input history in any order.
1173
1174 The macro is a simple object which holds its value in an attribute,
1175 but IPython's display system checks for macros and executes them as
1176 code instead of printing them when you type their name.
1177
1178 You can view a macro's contents by explicitly printing it with:
1179
1180 'print macro_name'.
1181
1182 For one-off cases which DON'T contain magic function calls in them you
1183 can obtain similar results by explicitly executing slices from your
1184 input history with:
1185
1186 In [60]: exec In[44:48]+In[49]
1187
1188 **%magic**::
1189
1190 Print information about the magic function system.
1191
1192 **%mglob**::
1193
1194 This program allows specifying filenames with "mglob" mechanism.
1195 Supported syntax in globs (wilcard matching patterns)::
1196
1197 *.cpp ?ellowo*
1198 - obvious. Differs from normal glob in that dirs are not included.
1199 Unix users might want to write this as: "*.cpp" "?ellowo*"
1200 rec:/usr/share=*.txt,*.doc
1201 - get all *.txt and *.doc under /usr/share,
1202 recursively
1203 rec:/usr/share
1204 - All files under /usr/share, recursively
1205 rec:*.py
1206 - All .py files under current working dir, recursively
1207 foo
1208 - File or dir foo
1209 !*.bak readme*
1210 - readme*, exclude files ending with .bak
1211 !.svn/ !.hg/ !*_Data/ rec:.
1212 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
1213 Trailing / is the key, \ does not work!
1214 dir:foo
1215 - the directory foo if it exists (not files in foo)
1216 dir:*
1217 - all directories in current folder
1218 foo.py bar.* !h* rec:*.py
1219 - Obvious. !h* exclusion only applies for rec:*.py.
1220 foo.py is *not* included twice.
1221 @filelist.txt
1222 - All files listed in 'filelist.txt' file, on separate lines.
1223
1224 **%page**::
1225
1226 Pretty print the object and display it through a pager.
1227
1228 %page [options] OBJECT
1229
1230 If no object is given, use _ (last output).
1231
1232 Options:
1233
1234 -r: page str(object), don't pretty-print it.
1235
1236 **%pdb**::
1237
1238 Control the automatic calling of the pdb interactive debugger.
1239
1240 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1241 argument it works as a toggle.
1242
1243 When an exception is triggered, IPython can optionally call the
1244 interactive pdb debugger after the traceback printout. %pdb toggles
1245 this feature on and off.
1246
1247 The initial state of this feature is set in your ipythonrc
1248 configuration file (the variable is called 'pdb').
1249
1250 If you want to just activate the debugger AFTER an exception has fired,
1251 without having to type '%pdb on' and rerunning your code, you can use
1252 the %debug magic.
1253
1254 **%pdef**::
1255
1256 Print the definition header for any callable object.
1257
1258 If the object is a class, print the constructor information.
1259
1260 **%pdoc**::
1261
1262 Print the docstring for an object.
1263
1264 If the given object is a class, it will print both the class and the
1265 constructor docstrings.
1266
1267 **%pfile**::
1268
1269 Print (or run through pager) the file where an object is defined.
1270
1271 The file opens at the line where the object definition begins. IPython
1272 will honor the environment variable PAGER if set, and otherwise will
1273 do its best to print the file in a convenient form.
1274
1275 If the given argument is not an object currently defined, IPython will
1276 try to interpret it as a filename (automatically adding a .py extension
1277 if needed). You can thus use %pfile as a syntax highlighting code
1278 viewer.
1279
1280 **%pinfo**::
1281
1282 Provide detailed information about an object.
1283
1284 '%pinfo object' is just a synonym for object? or ?object.
1285
1286 **%popd**::
1287
1288 Change to directory popped off the top of the stack.
1289
1290 **%profile**::
1291
1292 Print your currently active IPyhton profile.
1293
1294 **%prun**::
1295
1296 Run a statement through the python code profiler.
1297
1298 Usage:\
1299 %prun [options] statement
1300
1301 The given statement (which doesn't require quote marks) is run via the
1302 python profiler in a manner similar to the profile.run() function.
1303 Namespaces are internally managed to work correctly; profile.run
1304 cannot be used in IPython because it makes certain assumptions about
1305 namespaces which do not hold under IPython.
1306
1307 Options:
1308
1309 -l <limit>: you can place restrictions on what or how much of the
1310 profile gets printed. The limit value can be:
1311
1312 * A string: only information for function names containing this string
1313 is printed.
1314
1315 * An integer: only these many lines are printed.
1316
1317 * A float (between 0 and 1): this fraction of the report is printed
1318 (for example, use a limit of 0.4 to see the topmost 40% only).
1319
1320 You can combine several limits with repeated use of the option. For
1321 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1322 information about class constructors.
1323
1324 -r: return the pstats.Stats object generated by the profiling. This
1325 object has all the information about the profile in it, and you can
1326 later use it for further analysis or in other functions.
1327
1328 -s <key>: sort profile by given key. You can provide more than one key
1329 by using the option several times: '-s key1 -s key2 -s key3...'. The
1330 default sorting key is 'time'.
1331
1332 The following is copied verbatim from the profile documentation
1333 referenced below:
1334
1335 When more than one key is provided, additional keys are used as
1336 secondary criteria when the there is equality in all keys selected
1337 before them.
1338
1339 Abbreviations can be used for any key names, as long as the
1340 abbreviation is unambiguous. The following are the keys currently
1341 defined:
1342
1343 Valid Arg Meaning\
1344 "calls" call count\
1345 "cumulative" cumulative time\
1346 "file" file name\
1347 "module" file name\
1348 "pcalls" primitive call count\
1349 "line" line number\
1350 "name" function name\
1351 "nfl" name/file/line\
1352 "stdname" standard name\
1353 "time" internal time
1354
1355 Note that all sorts on statistics are in descending order (placing
1356 most time consuming items first), where as name, file, and line number
1357 searches are in ascending order (i.e., alphabetical). The subtle
1358 distinction between "nfl" and "stdname" is that the standard name is a
1359 sort of the name as printed, which means that the embedded line
1360 numbers get compared in an odd way. For example, lines 3, 20, and 40
1361 would (if the file names were the same) appear in the string order
1362 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1363 line numbers. In fact, sort_stats("nfl") is the same as
1364 sort_stats("name", "file", "line").
1365
1366 -T <filename>: save profile results as shown on screen to a text
1367 file. The profile is still shown on screen.
1368
1369 -D <filename>: save (via dump_stats) profile statistics to given
1370 filename. This data is in a format understod by the pstats module, and
1371 is generated by a call to the dump_stats() method of profile
1372 objects. The profile is still shown on screen.
1373
1374 If you want to run complete programs under the profiler's control, use
1375 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1376 contains profiler specific options as described here.
1377
1378 You can read the complete documentation for the profile module with:\
1379 In [1]: import profile; profile.help()
1380
1381 **%psearch**::
1382
1383 Search for object in namespaces by wildcard.
1384
1385 %psearch [options] PATTERN [OBJECT TYPE]
1386
1387 Note: ? can be used as a synonym for %psearch, at the beginning or at
1388 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
1389 rest of the command line must be unchanged (options come first), so
1390 for example the following forms are equivalent
1391
1392 %psearch -i a* function
1393 -i a* function?
1394 ?-i a* function
1395
1396 Arguments:
1397
1398 PATTERN
1399
1400 where PATTERN is a string containing * as a wildcard similar to its
1401 use in a shell. The pattern is matched in all namespaces on the
1402 search path. By default objects starting with a single _ are not
1403 matched, many IPython generated objects have a single
1404 underscore. The default is case insensitive matching. Matching is
1405 also done on the attributes of objects and not only on the objects
1406 in a module.
1407
1408 [OBJECT TYPE]
1409
1410 Is the name of a python type from the types module. The name is
1411 given in lowercase without the ending type, ex. StringType is
1412 written string. By adding a type here only objects matching the
1413 given type are matched. Using all here makes the pattern match all
1414 types (this is the default).
1415
1416 Options:
1417
1418 -a: makes the pattern match even objects whose names start with a
1419 single underscore. These names are normally ommitted from the
1420 search.
1421
1422 -i/-c: make the pattern case insensitive/sensitive. If neither of
1423 these options is given, the default is read from your ipythonrc
1424 file. The option name which sets this value is
1425 'wildcards_case_sensitive'. If this option is not specified in your
1426 ipythonrc file, IPython's internal default is to do a case sensitive
1427 search.
1428
1429 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
1430 specifiy can be searched in any of the following namespaces:
1431 'builtin', 'user', 'user_global','internal', 'alias', where
1432 'builtin' and 'user' are the search defaults. Note that you should
1433 not use quotes when specifying namespaces.
1434
1435 'Builtin' contains the python module builtin, 'user' contains all
1436 user data, 'alias' only contain the shell aliases and no python
1437 objects, 'internal' contains objects used by IPython. The
1438 'user_global' namespace is only used by embedded IPython instances,
1439 and it contains module-level globals. You can add namespaces to the
1440 search with -s or exclude them with -e (these options can be given
1441 more than once).
1442
1443 Examples:
1444
1445 %psearch a* -> objects beginning with an a
1446 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
1447 %psearch a* function -> all functions beginning with an a
1448 %psearch re.e* -> objects beginning with an e in module re
1449 %psearch r*.e* -> objects that start with e in modules starting in r
1450 %psearch r*.* string -> all strings in modules beginning with r
1451
1452 Case sensitve search:
1453
1454 %psearch -c a* list all object beginning with lower case a
1455
1456 Show objects beginning with a single _:
1457
1458 %psearch -a _* list objects beginning with a single underscore
1459
1460 **%psource**::
1461
1462 Print (or run through pager) the source code for an object.
1463
1464 **%pushd**::
1465
1466 Place the current dir on stack and change directory.
1467
1468 Usage:\
1469 %pushd ['dirname']
1470
1471 **%pwd**::
1472
1473 Return the current working directory path.
1474
1475 **%pycat**::
1476
1477 Show a syntax-highlighted file through a pager.
1478
1479 This magic is similar to the cat utility, but it will assume the file
1480 to be Python source and will show it with syntax highlighting.
1481
1482 **%quickref**::
1483
1484 Show a quick reference sheet
1485
1486 **%quit**::
1487
1488 Exit IPython, confirming if configured to do so (like %exit)
1489
1490 **%r**::
1491
1492 Repeat previous input.
1493
1494 Note: Consider using the more powerfull %rep instead!
1495
1496 If given an argument, repeats the previous command which starts with
1497 the same string, otherwise it just repeats the previous input.
1498
1499 Shell escaped commands (with ! as first character) are not recognized
1500 by this system, only pure python code and magic commands.
1501
1502 **%rehashdir**::
1503
1504 Add executables in all specified dirs to alias table
1505
1506 Usage:
1507
1508 %rehashdir c:/bin;c:/tools
1509 - Add all executables under c:/bin and c:/tools to alias table, in
1510 order to make them directly executable from any directory.
1511
1512 Without arguments, add all executables in current directory.
1513
1514 **%rehashx**::
1515
1516 Update the alias table with all executable files in $PATH.
1517
1518 This version explicitly checks that every entry in $PATH is a file
1519 with execute access (os.X_OK), so it is much slower than %rehash.
1520
1521 Under Windows, it checks executability as a match agains a
1522 '|'-separated string of extensions, stored in the IPython config
1523 variable win_exec_ext. This defaults to 'exe|com|bat'.
1524
1525 This function also resets the root module cache of module completer,
1526 used on slow filesystems.
1527
1528 **%rep**::
1529
1530 Repeat a command, or get command to input line for editing
1531
1532 - %rep (no arguments):
1533
1534 Place a string version of last computation result (stored in the special '_'
1535 variable) to the next input prompt. Allows you to create elaborate command
1536 lines without using copy-paste::
1537
1538 $ l = ["hei", "vaan"]
1539 $ "".join(l)
1540 ==> heivaan
1541 $ %rep
1542 $ heivaan_ <== cursor blinking
1543
1544 %rep 45
1545
1546 Place history line 45 to next input prompt. Use %hist to find out the
1547 number.
1548
1549 %rep 1-4 6-7 3
1550
1551 Repeat the specified lines immediately. Input slice syntax is the same as
1552 in %macro and %save.
1553
1554 %rep foo
1555
1556 Place the most recent line that has the substring "foo" to next input.
1557 (e.g. 'svn ci -m foobar').
1558
1559 **%reset**::
1560
1561 Resets the namespace by removing all names defined by the user.
1562
1563 Input/Output history are left around in case you need them.
1564
1565 **%run**::
1566
1567 Run the named file inside IPython as a program.
1568
1569 Usage:\
1570 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1571
1572 Parameters after the filename are passed as command-line arguments to
1573 the program (put in sys.argv). Then, control returns to IPython's
1574 prompt.
1575
1576 This is similar to running at a system prompt:\
1577 $ python file args\
1578 but with the advantage of giving you IPython's tracebacks, and of
1579 loading all variables into your interactive namespace for further use
1580 (unless -p is used, see below).
1581
1582 The file is executed in a namespace initially consisting only of
1583 __name__=='__main__' and sys.argv constructed as indicated. It thus
1584 sees its environment as if it were being run as a stand-alone program
1585 (except for sharing global objects such as previously imported
1586 modules). But after execution, the IPython interactive namespace gets
1587 updated with all variables defined in the program (except for __name__
1588 and sys.argv). This allows for very convenient loading of code for
1589 interactive work, while giving each program a 'clean sheet' to run in.
1590
1591 Options:
1592
1593 -n: __name__ is NOT set to '__main__', but to the running file's name
1594 without extension (as python does under import). This allows running
1595 scripts and reloading the definitions in them without calling code
1596 protected by an ' if __name__ == "__main__" ' clause.
1597
1598 -i: run the file in IPython's namespace instead of an empty one. This
1599 is useful if you are experimenting with code written in a text editor
1600 which depends on variables defined interactively.
1601
1602 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1603 being run. This is particularly useful if IPython is being used to
1604 run unittests, which always exit with a sys.exit() call. In such
1605 cases you are interested in the output of the test results, not in
1606 seeing a traceback of the unittest module.
1607
1608 -t: print timing information at the end of the run. IPython will give
1609 you an estimated CPU time consumption for your script, which under
1610 Unix uses the resource module to avoid the wraparound problems of
1611 time.clock(). Under Unix, an estimate of time spent on system tasks
1612 is also given (for Windows platforms this is reported as 0.0).
1613
1614 If -t is given, an additional -N<N> option can be given, where <N>
1615 must be an integer indicating how many times you want the script to
1616 run. The final timing report will include total and per run results.
1617
1618 For example (testing the script uniq_stable.py):
1619
1620 In [1]: run -t uniq_stable
1621
1622 IPython CPU timings (estimated):\
1623 User : 0.19597 s.\
1624 System: 0.0 s.\
1625
1626 In [2]: run -t -N5 uniq_stable
1627
1628 IPython CPU timings (estimated):\
1629 Total runs performed: 5\
1630 Times : Total Per run\
1631 User : 0.910862 s, 0.1821724 s.\
1632 System: 0.0 s, 0.0 s.
1633
1634 -d: run your program under the control of pdb, the Python debugger.
1635 This allows you to execute your program step by step, watch variables,
1636 etc. Internally, what IPython does is similar to calling:
1637
1638 pdb.run('execfile("YOURFILENAME")')
1639
1640 with a breakpoint set on line 1 of your file. You can change the line
1641 number for this automatic breakpoint to be <N> by using the -bN option
1642 (where N must be an integer). For example:
1643
1644 %run -d -b40 myscript
1645
1646 will set the first breakpoint at line 40 in myscript.py. Note that
1647 the first breakpoint must be set on a line which actually does
1648 something (not a comment or docstring) for it to stop execution.
1649
1650 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1651 first enter 'c' (without qoutes) to start execution up to the first
1652 breakpoint.
1653
1654 Entering 'help' gives information about the use of the debugger. You
1655 can easily see pdb's full documentation with "import pdb;pdb.help()"
1656 at a prompt.
1657
1658 -p: run program under the control of the Python profiler module (which
1659 prints a detailed report of execution times, function calls, etc).
1660
1661 You can pass other options after -p which affect the behavior of the
1662 profiler itself. See the docs for %prun for details.
1663
1664 In this mode, the program's variables do NOT propagate back to the
1665 IPython interactive namespace (because they remain in the namespace
1666 where the profiler executes them).
1667
1668 Internally this triggers a call to %prun, see its documentation for
1669 details on the options available specifically for profiling.
1670
1671 There is one special usage for which the text above doesn't apply:
1672 if the filename ends with .ipy, the file is run as ipython script,
1673 just as if the commands were written on IPython prompt.
1674
1675 **%runlog**::
1676
1677 Run files as logs.
1678
1679 Usage:\
1680 %runlog file1 file2 ...
1681
1682 Run the named files (treating them as log files) in sequence inside
1683 the interpreter, and return to the prompt. This is much slower than
1684 %run because each line is executed in a try/except block, but it
1685 allows running files with syntax errors in them.
1686
1687 Normally IPython will guess when a file is one of its own logfiles, so
1688 you can typically use %run even for logs. This shorthand allows you to
1689 force any file to be treated as a log file.
1690
1691 **%save**::
1692
1693 Save a set of lines to a given filename.
1694
1695 Usage:\
1696 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1697
1698 Options:
1699
1700 -r: use 'raw' input. By default, the 'processed' history is used,
1701 so that magics are loaded in their transformed version to valid
1702 Python. If this option is given, the raw input as typed as the
1703 command line is used instead.
1704
1705 This function uses the same syntax as %macro for line extraction, but
1706 instead of creating a macro it saves the resulting string to the
1707 filename you specify.
1708
1709 It adds a '.py' extension to the file if you don't do so yourself, and
1710 it asks for confirmation before overwriting existing files.
1711
1712 **%sc**::
1713
1714 Shell capture - execute a shell command and capture its output.
1715
1716 DEPRECATED. Suboptimal, retained for backwards compatibility.
1717
1718 You should use the form 'var = !command' instead. Example:
1719
1720 "%sc -l myfiles = ls ~" should now be written as
1721
1722 "myfiles = !ls ~"
1723
1724 myfiles.s, myfiles.l and myfiles.n still apply as documented
1725 below.
1726
1727 --
1728 %sc [options] varname=command
1729
1730 IPython will run the given command using commands.getoutput(), and
1731 will then update the user's interactive namespace with a variable
1732 called varname, containing the value of the call. Your command can
1733 contain shell wildcards, pipes, etc.
1734
1735 The '=' sign in the syntax is mandatory, and the variable name you
1736 supply must follow Python's standard conventions for valid names.
1737
1738 (A special format without variable name exists for internal use)
1739
1740 Options:
1741
1742 -l: list output. Split the output on newlines into a list before
1743 assigning it to the given variable. By default the output is stored
1744 as a single string.
1745
1746 -v: verbose. Print the contents of the variable.
1747
1748 In most cases you should not need to split as a list, because the
1749 returned value is a special type of string which can automatically
1750 provide its contents either as a list (split on newlines) or as a
1751 space-separated string. These are convenient, respectively, either
1752 for sequential processing or to be passed to a shell command.
1753
1754 For example:
1755
1756 # Capture into variable a
1757 In [9]: sc a=ls *py
1758
1759 # a is a string with embedded newlines
1760 In [10]: a
1761 Out[10]: 'setup.py win32_manual_post_install.py'
1762
1763 # which can be seen as a list:
1764 In [11]: a.l
1765 Out[11]: ['setup.py', 'win32_manual_post_install.py']
1766
1767 # or as a whitespace-separated string:
1768 In [12]: a.s
1769 Out[12]: 'setup.py win32_manual_post_install.py'
1770
1771 # a.s is useful to pass as a single command line:
1772 In [13]: !wc -l $a.s
1773 146 setup.py
1774 130 win32_manual_post_install.py
1775 276 total
1776
1777 # while the list form is useful to loop over:
1778 In [14]: for f in a.l:
1779 ....: !wc -l $f
1780 ....:
1781 146 setup.py
1782 130 win32_manual_post_install.py
1783
1784 Similiarly, the lists returned by the -l option are also special, in
1785 the sense that you can equally invoke the .s attribute on them to
1786 automatically get a whitespace-separated string from their contents:
1787
1788 In [1]: sc -l b=ls *py
1789
1790 In [2]: b
1791 Out[2]: ['setup.py', 'win32_manual_post_install.py']
1792
1793 In [3]: b.s
1794 Out[3]: 'setup.py win32_manual_post_install.py'
1795
1796 In summary, both the lists and strings used for ouptut capture have
1797 the following special attributes:
1798
1799 .l (or .list) : value as list.
1800 .n (or .nlstr): value as newline-separated string.
1801 .s (or .spstr): value as space-separated string.
1802
1803 **%store**::
1804
1805 Lightweight persistence for python variables.
1806
1807 Example:
1808
1809 ville@badger[~]|1> A = ['hello',10,'world']\
1810 ville@badger[~]|2> %store A\
1811 ville@badger[~]|3> Exit
1812
1813 (IPython session is closed and started again...)
1814
1815 ville@badger:~$ ipython -p pysh\
1816 ville@badger[~]|1> print A
1817
1818 ['hello', 10, 'world']
1819
1820 Usage:
1821
1822 %store - Show list of all variables and their current values\
1823 %store <var> - Store the *current* value of the variable to disk\
1824 %store -d <var> - Remove the variable and its value from storage\
1825 %store -z - Remove all variables from storage\
1826 %store -r - Refresh all variables from store (delete current vals)\
1827 %store foo >a.txt - Store value of foo to new file a.txt\
1828 %store foo >>a.txt - Append value of foo to file a.txt\
1829
1830 It should be noted that if you change the value of a variable, you
1831 need to %store it again if you want to persist the new value.
1832
1833 Note also that the variables will need to be pickleable; most basic
1834 python types can be safely %stored.
1835
1836 Also aliases can be %store'd across sessions.
1837
1838 **%sx**::
1839
1840 Shell execute - run a shell command and capture its output.
1841
1842 %sx command
1843
1844 IPython will run the given command using commands.getoutput(), and
1845 return the result formatted as a list (split on '\n'). Since the
1846 output is _returned_, it will be stored in ipython's regular output
1847 cache Out[N] and in the '_N' automatic variables.
1848
1849 Notes:
1850
1851 1) If an input line begins with '!!', then %sx is automatically
1852 invoked. That is, while:
1853 !ls
1854 causes ipython to simply issue system('ls'), typing
1855 !!ls
1856 is a shorthand equivalent to:
1857 %sx ls
1858
1859 2) %sx differs from %sc in that %sx automatically splits into a list,
1860 like '%sc -l'. The reason for this is to make it as easy as possible
1861 to process line-oriented shell output via further python commands.
1862 %sc is meant to provide much finer control, but requires more
1863 typing.
1864
1865 3) Just like %sc -l, this is a list with special attributes:
1866
1867 .l (or .list) : value as list.
1868 .n (or .nlstr): value as newline-separated string.
1869 .s (or .spstr): value as whitespace-separated string.
1870
1871 This is very useful when trying to use such lists as arguments to
1872 system commands.
1873
1874 **%system_verbose**::
1875
1876 Set verbose printing of system calls.
1877
1878 If called without an argument, act as a toggle
1879
1880 **%time**::
1881
1882 Time execution of a Python statement or expression.
1883
1884 The CPU and wall clock times are printed, and the value of the
1885 expression (if any) is returned. Note that under Win32, system time
1886 is always reported as 0, since it can not be measured.
1887
1888 This function provides very basic timing functionality. In Python
1889 2.3, the timeit module offers more control and sophistication, so this
1890 could be rewritten to use it (patches welcome).
1891
1892 Some examples:
1893
1894 In [1]: time 2**128
1895 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1896 Wall time: 0.00
1897 Out[1]: 340282366920938463463374607431768211456L
1898
1899 In [2]: n = 1000000
1900
1901 In [3]: time sum(range(n))
1902 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1903 Wall time: 1.37
1904 Out[3]: 499999500000L
1905
1906 In [4]: time print 'hello world'
1907 hello world
1908 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1909 Wall time: 0.00
1910
1911 Note that the time needed by Python to compile the given expression
1912 will be reported if it is more than 0.1s. In this example, the
1913 actual exponentiation is done by Python at compilation time, so while
1914 the expression can take a noticeable amount of time to compute, that
1915 time is purely due to the compilation:
1916
1917 In [5]: time 3**9999;
1918 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1919 Wall time: 0.00 s
1920
1921 In [6]: time 3**999999;
1922 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1923 Wall time: 0.00 s
1924 Compiler : 0.78 s
1925
1926 **%timeit**::
1927
1928 Time execution of a Python statement or expression
1929
1930 Usage:\
1931 %timeit [-n<N> -r<R> [-t|-c]] statement
1932
1933 Time execution of a Python statement or expression using the timeit
1934 module.
1935
1936 Options:
1937 -n<N>: execute the given statement <N> times in a loop. If this value
1938 is not given, a fitting value is chosen.
1939
1940 -r<R>: repeat the loop iteration <R> times and take the best result.
1941 Default: 3
1942
1943 -t: use time.time to measure the time, which is the default on Unix.
1944 This function measures wall time.
1945
1946 -c: use time.clock to measure the time, which is the default on
1947 Windows and measures wall time. On Unix, resource.getrusage is used
1948 instead and returns the CPU user time.
1949
1950 -p<P>: use a precision of <P> digits to display the timing result.
1951 Default: 3
1952
1953
1954 Examples:\
1955 In [1]: %timeit pass
1956 10000000 loops, best of 3: 53.3 ns per loop
1957
1958 In [2]: u = None
1959
1960 In [3]: %timeit u is None
1961 10000000 loops, best of 3: 184 ns per loop
1962
1963 In [4]: %timeit -r 4 u == None
1964 1000000 loops, best of 4: 242 ns per loop
1965
1966 In [5]: import time
1967
1968 In [6]: %timeit -n1 time.sleep(2)
1969 1 loops, best of 3: 2 s per loop
1970
1971
1972 The times reported by %timeit will be slightly higher than those
1973 reported by the timeit.py script when variables are accessed. This is
1974 due to the fact that %timeit executes the statement in the namespace
1975 of the shell, compared with timeit.py, which uses a single setup
1976 statement to import function or create variables. Generally, the bias
1977 does not matter as long as results from timeit.py are not mixed with
1978 those from %timeit.
1979
1980 **%unalias**::
1981
1982 Remove an alias
1983
1984 **%upgrade**::
1985
1986 Upgrade your IPython installation
1987
1988 This will copy the config files that don't yet exist in your
1989 ipython dir from the system config dir. Use this after upgrading
1990 IPython if you don't wish to delete your .ipython dir.
1991
1992 Call with -nolegacy to get rid of ipythonrc* files (recommended for
1993 new users)
1994
1995 **%which**::
1996
1997 %which <cmd> => search PATH for files matching cmd. Also scans aliases.
1998
1999 Traverses PATH and prints all files (not just executables!) that match the
2000 pattern on command line. Probably more useful in finding stuff
2001 interactively than 'which', which only prints the first matching item.
2002
2003 Also discovers and expands aliases, so you'll see what will be executed
2004 when you call an alias.
2005
2006 Example:
2007
2008 [~]|62> %which d
2009 d -> ls -F --color=auto
2010 == c:\cygwin\bin\ls.exe
2011 c:\cygwin\bin\d.exe
2012
2013 [~]|64> %which diff*
2014 diff3 -> diff3
2015 == c:\cygwin\bin\diff3.exe
2016 diff -> diff
2017 == c:\cygwin\bin\diff.exe
2018 c:\cygwin\bin\diff.exe
2019 c:\cygwin\bin\diff3.exe
2020
2021 **%who**::
2022
2023 Print all interactive variables, with some minimal formatting.
2024
2025 If any arguments are given, only variables whose type matches one of
2026 these are printed. For example:
2027
2028 %who function str
2029
2030 will only list functions and strings, excluding all other types of
2031 variables. To find the proper type names, simply use type(var) at a
2032 command line to see how python prints type names. For example:
2033
2034 In [1]: type('hello')\
2035 Out[1]: <type 'str'>
2036
2037 indicates that the type name for strings is 'str'.
2038
2039 %who always excludes executed names loaded through your configuration
2040 file and things which are internal to IPython.
2041
2042 This is deliberate, as typically you may load many modules and the
2043 purpose of %who is to show you only what you've manually defined.
2044
2045 **%who_ls**::
2046
2047 Return a sorted list of all interactive variables.
2048
2049 If arguments are given, only variables of types matching these
2050 arguments are returned.
2051
2052 **%whos**::
2053
2054 Like %who, but gives some extra information about each variable.
2055
2056 The same type filtering of %who can be applied here.
2057
2058 For all variables, the type is printed. Additionally it prints:
2059
2060 - For {},[],(): their length.
2061
2062 - For numpy and Numeric arrays, a summary with shape, number of
2063 elements, typecode and size in memory.
2064
2065 - Everything else: a string representation, snipping their middle if
2066 too long.
2067
2068 **%xmode**::
2069
2070 Switch modes for the exception handlers.
2071
2072 Valid modes: Plain, Context and Verbose.
2073
2074 If called without arguments, acts as a toggle.
2075
2076 .. magic_end
2077
514
2078 Access to the standard Python help
515 Access to the standard Python help
2079 ----------------------------------
516 ----------------------------------
@@ -39,11 +39,20 b' except ImportError:'
39 from md5 import md5
39 from md5 import md5
40
40
41 from docutils.nodes import Body, Element
41 from docutils.nodes import Body, Element
42 from docutils.writers.html4css1 import HTMLTranslator
43 from sphinx.latexwriter import LaTeXTranslator
44 from docutils.parsers.rst import directives
42 from docutils.parsers.rst import directives
45 from sphinx.roles import xfileref_role
43 from sphinx.roles import xfileref_role
46
44
45 def my_import(name):
46 """Module importer - taken from the python documentation.
47
48 This function allows importing names with dots in them."""
49
50 mod = __import__(name)
51 components = name.split('.')
52 for comp in components[1:]:
53 mod = getattr(mod, comp)
54 return mod
55
47 class DotException(Exception):
56 class DotException(Exception):
48 pass
57 pass
49
58
@@ -84,11 +93,15 b' class InheritanceGraph(object):'
84 path = (path and path.rstrip('.'))
93 path = (path and path.rstrip('.'))
85 if not path:
94 if not path:
86 path = base
95 path = base
87 if not path:
88 raise ValueError(
89 "Invalid class or module '%s' specified for inheritance diagram" % name)
90 try:
96 try:
91 module = __import__(path, None, None, [])
97 module = __import__(path, None, None, [])
98 # We must do an import of the fully qualified name. Otherwise if a
99 # subpackage 'a.b' is requested where 'import a' does NOT provide
100 # 'a.b' automatically, then 'a.b' will not be found below. This
101 # second call will force the equivalent of 'import a.b' to happen
102 # after the top-level import above.
103 my_import(fullname)
104
92 except ImportError:
105 except ImportError:
93 raise ValueError(
106 raise ValueError(
94 "Could not import class or module '%s' specified for inheritance diagram" % name)
107 "Could not import class or module '%s' specified for inheritance diagram" % name)
@@ -277,12 +290,16 b' class inheritance_diagram(Body, Element):'
277 """
290 """
278 pass
291 pass
279
292
280 def inheritance_diagram_directive_run(class_names, options, state):
293 def inheritance_diagram_directive(name, arguments, options, content, lineno,
294 content_offset, block_text, state,
295 state_machine):
281 """
296 """
282 Run when the inheritance_diagram directive is first encountered.
297 Run when the inheritance_diagram directive is first encountered.
283 """
298 """
284 node = inheritance_diagram()
299 node = inheritance_diagram()
285
300
301 class_names = arguments
302
286 # Create a graph starting with the list of classes
303 # Create a graph starting with the list of classes
287 graph = InheritanceGraph(class_names)
304 graph = InheritanceGraph(class_names)
288
305
@@ -315,15 +332,12 b' def html_output_graph(self, node):'
315
332
316 graph_hash = get_graph_hash(node)
333 graph_hash = get_graph_hash(node)
317 name = "inheritance%s" % graph_hash
334 name = "inheritance%s" % graph_hash
318 png_path = os.path.join('_static', name + ".png")
335 path = '_images'
319
336 dest_path = os.path.join(setup.app.builder.outdir, path)
320 path = '_static'
337 if not os.path.exists(dest_path):
321 source = self.document.attributes['source']
338 os.makedirs(dest_path)
322 count = source.split('/doc/')[-1].count('/')
339 png_path = os.path.join(dest_path, name + ".png")
323 for i in range(count):
340 path = setup.app.builder.imgpath
324 if os.path.exists(path): break
325 path = '../'+path
326 path = '../'+path #specifically added for matplotlib
327
341
328 # Create a mapping from fully-qualified class names to URLs.
342 # Create a mapping from fully-qualified class names to URLs.
329 urls = {}
343 urls = {}
@@ -349,11 +363,14 b' def latex_output_graph(self, node):'
349
363
350 graph_hash = get_graph_hash(node)
364 graph_hash = get_graph_hash(node)
351 name = "inheritance%s" % graph_hash
365 name = "inheritance%s" % graph_hash
352 pdf_path = os.path.join('_static', name + ".pdf")
366 dest_path = os.path.abspath(os.path.join(setup.app.builder.outdir, '_images'))
367 if not os.path.exists(dest_path):
368 os.makedirs(dest_path)
369 pdf_path = os.path.abspath(os.path.join(dest_path, name + ".pdf"))
353
370
354 graph.run_dot(['-Tpdf', '-o%s' % pdf_path],
371 graph.run_dot(['-Tpdf', '-o%s' % pdf_path],
355 name, parts, graph_options={'size': '"6.0,6.0"'})
372 name, parts, graph_options={'size': '"6.0,6.0"'})
356 return '\\includegraphics{../../%s}' % pdf_path
373 return '\n\\includegraphics{%s}\n\n' % pdf_path
357
374
358 def visit_inheritance_diagram(inner_func):
375 def visit_inheritance_diagram(inner_func):
359 """
376 """
@@ -377,47 +394,14 b' def visit_inheritance_diagram(inner_func):'
377 def do_nothing(self, node):
394 def do_nothing(self, node):
378 pass
395 pass
379
396
380 options_spec = {
381 'parts': directives.nonnegative_int
382 }
383
384 # Deal with the old and new way of registering directives
385 try:
386 from docutils.parsers.rst import Directive
387 except ImportError:
388 from docutils.parsers.rst.directives import _directives
389 def inheritance_diagram_directive(name, arguments, options, content, lineno,
390 content_offset, block_text, state,
391 state_machine):
392 return inheritance_diagram_directive_run(arguments, options, state)
393 inheritance_diagram_directive.__doc__ = __doc__
394 inheritance_diagram_directive.arguments = (1, 100, 0)
395 inheritance_diagram_directive.options = options_spec
396 inheritance_diagram_directive.content = 0
397 _directives['inheritance-diagram'] = inheritance_diagram_directive
398 else:
399 class inheritance_diagram_directive(Directive):
400 has_content = False
401 required_arguments = 1
402 optional_arguments = 100
403 final_argument_whitespace = False
404 option_spec = options_spec
405
406 def run(self):
407 return inheritance_diagram_directive_run(
408 self.arguments, self.options, self.state)
409 inheritance_diagram_directive.__doc__ = __doc__
410
411 directives.register_directive('inheritance-diagram',
412 inheritance_diagram_directive)
413
414 def setup(app):
397 def setup(app):
415 app.add_node(inheritance_diagram)
398 setup.app = app
416
399 setup.confdir = app.confdir
417 HTMLTranslator.visit_inheritance_diagram = \
400
418 visit_inheritance_diagram(html_output_graph)
401 app.add_node(
419 HTMLTranslator.depart_inheritance_diagram = do_nothing
402 inheritance_diagram,
420
403 latex=(visit_inheritance_diagram(latex_output_graph), do_nothing),
421 LaTeXTranslator.visit_inheritance_diagram = \
404 html=(visit_inheritance_diagram(html_output_graph), do_nothing))
422 visit_inheritance_diagram(latex_output_graph)
405 app.add_directive(
423 LaTeXTranslator.depart_inheritance_diagram = do_nothing
406 'inheritance-diagram', inheritance_diagram_directive,
407 False, (1, 100, 0), parts = directives.nonnegative_int)
@@ -1,18 +1,32 b''
1 """reST directive for syntax-highlighting ipython interactive sessions.
2 """
3
4 #-----------------------------------------------------------------------------
5 # Needed modules
6
7 # Standard library
8 import re
9
10 # Third party
1 from pygments.lexer import Lexer, do_insertions
11 from pygments.lexer import Lexer, do_insertions
2 from pygments.lexers.agile import PythonConsoleLexer, PythonLexer, \
12 from pygments.lexers.agile import (PythonConsoleLexer, PythonLexer,
3 PythonTracebackLexer
13 PythonTracebackLexer)
4 from pygments.token import Comment, Generic
14 from pygments.token import Comment, Generic
15
5 from sphinx import highlighting
16 from sphinx import highlighting
6 import re
7
17
18
19 #-----------------------------------------------------------------------------
20 # Global constants
8 line_re = re.compile('.*?\n')
21 line_re = re.compile('.*?\n')
9
22
23 #-----------------------------------------------------------------------------
24 # Code begins - classes and functions
25
10 class IPythonConsoleLexer(Lexer):
26 class IPythonConsoleLexer(Lexer):
11 """
27 """
12 For IPython console output or doctests, such as:
28 For IPython console output or doctests, such as:
13
29
14 Tracebacks are not currently supported.
15
16 .. sourcecode:: ipython
30 .. sourcecode:: ipython
17
31
18 In [1]: a = 'foo'
32 In [1]: a = 'foo'
@@ -24,7 +38,14 b' class IPythonConsoleLexer(Lexer):'
24 foo
38 foo
25
39
26 In [4]: 1 / 0
40 In [4]: 1 / 0
41
42 Notes:
43
44 - Tracebacks are not currently supported.
45
46 - It assumes the default IPython prompts, not customized ones.
27 """
47 """
48
28 name = 'IPython console session'
49 name = 'IPython console session'
29 aliases = ['ipython']
50 aliases = ['ipython']
30 mimetypes = ['text/x-ipython-console']
51 mimetypes = ['text/x-ipython-console']
@@ -72,4 +93,6 b' class IPythonConsoleLexer(Lexer):'
72 pylexer.get_tokens_unprocessed(curcode)):
93 pylexer.get_tokens_unprocessed(curcode)):
73 yield item
94 yield item
74
95
96 #-----------------------------------------------------------------------------
97 # Register the extension as a valid pygments lexer
75 highlighting.lexers['ipython'] = IPythonConsoleLexer()
98 highlighting.lexers['ipython'] = IPythonConsoleLexer()
General Comments 0
You need to be logged in to leave comments. Login now