##// 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)
@@ -1,640 +1,639 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 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
13 completes keywords, built-ins and globals in __main__; when completing
12 completes keywords, built-ins and globals in __main__; when completing
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 completes its attributes.
14 completes its attributes.
16
15
17 It's very cool to do "import string" type "string.", hit the
16 It's very cool to do "import string" type "string.", hit the
18 completion key (twice), and see the list of names defined by the
17 completion key (twice), and see the list of names defined by the
19 string module!
18 string module!
20
19
21 Tip: to use the tab key as the completion key, call
20 Tip: to use the tab key as the completion key, call
22
21
23 readline.parse_and_bind("tab: complete")
22 readline.parse_and_bind("tab: complete")
24
23
25 Notes:
24 Notes:
26
25
27 - Exceptions raised by the completer function are *ignored* (and
26 - Exceptions raised by the completer function are *ignored* (and
28 generally cause the completion to fail). This is a feature -- since
27 generally cause the completion to fail). This is a feature -- since
29 readline sets the tty device in raw (or cbreak) mode, printing a
28 readline sets the tty device in raw (or cbreak) mode, printing a
30 traceback wouldn't work well without some complicated hoopla to save,
29 traceback wouldn't work well without some complicated hoopla to save,
31 reset and restore the tty state.
30 reset and restore the tty state.
32
31
33 - The evaluation of the NAME.NAME... form may cause arbitrary
32 - The evaluation of the NAME.NAME... form may cause arbitrary
34 application defined code to be executed if an object with a
33 application defined code to be executed if an object with a
35 __getattr__ hook is found. Since it is the responsibility of the
34 __getattr__ hook is found. Since it is the responsibility of the
36 application (or the user) to enable this feature, I consider this an
35 application (or the user) to enable this feature, I consider this an
37 acceptable risk. More complicated expressions (e.g. function calls or
36 acceptable risk. More complicated expressions (e.g. function calls or
38 indexing operations) are *not* evaluated.
37 indexing operations) are *not* evaluated.
39
38
40 - GNU readline is also used by the built-in functions input() and
39 - GNU readline is also used by the built-in functions input() and
41 raw_input(), and thus these also benefit/suffer from the completer
40 raw_input(), and thus these also benefit/suffer from the completer
42 features. Clearly an interactive application can benefit by
41 features. Clearly an interactive application can benefit by
43 specifying its own completer function and using raw_input() for all
42 specifying its own completer function and using raw_input() for all
44 its input.
43 its input.
45
44
46 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
47 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
48
47
49 """
48 """
50
49
51 #*****************************************************************************
50 #*****************************************************************************
52 #
51 #
53 # Since this file is essentially a minimally modified copy of the rlcompleter
52 # Since this file is essentially a minimally modified copy of the rlcompleter
54 # module which is part of the standard Python distribution, I assume that the
53 # module which is part of the standard Python distribution, I assume that the
55 # proper procedure is to maintain its copyright as belonging to the Python
54 # proper procedure is to maintain its copyright as belonging to the Python
56 # Software Foundation (in addition to my own, for all new code).
55 # Software Foundation (in addition to my own, for all new code).
57 #
56 #
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
57 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
60 #
59 #
61 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
62 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
63 #
62 #
64 #*****************************************************************************
63 #*****************************************************************************
65
64
66 import __builtin__
65 import __builtin__
67 import __main__
66 import __main__
68 import glob
67 import glob
69 import keyword
68 import keyword
70 import os
69 import os
71 import re
70 import re
72 import shlex
71 import shlex
73 import sys
72 import sys
74 import IPython.rlineimpl as readline
73 import IPython.rlineimpl as readline
75 import itertools
74 import itertools
76 from IPython.ipstruct import Struct
75 from IPython.ipstruct import Struct
77 from IPython import ipapi
76 from IPython import ipapi
78 from IPython import generics
77 from IPython import generics
79 import types
78 import types
80
79
81 # Python 2.4 offers sets as a builtin
80 # Python 2.4 offers sets as a builtin
82 try:
81 try:
83 set()
82 set()
84 except NameError:
83 except NameError:
85 from sets import Set as set
84 from sets import Set as set
86
85
87 from IPython.genutils import debugx, dir2
86 from IPython.genutils import debugx, dir2
88
87
89 __all__ = ['Completer','IPCompleter']
88 __all__ = ['Completer','IPCompleter']
90
89
91 class Completer:
90 class Completer:
92 def __init__(self,namespace=None,global_namespace=None):
91 def __init__(self,namespace=None,global_namespace=None):
93 """Create a new completer for the command line.
92 """Create a new completer for the command line.
94
93
95 Completer([namespace,global_namespace]) -> completer instance.
94 Completer([namespace,global_namespace]) -> completer instance.
96
95
97 If unspecified, the default namespace where completions are performed
96 If unspecified, the default namespace where completions are performed
98 is __main__ (technically, __main__.__dict__). Namespaces should be
97 is __main__ (technically, __main__.__dict__). Namespaces should be
99 given as dictionaries.
98 given as dictionaries.
100
99
101 An optional second namespace can be given. This allows the completer
100 An optional second namespace can be given. This allows the completer
102 to handle cases where both the local and global scopes need to be
101 to handle cases where both the local and global scopes need to be
103 distinguished.
102 distinguished.
104
103
105 Completer instances should be used as the completion mechanism of
104 Completer instances should be used as the completion mechanism of
106 readline via the set_completer() call:
105 readline via the set_completer() call:
107
106
108 readline.set_completer(Completer(my_namespace).complete)
107 readline.set_completer(Completer(my_namespace).complete)
109 """
108 """
110
109
111 # Don't bind to namespace quite yet, but flag whether the user wants a
110 # Don't bind to namespace quite yet, but flag whether the user wants a
112 # specific namespace or to use __main__.__dict__. This will allow us
111 # specific namespace or to use __main__.__dict__. This will allow us
113 # to bind to __main__.__dict__ at completion time, not now.
112 # to bind to __main__.__dict__ at completion time, not now.
114 if namespace is None:
113 if namespace is None:
115 self.use_main_ns = 1
114 self.use_main_ns = 1
116 else:
115 else:
117 self.use_main_ns = 0
116 self.use_main_ns = 0
118 self.namespace = namespace
117 self.namespace = namespace
119
118
120 # The global namespace, if given, can be bound directly
119 # The global namespace, if given, can be bound directly
121 if global_namespace is None:
120 if global_namespace is None:
122 self.global_namespace = {}
121 self.global_namespace = {}
123 else:
122 else:
124 self.global_namespace = global_namespace
123 self.global_namespace = global_namespace
125
124
126 def complete(self, text, state):
125 def complete(self, text, state):
127 """Return the next possible completion for 'text'.
126 """Return the next possible completion for 'text'.
128
127
129 This is called successively with state == 0, 1, 2, ... until it
128 This is called successively with state == 0, 1, 2, ... until it
130 returns None. The completion should begin with 'text'.
129 returns None. The completion should begin with 'text'.
131
130
132 """
131 """
133 if self.use_main_ns:
132 if self.use_main_ns:
134 self.namespace = __main__.__dict__
133 self.namespace = __main__.__dict__
135
134
136 if state == 0:
135 if state == 0:
137 if "." in text:
136 if "." in text:
138 self.matches = self.attr_matches(text)
137 self.matches = self.attr_matches(text)
139 else:
138 else:
140 self.matches = self.global_matches(text)
139 self.matches = self.global_matches(text)
141 try:
140 try:
142 return self.matches[state]
141 return self.matches[state]
143 except IndexError:
142 except IndexError:
144 return None
143 return None
145
144
146 def global_matches(self, text):
145 def global_matches(self, text):
147 """Compute matches when text is a simple name.
146 """Compute matches when text is a simple name.
148
147
149 Return a list of all keywords, built-in functions and names currently
148 Return a list of all keywords, built-in functions and names currently
150 defined in self.namespace or self.global_namespace that match.
149 defined in self.namespace or self.global_namespace that match.
151
150
152 """
151 """
153 matches = []
152 matches = []
154 match_append = matches.append
153 match_append = matches.append
155 n = len(text)
154 n = len(text)
156 for lst in [keyword.kwlist,
155 for lst in [keyword.kwlist,
157 __builtin__.__dict__.keys(),
156 __builtin__.__dict__.keys(),
158 self.namespace.keys(),
157 self.namespace.keys(),
159 self.global_namespace.keys()]:
158 self.global_namespace.keys()]:
160 for word in lst:
159 for word in lst:
161 if word[:n] == text and word != "__builtins__":
160 if word[:n] == text and word != "__builtins__":
162 match_append(word)
161 match_append(word)
163 return matches
162 return matches
164
163
165 def attr_matches(self, text):
164 def attr_matches(self, text):
166 """Compute matches when text contains a dot.
165 """Compute matches when text contains a dot.
167
166
168 Assuming the text is of the form NAME.NAME....[NAME], and is
167 Assuming the text is of the form NAME.NAME....[NAME], and is
169 evaluatable in self.namespace or self.global_namespace, it will be
168 evaluatable in self.namespace or self.global_namespace, it will be
170 evaluated and its attributes (as revealed by dir()) are used as
169 evaluated and its attributes (as revealed by dir()) are used as
171 possible completions. (For class instances, class members are are
170 possible completions. (For class instances, class members are are
172 also considered.)
171 also considered.)
173
172
174 WARNING: this can still invoke arbitrary C code, if an object
173 WARNING: this can still invoke arbitrary C code, if an object
175 with a __getattr__ hook is evaluated.
174 with a __getattr__ hook is evaluated.
176
175
177 """
176 """
178 import re
177 import re
179
178
180 # Another option, seems to work great. Catches things like ''.<tab>
179 # Another option, seems to work great. Catches things like ''.<tab>
181 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
180 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
182
181
183 if not m:
182 if not m:
184 return []
183 return []
185
184
186 expr, attr = m.group(1, 3)
185 expr, attr = m.group(1, 3)
187 try:
186 try:
188 obj = eval(expr, self.namespace)
187 obj = eval(expr, self.namespace)
189 except:
188 except:
190 try:
189 try:
191 obj = eval(expr, self.global_namespace)
190 obj = eval(expr, self.global_namespace)
192 except:
191 except:
193 return []
192 return []
194
193
195 words = dir2(obj)
194 words = dir2(obj)
196
195
197 try:
196 try:
198 words = generics.complete_object(obj, words)
197 words = generics.complete_object(obj, words)
199 except ipapi.TryNext:
198 except ipapi.TryNext:
200 pass
199 pass
201 # Build match list to return
200 # Build match list to return
202 n = len(attr)
201 n = len(attr)
203 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
202 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
204 return res
203 return res
205
204
206 class IPCompleter(Completer):
205 class IPCompleter(Completer):
207 """Extension of the completer class with IPython-specific features"""
206 """Extension of the completer class with IPython-specific features"""
208
207
209 def __init__(self,shell,namespace=None,global_namespace=None,
208 def __init__(self,shell,namespace=None,global_namespace=None,
210 omit__names=0,alias_table=None):
209 omit__names=0,alias_table=None):
211 """IPCompleter() -> completer
210 """IPCompleter() -> completer
212
211
213 Return a completer object suitable for use by the readline library
212 Return a completer object suitable for use by the readline library
214 via readline.set_completer().
213 via readline.set_completer().
215
214
216 Inputs:
215 Inputs:
217
216
218 - shell: a pointer to the ipython shell itself. This is needed
217 - shell: a pointer to the ipython shell itself. This is needed
219 because this completer knows about magic functions, and those can
218 because this completer knows about magic functions, and those can
220 only be accessed via the ipython instance.
219 only be accessed via the ipython instance.
221
220
222 - namespace: an optional dict where completions are performed.
221 - namespace: an optional dict where completions are performed.
223
222
224 - global_namespace: secondary optional dict for completions, to
223 - global_namespace: secondary optional dict for completions, to
225 handle cases (such as IPython embedded inside functions) where
224 handle cases (such as IPython embedded inside functions) where
226 both Python scopes are visible.
225 both Python scopes are visible.
227
226
228 - The optional omit__names parameter sets the completer to omit the
227 - The optional omit__names parameter sets the completer to omit the
229 'magic' names (__magicname__) for python objects unless the text
228 'magic' names (__magicname__) for python objects unless the text
230 to be completed explicitly starts with one or more underscores.
229 to be completed explicitly starts with one or more underscores.
231
230
232 - If alias_table is supplied, it should be a dictionary of aliases
231 - If alias_table is supplied, it should be a dictionary of aliases
233 to complete. """
232 to complete. """
234
233
235 Completer.__init__(self,namespace,global_namespace)
234 Completer.__init__(self,namespace,global_namespace)
236 self.magic_prefix = shell.name+'.magic_'
235 self.magic_prefix = shell.name+'.magic_'
237 self.magic_escape = shell.ESC_MAGIC
236 self.magic_escape = shell.ESC_MAGIC
238 self.readline = readline
237 self.readline = readline
239 delims = self.readline.get_completer_delims()
238 delims = self.readline.get_completer_delims()
240 delims = delims.replace(self.magic_escape,'')
239 delims = delims.replace(self.magic_escape,'')
241 self.readline.set_completer_delims(delims)
240 self.readline.set_completer_delims(delims)
242 self.get_line_buffer = self.readline.get_line_buffer
241 self.get_line_buffer = self.readline.get_line_buffer
243 self.get_endidx = self.readline.get_endidx
242 self.get_endidx = self.readline.get_endidx
244 self.omit__names = omit__names
243 self.omit__names = omit__names
245 self.merge_completions = shell.rc.readline_merge_completions
244 self.merge_completions = shell.rc.readline_merge_completions
246 if alias_table is None:
245 if alias_table is None:
247 alias_table = {}
246 alias_table = {}
248 self.alias_table = alias_table
247 self.alias_table = alias_table
249 # Regexp to split filenames with spaces in them
248 # Regexp to split filenames with spaces in them
250 self.space_name_re = re.compile(r'([^\\] )')
249 self.space_name_re = re.compile(r'([^\\] )')
251 # Hold a local ref. to glob.glob for speed
250 # Hold a local ref. to glob.glob for speed
252 self.glob = glob.glob
251 self.glob = glob.glob
253
252
254 # Determine if we are running on 'dumb' terminals, like (X)Emacs
253 # Determine if we are running on 'dumb' terminals, like (X)Emacs
255 # buffers, to avoid completion problems.
254 # buffers, to avoid completion problems.
256 term = os.environ.get('TERM','xterm')
255 term = os.environ.get('TERM','xterm')
257 self.dumb_terminal = term in ['dumb','emacs']
256 self.dumb_terminal = term in ['dumb','emacs']
258
257
259 # Special handling of backslashes needed in win32 platforms
258 # Special handling of backslashes needed in win32 platforms
260 if sys.platform == "win32":
259 if sys.platform == "win32":
261 self.clean_glob = self._clean_glob_win32
260 self.clean_glob = self._clean_glob_win32
262 else:
261 else:
263 self.clean_glob = self._clean_glob
262 self.clean_glob = self._clean_glob
264 self.matchers = [self.python_matches,
263 self.matchers = [self.python_matches,
265 self.file_matches,
264 self.file_matches,
266 self.alias_matches,
265 self.alias_matches,
267 self.python_func_kw_matches]
266 self.python_func_kw_matches]
268
267
269
268
270 # Code contributed by Alex Schmolck, for ipython/emacs integration
269 # Code contributed by Alex Schmolck, for ipython/emacs integration
271 def all_completions(self, text):
270 def all_completions(self, text):
272 """Return all possible completions for the benefit of emacs."""
271 """Return all possible completions for the benefit of emacs."""
273
272
274 completions = []
273 completions = []
275 comp_append = completions.append
274 comp_append = completions.append
276 try:
275 try:
277 for i in xrange(sys.maxint):
276 for i in xrange(sys.maxint):
278 res = self.complete(text, i)
277 res = self.complete(text, i)
279
278
280 if not res: break
279 if not res: break
281
280
282 comp_append(res)
281 comp_append(res)
283 #XXX workaround for ``notDefined.<tab>``
282 #XXX workaround for ``notDefined.<tab>``
284 except NameError:
283 except NameError:
285 pass
284 pass
286 return completions
285 return completions
287 # /end Alex Schmolck code.
286 # /end Alex Schmolck code.
288
287
289 def _clean_glob(self,text):
288 def _clean_glob(self,text):
290 return self.glob("%s*" % text)
289 return self.glob("%s*" % text)
291
290
292 def _clean_glob_win32(self,text):
291 def _clean_glob_win32(self,text):
293 return [f.replace("\\","/")
292 return [f.replace("\\","/")
294 for f in self.glob("%s*" % text)]
293 for f in self.glob("%s*" % text)]
295
294
296 def file_matches(self, text):
295 def file_matches(self, text):
297 """Match filenames, expanding ~USER type strings.
296 """Match filenames, expanding ~USER type strings.
298
297
299 Most of the seemingly convoluted logic in this completer is an
298 Most of the seemingly convoluted logic in this completer is an
300 attempt to handle filenames with spaces in them. And yet it's not
299 attempt to handle filenames with spaces in them. And yet it's not
301 quite perfect, because Python's readline doesn't expose all of the
300 quite perfect, because Python's readline doesn't expose all of the
302 GNU readline details needed for this to be done correctly.
301 GNU readline details needed for this to be done correctly.
303
302
304 For a filename with a space in it, the printed completions will be
303 For a filename with a space in it, the printed completions will be
305 only the parts after what's already been typed (instead of the
304 only the parts after what's already been typed (instead of the
306 full completions, as is normally done). I don't think with the
305 full completions, as is normally done). I don't think with the
307 current (as of Python 2.3) Python readline it's possible to do
306 current (as of Python 2.3) Python readline it's possible to do
308 better."""
307 better."""
309
308
310 #print 'Completer->file_matches: <%s>' % text # dbg
309 #print 'Completer->file_matches: <%s>' % text # dbg
311
310
312 # chars that require escaping with backslash - i.e. chars
311 # chars that require escaping with backslash - i.e. chars
313 # that readline treats incorrectly as delimiters, but we
312 # that readline treats incorrectly as delimiters, but we
314 # don't want to treat as delimiters in filename matching
313 # don't want to treat as delimiters in filename matching
315 # when escaped with backslash
314 # when escaped with backslash
316
315
317 if sys.platform == 'win32':
316 if sys.platform == 'win32':
318 protectables = ' '
317 protectables = ' '
319 else:
318 else:
320 protectables = ' ()'
319 protectables = ' ()'
321
320
322 if text.startswith('!'):
321 if text.startswith('!'):
323 text = text[1:]
322 text = text[1:]
324 text_prefix = '!'
323 text_prefix = '!'
325 else:
324 else:
326 text_prefix = ''
325 text_prefix = ''
327
326
328 def protect_filename(s):
327 def protect_filename(s):
329 return "".join([(ch in protectables and '\\' + ch or ch)
328 return "".join([(ch in protectables and '\\' + ch or ch)
330 for ch in s])
329 for ch in s])
331
330
332 def single_dir_expand(matches):
331 def single_dir_expand(matches):
333 "Recursively expand match lists containing a single dir."
332 "Recursively expand match lists containing a single dir."
334
333
335 if len(matches) == 1 and os.path.isdir(matches[0]):
334 if len(matches) == 1 and os.path.isdir(matches[0]):
336 # Takes care of links to directories also. Use '/'
335 # Takes care of links to directories also. Use '/'
337 # explicitly, even under Windows, so that name completions
336 # explicitly, even under Windows, so that name completions
338 # don't end up escaped.
337 # don't end up escaped.
339 d = matches[0]
338 d = matches[0]
340 if d[-1] in ['/','\\']:
339 if d[-1] in ['/','\\']:
341 d = d[:-1]
340 d = d[:-1]
342
341
343 subdirs = os.listdir(d)
342 subdirs = os.listdir(d)
344 if subdirs:
343 if subdirs:
345 matches = [ (d + '/' + p) for p in subdirs]
344 matches = [ (d + '/' + p) for p in subdirs]
346 return single_dir_expand(matches)
345 return single_dir_expand(matches)
347 else:
346 else:
348 return matches
347 return matches
349 else:
348 else:
350 return matches
349 return matches
351
350
352 lbuf = self.lbuf
351 lbuf = self.lbuf
353 open_quotes = 0 # track strings with open quotes
352 open_quotes = 0 # track strings with open quotes
354 try:
353 try:
355 lsplit = shlex.split(lbuf)[-1]
354 lsplit = shlex.split(lbuf)[-1]
356 except ValueError:
355 except ValueError:
357 # typically an unmatched ", or backslash without escaped char.
356 # typically an unmatched ", or backslash without escaped char.
358 if lbuf.count('"')==1:
357 if lbuf.count('"')==1:
359 open_quotes = 1
358 open_quotes = 1
360 lsplit = lbuf.split('"')[-1]
359 lsplit = lbuf.split('"')[-1]
361 elif lbuf.count("'")==1:
360 elif lbuf.count("'")==1:
362 open_quotes = 1
361 open_quotes = 1
363 lsplit = lbuf.split("'")[-1]
362 lsplit = lbuf.split("'")[-1]
364 else:
363 else:
365 return []
364 return []
366 except IndexError:
365 except IndexError:
367 # tab pressed on empty line
366 # tab pressed on empty line
368 lsplit = ""
367 lsplit = ""
369
368
370 if lsplit != protect_filename(lsplit):
369 if lsplit != protect_filename(lsplit):
371 # if protectables are found, do matching on the whole escaped
370 # if protectables are found, do matching on the whole escaped
372 # name
371 # name
373 has_protectables = 1
372 has_protectables = 1
374 text0,text = text,lsplit
373 text0,text = text,lsplit
375 else:
374 else:
376 has_protectables = 0
375 has_protectables = 0
377 text = os.path.expanduser(text)
376 text = os.path.expanduser(text)
378
377
379 if text == "":
378 if text == "":
380 return [text_prefix + protect_filename(f) for f in self.glob("*")]
379 return [text_prefix + protect_filename(f) for f in self.glob("*")]
381
380
382 m0 = self.clean_glob(text.replace('\\',''))
381 m0 = self.clean_glob(text.replace('\\',''))
383 if has_protectables:
382 if has_protectables:
384 # If we had protectables, we need to revert our changes to the
383 # If we had protectables, we need to revert our changes to the
385 # beginning of filename so that we don't double-write the part
384 # beginning of filename so that we don't double-write the part
386 # of the filename we have so far
385 # of the filename we have so far
387 len_lsplit = len(lsplit)
386 len_lsplit = len(lsplit)
388 matches = [text_prefix + text0 +
387 matches = [text_prefix + text0 +
389 protect_filename(f[len_lsplit:]) for f in m0]
388 protect_filename(f[len_lsplit:]) for f in m0]
390 else:
389 else:
391 if open_quotes:
390 if open_quotes:
392 # if we have a string with an open quote, we don't need to
391 # if we have a string with an open quote, we don't need to
393 # protect the names at all (and we _shouldn't_, as it
392 # protect the names at all (and we _shouldn't_, as it
394 # would cause bugs when the filesystem call is made).
393 # would cause bugs when the filesystem call is made).
395 matches = m0
394 matches = m0
396 else:
395 else:
397 matches = [text_prefix +
396 matches = [text_prefix +
398 protect_filename(f) for f in m0]
397 protect_filename(f) for f in m0]
399
398
400 #print 'mm',matches # dbg
399 #print 'mm',matches # dbg
401 return single_dir_expand(matches)
400 return single_dir_expand(matches)
402
401
403 def alias_matches(self, text):
402 def alias_matches(self, text):
404 """Match internal system aliases"""
403 """Match internal system aliases"""
405 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
404 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
406
405
407 # if we are not in the first 'item', alias matching
406 # if we are not in the first 'item', alias matching
408 # doesn't make sense - unless we are starting with 'sudo' command.
407 # doesn't make sense - unless we are starting with 'sudo' command.
409 if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'):
408 if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'):
410 return []
409 return []
411 text = os.path.expanduser(text)
410 text = os.path.expanduser(text)
412 aliases = self.alias_table.keys()
411 aliases = self.alias_table.keys()
413 if text == "":
412 if text == "":
414 return aliases
413 return aliases
415 else:
414 else:
416 return [alias for alias in aliases if alias.startswith(text)]
415 return [alias for alias in aliases if alias.startswith(text)]
417
416
418 def python_matches(self,text):
417 def python_matches(self,text):
419 """Match attributes or global python names"""
418 """Match attributes or global python names"""
420
419
421 #print 'Completer->python_matches, txt=<%s>' % text # dbg
420 #print 'Completer->python_matches, txt=<%s>' % text # dbg
422 if "." in text:
421 if "." in text:
423 try:
422 try:
424 matches = self.attr_matches(text)
423 matches = self.attr_matches(text)
425 if text.endswith('.') and self.omit__names:
424 if text.endswith('.') and self.omit__names:
426 if self.omit__names == 1:
425 if self.omit__names == 1:
427 # true if txt is _not_ a __ name, false otherwise:
426 # true if txt is _not_ a __ name, false otherwise:
428 no__name = (lambda txt:
427 no__name = (lambda txt:
429 re.match(r'.*\.__.*?__',txt) is None)
428 re.match(r'.*\.__.*?__',txt) is None)
430 else:
429 else:
431 # true if txt is _not_ a _ name, false otherwise:
430 # true if txt is _not_ a _ name, false otherwise:
432 no__name = (lambda txt:
431 no__name = (lambda txt:
433 re.match(r'.*\._.*?',txt) is None)
432 re.match(r'.*\._.*?',txt) is None)
434 matches = filter(no__name, matches)
433 matches = filter(no__name, matches)
435 except NameError:
434 except NameError:
436 # catches <undefined attributes>.<tab>
435 # catches <undefined attributes>.<tab>
437 matches = []
436 matches = []
438 else:
437 else:
439 matches = self.global_matches(text)
438 matches = self.global_matches(text)
440 # this is so completion finds magics when automagic is on:
439 # this is so completion finds magics when automagic is on:
441 if (matches == [] and
440 if (matches == [] and
442 not text.startswith(os.sep) and
441 not text.startswith(os.sep) and
443 not ' ' in self.lbuf):
442 not ' ' in self.lbuf):
444 matches = self.attr_matches(self.magic_prefix+text)
443 matches = self.attr_matches(self.magic_prefix+text)
445 return matches
444 return matches
446
445
447 def _default_arguments(self, obj):
446 def _default_arguments(self, obj):
448 """Return the list of default arguments of obj if it is callable,
447 """Return the list of default arguments of obj if it is callable,
449 or empty list otherwise."""
448 or empty list otherwise."""
450
449
451 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
450 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
452 # for classes, check for __init__,__new__
451 # for classes, check for __init__,__new__
453 if inspect.isclass(obj):
452 if inspect.isclass(obj):
454 obj = (getattr(obj,'__init__',None) or
453 obj = (getattr(obj,'__init__',None) or
455 getattr(obj,'__new__',None))
454 getattr(obj,'__new__',None))
456 # for all others, check if they are __call__able
455 # for all others, check if they are __call__able
457 elif hasattr(obj, '__call__'):
456 elif hasattr(obj, '__call__'):
458 obj = obj.__call__
457 obj = obj.__call__
459 # XXX: is there a way to handle the builtins ?
458 # XXX: is there a way to handle the builtins ?
460 try:
459 try:
461 args,_,_1,defaults = inspect.getargspec(obj)
460 args,_,_1,defaults = inspect.getargspec(obj)
462 if defaults:
461 if defaults:
463 return args[-len(defaults):]
462 return args[-len(defaults):]
464 except TypeError: pass
463 except TypeError: pass
465 return []
464 return []
466
465
467 def python_func_kw_matches(self,text):
466 def python_func_kw_matches(self,text):
468 """Match named parameters (kwargs) of the last open function"""
467 """Match named parameters (kwargs) of the last open function"""
469
468
470 if "." in text: # a parameter cannot be dotted
469 if "." in text: # a parameter cannot be dotted
471 return []
470 return []
472 try: regexp = self.__funcParamsRegex
471 try: regexp = self.__funcParamsRegex
473 except AttributeError:
472 except AttributeError:
474 regexp = self.__funcParamsRegex = re.compile(r'''
473 regexp = self.__funcParamsRegex = re.compile(r'''
475 '.*?' | # single quoted strings or
474 '.*?' | # single quoted strings or
476 ".*?" | # double quoted strings or
475 ".*?" | # double quoted strings or
477 \w+ | # identifier
476 \w+ | # identifier
478 \S # other characters
477 \S # other characters
479 ''', re.VERBOSE | re.DOTALL)
478 ''', re.VERBOSE | re.DOTALL)
480 # 1. find the nearest identifier that comes before an unclosed
479 # 1. find the nearest identifier that comes before an unclosed
481 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
480 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
482 tokens = regexp.findall(self.get_line_buffer())
481 tokens = regexp.findall(self.get_line_buffer())
483 tokens.reverse()
482 tokens.reverse()
484 iterTokens = iter(tokens); openPar = 0
483 iterTokens = iter(tokens); openPar = 0
485 for token in iterTokens:
484 for token in iterTokens:
486 if token == ')':
485 if token == ')':
487 openPar -= 1
486 openPar -= 1
488 elif token == '(':
487 elif token == '(':
489 openPar += 1
488 openPar += 1
490 if openPar > 0:
489 if openPar > 0:
491 # found the last unclosed parenthesis
490 # found the last unclosed parenthesis
492 break
491 break
493 else:
492 else:
494 return []
493 return []
495 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
494 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
496 ids = []
495 ids = []
497 isId = re.compile(r'\w+$').match
496 isId = re.compile(r'\w+$').match
498 while True:
497 while True:
499 try:
498 try:
500 ids.append(iterTokens.next())
499 ids.append(iterTokens.next())
501 if not isId(ids[-1]):
500 if not isId(ids[-1]):
502 ids.pop(); break
501 ids.pop(); break
503 if not iterTokens.next() == '.':
502 if not iterTokens.next() == '.':
504 break
503 break
505 except StopIteration:
504 except StopIteration:
506 break
505 break
507 # lookup the candidate callable matches either using global_matches
506 # lookup the candidate callable matches either using global_matches
508 # or attr_matches for dotted names
507 # or attr_matches for dotted names
509 if len(ids) == 1:
508 if len(ids) == 1:
510 callableMatches = self.global_matches(ids[0])
509 callableMatches = self.global_matches(ids[0])
511 else:
510 else:
512 callableMatches = self.attr_matches('.'.join(ids[::-1]))
511 callableMatches = self.attr_matches('.'.join(ids[::-1]))
513 argMatches = []
512 argMatches = []
514 for callableMatch in callableMatches:
513 for callableMatch in callableMatches:
515 try: namedArgs = self._default_arguments(eval(callableMatch,
514 try: namedArgs = self._default_arguments(eval(callableMatch,
516 self.namespace))
515 self.namespace))
517 except: continue
516 except: continue
518 for namedArg in namedArgs:
517 for namedArg in namedArgs:
519 if namedArg.startswith(text):
518 if namedArg.startswith(text):
520 argMatches.append("%s=" %namedArg)
519 argMatches.append("%s=" %namedArg)
521 return argMatches
520 return argMatches
522
521
523 def dispatch_custom_completer(self,text):
522 def dispatch_custom_completer(self,text):
524 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
523 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
525 line = self.full_lbuf
524 line = self.full_lbuf
526 if not line.strip():
525 if not line.strip():
527 return None
526 return None
528
527
529 event = Struct()
528 event = Struct()
530 event.line = line
529 event.line = line
531 event.symbol = text
530 event.symbol = text
532 cmd = line.split(None,1)[0]
531 cmd = line.split(None,1)[0]
533 event.command = cmd
532 event.command = cmd
534 #print "\ncustom:{%s]\n" % event # dbg
533 #print "\ncustom:{%s]\n" % event # dbg
535
534
536 # for foo etc, try also to find completer for %foo
535 # for foo etc, try also to find completer for %foo
537 if not cmd.startswith(self.magic_escape):
536 if not cmd.startswith(self.magic_escape):
538 try_magic = self.custom_completers.s_matches(
537 try_magic = self.custom_completers.s_matches(
539 self.magic_escape + cmd)
538 self.magic_escape + cmd)
540 else:
539 else:
541 try_magic = []
540 try_magic = []
542
541
543
542
544 for c in itertools.chain(
543 for c in itertools.chain(
545 self.custom_completers.s_matches(cmd),
544 self.custom_completers.s_matches(cmd),
546 try_magic,
545 try_magic,
547 self.custom_completers.flat_matches(self.lbuf)):
546 self.custom_completers.flat_matches(self.lbuf)):
548 #print "try",c # dbg
547 #print "try",c # dbg
549 try:
548 try:
550 res = c(event)
549 res = c(event)
551 # first, try case sensitive match
550 # first, try case sensitive match
552 withcase = [r for r in res if r.startswith(text)]
551 withcase = [r for r in res if r.startswith(text)]
553 if withcase:
552 if withcase:
554 return withcase
553 return withcase
555 # if none, then case insensitive ones are ok too
554 # if none, then case insensitive ones are ok too
556 return [r for r in res if r.lower().startswith(text.lower())]
555 return [r for r in res if r.lower().startswith(text.lower())]
557 except ipapi.TryNext:
556 except ipapi.TryNext:
558 pass
557 pass
559
558
560 return None
559 return None
561
560
562 def complete(self, text, state,line_buffer=None):
561 def complete(self, text, state,line_buffer=None):
563 """Return the next possible completion for 'text'.
562 """Return the next possible completion for 'text'.
564
563
565 This is called successively with state == 0, 1, 2, ... until it
564 This is called successively with state == 0, 1, 2, ... until it
566 returns None. The completion should begin with 'text'.
565 returns None. The completion should begin with 'text'.
567
566
568 :Keywords:
567 :Keywords:
569 - line_buffer: string
568 - line_buffer: string
570 If not given, the completer attempts to obtain the current line buffer
569 If not given, the completer attempts to obtain the current line buffer
571 via readline. This keyword allows clients which are requesting for
570 via readline. This keyword allows clients which are requesting for
572 text completions in non-readline contexts to inform the completer of
571 text completions in non-readline contexts to inform the completer of
573 the entire text.
572 the entire text.
574 """
573 """
575
574
576 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
575 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
577
576
578 # if there is only a tab on a line with only whitespace, instead
577 # if there is only a tab on a line with only whitespace, instead
579 # of the mostly useless 'do you want to see all million
578 # of the mostly useless 'do you want to see all million
580 # completions' message, just do the right thing and give the user
579 # completions' message, just do the right thing and give the user
581 # his tab! Incidentally, this enables pasting of tabbed text from
580 # his tab! Incidentally, this enables pasting of tabbed text from
582 # an editor (as long as autoindent is off).
581 # an editor (as long as autoindent is off).
583
582
584 # It should be noted that at least pyreadline still shows
583 # It should be noted that at least pyreadline still shows
585 # file completions - is there a way around it?
584 # file completions - is there a way around it?
586
585
587 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
586 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
588 # don't interfere with their own tab-completion mechanism.
587 # don't interfere with their own tab-completion mechanism.
589 if line_buffer is None:
588 if line_buffer is None:
590 self.full_lbuf = self.get_line_buffer()
589 self.full_lbuf = self.get_line_buffer()
591 else:
590 else:
592 self.full_lbuf = line_buffer
591 self.full_lbuf = line_buffer
593
592
594 if not (self.dumb_terminal or self.full_lbuf.strip()):
593 if not (self.dumb_terminal or self.full_lbuf.strip()):
595 self.readline.insert_text('\t')
594 self.readline.insert_text('\t')
596 return None
595 return None
597
596
598 magic_escape = self.magic_escape
597 magic_escape = self.magic_escape
599 magic_prefix = self.magic_prefix
598 magic_prefix = self.magic_prefix
600
599
601 self.lbuf = self.full_lbuf[:self.get_endidx()]
600 self.lbuf = self.full_lbuf[:self.get_endidx()]
602
601
603 try:
602 try:
604 if text.startswith(magic_escape):
603 if text.startswith(magic_escape):
605 text = text.replace(magic_escape,magic_prefix)
604 text = text.replace(magic_escape,magic_prefix)
606 elif text.startswith('~'):
605 elif text.startswith('~'):
607 text = os.path.expanduser(text)
606 text = os.path.expanduser(text)
608 if state == 0:
607 if state == 0:
609 custom_res = self.dispatch_custom_completer(text)
608 custom_res = self.dispatch_custom_completer(text)
610 if custom_res is not None:
609 if custom_res is not None:
611 # did custom completers produce something?
610 # did custom completers produce something?
612 self.matches = custom_res
611 self.matches = custom_res
613 else:
612 else:
614 # Extend the list of completions with the results of each
613 # Extend the list of completions with the results of each
615 # matcher, so we return results to the user from all
614 # matcher, so we return results to the user from all
616 # namespaces.
615 # namespaces.
617 if self.merge_completions:
616 if self.merge_completions:
618 self.matches = []
617 self.matches = []
619 for matcher in self.matchers:
618 for matcher in self.matchers:
620 self.matches.extend(matcher(text))
619 self.matches.extend(matcher(text))
621 else:
620 else:
622 for matcher in self.matchers:
621 for matcher in self.matchers:
623 self.matches = matcher(text)
622 self.matches = matcher(text)
624 if self.matches:
623 if self.matches:
625 break
624 break
626 def uniq(alist):
625 def uniq(alist):
627 set = {}
626 set = {}
628 return [set.setdefault(e,e) for e in alist if e not in set]
627 return [set.setdefault(e,e) for e in alist if e not in set]
629 self.matches = uniq(self.matches)
628 self.matches = uniq(self.matches)
630 try:
629 try:
631 ret = self.matches[state].replace(magic_prefix,magic_escape)
630 ret = self.matches[state].replace(magic_prefix,magic_escape)
632 return ret
631 return ret
633 except IndexError:
632 except IndexError:
634 return None
633 return None
635 except:
634 except:
636 #from IPython.ultraTB import AutoFormattedTB; # dbg
635 #from IPython.ultraTB import AutoFormattedTB; # dbg
637 #tb=AutoFormattedTB('Verbose');tb() #dbg
636 #tb=AutoFormattedTB('Verbose');tb() #dbg
638
637
639 # If completion fails, don't annoy the user.
638 # If completion fails, don't annoy the user.
640 return None
639 return None
@@ -1,2164 +1,2164 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 General purpose utilities.
3 General purpose utilities.
4
4
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 2998 2008-01-31 10:06:04Z vivainio $"""
8 $Id: genutils.py 2998 2008-01-31 10:06:04Z vivainio $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __license__ = Release.license
19 __license__ = Release.license
20
20
21 #****************************************************************************
21 #****************************************************************************
22 # required modules from the Python standard library
22 # required modules from the Python standard library
23 import __main__
23 import __main__
24 import commands
24 import commands
25 try:
25 try:
26 import doctest
26 import doctest
27 except ImportError:
27 except ImportError:
28 pass
28 pass
29 import os
29 import os
30 import platform
30 import platform
31 import re
31 import re
32 import shlex
32 import shlex
33 import shutil
33 import shutil
34 import subprocess
34 import subprocess
35 import sys
35 import sys
36 import tempfile
36 import tempfile
37 import time
37 import time
38 import types
38 import types
39 import warnings
39 import warnings
40
40
41 # Curses and termios are Unix-only modules
41 # Curses and termios are Unix-only modules
42 try:
42 try:
43 import curses
43 import curses
44 # We need termios as well, so if its import happens to raise, we bail on
44 # We need termios as well, so if its import happens to raise, we bail on
45 # using curses altogether.
45 # using curses altogether.
46 import termios
46 import termios
47 except ImportError:
47 except ImportError:
48 USE_CURSES = False
48 USE_CURSES = False
49 else:
49 else:
50 # Curses on Solaris may not be complete, so we can't use it there
50 # Curses on Solaris may not be complete, so we can't use it there
51 USE_CURSES = hasattr(curses,'initscr')
51 USE_CURSES = hasattr(curses,'initscr')
52
52
53 # Other IPython utilities
53 # Other IPython utilities
54 import IPython
54 import IPython
55 from IPython.Itpl import Itpl,itpl,printpl
55 from IPython.Itpl import Itpl,itpl,printpl
56 from IPython import DPyGetOpt, platutils
56 from IPython import DPyGetOpt, platutils
57 from IPython.generics import result_display
57 from IPython.generics import result_display
58 import IPython.ipapi
58 import IPython.ipapi
59 from IPython.external.path import path
59 from IPython.external.path import path
60 if os.name == "nt":
60 if os.name == "nt":
61 from IPython.winconsole import get_console_size
61 from IPython.winconsole import get_console_size
62
62
63 try:
63 try:
64 set
64 set
65 except:
65 except:
66 from sets import Set as set
66 from sets import Set as set
67
67
68
68
69 #****************************************************************************
69 #****************************************************************************
70 # Exceptions
70 # Exceptions
71 class Error(Exception):
71 class Error(Exception):
72 """Base class for exceptions in this module."""
72 """Base class for exceptions in this module."""
73 pass
73 pass
74
74
75 #----------------------------------------------------------------------------
75 #----------------------------------------------------------------------------
76 class IOStream:
76 class IOStream:
77 def __init__(self,stream,fallback):
77 def __init__(self,stream,fallback):
78 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
78 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
79 stream = fallback
79 stream = fallback
80 self.stream = stream
80 self.stream = stream
81 self._swrite = stream.write
81 self._swrite = stream.write
82 self.flush = stream.flush
82 self.flush = stream.flush
83
83
84 def write(self,data):
84 def write(self,data):
85 try:
85 try:
86 self._swrite(data)
86 self._swrite(data)
87 except:
87 except:
88 try:
88 try:
89 # print handles some unicode issues which may trip a plain
89 # print handles some unicode issues which may trip a plain
90 # write() call. Attempt to emulate write() by using a
90 # write() call. Attempt to emulate write() by using a
91 # trailing comma
91 # trailing comma
92 print >> self.stream, data,
92 print >> self.stream, data,
93 except:
93 except:
94 # if we get here, something is seriously broken.
94 # if we get here, something is seriously broken.
95 print >> sys.stderr, \
95 print >> sys.stderr, \
96 'ERROR - failed to write data to stream:', self.stream
96 'ERROR - failed to write data to stream:', self.stream
97
97
98 def close(self):
98 def close(self):
99 pass
99 pass
100
100
101
101
102 class IOTerm:
102 class IOTerm:
103 """ Term holds the file or file-like objects for handling I/O operations.
103 """ Term holds the file or file-like objects for handling I/O operations.
104
104
105 These are normally just sys.stdin, sys.stdout and sys.stderr but for
105 These are normally just sys.stdin, sys.stdout and sys.stderr but for
106 Windows they can can replaced to allow editing the strings before they are
106 Windows they can can replaced to allow editing the strings before they are
107 displayed."""
107 displayed."""
108
108
109 # In the future, having IPython channel all its I/O operations through
109 # In the future, having IPython channel all its I/O operations through
110 # this class will make it easier to embed it into other environments which
110 # this class will make it easier to embed it into other environments which
111 # are not a normal terminal (such as a GUI-based shell)
111 # are not a normal terminal (such as a GUI-based shell)
112 def __init__(self,cin=None,cout=None,cerr=None):
112 def __init__(self,cin=None,cout=None,cerr=None):
113 self.cin = IOStream(cin,sys.stdin)
113 self.cin = IOStream(cin,sys.stdin)
114 self.cout = IOStream(cout,sys.stdout)
114 self.cout = IOStream(cout,sys.stdout)
115 self.cerr = IOStream(cerr,sys.stderr)
115 self.cerr = IOStream(cerr,sys.stderr)
116
116
117 # Global variable to be used for all I/O
117 # Global variable to be used for all I/O
118 Term = IOTerm()
118 Term = IOTerm()
119
119
120 import IPython.rlineimpl as readline
120 import IPython.rlineimpl as readline
121 # Remake Term to use the readline i/o facilities
121 # Remake Term to use the readline i/o facilities
122 if sys.platform == 'win32' and readline.have_readline:
122 if sys.platform == 'win32' and readline.have_readline:
123
123
124 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
124 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
125
125
126
126
127 #****************************************************************************
127 #****************************************************************************
128 # Generic warning/error printer, used by everything else
128 # Generic warning/error printer, used by everything else
129 def warn(msg,level=2,exit_val=1):
129 def warn(msg,level=2,exit_val=1):
130 """Standard warning printer. Gives formatting consistency.
130 """Standard warning printer. Gives formatting consistency.
131
131
132 Output is sent to Term.cerr (sys.stderr by default).
132 Output is sent to Term.cerr (sys.stderr by default).
133
133
134 Options:
134 Options:
135
135
136 -level(2): allows finer control:
136 -level(2): allows finer control:
137 0 -> Do nothing, dummy function.
137 0 -> Do nothing, dummy function.
138 1 -> Print message.
138 1 -> Print message.
139 2 -> Print 'WARNING:' + message. (Default level).
139 2 -> Print 'WARNING:' + message. (Default level).
140 3 -> Print 'ERROR:' + message.
140 3 -> Print 'ERROR:' + message.
141 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
141 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
142
142
143 -exit_val (1): exit value returned by sys.exit() for a level 4
143 -exit_val (1): exit value returned by sys.exit() for a level 4
144 warning. Ignored for all other levels."""
144 warning. Ignored for all other levels."""
145
145
146 if level>0:
146 if level>0:
147 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
147 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
148 print >> Term.cerr, '%s%s' % (header[level],msg)
148 print >> Term.cerr, '%s%s' % (header[level],msg)
149 if level == 4:
149 if level == 4:
150 print >> Term.cerr,'Exiting.\n'
150 print >> Term.cerr,'Exiting.\n'
151 sys.exit(exit_val)
151 sys.exit(exit_val)
152
152
153 def info(msg):
153 def info(msg):
154 """Equivalent to warn(msg,level=1)."""
154 """Equivalent to warn(msg,level=1)."""
155
155
156 warn(msg,level=1)
156 warn(msg,level=1)
157
157
158 def error(msg):
158 def error(msg):
159 """Equivalent to warn(msg,level=3)."""
159 """Equivalent to warn(msg,level=3)."""
160
160
161 warn(msg,level=3)
161 warn(msg,level=3)
162
162
163 def fatal(msg,exit_val=1):
163 def fatal(msg,exit_val=1):
164 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
164 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
165
165
166 warn(msg,exit_val=exit_val,level=4)
166 warn(msg,exit_val=exit_val,level=4)
167
167
168 #---------------------------------------------------------------------------
168 #---------------------------------------------------------------------------
169 # Debugging routines
169 # Debugging routines
170 #
170 #
171 def debugx(expr,pre_msg=''):
171 def debugx(expr,pre_msg=''):
172 """Print the value of an expression from the caller's frame.
172 """Print the value of an expression from the caller's frame.
173
173
174 Takes an expression, evaluates it in the caller's frame and prints both
174 Takes an expression, evaluates it in the caller's frame and prints both
175 the given expression and the resulting value (as well as a debug mark
175 the given expression and the resulting value (as well as a debug mark
176 indicating the name of the calling function. The input must be of a form
176 indicating the name of the calling function. The input must be of a form
177 suitable for eval().
177 suitable for eval().
178
178
179 An optional message can be passed, which will be prepended to the printed
179 An optional message can be passed, which will be prepended to the printed
180 expr->value pair."""
180 expr->value pair."""
181
181
182 cf = sys._getframe(1)
182 cf = sys._getframe(1)
183 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
183 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
184 eval(expr,cf.f_globals,cf.f_locals))
184 eval(expr,cf.f_globals,cf.f_locals))
185
185
186 # deactivate it by uncommenting the following line, which makes it a no-op
186 # deactivate it by uncommenting the following line, which makes it a no-op
187 #def debugx(expr,pre_msg=''): pass
187 #def debugx(expr,pre_msg=''): pass
188
188
189 #----------------------------------------------------------------------------
189 #----------------------------------------------------------------------------
190 StringTypes = types.StringTypes
190 StringTypes = types.StringTypes
191
191
192 # Basic timing functionality
192 # Basic timing functionality
193
193
194 # If possible (Unix), use the resource module instead of time.clock()
194 # If possible (Unix), use the resource module instead of time.clock()
195 try:
195 try:
196 import resource
196 import resource
197 def clocku():
197 def clocku():
198 """clocku() -> floating point number
198 """clocku() -> floating point number
199
199
200 Return the *USER* CPU time in seconds since the start of the process.
200 Return the *USER* CPU time in seconds since the start of the process.
201 This is done via a call to resource.getrusage, so it avoids the
201 This is done via a call to resource.getrusage, so it avoids the
202 wraparound problems in time.clock()."""
202 wraparound problems in time.clock()."""
203
203
204 return resource.getrusage(resource.RUSAGE_SELF)[0]
204 return resource.getrusage(resource.RUSAGE_SELF)[0]
205
205
206 def clocks():
206 def clocks():
207 """clocks() -> floating point number
207 """clocks() -> floating point number
208
208
209 Return the *SYSTEM* CPU time in seconds since the start of the process.
209 Return the *SYSTEM* CPU time in seconds since the start of the process.
210 This is done via a call to resource.getrusage, so it avoids the
210 This is done via a call to resource.getrusage, so it avoids the
211 wraparound problems in time.clock()."""
211 wraparound problems in time.clock()."""
212
212
213 return resource.getrusage(resource.RUSAGE_SELF)[1]
213 return resource.getrusage(resource.RUSAGE_SELF)[1]
214
214
215 def clock():
215 def clock():
216 """clock() -> floating point number
216 """clock() -> floating point number
217
217
218 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
218 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
219 the process. This is done via a call to resource.getrusage, so it
219 the process. This is done via a call to resource.getrusage, so it
220 avoids the wraparound problems in time.clock()."""
220 avoids the wraparound problems in time.clock()."""
221
221
222 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
222 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
223 return u+s
223 return u+s
224
224
225 def clock2():
225 def clock2():
226 """clock2() -> (t_user,t_system)
226 """clock2() -> (t_user,t_system)
227
227
228 Similar to clock(), but return a tuple of user/system times."""
228 Similar to clock(), but return a tuple of user/system times."""
229 return resource.getrusage(resource.RUSAGE_SELF)[:2]
229 return resource.getrusage(resource.RUSAGE_SELF)[:2]
230
230
231 except ImportError:
231 except ImportError:
232 # There is no distinction of user/system time under windows, so we just use
232 # There is no distinction of user/system time under windows, so we just use
233 # time.clock() for everything...
233 # time.clock() for everything...
234 clocku = clocks = clock = time.clock
234 clocku = clocks = clock = time.clock
235 def clock2():
235 def clock2():
236 """Under windows, system CPU time can't be measured.
236 """Under windows, system CPU time can't be measured.
237
237
238 This just returns clock() and zero."""
238 This just returns clock() and zero."""
239 return time.clock(),0.0
239 return time.clock(),0.0
240
240
241 def timings_out(reps,func,*args,**kw):
241 def timings_out(reps,func,*args,**kw):
242 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
242 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
243
243
244 Execute a function reps times, return a tuple with the elapsed total
244 Execute a function reps times, return a tuple with the elapsed total
245 CPU time in seconds, the time per call and the function's output.
245 CPU time in seconds, the time per call and the function's output.
246
246
247 Under Unix, the return value is the sum of user+system time consumed by
247 Under Unix, the return value is the sum of user+system time consumed by
248 the process, computed via the resource module. This prevents problems
248 the process, computed via the resource module. This prevents problems
249 related to the wraparound effect which the time.clock() function has.
249 related to the wraparound effect which the time.clock() function has.
250
250
251 Under Windows the return value is in wall clock seconds. See the
251 Under Windows the return value is in wall clock seconds. See the
252 documentation for the time module for more details."""
252 documentation for the time module for more details."""
253
253
254 reps = int(reps)
254 reps = int(reps)
255 assert reps >=1, 'reps must be >= 1'
255 assert reps >=1, 'reps must be >= 1'
256 if reps==1:
256 if reps==1:
257 start = clock()
257 start = clock()
258 out = func(*args,**kw)
258 out = func(*args,**kw)
259 tot_time = clock()-start
259 tot_time = clock()-start
260 else:
260 else:
261 rng = xrange(reps-1) # the last time is executed separately to store output
261 rng = xrange(reps-1) # the last time is executed separately to store output
262 start = clock()
262 start = clock()
263 for dummy in rng: func(*args,**kw)
263 for dummy in rng: func(*args,**kw)
264 out = func(*args,**kw) # one last time
264 out = func(*args,**kw) # one last time
265 tot_time = clock()-start
265 tot_time = clock()-start
266 av_time = tot_time / reps
266 av_time = tot_time / reps
267 return tot_time,av_time,out
267 return tot_time,av_time,out
268
268
269 def timings(reps,func,*args,**kw):
269 def timings(reps,func,*args,**kw):
270 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
270 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
271
271
272 Execute a function reps times, return a tuple with the elapsed total CPU
272 Execute a function reps times, return a tuple with the elapsed total CPU
273 time in seconds and the time per call. These are just the first two values
273 time in seconds and the time per call. These are just the first two values
274 in timings_out()."""
274 in timings_out()."""
275
275
276 return timings_out(reps,func,*args,**kw)[0:2]
276 return timings_out(reps,func,*args,**kw)[0:2]
277
277
278 def timing(func,*args,**kw):
278 def timing(func,*args,**kw):
279 """timing(func,*args,**kw) -> t_total
279 """timing(func,*args,**kw) -> t_total
280
280
281 Execute a function once, return the elapsed total CPU time in
281 Execute a function once, return the elapsed total CPU time in
282 seconds. This is just the first value in timings_out()."""
282 seconds. This is just the first value in timings_out()."""
283
283
284 return timings_out(1,func,*args,**kw)[0]
284 return timings_out(1,func,*args,**kw)[0]
285
285
286 #****************************************************************************
286 #****************************************************************************
287 # file and system
287 # file and system
288
288
289 def arg_split(s,posix=False):
289 def arg_split(s,posix=False):
290 """Split a command line's arguments in a shell-like manner.
290 """Split a command line's arguments in a shell-like manner.
291
291
292 This is a modified version of the standard library's shlex.split()
292 This is a modified version of the standard library's shlex.split()
293 function, but with a default of posix=False for splitting, so that quotes
293 function, but with a default of posix=False for splitting, so that quotes
294 in inputs are respected."""
294 in inputs are respected."""
295
295
296 # XXX - there may be unicode-related problems here!!! I'm not sure that
296 # XXX - there may be unicode-related problems here!!! I'm not sure that
297 # shlex is truly unicode-safe, so it might be necessary to do
297 # shlex is truly unicode-safe, so it might be necessary to do
298 #
298 #
299 # s = s.encode(sys.stdin.encoding)
299 # s = s.encode(sys.stdin.encoding)
300 #
300 #
301 # first, to ensure that shlex gets a normal string. Input from anyone who
301 # first, to ensure that shlex gets a normal string. Input from anyone who
302 # knows more about unicode and shlex than I would be good to have here...
302 # knows more about unicode and shlex than I would be good to have here...
303 lex = shlex.shlex(s, posix=posix)
303 lex = shlex.shlex(s, posix=posix)
304 lex.whitespace_split = True
304 lex.whitespace_split = True
305 return list(lex)
305 return list(lex)
306
306
307 def system(cmd,verbose=0,debug=0,header=''):
307 def system(cmd,verbose=0,debug=0,header=''):
308 """Execute a system command, return its exit status.
308 """Execute a system command, return its exit status.
309
309
310 Options:
310 Options:
311
311
312 - verbose (0): print the command to be executed.
312 - verbose (0): print the command to be executed.
313
313
314 - debug (0): only print, do not actually execute.
314 - debug (0): only print, do not actually execute.
315
315
316 - header (''): Header to print on screen prior to the executed command (it
316 - header (''): Header to print on screen prior to the executed command (it
317 is only prepended to the command, no newlines are added).
317 is only prepended to the command, no newlines are added).
318
318
319 Note: a stateful version of this function is available through the
319 Note: a stateful version of this function is available through the
320 SystemExec class."""
320 SystemExec class."""
321
321
322 stat = 0
322 stat = 0
323 if verbose or debug: print header+cmd
323 if verbose or debug: print header+cmd
324 sys.stdout.flush()
324 sys.stdout.flush()
325 if not debug: stat = os.system(cmd)
325 if not debug: stat = os.system(cmd)
326 return stat
326 return stat
327
327
328 def abbrev_cwd():
328 def abbrev_cwd():
329 """ Return abbreviated version of cwd, e.g. d:mydir """
329 """ Return abbreviated version of cwd, e.g. d:mydir """
330 cwd = os.getcwd().replace('\\','/')
330 cwd = os.getcwd().replace('\\','/')
331 drivepart = ''
331 drivepart = ''
332 tail = cwd
332 tail = cwd
333 if sys.platform == 'win32':
333 if sys.platform == 'win32':
334 if len(cwd) < 4:
334 if len(cwd) < 4:
335 return cwd
335 return cwd
336 drivepart,tail = os.path.splitdrive(cwd)
336 drivepart,tail = os.path.splitdrive(cwd)
337
337
338
338
339 parts = tail.split('/')
339 parts = tail.split('/')
340 if len(parts) > 2:
340 if len(parts) > 2:
341 tail = '/'.join(parts[-2:])
341 tail = '/'.join(parts[-2:])
342
342
343 return (drivepart + (
343 return (drivepart + (
344 cwd == '/' and '/' or tail))
344 cwd == '/' and '/' or tail))
345
345
346
346
347 # This function is used by ipython in a lot of places to make system calls.
347 # This function is used by ipython in a lot of places to make system calls.
348 # We need it to be slightly different under win32, due to the vagaries of
348 # We need it to be slightly different under win32, due to the vagaries of
349 # 'network shares'. A win32 override is below.
349 # 'network shares'. A win32 override is below.
350
350
351 def shell(cmd,verbose=0,debug=0,header=''):
351 def shell(cmd,verbose=0,debug=0,header=''):
352 """Execute a command in the system shell, always return None.
352 """Execute a command in the system shell, always return None.
353
353
354 Options:
354 Options:
355
355
356 - verbose (0): print the command to be executed.
356 - verbose (0): print the command to be executed.
357
357
358 - debug (0): only print, do not actually execute.
358 - debug (0): only print, do not actually execute.
359
359
360 - header (''): Header to print on screen prior to the executed command (it
360 - header (''): Header to print on screen prior to the executed command (it
361 is only prepended to the command, no newlines are added).
361 is only prepended to the command, no newlines are added).
362
362
363 Note: this is similar to genutils.system(), but it returns None so it can
363 Note: this is similar to genutils.system(), but it returns None so it can
364 be conveniently used in interactive loops without getting the return value
364 be conveniently used in interactive loops without getting the return value
365 (typically 0) printed many times."""
365 (typically 0) printed many times."""
366
366
367 stat = 0
367 stat = 0
368 if verbose or debug: print header+cmd
368 if verbose or debug: print header+cmd
369 # flush stdout so we don't mangle python's buffering
369 # flush stdout so we don't mangle python's buffering
370 sys.stdout.flush()
370 sys.stdout.flush()
371
371
372 if not debug:
372 if not debug:
373 platutils.set_term_title("IPy " + cmd)
373 platutils.set_term_title("IPy " + cmd)
374 os.system(cmd)
374 os.system(cmd)
375 platutils.set_term_title("IPy " + abbrev_cwd())
375 platutils.set_term_title("IPy " + abbrev_cwd())
376
376
377 # override shell() for win32 to deal with network shares
377 # override shell() for win32 to deal with network shares
378 if os.name in ('nt','dos'):
378 if os.name in ('nt','dos'):
379
379
380 shell_ori = shell
380 shell_ori = shell
381
381
382 def shell(cmd,verbose=0,debug=0,header=''):
382 def shell(cmd,verbose=0,debug=0,header=''):
383 if os.getcwd().startswith(r"\\"):
383 if os.getcwd().startswith(r"\\"):
384 path = os.getcwd()
384 path = os.getcwd()
385 # change to c drive (cannot be on UNC-share when issuing os.system,
385 # change to c drive (cannot be on UNC-share when issuing os.system,
386 # as cmd.exe cannot handle UNC addresses)
386 # as cmd.exe cannot handle UNC addresses)
387 os.chdir("c:")
387 os.chdir("c:")
388 # issue pushd to the UNC-share and then run the command
388 # issue pushd to the UNC-share and then run the command
389 try:
389 try:
390 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
390 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
391 finally:
391 finally:
392 os.chdir(path)
392 os.chdir(path)
393 else:
393 else:
394 shell_ori(cmd,verbose,debug,header)
394 shell_ori(cmd,verbose,debug,header)
395
395
396 shell.__doc__ = shell_ori.__doc__
396 shell.__doc__ = shell_ori.__doc__
397
397
398 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
398 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
399 """Dummy substitute for perl's backquotes.
399 """Dummy substitute for perl's backquotes.
400
400
401 Executes a command and returns the output.
401 Executes a command and returns the output.
402
402
403 Accepts the same arguments as system(), plus:
403 Accepts the same arguments as system(), plus:
404
404
405 - split(0): if true, the output is returned as a list split on newlines.
405 - split(0): if true, the output is returned as a list split on newlines.
406
406
407 Note: a stateful version of this function is available through the
407 Note: a stateful version of this function is available through the
408 SystemExec class.
408 SystemExec class.
409
409
410 This is pretty much deprecated and rarely used,
410 This is pretty much deprecated and rarely used,
411 genutils.getoutputerror may be what you need.
411 genutils.getoutputerror may be what you need.
412
412
413 """
413 """
414
414
415 if verbose or debug: print header+cmd
415 if verbose or debug: print header+cmd
416 if not debug:
416 if not debug:
417 output = os.popen(cmd).read()
417 output = os.popen(cmd).read()
418 # stipping last \n is here for backwards compat.
418 # stipping last \n is here for backwards compat.
419 if output.endswith('\n'):
419 if output.endswith('\n'):
420 output = output[:-1]
420 output = output[:-1]
421 if split:
421 if split:
422 return output.split('\n')
422 return output.split('\n')
423 else:
423 else:
424 return output
424 return output
425
425
426 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
426 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
427 """Return (standard output,standard error) of executing cmd in a shell.
427 """Return (standard output,standard error) of executing cmd in a shell.
428
428
429 Accepts the same arguments as system(), plus:
429 Accepts the same arguments as system(), plus:
430
430
431 - split(0): if true, each of stdout/err is returned as a list split on
431 - split(0): if true, each of stdout/err is returned as a list split on
432 newlines.
432 newlines.
433
433
434 Note: a stateful version of this function is available through the
434 Note: a stateful version of this function is available through the
435 SystemExec class."""
435 SystemExec class."""
436
436
437 if verbose or debug: print header+cmd
437 if verbose or debug: print header+cmd
438 if not cmd:
438 if not cmd:
439 if split:
439 if split:
440 return [],[]
440 return [],[]
441 else:
441 else:
442 return '',''
442 return '',''
443 if not debug:
443 if not debug:
444 pin,pout,perr = os.popen3(cmd)
444 pin,pout,perr = os.popen3(cmd)
445 tout = pout.read().rstrip()
445 tout = pout.read().rstrip()
446 terr = perr.read().rstrip()
446 terr = perr.read().rstrip()
447 pin.close()
447 pin.close()
448 pout.close()
448 pout.close()
449 perr.close()
449 perr.close()
450 if split:
450 if split:
451 return tout.split('\n'),terr.split('\n')
451 return tout.split('\n'),terr.split('\n')
452 else:
452 else:
453 return tout,terr
453 return tout,terr
454
454
455 # for compatibility with older naming conventions
455 # for compatibility with older naming conventions
456 xsys = system
456 xsys = system
457 bq = getoutput
457 bq = getoutput
458
458
459 class SystemExec:
459 class SystemExec:
460 """Access the system and getoutput functions through a stateful interface.
460 """Access the system and getoutput functions through a stateful interface.
461
461
462 Note: here we refer to the system and getoutput functions from this
462 Note: here we refer to the system and getoutput functions from this
463 library, not the ones from the standard python library.
463 library, not the ones from the standard python library.
464
464
465 This class offers the system and getoutput functions as methods, but the
465 This class offers the system and getoutput functions as methods, but the
466 verbose, debug and header parameters can be set for the instance (at
466 verbose, debug and header parameters can be set for the instance (at
467 creation time or later) so that they don't need to be specified on each
467 creation time or later) so that they don't need to be specified on each
468 call.
468 call.
469
469
470 For efficiency reasons, there's no way to override the parameters on a
470 For efficiency reasons, there's no way to override the parameters on a
471 per-call basis other than by setting instance attributes. If you need
471 per-call basis other than by setting instance attributes. If you need
472 local overrides, it's best to directly call system() or getoutput().
472 local overrides, it's best to directly call system() or getoutput().
473
473
474 The following names are provided as alternate options:
474 The following names are provided as alternate options:
475 - xsys: alias to system
475 - xsys: alias to system
476 - bq: alias to getoutput
476 - bq: alias to getoutput
477
477
478 An instance can then be created as:
478 An instance can then be created as:
479 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
479 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
480 """
480 """
481
481
482 def __init__(self,verbose=0,debug=0,header='',split=0):
482 def __init__(self,verbose=0,debug=0,header='',split=0):
483 """Specify the instance's values for verbose, debug and header."""
483 """Specify the instance's values for verbose, debug and header."""
484 setattr_list(self,'verbose debug header split')
484 setattr_list(self,'verbose debug header split')
485
485
486 def system(self,cmd):
486 def system(self,cmd):
487 """Stateful interface to system(), with the same keyword parameters."""
487 """Stateful interface to system(), with the same keyword parameters."""
488
488
489 system(cmd,self.verbose,self.debug,self.header)
489 system(cmd,self.verbose,self.debug,self.header)
490
490
491 def shell(self,cmd):
491 def shell(self,cmd):
492 """Stateful interface to shell(), with the same keyword parameters."""
492 """Stateful interface to shell(), with the same keyword parameters."""
493
493
494 shell(cmd,self.verbose,self.debug,self.header)
494 shell(cmd,self.verbose,self.debug,self.header)
495
495
496 xsys = system # alias
496 xsys = system # alias
497
497
498 def getoutput(self,cmd):
498 def getoutput(self,cmd):
499 """Stateful interface to getoutput()."""
499 """Stateful interface to getoutput()."""
500
500
501 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
501 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
502
502
503 def getoutputerror(self,cmd):
503 def getoutputerror(self,cmd):
504 """Stateful interface to getoutputerror()."""
504 """Stateful interface to getoutputerror()."""
505
505
506 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
506 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
507
507
508 bq = getoutput # alias
508 bq = getoutput # alias
509
509
510 #-----------------------------------------------------------------------------
510 #-----------------------------------------------------------------------------
511 def mutex_opts(dict,ex_op):
511 def mutex_opts(dict,ex_op):
512 """Check for presence of mutually exclusive keys in a dict.
512 """Check for presence of mutually exclusive keys in a dict.
513
513
514 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
514 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
515 for op1,op2 in ex_op:
515 for op1,op2 in ex_op:
516 if op1 in dict and op2 in dict:
516 if op1 in dict and op2 in dict:
517 raise ValueError,'\n*** ERROR in Arguments *** '\
517 raise ValueError,'\n*** ERROR in Arguments *** '\
518 'Options '+op1+' and '+op2+' are mutually exclusive.'
518 'Options '+op1+' and '+op2+' are mutually exclusive.'
519
519
520 #-----------------------------------------------------------------------------
520 #-----------------------------------------------------------------------------
521 def get_py_filename(name):
521 def get_py_filename(name):
522 """Return a valid python filename in the current directory.
522 """Return a valid python filename in the current directory.
523
523
524 If the given name is not a file, it adds '.py' and searches again.
524 If the given name is not a file, it adds '.py' and searches again.
525 Raises IOError with an informative message if the file isn't found."""
525 Raises IOError with an informative message if the file isn't found."""
526
526
527 name = os.path.expanduser(name)
527 name = os.path.expanduser(name)
528 if not os.path.isfile(name) and not name.endswith('.py'):
528 if not os.path.isfile(name) and not name.endswith('.py'):
529 name += '.py'
529 name += '.py'
530 if os.path.isfile(name):
530 if os.path.isfile(name):
531 return name
531 return name
532 else:
532 else:
533 raise IOError,'File `%s` not found.' % name
533 raise IOError,'File `%s` not found.' % name
534
534
535 #-----------------------------------------------------------------------------
535 #-----------------------------------------------------------------------------
536 def filefind(fname,alt_dirs = None):
536 def filefind(fname,alt_dirs = None):
537 """Return the given filename either in the current directory, if it
537 """Return the given filename either in the current directory, if it
538 exists, or in a specified list of directories.
538 exists, or in a specified list of directories.
539
539
540 ~ expansion is done on all file and directory names.
540 ~ expansion is done on all file and directory names.
541
541
542 Upon an unsuccessful search, raise an IOError exception."""
542 Upon an unsuccessful search, raise an IOError exception."""
543
543
544 if alt_dirs is None:
544 if alt_dirs is None:
545 try:
545 try:
546 alt_dirs = get_home_dir()
546 alt_dirs = get_home_dir()
547 except HomeDirError:
547 except HomeDirError:
548 alt_dirs = os.getcwd()
548 alt_dirs = os.getcwd()
549 search = [fname] + list_strings(alt_dirs)
549 search = [fname] + list_strings(alt_dirs)
550 search = map(os.path.expanduser,search)
550 search = map(os.path.expanduser,search)
551 #print 'search list for',fname,'list:',search # dbg
551 #print 'search list for',fname,'list:',search # dbg
552 fname = search[0]
552 fname = search[0]
553 if os.path.isfile(fname):
553 if os.path.isfile(fname):
554 return fname
554 return fname
555 for direc in search[1:]:
555 for direc in search[1:]:
556 testname = os.path.join(direc,fname)
556 testname = os.path.join(direc,fname)
557 #print 'testname',testname # dbg
557 #print 'testname',testname # dbg
558 if os.path.isfile(testname):
558 if os.path.isfile(testname):
559 return testname
559 return testname
560 raise IOError,'File' + `fname` + \
560 raise IOError,'File' + `fname` + \
561 ' not found in current or supplied directories:' + `alt_dirs`
561 ' not found in current or supplied directories:' + `alt_dirs`
562
562
563 #----------------------------------------------------------------------------
563 #----------------------------------------------------------------------------
564 def file_read(filename):
564 def file_read(filename):
565 """Read a file and close it. Returns the file source."""
565 """Read a file and close it. Returns the file source."""
566 fobj = open(filename,'r');
566 fobj = open(filename,'r');
567 source = fobj.read();
567 source = fobj.read();
568 fobj.close()
568 fobj.close()
569 return source
569 return source
570
570
571 def file_readlines(filename):
571 def file_readlines(filename):
572 """Read a file and close it. Returns the file source using readlines()."""
572 """Read a file and close it. Returns the file source using readlines()."""
573 fobj = open(filename,'r');
573 fobj = open(filename,'r');
574 lines = fobj.readlines();
574 lines = fobj.readlines();
575 fobj.close()
575 fobj.close()
576 return lines
576 return lines
577
577
578 #----------------------------------------------------------------------------
578 #----------------------------------------------------------------------------
579 def target_outdated(target,deps):
579 def target_outdated(target,deps):
580 """Determine whether a target is out of date.
580 """Determine whether a target is out of date.
581
581
582 target_outdated(target,deps) -> 1/0
582 target_outdated(target,deps) -> 1/0
583
583
584 deps: list of filenames which MUST exist.
584 deps: list of filenames which MUST exist.
585 target: single filename which may or may not exist.
585 target: single filename which may or may not exist.
586
586
587 If target doesn't exist or is older than any file listed in deps, return
587 If target doesn't exist or is older than any file listed in deps, return
588 true, otherwise return false.
588 true, otherwise return false.
589 """
589 """
590 try:
590 try:
591 target_time = os.path.getmtime(target)
591 target_time = os.path.getmtime(target)
592 except os.error:
592 except os.error:
593 return 1
593 return 1
594 for dep in deps:
594 for dep in deps:
595 dep_time = os.path.getmtime(dep)
595 dep_time = os.path.getmtime(dep)
596 if dep_time > target_time:
596 if dep_time > target_time:
597 #print "For target",target,"Dep failed:",dep # dbg
597 #print "For target",target,"Dep failed:",dep # dbg
598 #print "times (dep,tar):",dep_time,target_time # dbg
598 #print "times (dep,tar):",dep_time,target_time # dbg
599 return 1
599 return 1
600 return 0
600 return 0
601
601
602 #-----------------------------------------------------------------------------
602 #-----------------------------------------------------------------------------
603 def target_update(target,deps,cmd):
603 def target_update(target,deps,cmd):
604 """Update a target with a given command given a list of dependencies.
604 """Update a target with a given command given a list of dependencies.
605
605
606 target_update(target,deps,cmd) -> runs cmd if target is outdated.
606 target_update(target,deps,cmd) -> runs cmd if target is outdated.
607
607
608 This is just a wrapper around target_outdated() which calls the given
608 This is just a wrapper around target_outdated() which calls the given
609 command if target is outdated."""
609 command if target is outdated."""
610
610
611 if target_outdated(target,deps):
611 if target_outdated(target,deps):
612 xsys(cmd)
612 xsys(cmd)
613
613
614 #----------------------------------------------------------------------------
614 #----------------------------------------------------------------------------
615 def unquote_ends(istr):
615 def unquote_ends(istr):
616 """Remove a single pair of quotes from the endpoints of a string."""
616 """Remove a single pair of quotes from the endpoints of a string."""
617
617
618 if not istr:
618 if not istr:
619 return istr
619 return istr
620 if (istr[0]=="'" and istr[-1]=="'") or \
620 if (istr[0]=="'" and istr[-1]=="'") or \
621 (istr[0]=='"' and istr[-1]=='"'):
621 (istr[0]=='"' and istr[-1]=='"'):
622 return istr[1:-1]
622 return istr[1:-1]
623 else:
623 else:
624 return istr
624 return istr
625
625
626 #----------------------------------------------------------------------------
626 #----------------------------------------------------------------------------
627 def process_cmdline(argv,names=[],defaults={},usage=''):
627 def process_cmdline(argv,names=[],defaults={},usage=''):
628 """ Process command-line options and arguments.
628 """ Process command-line options and arguments.
629
629
630 Arguments:
630 Arguments:
631
631
632 - argv: list of arguments, typically sys.argv.
632 - argv: list of arguments, typically sys.argv.
633
633
634 - names: list of option names. See DPyGetOpt docs for details on options
634 - names: list of option names. See DPyGetOpt docs for details on options
635 syntax.
635 syntax.
636
636
637 - defaults: dict of default values.
637 - defaults: dict of default values.
638
638
639 - usage: optional usage notice to print if a wrong argument is passed.
639 - usage: optional usage notice to print if a wrong argument is passed.
640
640
641 Return a dict of options and a list of free arguments."""
641 Return a dict of options and a list of free arguments."""
642
642
643 getopt = DPyGetOpt.DPyGetOpt()
643 getopt = DPyGetOpt.DPyGetOpt()
644 getopt.setIgnoreCase(0)
644 getopt.setIgnoreCase(0)
645 getopt.parseConfiguration(names)
645 getopt.parseConfiguration(names)
646
646
647 try:
647 try:
648 getopt.processArguments(argv)
648 getopt.processArguments(argv)
649 except DPyGetOpt.ArgumentError, exc:
649 except DPyGetOpt.ArgumentError, exc:
650 print usage
650 print usage
651 warn('"%s"' % exc,level=4)
651 warn('"%s"' % exc,level=4)
652
652
653 defaults.update(getopt.optionValues)
653 defaults.update(getopt.optionValues)
654 args = getopt.freeValues
654 args = getopt.freeValues
655
655
656 return defaults,args
656 return defaults,args
657
657
658 #----------------------------------------------------------------------------
658 #----------------------------------------------------------------------------
659 def optstr2types(ostr):
659 def optstr2types(ostr):
660 """Convert a string of option names to a dict of type mappings.
660 """Convert a string of option names to a dict of type mappings.
661
661
662 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
662 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
663
663
664 This is used to get the types of all the options in a string formatted
664 This is used to get the types of all the options in a string formatted
665 with the conventions of DPyGetOpt. The 'type' None is used for options
665 with the conventions of DPyGetOpt. The 'type' None is used for options
666 which are strings (they need no further conversion). This function's main
666 which are strings (they need no further conversion). This function's main
667 use is to get a typemap for use with read_dict().
667 use is to get a typemap for use with read_dict().
668 """
668 """
669
669
670 typeconv = {None:'',int:'',float:''}
670 typeconv = {None:'',int:'',float:''}
671 typemap = {'s':None,'i':int,'f':float}
671 typemap = {'s':None,'i':int,'f':float}
672 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
672 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
673
673
674 for w in ostr.split():
674 for w in ostr.split():
675 oname,alias,otype = opt_re.match(w).groups()
675 oname,alias,otype = opt_re.match(w).groups()
676 if otype == '' or alias == '!': # simple switches are integers too
676 if otype == '' or alias == '!': # simple switches are integers too
677 otype = 'i'
677 otype = 'i'
678 typeconv[typemap[otype]] += oname + ' '
678 typeconv[typemap[otype]] += oname + ' '
679 return typeconv
679 return typeconv
680
680
681 #----------------------------------------------------------------------------
681 #----------------------------------------------------------------------------
682 def read_dict(filename,type_conv=None,**opt):
682 def read_dict(filename,type_conv=None,**opt):
683 r"""Read a dictionary of key=value pairs from an input file, optionally
683 r"""Read a dictionary of key=value pairs from an input file, optionally
684 performing conversions on the resulting values.
684 performing conversions on the resulting values.
685
685
686 read_dict(filename,type_conv,**opt) -> dict
686 read_dict(filename,type_conv,**opt) -> dict
687
687
688 Only one value per line is accepted, the format should be
688 Only one value per line is accepted, the format should be
689 # optional comments are ignored
689 # optional comments are ignored
690 key value\n
690 key value\n
691
691
692 Args:
692 Args:
693
693
694 - type_conv: A dictionary specifying which keys need to be converted to
694 - type_conv: A dictionary specifying which keys need to be converted to
695 which types. By default all keys are read as strings. This dictionary
695 which types. By default all keys are read as strings. This dictionary
696 should have as its keys valid conversion functions for strings
696 should have as its keys valid conversion functions for strings
697 (int,long,float,complex, or your own). The value for each key
697 (int,long,float,complex, or your own). The value for each key
698 (converter) should be a whitespace separated string containing the names
698 (converter) should be a whitespace separated string containing the names
699 of all the entries in the file to be converted using that function. For
699 of all the entries in the file to be converted using that function. For
700 keys to be left alone, use None as the conversion function (only needed
700 keys to be left alone, use None as the conversion function (only needed
701 with purge=1, see below).
701 with purge=1, see below).
702
702
703 - opt: dictionary with extra options as below (default in parens)
703 - opt: dictionary with extra options as below (default in parens)
704
704
705 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
705 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
706 of the dictionary to be returned. If purge is going to be used, the
706 of the dictionary to be returned. If purge is going to be used, the
707 set of keys to be left as strings also has to be explicitly specified
707 set of keys to be left as strings also has to be explicitly specified
708 using the (non-existent) conversion function None.
708 using the (non-existent) conversion function None.
709
709
710 fs(None): field separator. This is the key/value separator to be used
710 fs(None): field separator. This is the key/value separator to be used
711 when parsing the file. The None default means any whitespace [behavior
711 when parsing the file. The None default means any whitespace [behavior
712 of string.split()].
712 of string.split()].
713
713
714 strip(0): if 1, strip string values of leading/trailinig whitespace.
714 strip(0): if 1, strip string values of leading/trailinig whitespace.
715
715
716 warn(1): warning level if requested keys are not found in file.
716 warn(1): warning level if requested keys are not found in file.
717 - 0: silently ignore.
717 - 0: silently ignore.
718 - 1: inform but proceed.
718 - 1: inform but proceed.
719 - 2: raise KeyError exception.
719 - 2: raise KeyError exception.
720
720
721 no_empty(0): if 1, remove keys with whitespace strings as a value.
721 no_empty(0): if 1, remove keys with whitespace strings as a value.
722
722
723 unique([]): list of keys (or space separated string) which can't be
723 unique([]): list of keys (or space separated string) which can't be
724 repeated. If one such key is found in the file, each new instance
724 repeated. If one such key is found in the file, each new instance
725 overwrites the previous one. For keys not listed here, the behavior is
725 overwrites the previous one. For keys not listed here, the behavior is
726 to make a list of all appearances.
726 to make a list of all appearances.
727
727
728 Example:
728 Example:
729
729
730 If the input file test.ini contains (we put it in a string to keep the test
730 If the input file test.ini contains (we put it in a string to keep the test
731 self-contained):
731 self-contained):
732
732
733 >>> test_ini = '''\
733 >>> test_ini = '''\
734 ... i 3
734 ... i 3
735 ... x 4.5
735 ... x 4.5
736 ... y 5.5
736 ... y 5.5
737 ... s hi ho'''
737 ... s hi ho'''
738
738
739 Then we can use it as follows:
739 Then we can use it as follows:
740 >>> type_conv={int:'i',float:'x',None:'s'}
740 >>> type_conv={int:'i',float:'x',None:'s'}
741
741
742 >>> d = read_dict(test_ini)
742 >>> d = read_dict(test_ini)
743
743
744 >>> sorted(d.items())
744 >>> sorted(d.items())
745 [('i', '3'), ('s', 'hi ho'), ('x', '4.5'), ('y', '5.5')]
745 [('i', '3'), ('s', 'hi ho'), ('x', '4.5'), ('y', '5.5')]
746
746
747 >>> d = read_dict(test_ini,type_conv)
747 >>> d = read_dict(test_ini,type_conv)
748
748
749 >>> sorted(d.items())
749 >>> sorted(d.items())
750 [('i', 3), ('s', 'hi ho'), ('x', 4.5), ('y', '5.5')]
750 [('i', 3), ('s', 'hi ho'), ('x', 4.5), ('y', '5.5')]
751
751
752 >>> d = read_dict(test_ini,type_conv,purge=True)
752 >>> d = read_dict(test_ini,type_conv,purge=True)
753
753
754 >>> sorted(d.items())
754 >>> sorted(d.items())
755 [('i', 3), ('s', 'hi ho'), ('x', 4.5)]
755 [('i', 3), ('s', 'hi ho'), ('x', 4.5)]
756 """
756 """
757
757
758 # starting config
758 # starting config
759 opt.setdefault('purge',0)
759 opt.setdefault('purge',0)
760 opt.setdefault('fs',None) # field sep defaults to any whitespace
760 opt.setdefault('fs',None) # field sep defaults to any whitespace
761 opt.setdefault('strip',0)
761 opt.setdefault('strip',0)
762 opt.setdefault('warn',1)
762 opt.setdefault('warn',1)
763 opt.setdefault('no_empty',0)
763 opt.setdefault('no_empty',0)
764 opt.setdefault('unique','')
764 opt.setdefault('unique','')
765 if type(opt['unique']) in StringTypes:
765 if type(opt['unique']) in StringTypes:
766 unique_keys = qw(opt['unique'])
766 unique_keys = qw(opt['unique'])
767 elif type(opt['unique']) in (types.TupleType,types.ListType):
767 elif type(opt['unique']) in (types.TupleType,types.ListType):
768 unique_keys = opt['unique']
768 unique_keys = opt['unique']
769 else:
769 else:
770 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
770 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
771
771
772 dict = {}
772 dict = {}
773
773
774 # first read in table of values as strings
774 # first read in table of values as strings
775 if '\n' in filename:
775 if '\n' in filename:
776 lines = filename.splitlines()
776 lines = filename.splitlines()
777 file = None
777 file = None
778 else:
778 else:
779 file = open(filename,'r')
779 file = open(filename,'r')
780 lines = file.readlines()
780 lines = file.readlines()
781 for line in lines:
781 for line in lines:
782 line = line.strip()
782 line = line.strip()
783 if len(line) and line[0]=='#': continue
783 if len(line) and line[0]=='#': continue
784 if len(line)>0:
784 if len(line)>0:
785 lsplit = line.split(opt['fs'],1)
785 lsplit = line.split(opt['fs'],1)
786 try:
786 try:
787 key,val = lsplit
787 key,val = lsplit
788 except ValueError:
788 except ValueError:
789 key,val = lsplit[0],''
789 key,val = lsplit[0],''
790 key = key.strip()
790 key = key.strip()
791 if opt['strip']: val = val.strip()
791 if opt['strip']: val = val.strip()
792 if val == "''" or val == '""': val = ''
792 if val == "''" or val == '""': val = ''
793 if opt['no_empty'] and (val=='' or val.isspace()):
793 if opt['no_empty'] and (val=='' or val.isspace()):
794 continue
794 continue
795 # if a key is found more than once in the file, build a list
795 # if a key is found more than once in the file, build a list
796 # unless it's in the 'unique' list. In that case, last found in file
796 # unless it's in the 'unique' list. In that case, last found in file
797 # takes precedence. User beware.
797 # takes precedence. User beware.
798 try:
798 try:
799 if dict[key] and key in unique_keys:
799 if dict[key] and key in unique_keys:
800 dict[key] = val
800 dict[key] = val
801 elif type(dict[key]) is types.ListType:
801 elif type(dict[key]) is types.ListType:
802 dict[key].append(val)
802 dict[key].append(val)
803 else:
803 else:
804 dict[key] = [dict[key],val]
804 dict[key] = [dict[key],val]
805 except KeyError:
805 except KeyError:
806 dict[key] = val
806 dict[key] = val
807 # purge if requested
807 # purge if requested
808 if opt['purge']:
808 if opt['purge']:
809 accepted_keys = qwflat(type_conv.values())
809 accepted_keys = qwflat(type_conv.values())
810 for key in dict.keys():
810 for key in dict.keys():
811 if key in accepted_keys: continue
811 if key in accepted_keys: continue
812 del(dict[key])
812 del(dict[key])
813 # now convert if requested
813 # now convert if requested
814 if type_conv==None: return dict
814 if type_conv==None: return dict
815 conversions = type_conv.keys()
815 conversions = type_conv.keys()
816 try: conversions.remove(None)
816 try: conversions.remove(None)
817 except: pass
817 except: pass
818 for convert in conversions:
818 for convert in conversions:
819 for val in qw(type_conv[convert]):
819 for val in qw(type_conv[convert]):
820 try:
820 try:
821 dict[val] = convert(dict[val])
821 dict[val] = convert(dict[val])
822 except KeyError,e:
822 except KeyError,e:
823 if opt['warn'] == 0:
823 if opt['warn'] == 0:
824 pass
824 pass
825 elif opt['warn'] == 1:
825 elif opt['warn'] == 1:
826 print >>sys.stderr, 'Warning: key',val,\
826 print >>sys.stderr, 'Warning: key',val,\
827 'not found in file',filename
827 'not found in file',filename
828 elif opt['warn'] == 2:
828 elif opt['warn'] == 2:
829 raise KeyError,e
829 raise KeyError,e
830 else:
830 else:
831 raise ValueError,'Warning level must be 0,1 or 2'
831 raise ValueError,'Warning level must be 0,1 or 2'
832
832
833 return dict
833 return dict
834
834
835 #----------------------------------------------------------------------------
835 #----------------------------------------------------------------------------
836 def flag_calls(func):
836 def flag_calls(func):
837 """Wrap a function to detect and flag when it gets called.
837 """Wrap a function to detect and flag when it gets called.
838
838
839 This is a decorator which takes a function and wraps it in a function with
839 This is a decorator which takes a function and wraps it in a function with
840 a 'called' attribute. wrapper.called is initialized to False.
840 a 'called' attribute. wrapper.called is initialized to False.
841
841
842 The wrapper.called attribute is set to False right before each call to the
842 The wrapper.called attribute is set to False right before each call to the
843 wrapped function, so if the call fails it remains False. After the call
843 wrapped function, so if the call fails it remains False. After the call
844 completes, wrapper.called is set to True and the output is returned.
844 completes, wrapper.called is set to True and the output is returned.
845
845
846 Testing for truth in wrapper.called allows you to determine if a call to
846 Testing for truth in wrapper.called allows you to determine if a call to
847 func() was attempted and succeeded."""
847 func() was attempted and succeeded."""
848
848
849 def wrapper(*args,**kw):
849 def wrapper(*args,**kw):
850 wrapper.called = False
850 wrapper.called = False
851 out = func(*args,**kw)
851 out = func(*args,**kw)
852 wrapper.called = True
852 wrapper.called = True
853 return out
853 return out
854
854
855 wrapper.called = False
855 wrapper.called = False
856 wrapper.__doc__ = func.__doc__
856 wrapper.__doc__ = func.__doc__
857 return wrapper
857 return wrapper
858
858
859 #----------------------------------------------------------------------------
859 #----------------------------------------------------------------------------
860 def dhook_wrap(func,*a,**k):
860 def dhook_wrap(func,*a,**k):
861 """Wrap a function call in a sys.displayhook controller.
861 """Wrap a function call in a sys.displayhook controller.
862
862
863 Returns a wrapper around func which calls func, with all its arguments and
863 Returns a wrapper around func which calls func, with all its arguments and
864 keywords unmodified, using the default sys.displayhook. Since IPython
864 keywords unmodified, using the default sys.displayhook. Since IPython
865 modifies sys.displayhook, it breaks the behavior of certain systems that
865 modifies sys.displayhook, it breaks the behavior of certain systems that
866 rely on the default behavior, notably doctest.
866 rely on the default behavior, notably doctest.
867 """
867 """
868
868
869 def f(*a,**k):
869 def f(*a,**k):
870
870
871 dhook_s = sys.displayhook
871 dhook_s = sys.displayhook
872 sys.displayhook = sys.__displayhook__
872 sys.displayhook = sys.__displayhook__
873 try:
873 try:
874 out = func(*a,**k)
874 out = func(*a,**k)
875 finally:
875 finally:
876 sys.displayhook = dhook_s
876 sys.displayhook = dhook_s
877
877
878 return out
878 return out
879
879
880 f.__doc__ = func.__doc__
880 f.__doc__ = func.__doc__
881 return f
881 return f
882
882
883 #----------------------------------------------------------------------------
883 #----------------------------------------------------------------------------
884 def doctest_reload():
884 def doctest_reload():
885 """Properly reload doctest to reuse it interactively.
885 """Properly reload doctest to reuse it interactively.
886
886
887 This routine:
887 This routine:
888
888
889 - reloads doctest
889 - reloads doctest
890
890
891 - resets its global 'master' attribute to None, so that multiple uses of
891 - resets its global 'master' attribute to None, so that multiple uses of
892 the module interactively don't produce cumulative reports.
892 the module interactively don't produce cumulative reports.
893
893
894 - Monkeypatches its core test runner method to protect it from IPython's
894 - Monkeypatches its core test runner method to protect it from IPython's
895 modified displayhook. Doctest expects the default displayhook behavior
895 modified displayhook. Doctest expects the default displayhook behavior
896 deep down, so our modification breaks it completely. For this reason, a
896 deep down, so our modification breaks it completely. For this reason, a
897 hard monkeypatch seems like a reasonable solution rather than asking
897 hard monkeypatch seems like a reasonable solution rather than asking
898 users to manually use a different doctest runner when under IPython."""
898 users to manually use a different doctest runner when under IPython."""
899
899
900 import doctest
900 import doctest
901 reload(doctest)
901 reload(doctest)
902 doctest.master=None
902 doctest.master=None
903
903
904 try:
904 try:
905 doctest.DocTestRunner
905 doctest.DocTestRunner
906 except AttributeError:
906 except AttributeError:
907 # This is only for python 2.3 compatibility, remove once we move to
907 # This is only for python 2.3 compatibility, remove once we move to
908 # 2.4 only.
908 # 2.4 only.
909 pass
909 pass
910 else:
910 else:
911 doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run)
911 doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run)
912
912
913 #----------------------------------------------------------------------------
913 #----------------------------------------------------------------------------
914 class HomeDirError(Error):
914 class HomeDirError(Error):
915 pass
915 pass
916
916
917 def get_home_dir():
917 def get_home_dir():
918 """Return the closest possible equivalent to a 'home' directory.
918 """Return the closest possible equivalent to a 'home' directory.
919
919
920 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
920 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
921
921
922 Currently only Posix and NT are implemented, a HomeDirError exception is
922 Currently only Posix and NT are implemented, a HomeDirError exception is
923 raised for all other OSes. """
923 raised for all other OSes. """
924
924
925 isdir = os.path.isdir
925 isdir = os.path.isdir
926 env = os.environ
926 env = os.environ
927
927
928 # first, check py2exe distribution root directory for _ipython.
928 # first, check py2exe distribution root directory for _ipython.
929 # This overrides all. Normally does not exist.
929 # This overrides all. Normally does not exist.
930
930
931 if '\\library.zip\\' in IPython.__file__.lower():
931 if '\\library.zip\\' in IPython.__file__.lower():
932 root, rest = IPython.__file__.lower().split('library.zip')
932 root, rest = IPython.__file__.lower().split('library.zip')
933 if isdir(root + '_ipython'):
933 if isdir(root + '_ipython'):
934 os.environ["IPYKITROOT"] = root.rstrip('\\')
934 os.environ["IPYKITROOT"] = root.rstrip('\\')
935 return root
935 return root
936
936
937 try:
937 try:
938 homedir = env['HOME']
938 homedir = env['HOME']
939 if not isdir(homedir):
939 if not isdir(homedir):
940 # in case a user stuck some string which does NOT resolve to a
940 # in case a user stuck some string which does NOT resolve to a
941 # valid path, it's as good as if we hadn't foud it
941 # valid path, it's as good as if we hadn't foud it
942 raise KeyError
942 raise KeyError
943 return homedir
943 return homedir
944 except KeyError:
944 except KeyError:
945 if os.name == 'posix':
945 if os.name == 'posix':
946 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
946 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
947 elif os.name == 'nt':
947 elif os.name == 'nt':
948 # For some strange reason, win9x returns 'nt' for os.name.
948 # For some strange reason, win9x returns 'nt' for os.name.
949 try:
949 try:
950 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
950 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
951 if not isdir(homedir):
951 if not isdir(homedir):
952 homedir = os.path.join(env['USERPROFILE'])
952 homedir = os.path.join(env['USERPROFILE'])
953 if not isdir(homedir):
953 if not isdir(homedir):
954 raise HomeDirError
954 raise HomeDirError
955 return homedir
955 return homedir
956 except:
956 except:
957 try:
957 try:
958 # Use the registry to get the 'My Documents' folder.
958 # Use the registry to get the 'My Documents' folder.
959 import _winreg as wreg
959 import _winreg as wreg
960 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
960 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
961 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
961 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
962 homedir = wreg.QueryValueEx(key,'Personal')[0]
962 homedir = wreg.QueryValueEx(key,'Personal')[0]
963 key.Close()
963 key.Close()
964 if not isdir(homedir):
964 if not isdir(homedir):
965 e = ('Invalid "Personal" folder registry key '
965 e = ('Invalid "Personal" folder registry key '
966 'typically "My Documents".\n'
966 'typically "My Documents".\n'
967 'Value: %s\n'
967 'Value: %s\n'
968 'This is not a valid directory on your system.' %
968 'This is not a valid directory on your system.' %
969 homedir)
969 homedir)
970 raise HomeDirError(e)
970 raise HomeDirError(e)
971 return homedir
971 return homedir
972 except HomeDirError:
972 except HomeDirError:
973 raise
973 raise
974 except:
974 except:
975 return 'C:\\'
975 return 'C:\\'
976 elif os.name == 'dos':
976 elif os.name == 'dos':
977 # Desperate, may do absurd things in classic MacOS. May work under DOS.
977 # Desperate, may do absurd things in classic MacOS. May work under DOS.
978 return 'C:\\'
978 return 'C:\\'
979 else:
979 else:
980 raise HomeDirError,'support for your operating system not implemented.'
980 raise HomeDirError,'support for your operating system not implemented.'
981
981
982
982
983 def get_ipython_dir():
983 def get_ipython_dir():
984 """Get the IPython directory for this platform and user.
984 """Get the IPython directory for this platform and user.
985
985
986 This uses the logic in `get_home_dir` to find the home directory
986 This uses the logic in `get_home_dir` to find the home directory
987 and the adds either .ipython or _ipython to the end of the path.
987 and the adds either .ipython or _ipython to the end of the path.
988 """
988 """
989 if os.name == 'posix':
989 if os.name == 'posix':
990 ipdir_def = '.ipython'
990 ipdir_def = '.ipython'
991 else:
991 else:
992 ipdir_def = '_ipython'
992 ipdir_def = '_ipython'
993 home_dir = get_home_dir()
993 home_dir = get_home_dir()
994 ipdir = os.path.abspath(os.environ.get('IPYTHONDIR',
994 ipdir = os.path.abspath(os.environ.get('IPYTHONDIR',
995 os.path.join(home_dir,ipdir_def)))
995 os.path.join(home_dir,ipdir_def)))
996 return ipdir
996 return ipdir
997
997
998 def get_security_dir():
998 def get_security_dir():
999 """Get the IPython security directory.
999 """Get the IPython security directory.
1000
1000
1001 This directory is the default location for all security related files,
1001 This directory is the default location for all security related files,
1002 including SSL/TLS certificates and FURL files.
1002 including SSL/TLS certificates and FURL files.
1003
1003
1004 If the directory does not exist, it is created with 0700 permissions.
1004 If the directory does not exist, it is created with 0700 permissions.
1005 If it exists, permissions are set to 0700.
1005 If it exists, permissions are set to 0700.
1006 """
1006 """
1007 security_dir = os.path.join(get_ipython_dir(), 'security')
1007 security_dir = os.path.join(get_ipython_dir(), 'security')
1008 if not os.path.isdir(security_dir):
1008 if not os.path.isdir(security_dir):
1009 os.mkdir(security_dir, 0700)
1009 os.mkdir(security_dir, 0700)
1010 else:
1010 else:
1011 os.chmod(security_dir, 0700)
1011 os.chmod(security_dir, 0700)
1012 return security_dir
1012 return security_dir
1013
1013
1014 #****************************************************************************
1014 #****************************************************************************
1015 # strings and text
1015 # strings and text
1016
1016
1017 class LSString(str):
1017 class LSString(str):
1018 """String derivative with a special access attributes.
1018 """String derivative with a special access attributes.
1019
1019
1020 These are normal strings, but with the special attributes:
1020 These are normal strings, but with the special attributes:
1021
1021
1022 .l (or .list) : value as list (split on newlines).
1022 .l (or .list) : value as list (split on newlines).
1023 .n (or .nlstr): original value (the string itself).
1023 .n (or .nlstr): original value (the string itself).
1024 .s (or .spstr): value as whitespace-separated string.
1024 .s (or .spstr): value as whitespace-separated string.
1025 .p (or .paths): list of path objects
1025 .p (or .paths): list of path objects
1026
1026
1027 Any values which require transformations are computed only once and
1027 Any values which require transformations are computed only once and
1028 cached.
1028 cached.
1029
1029
1030 Such strings are very useful to efficiently interact with the shell, which
1030 Such strings are very useful to efficiently interact with the shell, which
1031 typically only understands whitespace-separated options for commands."""
1031 typically only understands whitespace-separated options for commands."""
1032
1032
1033 def get_list(self):
1033 def get_list(self):
1034 try:
1034 try:
1035 return self.__list
1035 return self.__list
1036 except AttributeError:
1036 except AttributeError:
1037 self.__list = self.split('\n')
1037 self.__list = self.split('\n')
1038 return self.__list
1038 return self.__list
1039
1039
1040 l = list = property(get_list)
1040 l = list = property(get_list)
1041
1041
1042 def get_spstr(self):
1042 def get_spstr(self):
1043 try:
1043 try:
1044 return self.__spstr
1044 return self.__spstr
1045 except AttributeError:
1045 except AttributeError:
1046 self.__spstr = self.replace('\n',' ')
1046 self.__spstr = self.replace('\n',' ')
1047 return self.__spstr
1047 return self.__spstr
1048
1048
1049 s = spstr = property(get_spstr)
1049 s = spstr = property(get_spstr)
1050
1050
1051 def get_nlstr(self):
1051 def get_nlstr(self):
1052 return self
1052 return self
1053
1053
1054 n = nlstr = property(get_nlstr)
1054 n = nlstr = property(get_nlstr)
1055
1055
1056 def get_paths(self):
1056 def get_paths(self):
1057 try:
1057 try:
1058 return self.__paths
1058 return self.__paths
1059 except AttributeError:
1059 except AttributeError:
1060 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
1060 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
1061 return self.__paths
1061 return self.__paths
1062
1062
1063 p = paths = property(get_paths)
1063 p = paths = property(get_paths)
1064
1064
1065 def print_lsstring(arg):
1065 def print_lsstring(arg):
1066 """ Prettier (non-repr-like) and more informative printer for LSString """
1066 """ Prettier (non-repr-like) and more informative printer for LSString """
1067 print "LSString (.p, .n, .l, .s available). Value:"
1067 print "LSString (.p, .n, .l, .s available). Value:"
1068 print arg
1068 print arg
1069
1069
1070 print_lsstring = result_display.when_type(LSString)(print_lsstring)
1070 print_lsstring = result_display.when_type(LSString)(print_lsstring)
1071
1071
1072 #----------------------------------------------------------------------------
1072 #----------------------------------------------------------------------------
1073 class SList(list):
1073 class SList(list):
1074 """List derivative with a special access attributes.
1074 """List derivative with a special access attributes.
1075
1075
1076 These are normal lists, but with the special attributes:
1076 These are normal lists, but with the special attributes:
1077
1077
1078 .l (or .list) : value as list (the list itself).
1078 .l (or .list) : value as list (the list itself).
1079 .n (or .nlstr): value as a string, joined on newlines.
1079 .n (or .nlstr): value as a string, joined on newlines.
1080 .s (or .spstr): value as a string, joined on spaces.
1080 .s (or .spstr): value as a string, joined on spaces.
1081 .p (or .paths): list of path objects
1081 .p (or .paths): list of path objects
1082
1082
1083 Any values which require transformations are computed only once and
1083 Any values which require transformations are computed only once and
1084 cached."""
1084 cached."""
1085
1085
1086 def get_list(self):
1086 def get_list(self):
1087 return self
1087 return self
1088
1088
1089 l = list = property(get_list)
1089 l = list = property(get_list)
1090
1090
1091 def get_spstr(self):
1091 def get_spstr(self):
1092 try:
1092 try:
1093 return self.__spstr
1093 return self.__spstr
1094 except AttributeError:
1094 except AttributeError:
1095 self.__spstr = ' '.join(self)
1095 self.__spstr = ' '.join(self)
1096 return self.__spstr
1096 return self.__spstr
1097
1097
1098 s = spstr = property(get_spstr)
1098 s = spstr = property(get_spstr)
1099
1099
1100 def get_nlstr(self):
1100 def get_nlstr(self):
1101 try:
1101 try:
1102 return self.__nlstr
1102 return self.__nlstr
1103 except AttributeError:
1103 except AttributeError:
1104 self.__nlstr = '\n'.join(self)
1104 self.__nlstr = '\n'.join(self)
1105 return self.__nlstr
1105 return self.__nlstr
1106
1106
1107 n = nlstr = property(get_nlstr)
1107 n = nlstr = property(get_nlstr)
1108
1108
1109 def get_paths(self):
1109 def get_paths(self):
1110 try:
1110 try:
1111 return self.__paths
1111 return self.__paths
1112 except AttributeError:
1112 except AttributeError:
1113 self.__paths = [path(p) for p in self if os.path.exists(p)]
1113 self.__paths = [path(p) for p in self if os.path.exists(p)]
1114 return self.__paths
1114 return self.__paths
1115
1115
1116 p = paths = property(get_paths)
1116 p = paths = property(get_paths)
1117
1117
1118 def grep(self, pattern, prune = False, field = None):
1118 def grep(self, pattern, prune = False, field = None):
1119 """ Return all strings matching 'pattern' (a regex or callable)
1119 """ Return all strings matching 'pattern' (a regex or callable)
1120
1120
1121 This is case-insensitive. If prune is true, return all items
1121 This is case-insensitive. If prune is true, return all items
1122 NOT matching the pattern.
1122 NOT matching the pattern.
1123
1123
1124 If field is specified, the match must occur in the specified
1124 If field is specified, the match must occur in the specified
1125 whitespace-separated field.
1125 whitespace-separated field.
1126
1126
1127 Examples::
1127 Examples::
1128
1128
1129 a.grep( lambda x: x.startswith('C') )
1129 a.grep( lambda x: x.startswith('C') )
1130 a.grep('Cha.*log', prune=1)
1130 a.grep('Cha.*log', prune=1)
1131 a.grep('chm', field=-1)
1131 a.grep('chm', field=-1)
1132 """
1132 """
1133
1133
1134 def match_target(s):
1134 def match_target(s):
1135 if field is None:
1135 if field is None:
1136 return s
1136 return s
1137 parts = s.split()
1137 parts = s.split()
1138 try:
1138 try:
1139 tgt = parts[field]
1139 tgt = parts[field]
1140 return tgt
1140 return tgt
1141 except IndexError:
1141 except IndexError:
1142 return ""
1142 return ""
1143
1143
1144 if isinstance(pattern, basestring):
1144 if isinstance(pattern, basestring):
1145 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
1145 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
1146 else:
1146 else:
1147 pred = pattern
1147 pred = pattern
1148 if not prune:
1148 if not prune:
1149 return SList([el for el in self if pred(match_target(el))])
1149 return SList([el for el in self if pred(match_target(el))])
1150 else:
1150 else:
1151 return SList([el for el in self if not pred(match_target(el))])
1151 return SList([el for el in self if not pred(match_target(el))])
1152 def fields(self, *fields):
1152 def fields(self, *fields):
1153 """ Collect whitespace-separated fields from string list
1153 """ Collect whitespace-separated fields from string list
1154
1154
1155 Allows quick awk-like usage of string lists.
1155 Allows quick awk-like usage of string lists.
1156
1156
1157 Example data (in var a, created by 'a = !ls -l')::
1157 Example data (in var a, created by 'a = !ls -l')::
1158 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
1158 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
1159 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
1159 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
1160
1160
1161 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
1161 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
1162 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
1162 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
1163 (note the joining by space).
1163 (note the joining by space).
1164 a.fields(-1) is ['ChangeLog', 'IPython']
1164 a.fields(-1) is ['ChangeLog', 'IPython']
1165
1165
1166 IndexErrors are ignored.
1166 IndexErrors are ignored.
1167
1167
1168 Without args, fields() just split()'s the strings.
1168 Without args, fields() just split()'s the strings.
1169 """
1169 """
1170 if len(fields) == 0:
1170 if len(fields) == 0:
1171 return [el.split() for el in self]
1171 return [el.split() for el in self]
1172
1172
1173 res = SList()
1173 res = SList()
1174 for el in [f.split() for f in self]:
1174 for el in [f.split() for f in self]:
1175 lineparts = []
1175 lineparts = []
1176
1176
1177 for fd in fields:
1177 for fd in fields:
1178 try:
1178 try:
1179 lineparts.append(el[fd])
1179 lineparts.append(el[fd])
1180 except IndexError:
1180 except IndexError:
1181 pass
1181 pass
1182 if lineparts:
1182 if lineparts:
1183 res.append(" ".join(lineparts))
1183 res.append(" ".join(lineparts))
1184
1184
1185 return res
1185 return res
1186 def sort(self,field= None, nums = False):
1186 def sort(self,field= None, nums = False):
1187 """ sort by specified fields (see fields())
1187 """ sort by specified fields (see fields())
1188
1188
1189 Example::
1189 Example::
1190 a.sort(1, nums = True)
1190 a.sort(1, nums = True)
1191
1191
1192 Sorts a by second field, in numerical order (so that 21 > 3)
1192 Sorts a by second field, in numerical order (so that 21 > 3)
1193
1193
1194 """
1194 """
1195
1195
1196 #decorate, sort, undecorate
1196 #decorate, sort, undecorate
1197 if field is not None:
1197 if field is not None:
1198 dsu = [[SList([line]).fields(field), line] for line in self]
1198 dsu = [[SList([line]).fields(field), line] for line in self]
1199 else:
1199 else:
1200 dsu = [[line, line] for line in self]
1200 dsu = [[line, line] for line in self]
1201 if nums:
1201 if nums:
1202 for i in range(len(dsu)):
1202 for i in range(len(dsu)):
1203 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
1203 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
1204 try:
1204 try:
1205 n = int(numstr)
1205 n = int(numstr)
1206 except ValueError:
1206 except ValueError:
1207 n = 0;
1207 n = 0;
1208 dsu[i][0] = n
1208 dsu[i][0] = n
1209
1209
1210
1210
1211 dsu.sort()
1211 dsu.sort()
1212 return SList([t[1] for t in dsu])
1212 return SList([t[1] for t in dsu])
1213
1213
1214 def print_slist(arg):
1214 def print_slist(arg):
1215 """ Prettier (non-repr-like) and more informative printer for SList """
1215 """ Prettier (non-repr-like) and more informative printer for SList """
1216 print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
1216 print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
1217 if hasattr(arg, 'hideonce') and arg.hideonce:
1217 if hasattr(arg, 'hideonce') and arg.hideonce:
1218 arg.hideonce = False
1218 arg.hideonce = False
1219 return
1219 return
1220
1220
1221 nlprint(arg)
1221 nlprint(arg)
1222
1222
1223 print_slist = result_display.when_type(SList)(print_slist)
1223 print_slist = result_display.when_type(SList)(print_slist)
1224
1224
1225
1225
1226
1226
1227 #----------------------------------------------------------------------------
1227 #----------------------------------------------------------------------------
1228 def esc_quotes(strng):
1228 def esc_quotes(strng):
1229 """Return the input string with single and double quotes escaped out"""
1229 """Return the input string with single and double quotes escaped out"""
1230
1230
1231 return strng.replace('"','\\"').replace("'","\\'")
1231 return strng.replace('"','\\"').replace("'","\\'")
1232
1232
1233 #----------------------------------------------------------------------------
1233 #----------------------------------------------------------------------------
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 = ''
1245 tailpadding = ''
1245 tailpadding = ''
1246 raw = ''
1246 raw = ''
1247 if "\\" in s:
1247 if "\\" in s:
1248 raw = 'r'
1248 raw = 'r'
1249 if s.endswith('\\'):
1249 if s.endswith('\\'):
1250 tail = '[:-1]'
1250 tail = '[:-1]'
1251 tailpadding = '_'
1251 tailpadding = '_'
1252 if '"' not in s:
1252 if '"' not in s:
1253 quote = '"'
1253 quote = '"'
1254 elif "'" not in s:
1254 elif "'" not in s:
1255 quote = "'"
1255 quote = "'"
1256 elif '"""' not in s and not s.endswith('"'):
1256 elif '"""' not in s and not s.endswith('"'):
1257 quote = '"""'
1257 quote = '"""'
1258 elif "'''" not in s and not s.endswith("'"):
1258 elif "'''" not in s and not s.endswith("'"):
1259 quote = "'''"
1259 quote = "'''"
1260 else:
1260 else:
1261 # give up, backslash-escaped string will do
1261 # give up, backslash-escaped string will do
1262 return '"%s"' % esc_quotes(s)
1262 return '"%s"' % esc_quotes(s)
1263 res = raw + quote + s + tailpadding + quote + tail
1263 res = raw + quote + s + tailpadding + quote + tail
1264 return res
1264 return res
1265
1265
1266
1266
1267 #----------------------------------------------------------------------------
1267 #----------------------------------------------------------------------------
1268 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1268 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1269 """Take multiple lines of input.
1269 """Take multiple lines of input.
1270
1270
1271 A list with each line of input as a separate element is returned when a
1271 A list with each line of input as a separate element is returned when a
1272 termination string is entered (defaults to a single '.'). Input can also
1272 termination string is entered (defaults to a single '.'). Input can also
1273 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1273 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1274
1274
1275 Lines of input which end in \\ are joined into single entries (and a
1275 Lines of input which end in \\ are joined into single entries (and a
1276 secondary continuation prompt is issued as long as the user terminates
1276 secondary continuation prompt is issued as long as the user terminates
1277 lines with \\). This allows entering very long strings which are still
1277 lines with \\). This allows entering very long strings which are still
1278 meant to be treated as single entities.
1278 meant to be treated as single entities.
1279 """
1279 """
1280
1280
1281 try:
1281 try:
1282 if header:
1282 if header:
1283 header += '\n'
1283 header += '\n'
1284 lines = [raw_input(header + ps1)]
1284 lines = [raw_input(header + ps1)]
1285 except EOFError:
1285 except EOFError:
1286 return []
1286 return []
1287 terminate = [terminate_str]
1287 terminate = [terminate_str]
1288 try:
1288 try:
1289 while lines[-1:] != terminate:
1289 while lines[-1:] != terminate:
1290 new_line = raw_input(ps1)
1290 new_line = raw_input(ps1)
1291 while new_line.endswith('\\'):
1291 while new_line.endswith('\\'):
1292 new_line = new_line[:-1] + raw_input(ps2)
1292 new_line = new_line[:-1] + raw_input(ps2)
1293 lines.append(new_line)
1293 lines.append(new_line)
1294
1294
1295 return lines[:-1] # don't return the termination command
1295 return lines[:-1] # don't return the termination command
1296 except EOFError:
1296 except EOFError:
1297 print
1297 print
1298 return lines
1298 return lines
1299
1299
1300 #----------------------------------------------------------------------------
1300 #----------------------------------------------------------------------------
1301 def raw_input_ext(prompt='', ps2='... '):
1301 def raw_input_ext(prompt='', ps2='... '):
1302 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1302 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1303
1303
1304 line = raw_input(prompt)
1304 line = raw_input(prompt)
1305 while line.endswith('\\'):
1305 while line.endswith('\\'):
1306 line = line[:-1] + raw_input(ps2)
1306 line = line[:-1] + raw_input(ps2)
1307 return line
1307 return line
1308
1308
1309 #----------------------------------------------------------------------------
1309 #----------------------------------------------------------------------------
1310 def ask_yes_no(prompt,default=None):
1310 def ask_yes_no(prompt,default=None):
1311 """Asks a question and returns a boolean (y/n) answer.
1311 """Asks a question and returns a boolean (y/n) answer.
1312
1312
1313 If default is given (one of 'y','n'), it is used if the user input is
1313 If default is given (one of 'y','n'), it is used if the user input is
1314 empty. Otherwise the question is repeated until an answer is given.
1314 empty. Otherwise the question is repeated until an answer is given.
1315
1315
1316 An EOF is treated as the default answer. If there is no default, an
1316 An EOF is treated as the default answer. If there is no default, an
1317 exception is raised to prevent infinite loops.
1317 exception is raised to prevent infinite loops.
1318
1318
1319 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1319 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1320
1320
1321 answers = {'y':True,'n':False,'yes':True,'no':False}
1321 answers = {'y':True,'n':False,'yes':True,'no':False}
1322 ans = None
1322 ans = None
1323 while ans not in answers.keys():
1323 while ans not in answers.keys():
1324 try:
1324 try:
1325 ans = raw_input(prompt+' ').lower()
1325 ans = raw_input(prompt+' ').lower()
1326 if not ans: # response was an empty string
1326 if not ans: # response was an empty string
1327 ans = default
1327 ans = default
1328 except KeyboardInterrupt:
1328 except KeyboardInterrupt:
1329 pass
1329 pass
1330 except EOFError:
1330 except EOFError:
1331 if default in answers.keys():
1331 if default in answers.keys():
1332 ans = default
1332 ans = default
1333 print
1333 print
1334 else:
1334 else:
1335 raise
1335 raise
1336
1336
1337 return answers[ans]
1337 return answers[ans]
1338
1338
1339 #----------------------------------------------------------------------------
1339 #----------------------------------------------------------------------------
1340 def marquee(txt='',width=78,mark='*'):
1340 def marquee(txt='',width=78,mark='*'):
1341 """Return the input string centered in a 'marquee'."""
1341 """Return the input string centered in a 'marquee'."""
1342 if not txt:
1342 if not txt:
1343 return (mark*width)[:width]
1343 return (mark*width)[:width]
1344 nmark = (width-len(txt)-2)/len(mark)/2
1344 nmark = (width-len(txt)-2)/len(mark)/2
1345 if nmark < 0: nmark =0
1345 if nmark < 0: nmark =0
1346 marks = mark*nmark
1346 marks = mark*nmark
1347 return '%s %s %s' % (marks,txt,marks)
1347 return '%s %s %s' % (marks,txt,marks)
1348
1348
1349 #----------------------------------------------------------------------------
1349 #----------------------------------------------------------------------------
1350 class EvalDict:
1350 class EvalDict:
1351 """
1351 """
1352 Emulate a dict which evaluates its contents in the caller's frame.
1352 Emulate a dict which evaluates its contents in the caller's frame.
1353
1353
1354 Usage:
1354 Usage:
1355 >>> number = 19
1355 >>> number = 19
1356
1356
1357 >>> text = "python"
1357 >>> text = "python"
1358
1358
1359 >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1359 >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1360 Python 2.1 rules!
1360 Python 2.1 rules!
1361 """
1361 """
1362
1362
1363 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1363 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1364 # modified (shorter) version of:
1364 # modified (shorter) version of:
1365 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1365 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1366 # Skip Montanaro (skip@pobox.com).
1366 # Skip Montanaro (skip@pobox.com).
1367
1367
1368 def __getitem__(self, name):
1368 def __getitem__(self, name):
1369 frame = sys._getframe(1)
1369 frame = sys._getframe(1)
1370 return eval(name, frame.f_globals, frame.f_locals)
1370 return eval(name, frame.f_globals, frame.f_locals)
1371
1371
1372 EvalString = EvalDict # for backwards compatibility
1372 EvalString = EvalDict # for backwards compatibility
1373 #----------------------------------------------------------------------------
1373 #----------------------------------------------------------------------------
1374 def qw(words,flat=0,sep=None,maxsplit=-1):
1374 def qw(words,flat=0,sep=None,maxsplit=-1):
1375 """Similar to Perl's qw() operator, but with some more options.
1375 """Similar to Perl's qw() operator, but with some more options.
1376
1376
1377 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1377 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1378
1378
1379 words can also be a list itself, and with flat=1, the output will be
1379 words can also be a list itself, and with flat=1, the output will be
1380 recursively flattened.
1380 recursively flattened.
1381
1381
1382 Examples:
1382 Examples:
1383
1383
1384 >>> qw('1 2')
1384 >>> qw('1 2')
1385 ['1', '2']
1385 ['1', '2']
1386
1386
1387 >>> qw(['a b','1 2',['m n','p q']])
1387 >>> qw(['a b','1 2',['m n','p q']])
1388 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1388 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1389
1389
1390 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1390 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1391 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
1391 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
1392 """
1392 """
1393
1393
1394 if type(words) in StringTypes:
1394 if type(words) in StringTypes:
1395 return [word.strip() for word in words.split(sep,maxsplit)
1395 return [word.strip() for word in words.split(sep,maxsplit)
1396 if word and not word.isspace() ]
1396 if word and not word.isspace() ]
1397 if flat:
1397 if flat:
1398 return flatten(map(qw,words,[1]*len(words)))
1398 return flatten(map(qw,words,[1]*len(words)))
1399 return map(qw,words)
1399 return map(qw,words)
1400
1400
1401 #----------------------------------------------------------------------------
1401 #----------------------------------------------------------------------------
1402 def qwflat(words,sep=None,maxsplit=-1):
1402 def qwflat(words,sep=None,maxsplit=-1):
1403 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1403 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1404 return qw(words,1,sep,maxsplit)
1404 return qw(words,1,sep,maxsplit)
1405
1405
1406 #----------------------------------------------------------------------------
1406 #----------------------------------------------------------------------------
1407 def qw_lol(indata):
1407 def qw_lol(indata):
1408 """qw_lol('a b') -> [['a','b']],
1408 """qw_lol('a b') -> [['a','b']],
1409 otherwise it's just a call to qw().
1409 otherwise it's just a call to qw().
1410
1410
1411 We need this to make sure the modules_some keys *always* end up as a
1411 We need this to make sure the modules_some keys *always* end up as a
1412 list of lists."""
1412 list of lists."""
1413
1413
1414 if type(indata) in StringTypes:
1414 if type(indata) in StringTypes:
1415 return [qw(indata)]
1415 return [qw(indata)]
1416 else:
1416 else:
1417 return qw(indata)
1417 return qw(indata)
1418
1418
1419 #-----------------------------------------------------------------------------
1419 #-----------------------------------------------------------------------------
1420 def list_strings(arg):
1420 def list_strings(arg):
1421 """Always return a list of strings, given a string or list of strings
1421 """Always return a list of strings, given a string or list of strings
1422 as input."""
1422 as input."""
1423
1423
1424 if type(arg) in StringTypes: return [arg]
1424 if type(arg) in StringTypes: return [arg]
1425 else: return arg
1425 else: return arg
1426
1426
1427 #----------------------------------------------------------------------------
1427 #----------------------------------------------------------------------------
1428 def grep(pat,list,case=1):
1428 def grep(pat,list,case=1):
1429 """Simple minded grep-like function.
1429 """Simple minded grep-like function.
1430 grep(pat,list) returns occurrences of pat in list, None on failure.
1430 grep(pat,list) returns occurrences of pat in list, None on failure.
1431
1431
1432 It only does simple string matching, with no support for regexps. Use the
1432 It only does simple string matching, with no support for regexps. Use the
1433 option case=0 for case-insensitive matching."""
1433 option case=0 for case-insensitive matching."""
1434
1434
1435 # This is pretty crude. At least it should implement copying only references
1435 # This is pretty crude. At least it should implement copying only references
1436 # to the original data in case it's big. Now it copies the data for output.
1436 # to the original data in case it's big. Now it copies the data for output.
1437 out=[]
1437 out=[]
1438 if case:
1438 if case:
1439 for term in list:
1439 for term in list:
1440 if term.find(pat)>-1: out.append(term)
1440 if term.find(pat)>-1: out.append(term)
1441 else:
1441 else:
1442 lpat=pat.lower()
1442 lpat=pat.lower()
1443 for term in list:
1443 for term in list:
1444 if term.lower().find(lpat)>-1: out.append(term)
1444 if term.lower().find(lpat)>-1: out.append(term)
1445
1445
1446 if len(out): return out
1446 if len(out): return out
1447 else: return None
1447 else: return None
1448
1448
1449 #----------------------------------------------------------------------------
1449 #----------------------------------------------------------------------------
1450 def dgrep(pat,*opts):
1450 def dgrep(pat,*opts):
1451 """Return grep() on dir()+dir(__builtins__).
1451 """Return grep() on dir()+dir(__builtins__).
1452
1452
1453 A very common use of grep() when working interactively."""
1453 A very common use of grep() when working interactively."""
1454
1454
1455 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1455 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1456
1456
1457 #----------------------------------------------------------------------------
1457 #----------------------------------------------------------------------------
1458 def idgrep(pat):
1458 def idgrep(pat):
1459 """Case-insensitive dgrep()"""
1459 """Case-insensitive dgrep()"""
1460
1460
1461 return dgrep(pat,0)
1461 return dgrep(pat,0)
1462
1462
1463 #----------------------------------------------------------------------------
1463 #----------------------------------------------------------------------------
1464 def igrep(pat,list):
1464 def igrep(pat,list):
1465 """Synonym for case-insensitive grep."""
1465 """Synonym for case-insensitive grep."""
1466
1466
1467 return grep(pat,list,case=0)
1467 return grep(pat,list,case=0)
1468
1468
1469 #----------------------------------------------------------------------------
1469 #----------------------------------------------------------------------------
1470 def indent(str,nspaces=4,ntabs=0):
1470 def indent(str,nspaces=4,ntabs=0):
1471 """Indent a string a given number of spaces or tabstops.
1471 """Indent a string a given number of spaces or tabstops.
1472
1472
1473 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1473 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1474 """
1474 """
1475 if str is None:
1475 if str is None:
1476 return
1476 return
1477 ind = '\t'*ntabs+' '*nspaces
1477 ind = '\t'*ntabs+' '*nspaces
1478 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1478 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1479 if outstr.endswith(os.linesep+ind):
1479 if outstr.endswith(os.linesep+ind):
1480 return outstr[:-len(ind)]
1480 return outstr[:-len(ind)]
1481 else:
1481 else:
1482 return outstr
1482 return outstr
1483
1483
1484 #-----------------------------------------------------------------------------
1484 #-----------------------------------------------------------------------------
1485 def native_line_ends(filename,backup=1):
1485 def native_line_ends(filename,backup=1):
1486 """Convert (in-place) a file to line-ends native to the current OS.
1486 """Convert (in-place) a file to line-ends native to the current OS.
1487
1487
1488 If the optional backup argument is given as false, no backup of the
1488 If the optional backup argument is given as false, no backup of the
1489 original file is left. """
1489 original file is left. """
1490
1490
1491 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1491 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1492
1492
1493 bak_filename = filename + backup_suffixes[os.name]
1493 bak_filename = filename + backup_suffixes[os.name]
1494
1494
1495 original = open(filename).read()
1495 original = open(filename).read()
1496 shutil.copy2(filename,bak_filename)
1496 shutil.copy2(filename,bak_filename)
1497 try:
1497 try:
1498 new = open(filename,'wb')
1498 new = open(filename,'wb')
1499 new.write(os.linesep.join(original.splitlines()))
1499 new.write(os.linesep.join(original.splitlines()))
1500 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1500 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1501 new.close()
1501 new.close()
1502 except:
1502 except:
1503 os.rename(bak_filename,filename)
1503 os.rename(bak_filename,filename)
1504 if not backup:
1504 if not backup:
1505 try:
1505 try:
1506 os.remove(bak_filename)
1506 os.remove(bak_filename)
1507 except:
1507 except:
1508 pass
1508 pass
1509
1509
1510 #----------------------------------------------------------------------------
1510 #----------------------------------------------------------------------------
1511 def get_pager_cmd(pager_cmd = None):
1511 def get_pager_cmd(pager_cmd = None):
1512 """Return a pager command.
1512 """Return a pager command.
1513
1513
1514 Makes some attempts at finding an OS-correct one."""
1514 Makes some attempts at finding an OS-correct one."""
1515
1515
1516 if os.name == 'posix':
1516 if os.name == 'posix':
1517 default_pager_cmd = 'less -r' # -r for color control sequences
1517 default_pager_cmd = 'less -r' # -r for color control sequences
1518 elif os.name in ['nt','dos']:
1518 elif os.name in ['nt','dos']:
1519 default_pager_cmd = 'type'
1519 default_pager_cmd = 'type'
1520
1520
1521 if pager_cmd is None:
1521 if pager_cmd is None:
1522 try:
1522 try:
1523 pager_cmd = os.environ['PAGER']
1523 pager_cmd = os.environ['PAGER']
1524 except:
1524 except:
1525 pager_cmd = default_pager_cmd
1525 pager_cmd = default_pager_cmd
1526 return pager_cmd
1526 return pager_cmd
1527
1527
1528 #-----------------------------------------------------------------------------
1528 #-----------------------------------------------------------------------------
1529 def get_pager_start(pager,start):
1529 def get_pager_start(pager,start):
1530 """Return the string for paging files with an offset.
1530 """Return the string for paging files with an offset.
1531
1531
1532 This is the '+N' argument which less and more (under Unix) accept.
1532 This is the '+N' argument which less and more (under Unix) accept.
1533 """
1533 """
1534
1534
1535 if pager in ['less','more']:
1535 if pager in ['less','more']:
1536 if start:
1536 if start:
1537 start_string = '+' + str(start)
1537 start_string = '+' + str(start)
1538 else:
1538 else:
1539 start_string = ''
1539 start_string = ''
1540 else:
1540 else:
1541 start_string = ''
1541 start_string = ''
1542 return start_string
1542 return start_string
1543
1543
1544 #----------------------------------------------------------------------------
1544 #----------------------------------------------------------------------------
1545 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1545 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
1546 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1546 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
1547 import msvcrt
1547 import msvcrt
1548 def page_more():
1548 def page_more():
1549 """ Smart pausing between pages
1549 """ Smart pausing between pages
1550
1550
1551 @return: True if need print more lines, False if quit
1551 @return: True if need print more lines, False if quit
1552 """
1552 """
1553 Term.cout.write('---Return to continue, q to quit--- ')
1553 Term.cout.write('---Return to continue, q to quit--- ')
1554 ans = msvcrt.getch()
1554 ans = msvcrt.getch()
1555 if ans in ("q", "Q"):
1555 if ans in ("q", "Q"):
1556 result = False
1556 result = False
1557 else:
1557 else:
1558 result = True
1558 result = True
1559 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1559 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1560 return result
1560 return result
1561 else:
1561 else:
1562 def page_more():
1562 def page_more():
1563 ans = raw_input('---Return to continue, q to quit--- ')
1563 ans = raw_input('---Return to continue, q to quit--- ')
1564 if ans.lower().startswith('q'):
1564 if ans.lower().startswith('q'):
1565 return False
1565 return False
1566 else:
1566 else:
1567 return True
1567 return True
1568
1568
1569 esc_re = re.compile(r"(\x1b[^m]+m)")
1569 esc_re = re.compile(r"(\x1b[^m]+m)")
1570
1570
1571 def page_dumb(strng,start=0,screen_lines=25):
1571 def page_dumb(strng,start=0,screen_lines=25):
1572 """Very dumb 'pager' in Python, for when nothing else works.
1572 """Very dumb 'pager' in Python, for when nothing else works.
1573
1573
1574 Only moves forward, same interface as page(), except for pager_cmd and
1574 Only moves forward, same interface as page(), except for pager_cmd and
1575 mode."""
1575 mode."""
1576
1576
1577 out_ln = strng.splitlines()[start:]
1577 out_ln = strng.splitlines()[start:]
1578 screens = chop(out_ln,screen_lines-1)
1578 screens = chop(out_ln,screen_lines-1)
1579 if len(screens) == 1:
1579 if len(screens) == 1:
1580 print >>Term.cout, os.linesep.join(screens[0])
1580 print >>Term.cout, os.linesep.join(screens[0])
1581 else:
1581 else:
1582 last_escape = ""
1582 last_escape = ""
1583 for scr in screens[0:-1]:
1583 for scr in screens[0:-1]:
1584 hunk = os.linesep.join(scr)
1584 hunk = os.linesep.join(scr)
1585 print >>Term.cout, last_escape + hunk
1585 print >>Term.cout, last_escape + hunk
1586 if not page_more():
1586 if not page_more():
1587 return
1587 return
1588 esc_list = esc_re.findall(hunk)
1588 esc_list = esc_re.findall(hunk)
1589 if len(esc_list) > 0:
1589 if len(esc_list) > 0:
1590 last_escape = esc_list[-1]
1590 last_escape = esc_list[-1]
1591 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1591 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1592
1592
1593 #----------------------------------------------------------------------------
1593 #----------------------------------------------------------------------------
1594 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1594 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1595 """Print a string, piping through a pager after a certain length.
1595 """Print a string, piping through a pager after a certain length.
1596
1596
1597 The screen_lines parameter specifies the number of *usable* lines of your
1597 The screen_lines parameter specifies the number of *usable* lines of your
1598 terminal screen (total lines minus lines you need to reserve to show other
1598 terminal screen (total lines minus lines you need to reserve to show other
1599 information).
1599 information).
1600
1600
1601 If you set screen_lines to a number <=0, page() will try to auto-determine
1601 If you set screen_lines to a number <=0, page() will try to auto-determine
1602 your screen size and will only use up to (screen_size+screen_lines) for
1602 your screen size and will only use up to (screen_size+screen_lines) for
1603 printing, paging after that. That is, if you want auto-detection but need
1603 printing, paging after that. That is, if you want auto-detection but need
1604 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1604 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1605 auto-detection without any lines reserved simply use screen_lines = 0.
1605 auto-detection without any lines reserved simply use screen_lines = 0.
1606
1606
1607 If a string won't fit in the allowed lines, it is sent through the
1607 If a string won't fit in the allowed lines, it is sent through the
1608 specified pager command. If none given, look for PAGER in the environment,
1608 specified pager command. If none given, look for PAGER in the environment,
1609 and ultimately default to less.
1609 and ultimately default to less.
1610
1610
1611 If no system pager works, the string is sent through a 'dumb pager'
1611 If no system pager works, the string is sent through a 'dumb pager'
1612 written in python, very simplistic.
1612 written in python, very simplistic.
1613 """
1613 """
1614
1614
1615 # Some routines may auto-compute start offsets incorrectly and pass a
1615 # Some routines may auto-compute start offsets incorrectly and pass a
1616 # negative value. Offset to 0 for robustness.
1616 # negative value. Offset to 0 for robustness.
1617 start = max(0,start)
1617 start = max(0,start)
1618
1618
1619 # first, try the hook
1619 # first, try the hook
1620 ip = IPython.ipapi.get()
1620 ip = IPython.ipapi.get()
1621 if ip:
1621 if ip:
1622 try:
1622 try:
1623 ip.IP.hooks.show_in_pager(strng)
1623 ip.IP.hooks.show_in_pager(strng)
1624 return
1624 return
1625 except IPython.ipapi.TryNext:
1625 except IPython.ipapi.TryNext:
1626 pass
1626 pass
1627
1627
1628 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1628 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1629 TERM = os.environ.get('TERM','dumb')
1629 TERM = os.environ.get('TERM','dumb')
1630 if TERM in ['dumb','emacs'] and os.name != 'nt':
1630 if TERM in ['dumb','emacs'] and os.name != 'nt':
1631 print strng
1631 print strng
1632 return
1632 return
1633 # chop off the topmost part of the string we don't want to see
1633 # chop off the topmost part of the string we don't want to see
1634 str_lines = strng.split(os.linesep)[start:]
1634 str_lines = strng.split(os.linesep)[start:]
1635 str_toprint = os.linesep.join(str_lines)
1635 str_toprint = os.linesep.join(str_lines)
1636 num_newlines = len(str_lines)
1636 num_newlines = len(str_lines)
1637 len_str = len(str_toprint)
1637 len_str = len(str_toprint)
1638
1638
1639 # Dumb heuristics to guesstimate number of on-screen lines the string
1639 # Dumb heuristics to guesstimate number of on-screen lines the string
1640 # takes. Very basic, but good enough for docstrings in reasonable
1640 # takes. Very basic, but good enough for docstrings in reasonable
1641 # terminals. If someone later feels like refining it, it's not hard.
1641 # terminals. If someone later feels like refining it, it's not hard.
1642 numlines = max(num_newlines,int(len_str/80)+1)
1642 numlines = max(num_newlines,int(len_str/80)+1)
1643
1643
1644 if os.name == "nt":
1644 if os.name == "nt":
1645 screen_lines_def = get_console_size(defaulty=25)[1]
1645 screen_lines_def = get_console_size(defaulty=25)[1]
1646 else:
1646 else:
1647 screen_lines_def = 25 # default value if we can't auto-determine
1647 screen_lines_def = 25 # default value if we can't auto-determine
1648
1648
1649 # auto-determine screen size
1649 # auto-determine screen size
1650 if screen_lines <= 0:
1650 if screen_lines <= 0:
1651 if TERM=='xterm':
1651 if TERM=='xterm':
1652 use_curses = USE_CURSES
1652 use_curses = USE_CURSES
1653 else:
1653 else:
1654 # curses causes problems on many terminals other than xterm.
1654 # curses causes problems on many terminals other than xterm.
1655 use_curses = False
1655 use_curses = False
1656 if use_curses:
1656 if use_curses:
1657 # There is a bug in curses, where *sometimes* it fails to properly
1657 # There is a bug in curses, where *sometimes* it fails to properly
1658 # initialize, and then after the endwin() call is made, the
1658 # initialize, and then after the endwin() call is made, the
1659 # terminal is left in an unusable state. Rather than trying to
1659 # terminal is left in an unusable state. Rather than trying to
1660 # check everytime for this (by requesting and comparing termios
1660 # check everytime for this (by requesting and comparing termios
1661 # flags each time), we just save the initial terminal state and
1661 # flags each time), we just save the initial terminal state and
1662 # unconditionally reset it every time. It's cheaper than making
1662 # unconditionally reset it every time. It's cheaper than making
1663 # the checks.
1663 # the checks.
1664 term_flags = termios.tcgetattr(sys.stdout)
1664 term_flags = termios.tcgetattr(sys.stdout)
1665 scr = curses.initscr()
1665 scr = curses.initscr()
1666 screen_lines_real,screen_cols = scr.getmaxyx()
1666 screen_lines_real,screen_cols = scr.getmaxyx()
1667 curses.endwin()
1667 curses.endwin()
1668 # Restore terminal state in case endwin() didn't.
1668 # Restore terminal state in case endwin() didn't.
1669 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
1669 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
1670 # Now we have what we needed: the screen size in rows/columns
1670 # Now we have what we needed: the screen size in rows/columns
1671 screen_lines += screen_lines_real
1671 screen_lines += screen_lines_real
1672 #print '***Screen size:',screen_lines_real,'lines x',\
1672 #print '***Screen size:',screen_lines_real,'lines x',\
1673 #screen_cols,'columns.' # dbg
1673 #screen_cols,'columns.' # dbg
1674 else:
1674 else:
1675 screen_lines += screen_lines_def
1675 screen_lines += screen_lines_def
1676
1676
1677 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1677 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1678 if numlines <= screen_lines :
1678 if numlines <= screen_lines :
1679 #print '*** normal print' # dbg
1679 #print '*** normal print' # dbg
1680 print >>Term.cout, str_toprint
1680 print >>Term.cout, str_toprint
1681 else:
1681 else:
1682 # Try to open pager and default to internal one if that fails.
1682 # Try to open pager and default to internal one if that fails.
1683 # All failure modes are tagged as 'retval=1', to match the return
1683 # All failure modes are tagged as 'retval=1', to match the return
1684 # value of a failed system command. If any intermediate attempt
1684 # value of a failed system command. If any intermediate attempt
1685 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1685 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1686 pager_cmd = get_pager_cmd(pager_cmd)
1686 pager_cmd = get_pager_cmd(pager_cmd)
1687 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1687 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1688 if os.name == 'nt':
1688 if os.name == 'nt':
1689 if pager_cmd.startswith('type'):
1689 if pager_cmd.startswith('type'):
1690 # The default WinXP 'type' command is failing on complex strings.
1690 # The default WinXP 'type' command is failing on complex strings.
1691 retval = 1
1691 retval = 1
1692 else:
1692 else:
1693 tmpname = tempfile.mktemp('.txt')
1693 tmpname = tempfile.mktemp('.txt')
1694 tmpfile = file(tmpname,'wt')
1694 tmpfile = file(tmpname,'wt')
1695 tmpfile.write(strng)
1695 tmpfile.write(strng)
1696 tmpfile.close()
1696 tmpfile.close()
1697 cmd = "%s < %s" % (pager_cmd,tmpname)
1697 cmd = "%s < %s" % (pager_cmd,tmpname)
1698 if os.system(cmd):
1698 if os.system(cmd):
1699 retval = 1
1699 retval = 1
1700 else:
1700 else:
1701 retval = None
1701 retval = None
1702 os.remove(tmpname)
1702 os.remove(tmpname)
1703 else:
1703 else:
1704 try:
1704 try:
1705 retval = None
1705 retval = None
1706 # if I use popen4, things hang. No idea why.
1706 # if I use popen4, things hang. No idea why.
1707 #pager,shell_out = os.popen4(pager_cmd)
1707 #pager,shell_out = os.popen4(pager_cmd)
1708 pager = os.popen(pager_cmd,'w')
1708 pager = os.popen(pager_cmd,'w')
1709 pager.write(strng)
1709 pager.write(strng)
1710 pager.close()
1710 pager.close()
1711 retval = pager.close() # success returns None
1711 retval = pager.close() # success returns None
1712 except IOError,msg: # broken pipe when user quits
1712 except IOError,msg: # broken pipe when user quits
1713 if msg.args == (32,'Broken pipe'):
1713 if msg.args == (32,'Broken pipe'):
1714 retval = None
1714 retval = None
1715 else:
1715 else:
1716 retval = 1
1716 retval = 1
1717 except OSError:
1717 except OSError:
1718 # Other strange problems, sometimes seen in Win2k/cygwin
1718 # Other strange problems, sometimes seen in Win2k/cygwin
1719 retval = 1
1719 retval = 1
1720 if retval is not None:
1720 if retval is not None:
1721 page_dumb(strng,screen_lines=screen_lines)
1721 page_dumb(strng,screen_lines=screen_lines)
1722
1722
1723 #----------------------------------------------------------------------------
1723 #----------------------------------------------------------------------------
1724 def page_file(fname,start = 0, pager_cmd = None):
1724 def page_file(fname,start = 0, pager_cmd = None):
1725 """Page a file, using an optional pager command and starting line.
1725 """Page a file, using an optional pager command and starting line.
1726 """
1726 """
1727
1727
1728 pager_cmd = get_pager_cmd(pager_cmd)
1728 pager_cmd = get_pager_cmd(pager_cmd)
1729 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1729 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1730
1730
1731 try:
1731 try:
1732 if os.environ['TERM'] in ['emacs','dumb']:
1732 if os.environ['TERM'] in ['emacs','dumb']:
1733 raise EnvironmentError
1733 raise EnvironmentError
1734 xsys(pager_cmd + ' ' + fname)
1734 xsys(pager_cmd + ' ' + fname)
1735 except:
1735 except:
1736 try:
1736 try:
1737 if start > 0:
1737 if start > 0:
1738 start -= 1
1738 start -= 1
1739 page(open(fname).read(),start)
1739 page(open(fname).read(),start)
1740 except:
1740 except:
1741 print 'Unable to show file',`fname`
1741 print 'Unable to show file',`fname`
1742
1742
1743
1743
1744 #----------------------------------------------------------------------------
1744 #----------------------------------------------------------------------------
1745 def snip_print(str,width = 75,print_full = 0,header = ''):
1745 def snip_print(str,width = 75,print_full = 0,header = ''):
1746 """Print a string snipping the midsection to fit in width.
1746 """Print a string snipping the midsection to fit in width.
1747
1747
1748 print_full: mode control:
1748 print_full: mode control:
1749 - 0: only snip long strings
1749 - 0: only snip long strings
1750 - 1: send to page() directly.
1750 - 1: send to page() directly.
1751 - 2: snip long strings and ask for full length viewing with page()
1751 - 2: snip long strings and ask for full length viewing with page()
1752 Return 1 if snipping was necessary, 0 otherwise."""
1752 Return 1 if snipping was necessary, 0 otherwise."""
1753
1753
1754 if print_full == 1:
1754 if print_full == 1:
1755 page(header+str)
1755 page(header+str)
1756 return 0
1756 return 0
1757
1757
1758 print header,
1758 print header,
1759 if len(str) < width:
1759 if len(str) < width:
1760 print str
1760 print str
1761 snip = 0
1761 snip = 0
1762 else:
1762 else:
1763 whalf = int((width -5)/2)
1763 whalf = int((width -5)/2)
1764 print str[:whalf] + ' <...> ' + str[-whalf:]
1764 print str[:whalf] + ' <...> ' + str[-whalf:]
1765 snip = 1
1765 snip = 1
1766 if snip and print_full == 2:
1766 if snip and print_full == 2:
1767 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1767 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1768 page(str)
1768 page(str)
1769 return snip
1769 return snip
1770
1770
1771 #****************************************************************************
1771 #****************************************************************************
1772 # lists, dicts and structures
1772 # lists, dicts and structures
1773
1773
1774 def belong(candidates,checklist):
1774 def belong(candidates,checklist):
1775 """Check whether a list of items appear in a given list of options.
1775 """Check whether a list of items appear in a given list of options.
1776
1776
1777 Returns a list of 1 and 0, one for each candidate given."""
1777 Returns a list of 1 and 0, one for each candidate given."""
1778
1778
1779 return [x in checklist for x in candidates]
1779 return [x in checklist for x in candidates]
1780
1780
1781 #----------------------------------------------------------------------------
1781 #----------------------------------------------------------------------------
1782 def uniq_stable(elems):
1782 def uniq_stable(elems):
1783 """uniq_stable(elems) -> list
1783 """uniq_stable(elems) -> list
1784
1784
1785 Return from an iterable, a list of all the unique elements in the input,
1785 Return from an iterable, a list of all the unique elements in the input,
1786 but maintaining the order in which they first appear.
1786 but maintaining the order in which they first appear.
1787
1787
1788 A naive solution to this problem which just makes a dictionary with the
1788 A naive solution to this problem which just makes a dictionary with the
1789 elements as keys fails to respect the stability condition, since
1789 elements as keys fails to respect the stability condition, since
1790 dictionaries are unsorted by nature.
1790 dictionaries are unsorted by nature.
1791
1791
1792 Note: All elements in the input must be valid dictionary keys for this
1792 Note: All elements in the input must be valid dictionary keys for this
1793 routine to work, as it internally uses a dictionary for efficiency
1793 routine to work, as it internally uses a dictionary for efficiency
1794 reasons."""
1794 reasons."""
1795
1795
1796 unique = []
1796 unique = []
1797 unique_dict = {}
1797 unique_dict = {}
1798 for nn in elems:
1798 for nn in elems:
1799 if nn not in unique_dict:
1799 if nn not in unique_dict:
1800 unique.append(nn)
1800 unique.append(nn)
1801 unique_dict[nn] = None
1801 unique_dict[nn] = None
1802 return unique
1802 return unique
1803
1803
1804 #----------------------------------------------------------------------------
1804 #----------------------------------------------------------------------------
1805 class NLprinter:
1805 class NLprinter:
1806 """Print an arbitrarily nested list, indicating index numbers.
1806 """Print an arbitrarily nested list, indicating index numbers.
1807
1807
1808 An instance of this class called nlprint is available and callable as a
1808 An instance of this class called nlprint is available and callable as a
1809 function.
1809 function.
1810
1810
1811 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1811 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1812 and using 'sep' to separate the index from the value. """
1812 and using 'sep' to separate the index from the value. """
1813
1813
1814 def __init__(self):
1814 def __init__(self):
1815 self.depth = 0
1815 self.depth = 0
1816
1816
1817 def __call__(self,lst,pos='',**kw):
1817 def __call__(self,lst,pos='',**kw):
1818 """Prints the nested list numbering levels."""
1818 """Prints the nested list numbering levels."""
1819 kw.setdefault('indent',' ')
1819 kw.setdefault('indent',' ')
1820 kw.setdefault('sep',': ')
1820 kw.setdefault('sep',': ')
1821 kw.setdefault('start',0)
1821 kw.setdefault('start',0)
1822 kw.setdefault('stop',len(lst))
1822 kw.setdefault('stop',len(lst))
1823 # we need to remove start and stop from kw so they don't propagate
1823 # we need to remove start and stop from kw so they don't propagate
1824 # into a recursive call for a nested list.
1824 # into a recursive call for a nested list.
1825 start = kw['start']; del kw['start']
1825 start = kw['start']; del kw['start']
1826 stop = kw['stop']; del kw['stop']
1826 stop = kw['stop']; del kw['stop']
1827 if self.depth == 0 and 'header' in kw.keys():
1827 if self.depth == 0 and 'header' in kw.keys():
1828 print kw['header']
1828 print kw['header']
1829
1829
1830 for idx in range(start,stop):
1830 for idx in range(start,stop):
1831 elem = lst[idx]
1831 elem = lst[idx]
1832 if type(elem)==type([]):
1832 if type(elem)==type([]):
1833 self.depth += 1
1833 self.depth += 1
1834 self.__call__(elem,itpl('$pos$idx,'),**kw)
1834 self.__call__(elem,itpl('$pos$idx,'),**kw)
1835 self.depth -= 1
1835 self.depth -= 1
1836 else:
1836 else:
1837 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1837 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1838
1838
1839 nlprint = NLprinter()
1839 nlprint = NLprinter()
1840 #----------------------------------------------------------------------------
1840 #----------------------------------------------------------------------------
1841 def all_belong(candidates,checklist):
1841 def all_belong(candidates,checklist):
1842 """Check whether a list of items ALL appear in a given list of options.
1842 """Check whether a list of items ALL appear in a given list of options.
1843
1843
1844 Returns a single 1 or 0 value."""
1844 Returns a single 1 or 0 value."""
1845
1845
1846 return 1-(0 in [x in checklist for x in candidates])
1846 return 1-(0 in [x in checklist for x in candidates])
1847
1847
1848 #----------------------------------------------------------------------------
1848 #----------------------------------------------------------------------------
1849 def sort_compare(lst1,lst2,inplace = 1):
1849 def sort_compare(lst1,lst2,inplace = 1):
1850 """Sort and compare two lists.
1850 """Sort and compare two lists.
1851
1851
1852 By default it does it in place, thus modifying the lists. Use inplace = 0
1852 By default it does it in place, thus modifying the lists. Use inplace = 0
1853 to avoid that (at the cost of temporary copy creation)."""
1853 to avoid that (at the cost of temporary copy creation)."""
1854 if not inplace:
1854 if not inplace:
1855 lst1 = lst1[:]
1855 lst1 = lst1[:]
1856 lst2 = lst2[:]
1856 lst2 = lst2[:]
1857 lst1.sort(); lst2.sort()
1857 lst1.sort(); lst2.sort()
1858 return lst1 == lst2
1858 return lst1 == lst2
1859
1859
1860 #----------------------------------------------------------------------------
1860 #----------------------------------------------------------------------------
1861 def list2dict(lst):
1861 def list2dict(lst):
1862 """Takes a list of (key,value) pairs and turns it into a dict."""
1862 """Takes a list of (key,value) pairs and turns it into a dict."""
1863
1863
1864 dic = {}
1864 dic = {}
1865 for k,v in lst: dic[k] = v
1865 for k,v in lst: dic[k] = v
1866 return dic
1866 return dic
1867
1867
1868 #----------------------------------------------------------------------------
1868 #----------------------------------------------------------------------------
1869 def list2dict2(lst,default=''):
1869 def list2dict2(lst,default=''):
1870 """Takes a list and turns it into a dict.
1870 """Takes a list and turns it into a dict.
1871 Much slower than list2dict, but more versatile. This version can take
1871 Much slower than list2dict, but more versatile. This version can take
1872 lists with sublists of arbitrary length (including sclars)."""
1872 lists with sublists of arbitrary length (including sclars)."""
1873
1873
1874 dic = {}
1874 dic = {}
1875 for elem in lst:
1875 for elem in lst:
1876 if type(elem) in (types.ListType,types.TupleType):
1876 if type(elem) in (types.ListType,types.TupleType):
1877 size = len(elem)
1877 size = len(elem)
1878 if size == 0:
1878 if size == 0:
1879 pass
1879 pass
1880 elif size == 1:
1880 elif size == 1:
1881 dic[elem] = default
1881 dic[elem] = default
1882 else:
1882 else:
1883 k,v = elem[0], elem[1:]
1883 k,v = elem[0], elem[1:]
1884 if len(v) == 1: v = v[0]
1884 if len(v) == 1: v = v[0]
1885 dic[k] = v
1885 dic[k] = v
1886 else:
1886 else:
1887 dic[elem] = default
1887 dic[elem] = default
1888 return dic
1888 return dic
1889
1889
1890 #----------------------------------------------------------------------------
1890 #----------------------------------------------------------------------------
1891 def flatten(seq):
1891 def flatten(seq):
1892 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1892 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1893
1893
1894 return [x for subseq in seq for x in subseq]
1894 return [x for subseq in seq for x in subseq]
1895
1895
1896 #----------------------------------------------------------------------------
1896 #----------------------------------------------------------------------------
1897 def get_slice(seq,start=0,stop=None,step=1):
1897 def get_slice(seq,start=0,stop=None,step=1):
1898 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1898 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1899 if stop == None:
1899 if stop == None:
1900 stop = len(seq)
1900 stop = len(seq)
1901 item = lambda i: seq[i]
1901 item = lambda i: seq[i]
1902 return map(item,xrange(start,stop,step))
1902 return map(item,xrange(start,stop,step))
1903
1903
1904 #----------------------------------------------------------------------------
1904 #----------------------------------------------------------------------------
1905 def chop(seq,size):
1905 def chop(seq,size):
1906 """Chop a sequence into chunks of the given size."""
1906 """Chop a sequence into chunks of the given size."""
1907 chunk = lambda i: seq[i:i+size]
1907 chunk = lambda i: seq[i:i+size]
1908 return map(chunk,xrange(0,len(seq),size))
1908 return map(chunk,xrange(0,len(seq),size))
1909
1909
1910 #----------------------------------------------------------------------------
1910 #----------------------------------------------------------------------------
1911 # with is a keyword as of python 2.5, so this function is renamed to withobj
1911 # with is a keyword as of python 2.5, so this function is renamed to withobj
1912 # from its old 'with' name.
1912 # from its old 'with' name.
1913 def with_obj(object, **args):
1913 def with_obj(object, **args):
1914 """Set multiple attributes for an object, similar to Pascal's with.
1914 """Set multiple attributes for an object, similar to Pascal's with.
1915
1915
1916 Example:
1916 Example:
1917 with_obj(jim,
1917 with_obj(jim,
1918 born = 1960,
1918 born = 1960,
1919 haircolour = 'Brown',
1919 haircolour = 'Brown',
1920 eyecolour = 'Green')
1920 eyecolour = 'Green')
1921
1921
1922 Credit: Greg Ewing, in
1922 Credit: Greg Ewing, in
1923 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1923 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1924
1924
1925 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1925 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1926 has become a keyword for Python 2.5, so we had to rename it."""
1926 has become a keyword for Python 2.5, so we had to rename it."""
1927
1927
1928 object.__dict__.update(args)
1928 object.__dict__.update(args)
1929
1929
1930 #----------------------------------------------------------------------------
1930 #----------------------------------------------------------------------------
1931 def setattr_list(obj,alist,nspace = None):
1931 def setattr_list(obj,alist,nspace = None):
1932 """Set a list of attributes for an object taken from a namespace.
1932 """Set a list of attributes for an object taken from a namespace.
1933
1933
1934 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1934 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1935 alist with their values taken from nspace, which must be a dict (something
1935 alist with their values taken from nspace, which must be a dict (something
1936 like locals() will often do) If nspace isn't given, locals() of the
1936 like locals() will often do) If nspace isn't given, locals() of the
1937 *caller* is used, so in most cases you can omit it.
1937 *caller* is used, so in most cases you can omit it.
1938
1938
1939 Note that alist can be given as a string, which will be automatically
1939 Note that alist can be given as a string, which will be automatically
1940 split into a list on whitespace. If given as a list, it must be a list of
1940 split into a list on whitespace. If given as a list, it must be a list of
1941 *strings* (the variable names themselves), not of variables."""
1941 *strings* (the variable names themselves), not of variables."""
1942
1942
1943 # this grabs the local variables from the *previous* call frame -- that is
1943 # this grabs the local variables from the *previous* call frame -- that is
1944 # the locals from the function that called setattr_list().
1944 # the locals from the function that called setattr_list().
1945 # - snipped from weave.inline()
1945 # - snipped from weave.inline()
1946 if nspace is None:
1946 if nspace is None:
1947 call_frame = sys._getframe().f_back
1947 call_frame = sys._getframe().f_back
1948 nspace = call_frame.f_locals
1948 nspace = call_frame.f_locals
1949
1949
1950 if type(alist) in StringTypes:
1950 if type(alist) in StringTypes:
1951 alist = alist.split()
1951 alist = alist.split()
1952 for attr in alist:
1952 for attr in alist:
1953 val = eval(attr,nspace)
1953 val = eval(attr,nspace)
1954 setattr(obj,attr,val)
1954 setattr(obj,attr,val)
1955
1955
1956 #----------------------------------------------------------------------------
1956 #----------------------------------------------------------------------------
1957 def getattr_list(obj,alist,*args):
1957 def getattr_list(obj,alist,*args):
1958 """getattr_list(obj,alist[, default]) -> attribute list.
1958 """getattr_list(obj,alist[, default]) -> attribute list.
1959
1959
1960 Get a list of named attributes for an object. When a default argument is
1960 Get a list of named attributes for an object. When a default argument is
1961 given, it is returned when the attribute doesn't exist; without it, an
1961 given, it is returned when the attribute doesn't exist; without it, an
1962 exception is raised in that case.
1962 exception is raised in that case.
1963
1963
1964 Note that alist can be given as a string, which will be automatically
1964 Note that alist can be given as a string, which will be automatically
1965 split into a list on whitespace. If given as a list, it must be a list of
1965 split into a list on whitespace. If given as a list, it must be a list of
1966 *strings* (the variable names themselves), not of variables."""
1966 *strings* (the variable names themselves), not of variables."""
1967
1967
1968 if type(alist) in StringTypes:
1968 if type(alist) in StringTypes:
1969 alist = alist.split()
1969 alist = alist.split()
1970 if args:
1970 if args:
1971 if len(args)==1:
1971 if len(args)==1:
1972 default = args[0]
1972 default = args[0]
1973 return map(lambda attr: getattr(obj,attr,default),alist)
1973 return map(lambda attr: getattr(obj,attr,default),alist)
1974 else:
1974 else:
1975 raise ValueError,'getattr_list() takes only one optional argument'
1975 raise ValueError,'getattr_list() takes only one optional argument'
1976 else:
1976 else:
1977 return map(lambda attr: getattr(obj,attr),alist)
1977 return map(lambda attr: getattr(obj,attr),alist)
1978
1978
1979 #----------------------------------------------------------------------------
1979 #----------------------------------------------------------------------------
1980 def map_method(method,object_list,*argseq,**kw):
1980 def map_method(method,object_list,*argseq,**kw):
1981 """map_method(method,object_list,*args,**kw) -> list
1981 """map_method(method,object_list,*args,**kw) -> list
1982
1982
1983 Return a list of the results of applying the methods to the items of the
1983 Return a list of the results of applying the methods to the items of the
1984 argument sequence(s). If more than one sequence is given, the method is
1984 argument sequence(s). If more than one sequence is given, the method is
1985 called with an argument list consisting of the corresponding item of each
1985 called with an argument list consisting of the corresponding item of each
1986 sequence. All sequences must be of the same length.
1986 sequence. All sequences must be of the same length.
1987
1987
1988 Keyword arguments are passed verbatim to all objects called.
1988 Keyword arguments are passed verbatim to all objects called.
1989
1989
1990 This is Python code, so it's not nearly as fast as the builtin map()."""
1990 This is Python code, so it's not nearly as fast as the builtin map()."""
1991
1991
1992 out_list = []
1992 out_list = []
1993 idx = 0
1993 idx = 0
1994 for object in object_list:
1994 for object in object_list:
1995 try:
1995 try:
1996 handler = getattr(object, method)
1996 handler = getattr(object, method)
1997 except AttributeError:
1997 except AttributeError:
1998 out_list.append(None)
1998 out_list.append(None)
1999 else:
1999 else:
2000 if argseq:
2000 if argseq:
2001 args = map(lambda lst:lst[idx],argseq)
2001 args = map(lambda lst:lst[idx],argseq)
2002 #print 'ob',object,'hand',handler,'ar',args # dbg
2002 #print 'ob',object,'hand',handler,'ar',args # dbg
2003 out_list.append(handler(args,**kw))
2003 out_list.append(handler(args,**kw))
2004 else:
2004 else:
2005 out_list.append(handler(**kw))
2005 out_list.append(handler(**kw))
2006 idx += 1
2006 idx += 1
2007 return out_list
2007 return out_list
2008
2008
2009 #----------------------------------------------------------------------------
2009 #----------------------------------------------------------------------------
2010 def get_class_members(cls):
2010 def get_class_members(cls):
2011 ret = dir(cls)
2011 ret = dir(cls)
2012 if hasattr(cls,'__bases__'):
2012 if hasattr(cls,'__bases__'):
2013 for base in cls.__bases__:
2013 for base in cls.__bases__:
2014 ret.extend(get_class_members(base))
2014 ret.extend(get_class_members(base))
2015 return ret
2015 return ret
2016
2016
2017 #----------------------------------------------------------------------------
2017 #----------------------------------------------------------------------------
2018 def dir2(obj):
2018 def dir2(obj):
2019 """dir2(obj) -> list of strings
2019 """dir2(obj) -> list of strings
2020
2020
2021 Extended version of the Python builtin dir(), which does a few extra
2021 Extended version of the Python builtin dir(), which does a few extra
2022 checks, and supports common objects with unusual internals that confuse
2022 checks, and supports common objects with unusual internals that confuse
2023 dir(), such as Traits and PyCrust.
2023 dir(), such as Traits and PyCrust.
2024
2024
2025 This version is guaranteed to return only a list of true strings, whereas
2025 This version is guaranteed to return only a list of true strings, whereas
2026 dir() returns anything that objects inject into themselves, even if they
2026 dir() returns anything that objects inject into themselves, even if they
2027 are later not really valid for attribute access (many extension libraries
2027 are later not really valid for attribute access (many extension libraries
2028 have such bugs).
2028 have such bugs).
2029 """
2029 """
2030
2030
2031 # Start building the attribute list via dir(), and then complete it
2031 # Start building the attribute list via dir(), and then complete it
2032 # with a few extra special-purpose calls.
2032 # with a few extra special-purpose calls.
2033 words = dir(obj)
2033 words = dir(obj)
2034
2034
2035 if hasattr(obj,'__class__'):
2035 if hasattr(obj,'__class__'):
2036 words.append('__class__')
2036 words.append('__class__')
2037 words.extend(get_class_members(obj.__class__))
2037 words.extend(get_class_members(obj.__class__))
2038 #if '__base__' in words: 1/0
2038 #if '__base__' in words: 1/0
2039
2039
2040 # Some libraries (such as traits) may introduce duplicates, we want to
2040 # Some libraries (such as traits) may introduce duplicates, we want to
2041 # track and clean this up if it happens
2041 # track and clean this up if it happens
2042 may_have_dupes = False
2042 may_have_dupes = False
2043
2043
2044 # this is the 'dir' function for objects with Enthought's traits
2044 # this is the 'dir' function for objects with Enthought's traits
2045 if hasattr(obj, 'trait_names'):
2045 if hasattr(obj, 'trait_names'):
2046 try:
2046 try:
2047 words.extend(obj.trait_names())
2047 words.extend(obj.trait_names())
2048 may_have_dupes = True
2048 may_have_dupes = True
2049 except TypeError:
2049 except TypeError:
2050 # This will happen if `obj` is a class and not an instance.
2050 # This will happen if `obj` is a class and not an instance.
2051 pass
2051 pass
2052
2052
2053 # Support for PyCrust-style _getAttributeNames magic method.
2053 # Support for PyCrust-style _getAttributeNames magic method.
2054 if hasattr(obj, '_getAttributeNames'):
2054 if hasattr(obj, '_getAttributeNames'):
2055 try:
2055 try:
2056 words.extend(obj._getAttributeNames())
2056 words.extend(obj._getAttributeNames())
2057 may_have_dupes = True
2057 may_have_dupes = True
2058 except TypeError:
2058 except TypeError:
2059 # `obj` is a class and not an instance. Ignore
2059 # `obj` is a class and not an instance. Ignore
2060 # this error.
2060 # this error.
2061 pass
2061 pass
2062
2062
2063 if may_have_dupes:
2063 if may_have_dupes:
2064 # eliminate possible duplicates, as some traits may also
2064 # eliminate possible duplicates, as some traits may also
2065 # appear as normal attributes in the dir() call.
2065 # appear as normal attributes in the dir() call.
2066 words = list(set(words))
2066 words = list(set(words))
2067 words.sort()
2067 words.sort()
2068
2068
2069 # filter out non-string attributes which may be stuffed by dir() calls
2069 # filter out non-string attributes which may be stuffed by dir() calls
2070 # and poor coding in third-party modules
2070 # and poor coding in third-party modules
2071 return [w for w in words if isinstance(w, basestring)]
2071 return [w for w in words if isinstance(w, basestring)]
2072
2072
2073 #----------------------------------------------------------------------------
2073 #----------------------------------------------------------------------------
2074 def import_fail_info(mod_name,fns=None):
2074 def import_fail_info(mod_name,fns=None):
2075 """Inform load failure for a module."""
2075 """Inform load failure for a module."""
2076
2076
2077 if fns == None:
2077 if fns == None:
2078 warn("Loading of %s failed.\n" % (mod_name,))
2078 warn("Loading of %s failed.\n" % (mod_name,))
2079 else:
2079 else:
2080 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
2080 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
2081
2081
2082 #----------------------------------------------------------------------------
2082 #----------------------------------------------------------------------------
2083 # Proposed popitem() extension, written as a method
2083 # Proposed popitem() extension, written as a method
2084
2084
2085
2085
2086 class NotGiven: pass
2086 class NotGiven: pass
2087
2087
2088 def popkey(dct,key,default=NotGiven):
2088 def popkey(dct,key,default=NotGiven):
2089 """Return dct[key] and delete dct[key].
2089 """Return dct[key] and delete dct[key].
2090
2090
2091 If default is given, return it if dct[key] doesn't exist, otherwise raise
2091 If default is given, return it if dct[key] doesn't exist, otherwise raise
2092 KeyError. """
2092 KeyError. """
2093
2093
2094 try:
2094 try:
2095 val = dct[key]
2095 val = dct[key]
2096 except KeyError:
2096 except KeyError:
2097 if default is NotGiven:
2097 if default is NotGiven:
2098 raise
2098 raise
2099 else:
2099 else:
2100 return default
2100 return default
2101 else:
2101 else:
2102 del dct[key]
2102 del dct[key]
2103 return val
2103 return val
2104
2104
2105 def wrap_deprecated(func, suggest = '<nothing>'):
2105 def wrap_deprecated(func, suggest = '<nothing>'):
2106 def newFunc(*args, **kwargs):
2106 def newFunc(*args, **kwargs):
2107 warnings.warn("Call to deprecated function %s, use %s instead" %
2107 warnings.warn("Call to deprecated function %s, use %s instead" %
2108 ( func.__name__, suggest),
2108 ( func.__name__, suggest),
2109 category=DeprecationWarning,
2109 category=DeprecationWarning,
2110 stacklevel = 2)
2110 stacklevel = 2)
2111 return func(*args, **kwargs)
2111 return func(*args, **kwargs)
2112 return newFunc
2112 return newFunc
2113
2113
2114
2114
2115 def _num_cpus_unix():
2115 def _num_cpus_unix():
2116 """Return the number of active CPUs on a Unix system."""
2116 """Return the number of active CPUs on a Unix system."""
2117 return os.sysconf("SC_NPROCESSORS_ONLN")
2117 return os.sysconf("SC_NPROCESSORS_ONLN")
2118
2118
2119
2119
2120 def _num_cpus_darwin():
2120 def _num_cpus_darwin():
2121 """Return the number of active CPUs on a Darwin system."""
2121 """Return the number of active CPUs on a Darwin system."""
2122 p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)
2122 p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)
2123 return p.stdout.read()
2123 return p.stdout.read()
2124
2124
2125
2125
2126 def _num_cpus_windows():
2126 def _num_cpus_windows():
2127 """Return the number of active CPUs on a Windows system."""
2127 """Return the number of active CPUs on a Windows system."""
2128 return os.environ.get("NUMBER_OF_PROCESSORS")
2128 return os.environ.get("NUMBER_OF_PROCESSORS")
2129
2129
2130
2130
2131 def num_cpus():
2131 def num_cpus():
2132 """Return the effective number of CPUs in the system as an integer.
2132 """Return the effective number of CPUs in the system as an integer.
2133
2133
2134 This cross-platform function makes an attempt at finding the total number of
2134 This cross-platform function makes an attempt at finding the total number of
2135 available CPUs in the system, as returned by various underlying system and
2135 available CPUs in the system, as returned by various underlying system and
2136 python calls.
2136 python calls.
2137
2137
2138 If it can't find a sensible answer, it returns 1 (though an error *may* make
2138 If it can't find a sensible answer, it returns 1 (though an error *may* make
2139 it return a large positive number that's actually incorrect).
2139 it return a large positive number that's actually incorrect).
2140 """
2140 """
2141
2141
2142 # Many thanks to the Parallel Python project (http://www.parallelpython.com)
2142 # Many thanks to the Parallel Python project (http://www.parallelpython.com)
2143 # for the names of the keys we needed to look up for this function. This
2143 # for the names of the keys we needed to look up for this function. This
2144 # code was inspired by their equivalent function.
2144 # code was inspired by their equivalent function.
2145
2145
2146 ncpufuncs = {'Linux':_num_cpus_unix,
2146 ncpufuncs = {'Linux':_num_cpus_unix,
2147 'Darwin':_num_cpus_darwin,
2147 'Darwin':_num_cpus_darwin,
2148 'Windows':_num_cpus_windows,
2148 'Windows':_num_cpus_windows,
2149 # On Vista, python < 2.5.2 has a bug and returns 'Microsoft'
2149 # On Vista, python < 2.5.2 has a bug and returns 'Microsoft'
2150 # See http://bugs.python.org/issue1082 for details.
2150 # See http://bugs.python.org/issue1082 for details.
2151 'Microsoft':_num_cpus_windows,
2151 'Microsoft':_num_cpus_windows,
2152 }
2152 }
2153
2153
2154 ncpufunc = ncpufuncs.get(platform.system(),
2154 ncpufunc = ncpufuncs.get(platform.system(),
2155 # default to unix version (Solaris, AIX, etc)
2155 # default to unix version (Solaris, AIX, etc)
2156 _num_cpus_unix)
2156 _num_cpus_unix)
2157
2157
2158 try:
2158 try:
2159 ncpus = max(1,int(ncpufunc()))
2159 ncpus = max(1,int(ncpufunc()))
2160 except:
2160 except:
2161 ncpus = 1
2161 ncpus = 1
2162 return ncpus
2162 return ncpus
2163
2163
2164 #*************************** end of file <genutils.py> **********************
2164 #*************************** end of file <genutils.py> **********************
@@ -1,687 +1,686 b''
1 """IPython customization API
1 """IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 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
31 def ankka_f(self, arg):
30 def ankka_f(self, arg):
32 print 'Ankka',self,'says uppercase:',arg.upper()
31 print 'Ankka',self,'says uppercase:',arg.upper()
33
32
34 ip.expose_magic('ankka',ankka_f)
33 ip.expose_magic('ankka',ankka_f)
35
34
36 ip.magic('alias sayhi echo "Testing, hi ok"')
35 ip.magic('alias sayhi echo "Testing, hi ok"')
37 ip.magic('alias helloworld echo "Hello world"')
36 ip.magic('alias helloworld echo "Hello world"')
38 ip.system('pwd')
37 ip.system('pwd')
39
38
40 ip.ex('import re')
39 ip.ex('import re')
41 ip.ex('''
40 ip.ex('''
42 def funcci(a,b):
41 def funcci(a,b):
43 print a+b
42 print a+b
44 print funcci(3,4)
43 print funcci(3,4)
45 ''')
44 ''')
46 ip.ex('funcci(348,9)')
45 ip.ex('funcci(348,9)')
47
46
48 def jed_editor(self,filename, linenum=None):
47 def jed_editor(self,filename, linenum=None):
49 print 'Calling my own editor, jed ... via hook!'
48 print 'Calling my own editor, jed ... via hook!'
50 import os
49 import os
51 if linenum is None: linenum = 0
50 if linenum is None: linenum = 0
52 os.system('jed +%d %s' % (linenum, filename))
51 os.system('jed +%d %s' % (linenum, filename))
53 print 'exiting jed'
52 print 'exiting jed'
54
53
55 ip.set_hook('editor',jed_editor)
54 ip.set_hook('editor',jed_editor)
56
55
57 o = ip.options
56 o = ip.options
58 o.autocall = 2 # FULL autocall mode
57 o.autocall = 2 # FULL autocall mode
59
58
60 print 'done!'
59 print 'done!'
61 """
60 """
62
61
63 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
64 # Modules and globals
63 # Modules and globals
65
64
66 # stdlib imports
65 # stdlib imports
67 import __builtin__
66 import __builtin__
68 import sys
67 import sys
69
68
70 # contains the most recently instantiated IPApi
69 # contains the most recently instantiated IPApi
71 _RECENT_IP = None
70 _RECENT_IP = None
72
71
73 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
74 # Code begins
73 # Code begins
75
74
76 class TryNext(Exception):
75 class TryNext(Exception):
77 """Try next hook exception.
76 """Try next hook exception.
78
77
79 Raise this in your hook function to indicate that the next hook handler
78 Raise this in your hook function to indicate that the next hook handler
80 should be used to handle the operation. If you pass arguments to the
79 should be used to handle the operation. If you pass arguments to the
81 constructor those arguments will be used by the next hook instead of the
80 constructor those arguments will be used by the next hook instead of the
82 original ones.
81 original ones.
83 """
82 """
84
83
85 def __init__(self, *args, **kwargs):
84 def __init__(self, *args, **kwargs):
86 self.args = args
85 self.args = args
87 self.kwargs = kwargs
86 self.kwargs = kwargs
88
87
89
88
90 class UsageError(Exception):
89 class UsageError(Exception):
91 """ Error in magic function arguments, etc.
90 """ Error in magic function arguments, etc.
92
91
93 Something that probably won't warrant a full traceback, but should
92 Something that probably won't warrant a full traceback, but should
94 nevertheless interrupt a macro / batch file.
93 nevertheless interrupt a macro / batch file.
95 """
94 """
96
95
97
96
98 class IPyAutocall:
97 class IPyAutocall:
99 """ Instances of this class are always autocalled
98 """ Instances of this class are always autocalled
100
99
101 This happens regardless of 'autocall' variable state. Use this to
100 This happens regardless of 'autocall' variable state. Use this to
102 develop macro-like mechanisms.
101 develop macro-like mechanisms.
103 """
102 """
104
103
105 def set_ip(self,ip):
104 def set_ip(self,ip):
106 """ Will be used to set _ip point to current ipython instance b/f call
105 """ Will be used to set _ip point to current ipython instance b/f call
107
106
108 Override this method if you don't want this to happen.
107 Override this method if you don't want this to happen.
109
108
110 """
109 """
111 self._ip = ip
110 self._ip = ip
112
111
113
112
114 class IPythonNotRunning:
113 class IPythonNotRunning:
115 """Dummy do-nothing class.
114 """Dummy do-nothing class.
116
115
117 Instances of this class return a dummy attribute on all accesses, which
116 Instances of this class return a dummy attribute on all accesses, which
118 can be called and warns. This makes it easier to write scripts which use
117 can be called and warns. This makes it easier to write scripts which use
119 the ipapi.get() object for informational purposes to operate both with and
118 the ipapi.get() object for informational purposes to operate both with and
120 without ipython. Obviously code which uses the ipython object for
119 without ipython. Obviously code which uses the ipython object for
121 computations will not work, but this allows a wider range of code to
120 computations will not work, but this allows a wider range of code to
122 transparently work whether ipython is being used or not."""
121 transparently work whether ipython is being used or not."""
123
122
124 def __init__(self,warn=True):
123 def __init__(self,warn=True):
125 if warn:
124 if warn:
126 self.dummy = self._dummy_warn
125 self.dummy = self._dummy_warn
127 else:
126 else:
128 self.dummy = self._dummy_silent
127 self.dummy = self._dummy_silent
129
128
130 def __str__(self):
129 def __str__(self):
131 return "<IPythonNotRunning>"
130 return "<IPythonNotRunning>"
132
131
133 __repr__ = __str__
132 __repr__ = __str__
134
133
135 def __getattr__(self,name):
134 def __getattr__(self,name):
136 return self.dummy
135 return self.dummy
137
136
138 def _dummy_warn(self,*args,**kw):
137 def _dummy_warn(self,*args,**kw):
139 """Dummy function, which doesn't do anything but warn."""
138 """Dummy function, which doesn't do anything but warn."""
140
139
141 print ("IPython is not running, this is a dummy no-op function")
140 print ("IPython is not running, this is a dummy no-op function")
142
141
143 def _dummy_silent(self,*args,**kw):
142 def _dummy_silent(self,*args,**kw):
144 """Dummy function, which doesn't do anything and emits no warnings."""
143 """Dummy function, which doesn't do anything and emits no warnings."""
145 pass
144 pass
146
145
147
146
148 def get(allow_dummy=False,dummy_warn=True):
147 def get(allow_dummy=False,dummy_warn=True):
149 """Get an IPApi object.
148 """Get an IPApi object.
150
149
151 If allow_dummy is true, returns an instance of IPythonNotRunning
150 If allow_dummy is true, returns an instance of IPythonNotRunning
152 instead of None if not running under IPython.
151 instead of None if not running under IPython.
153
152
154 If dummy_warn is false, the dummy instance will be completely silent.
153 If dummy_warn is false, the dummy instance will be completely silent.
155
154
156 Running this should be the first thing you do when writing extensions that
155 Running this should be the first thing you do when writing extensions that
157 can be imported as normal modules. You can then direct all the
156 can be imported as normal modules. You can then direct all the
158 configuration operations against the returned object.
157 configuration operations against the returned object.
159 """
158 """
160 global _RECENT_IP
159 global _RECENT_IP
161 if allow_dummy and not _RECENT_IP:
160 if allow_dummy and not _RECENT_IP:
162 _RECENT_IP = IPythonNotRunning(dummy_warn)
161 _RECENT_IP = IPythonNotRunning(dummy_warn)
163 return _RECENT_IP
162 return _RECENT_IP
164
163
165
164
166 class IPApi(object):
165 class IPApi(object):
167 """ The actual API class for configuring IPython
166 """ The actual API class for configuring IPython
168
167
169 You should do all of the IPython configuration by getting an IPApi object
168 You should do all of the IPython configuration by getting an IPApi object
170 with IPython.ipapi.get() and using the attributes and methods of the
169 with IPython.ipapi.get() and using the attributes and methods of the
171 returned object."""
170 returned object."""
172
171
173 def __init__(self,ip):
172 def __init__(self,ip):
174
173
175 global _RECENT_IP
174 global _RECENT_IP
176
175
177 # All attributes exposed here are considered to be the public API of
176 # All attributes exposed here are considered to be the public API of
178 # IPython. As needs dictate, some of these may be wrapped as
177 # IPython. As needs dictate, some of these may be wrapped as
179 # properties.
178 # properties.
180
179
181 self.magic = ip.ipmagic
180 self.magic = ip.ipmagic
182
181
183 self.system = ip.system
182 self.system = ip.system
184
183
185 self.set_hook = ip.set_hook
184 self.set_hook = ip.set_hook
186
185
187 self.set_custom_exc = ip.set_custom_exc
186 self.set_custom_exc = ip.set_custom_exc
188
187
189 self.user_ns = ip.user_ns
188 self.user_ns = ip.user_ns
190 self.user_ns['_ip'] = self
189 self.user_ns['_ip'] = self
191
190
192 self.set_crash_handler = ip.set_crash_handler
191 self.set_crash_handler = ip.set_crash_handler
193
192
194 # Session-specific data store, which can be used to store
193 # Session-specific data store, which can be used to store
195 # data that should persist through the ipython session.
194 # data that should persist through the ipython session.
196 self.meta = ip.meta
195 self.meta = ip.meta
197
196
198 # The ipython instance provided
197 # The ipython instance provided
199 self.IP = ip
198 self.IP = ip
200
199
201 self.extensions = {}
200 self.extensions = {}
202
201
203 self.dbg = DebugTools(self)
202 self.dbg = DebugTools(self)
204
203
205 _RECENT_IP = self
204 _RECENT_IP = self
206
205
207 # Use a property for some things which are added to the instance very
206 # Use a property for some things which are added to the instance very
208 # late. I don't have time right now to disentangle the initialization
207 # late. I don't have time right now to disentangle the initialization
209 # order issues, so a property lets us delay item extraction while
208 # order issues, so a property lets us delay item extraction while
210 # providing a normal attribute API.
209 # providing a normal attribute API.
211 def get_db(self):
210 def get_db(self):
212 """A handle to persistent dict-like database (a PickleShareDB object)"""
211 """A handle to persistent dict-like database (a PickleShareDB object)"""
213 return self.IP.db
212 return self.IP.db
214
213
215 db = property(get_db,None,None,get_db.__doc__)
214 db = property(get_db,None,None,get_db.__doc__)
216
215
217 def get_options(self):
216 def get_options(self):
218 """All configurable variables."""
217 """All configurable variables."""
219
218
220 # catch typos by disabling new attribute creation. If new attr creation
219 # catch typos by disabling new attribute creation. If new attr creation
221 # is in fact wanted (e.g. when exposing new options), do
220 # is in fact wanted (e.g. when exposing new options), do
222 # allow_new_attr(True) for the received rc struct.
221 # allow_new_attr(True) for the received rc struct.
223
222
224 self.IP.rc.allow_new_attr(False)
223 self.IP.rc.allow_new_attr(False)
225 return self.IP.rc
224 return self.IP.rc
226
225
227 options = property(get_options,None,None,get_options.__doc__)
226 options = property(get_options,None,None,get_options.__doc__)
228
227
229 def expose_magic(self,magicname, func):
228 def expose_magic(self,magicname, func):
230 """Expose own function as magic function for ipython
229 """Expose own function as magic function for ipython
231
230
232 def foo_impl(self,parameter_s=''):
231 def foo_impl(self,parameter_s=''):
233 'My very own magic!. (Use docstrings, IPython reads them).'
232 'My very own magic!. (Use docstrings, IPython reads them).'
234 print 'Magic function. Passed parameter is between < >:'
233 print 'Magic function. Passed parameter is between < >:'
235 print '<%s>' % parameter_s
234 print '<%s>' % parameter_s
236 print 'The self object is:',self
235 print 'The self object is:',self
237
236
238 ipapi.expose_magic('foo',foo_impl)
237 ipapi.expose_magic('foo',foo_impl)
239 """
238 """
240
239
241 import new
240 import new
242 im = new.instancemethod(func,self.IP, self.IP.__class__)
241 im = new.instancemethod(func,self.IP, self.IP.__class__)
243 old = getattr(self.IP, "magic_" + magicname, None)
242 old = getattr(self.IP, "magic_" + magicname, None)
244 if old:
243 if old:
245 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
244 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
246 (magicname,old) )
245 (magicname,old) )
247
246
248 setattr(self.IP, "magic_" + magicname, im)
247 setattr(self.IP, "magic_" + magicname, im)
249
248
250 def ex(self,cmd):
249 def ex(self,cmd):
251 """ Execute a normal python statement in user namespace """
250 """ Execute a normal python statement in user namespace """
252 exec cmd in self.user_ns
251 exec cmd in self.user_ns
253
252
254 def ev(self,expr):
253 def ev(self,expr):
255 """ Evaluate python expression expr in user namespace
254 """ Evaluate python expression expr in user namespace
256
255
257 Returns the result of evaluation"""
256 Returns the result of evaluation"""
258 return eval(expr,self.user_ns)
257 return eval(expr,self.user_ns)
259
258
260 def runlines(self,lines):
259 def runlines(self,lines):
261 """ Run the specified lines in interpreter, honoring ipython directives.
260 """ Run the specified lines in interpreter, honoring ipython directives.
262
261
263 This allows %magic and !shell escape notations.
262 This allows %magic and !shell escape notations.
264
263
265 Takes either all lines in one string or list of lines.
264 Takes either all lines in one string or list of lines.
266 """
265 """
267
266
268 def cleanup_ipy_script(script):
267 def cleanup_ipy_script(script):
269 """ Make a script safe for _ip.runlines()
268 """ Make a script safe for _ip.runlines()
270
269
271 - Removes empty lines Suffixes all indented blocks that end with
270 - Removes empty lines Suffixes all indented blocks that end with
272 - unindented lines with empty lines
271 - unindented lines with empty lines
273 """
272 """
274
273
275 res = []
274 res = []
276 lines = script.splitlines()
275 lines = script.splitlines()
277
276
278 level = 0
277 level = 0
279 for l in lines:
278 for l in lines:
280 lstripped = l.lstrip()
279 lstripped = l.lstrip()
281 stripped = l.strip()
280 stripped = l.strip()
282 if not stripped:
281 if not stripped:
283 continue
282 continue
284 newlevel = len(l) - len(lstripped)
283 newlevel = len(l) - len(lstripped)
285 def is_secondary_block_start(s):
284 def is_secondary_block_start(s):
286 if not s.endswith(':'):
285 if not s.endswith(':'):
287 return False
286 return False
288 if (s.startswith('elif') or
287 if (s.startswith('elif') or
289 s.startswith('else') or
288 s.startswith('else') or
290 s.startswith('except') or
289 s.startswith('except') or
291 s.startswith('finally')):
290 s.startswith('finally')):
292 return True
291 return True
293
292
294 if level > 0 and newlevel == 0 and \
293 if level > 0 and newlevel == 0 and \
295 not is_secondary_block_start(stripped):
294 not is_secondary_block_start(stripped):
296 # add empty line
295 # add empty line
297 res.append('')
296 res.append('')
298
297
299 res.append(l)
298 res.append(l)
300 level = newlevel
299 level = newlevel
301 return '\n'.join(res) + '\n'
300 return '\n'.join(res) + '\n'
302
301
303 if isinstance(lines,basestring):
302 if isinstance(lines,basestring):
304 script = lines
303 script = lines
305 else:
304 else:
306 script = '\n'.join(lines)
305 script = '\n'.join(lines)
307 clean=cleanup_ipy_script(script)
306 clean=cleanup_ipy_script(script)
308 # print "_ip.runlines() script:\n",clean # dbg
307 # print "_ip.runlines() script:\n",clean # dbg
309 self.IP.runlines(clean)
308 self.IP.runlines(clean)
310
309
311 def to_user_ns(self,vars, interactive = True):
310 def to_user_ns(self,vars, interactive = True):
312 """Inject a group of variables into the IPython user namespace.
311 """Inject a group of variables into the IPython user namespace.
313
312
314 Inputs:
313 Inputs:
315
314
316 - vars: string with variable names separated by whitespace, or a
315 - vars: string with variable names separated by whitespace, or a
317 dict with name/value pairs.
316 dict with name/value pairs.
318
317
319 - interactive: if True (default), the var will be listed with
318 - interactive: if True (default), the var will be listed with
320 %whos et. al.
319 %whos et. al.
321
320
322 This utility routine is meant to ease interactive debugging work,
321 This utility routine is meant to ease interactive debugging work,
323 where you want to easily propagate some internal variable in your code
322 where you want to easily propagate some internal variable in your code
324 up to the interactive namespace for further exploration.
323 up to the interactive namespace for further exploration.
325
324
326 When you run code via %run, globals in your script become visible at
325 When you run code via %run, globals in your script become visible at
327 the interactive prompt, but this doesn't happen for locals inside your
326 the interactive prompt, but this doesn't happen for locals inside your
328 own functions and methods. Yet when debugging, it is common to want
327 own functions and methods. Yet when debugging, it is common to want
329 to explore some internal variables further at the interactive propmt.
328 to explore some internal variables further at the interactive propmt.
330
329
331 Examples:
330 Examples:
332
331
333 To use this, you first must obtain a handle on the ipython object as
332 To use this, you first must obtain a handle on the ipython object as
334 indicated above, via:
333 indicated above, via:
335
334
336 import IPython.ipapi
335 import IPython.ipapi
337 ip = IPython.ipapi.get()
336 ip = IPython.ipapi.get()
338
337
339 Once this is done, inside a routine foo() where you want to expose
338 Once this is done, inside a routine foo() where you want to expose
340 variables x and y, you do the following:
339 variables x and y, you do the following:
341
340
342 def foo():
341 def foo():
343 ...
342 ...
344 x = your_computation()
343 x = your_computation()
345 y = something_else()
344 y = something_else()
346
345
347 # This pushes x and y to the interactive prompt immediately, even
346 # This pushes x and y to the interactive prompt immediately, even
348 # if this routine crashes on the next line after:
347 # if this routine crashes on the next line after:
349 ip.to_user_ns('x y')
348 ip.to_user_ns('x y')
350 ...
349 ...
351
350
352 # To expose *ALL* the local variables from the function, use:
351 # To expose *ALL* the local variables from the function, use:
353 ip.to_user_ns(locals())
352 ip.to_user_ns(locals())
354
353
355 ...
354 ...
356 # return
355 # return
357
356
358
357
359 If you need to rename variables, the dict input makes it easy. For
358 If you need to rename variables, the dict input makes it easy. For
360 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
359 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
361 in IPython user namespace:
360 in IPython user namespace:
362
361
363 ip.to_user_ns(dict(x=foo,y=bar))
362 ip.to_user_ns(dict(x=foo,y=bar))
364 """
363 """
365
364
366 # print 'vars given:',vars # dbg
365 # print 'vars given:',vars # dbg
367
366
368 # We need a dict of name/value pairs to do namespace updates.
367 # We need a dict of name/value pairs to do namespace updates.
369 if isinstance(vars,dict):
368 if isinstance(vars,dict):
370 # If a dict was given, no need to change anything.
369 # If a dict was given, no need to change anything.
371 vdict = vars
370 vdict = vars
372 elif isinstance(vars,basestring):
371 elif isinstance(vars,basestring):
373 # If a string with names was given, get the caller's frame to
372 # If a string with names was given, get the caller's frame to
374 # evaluate the given names in
373 # evaluate the given names in
375 cf = sys._getframe(1)
374 cf = sys._getframe(1)
376 vdict = {}
375 vdict = {}
377 for name in vars.split():
376 for name in vars.split():
378 try:
377 try:
379 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
378 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
380 except:
379 except:
381 print ('could not get var. %s from %s' %
380 print ('could not get var. %s from %s' %
382 (name,cf.f_code.co_name))
381 (name,cf.f_code.co_name))
383 else:
382 else:
384 raise ValueError('vars must be a string or a dict')
383 raise ValueError('vars must be a string or a dict')
385
384
386 # Propagate variables to user namespace
385 # Propagate variables to user namespace
387 self.user_ns.update(vdict)
386 self.user_ns.update(vdict)
388
387
389 # And configure interactive visibility
388 # And configure interactive visibility
390 config_ns = self.IP.user_config_ns
389 config_ns = self.IP.user_config_ns
391 if interactive:
390 if interactive:
392 for name,val in vdict.iteritems():
391 for name,val in vdict.iteritems():
393 config_ns.pop(name,None)
392 config_ns.pop(name,None)
394 else:
393 else:
395 for name,val in vdict.iteritems():
394 for name,val in vdict.iteritems():
396 config_ns[name] = val
395 config_ns[name] = val
397
396
398 def expand_alias(self,line):
397 def expand_alias(self,line):
399 """ Expand an alias in the command line
398 """ Expand an alias in the command line
400
399
401 Returns the provided command line, possibly with the first word
400 Returns the provided command line, possibly with the first word
402 (command) translated according to alias expansion rules.
401 (command) translated according to alias expansion rules.
403
402
404 [ipython]|16> _ip.expand_aliases("np myfile.txt")
403 [ipython]|16> _ip.expand_aliases("np myfile.txt")
405 <16> 'q:/opt/np/notepad++.exe myfile.txt'
404 <16> 'q:/opt/np/notepad++.exe myfile.txt'
406 """
405 """
407
406
408 pre,fn,rest = self.IP.split_user_input(line)
407 pre,fn,rest = self.IP.split_user_input(line)
409 res = pre + self.IP.expand_aliases(fn,rest)
408 res = pre + self.IP.expand_aliases(fn,rest)
410 return res
409 return res
411
410
412 def itpl(self, s, depth = 1):
411 def itpl(self, s, depth = 1):
413 """ Expand Itpl format string s.
412 """ Expand Itpl format string s.
414
413
415 Only callable from command line (i.e. prefilter results);
414 Only callable from command line (i.e. prefilter results);
416 If you use in your scripts, you need to use a bigger depth!
415 If you use in your scripts, you need to use a bigger depth!
417 """
416 """
418 return self.IP.var_expand(s, depth)
417 return self.IP.var_expand(s, depth)
419
418
420 def defalias(self, name, cmd):
419 def defalias(self, name, cmd):
421 """ Define a new alias
420 """ Define a new alias
422
421
423 _ip.defalias('bb','bldmake bldfiles')
422 _ip.defalias('bb','bldmake bldfiles')
424
423
425 Creates a new alias named 'bb' in ipython user namespace
424 Creates a new alias named 'bb' in ipython user namespace
426 """
425 """
427
426
428 self.dbg.check_hotname(name)
427 self.dbg.check_hotname(name)
429
428
430 if name in self.IP.alias_table:
429 if name in self.IP.alias_table:
431 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
430 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
432 % (name, cmd, self.IP.alias_table[name]))
431 % (name, cmd, self.IP.alias_table[name]))
433
432
434 if callable(cmd):
433 if callable(cmd):
435 self.IP.alias_table[name] = cmd
434 self.IP.alias_table[name] = cmd
436 import IPython.shadowns
435 import IPython.shadowns
437 setattr(IPython.shadowns, name,cmd)
436 setattr(IPython.shadowns, name,cmd)
438 return
437 return
439
438
440 if isinstance(cmd,basestring):
439 if isinstance(cmd,basestring):
441 nargs = cmd.count('%s')
440 nargs = cmd.count('%s')
442 if nargs>0 and cmd.find('%l')>=0:
441 if nargs>0 and cmd.find('%l')>=0:
443 raise Exception('The %s and %l specifiers are mutually '
442 raise Exception('The %s and %l specifiers are mutually '
444 'exclusive in alias definitions.')
443 'exclusive in alias definitions.')
445
444
446 self.IP.alias_table[name] = (nargs,cmd)
445 self.IP.alias_table[name] = (nargs,cmd)
447 return
446 return
448
447
449 # just put it in - it's probably (0,'foo')
448 # just put it in - it's probably (0,'foo')
450 self.IP.alias_table[name] = cmd
449 self.IP.alias_table[name] = cmd
451
450
452 def defmacro(self, *args):
451 def defmacro(self, *args):
453 """ Define a new macro
452 """ Define a new macro
454
453
455 2 forms of calling:
454 2 forms of calling:
456
455
457 mac = _ip.defmacro('print "hello"\nprint "world"')
456 mac = _ip.defmacro('print "hello"\nprint "world"')
458
457
459 (doesn't put the created macro on user namespace)
458 (doesn't put the created macro on user namespace)
460
459
461 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
460 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
462
461
463 (creates a macro named 'build' in user namespace)
462 (creates a macro named 'build' in user namespace)
464 """
463 """
465
464
466 import IPython.macro
465 import IPython.macro
467
466
468 if len(args) == 1:
467 if len(args) == 1:
469 return IPython.macro.Macro(args[0])
468 return IPython.macro.Macro(args[0])
470 elif len(args) == 2:
469 elif len(args) == 2:
471 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
470 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
472 else:
471 else:
473 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
472 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
474
473
475 def set_next_input(self, s):
474 def set_next_input(self, s):
476 """ Sets the 'default' input string for the next command line.
475 """ Sets the 'default' input string for the next command line.
477
476
478 Requires readline.
477 Requires readline.
479
478
480 Example:
479 Example:
481
480
482 [D:\ipython]|1> _ip.set_next_input("Hello Word")
481 [D:\ipython]|1> _ip.set_next_input("Hello Word")
483 [D:\ipython]|2> Hello Word_ # cursor is here
482 [D:\ipython]|2> Hello Word_ # cursor is here
484 """
483 """
485
484
486 self.IP.rl_next_input = s
485 self.IP.rl_next_input = s
487
486
488 def load(self, mod):
487 def load(self, mod):
489 """ Load an extension.
488 """ Load an extension.
490
489
491 Some modules should (or must) be 'load()':ed, rather than just imported.
490 Some modules should (or must) be 'load()':ed, rather than just imported.
492
491
493 Loading will do:
492 Loading will do:
494
493
495 - run init_ipython(ip)
494 - run init_ipython(ip)
496 - run ipython_firstrun(ip)
495 - run ipython_firstrun(ip)
497 """
496 """
498
497
499 if mod in self.extensions:
498 if mod in self.extensions:
500 # just to make sure we don't init it twice
499 # just to make sure we don't init it twice
501 # note that if you 'load' a module that has already been
500 # note that if you 'load' a module that has already been
502 # imported, init_ipython gets run anyway
501 # imported, init_ipython gets run anyway
503
502
504 return self.extensions[mod]
503 return self.extensions[mod]
505 __import__(mod)
504 __import__(mod)
506 m = sys.modules[mod]
505 m = sys.modules[mod]
507 if hasattr(m,'init_ipython'):
506 if hasattr(m,'init_ipython'):
508 m.init_ipython(self)
507 m.init_ipython(self)
509
508
510 if hasattr(m,'ipython_firstrun'):
509 if hasattr(m,'ipython_firstrun'):
511 already_loaded = self.db.get('firstrun_done', set())
510 already_loaded = self.db.get('firstrun_done', set())
512 if mod not in already_loaded:
511 if mod not in already_loaded:
513 m.ipython_firstrun(self)
512 m.ipython_firstrun(self)
514 already_loaded.add(mod)
513 already_loaded.add(mod)
515 self.db['firstrun_done'] = already_loaded
514 self.db['firstrun_done'] = already_loaded
516
515
517 self.extensions[mod] = m
516 self.extensions[mod] = m
518 return m
517 return m
519
518
520
519
521 class DebugTools:
520 class DebugTools:
522 """ Used for debugging mishaps in api usage
521 """ Used for debugging mishaps in api usage
523
522
524 So far, tracing redefinitions is supported.
523 So far, tracing redefinitions is supported.
525 """
524 """
526
525
527 def __init__(self, ip):
526 def __init__(self, ip):
528 self.ip = ip
527 self.ip = ip
529 self.debugmode = False
528 self.debugmode = False
530 self.hotnames = set()
529 self.hotnames = set()
531
530
532 def hotname(self, name_to_catch):
531 def hotname(self, name_to_catch):
533 self.hotnames.add(name_to_catch)
532 self.hotnames.add(name_to_catch)
534
533
535 def debug_stack(self, msg = None):
534 def debug_stack(self, msg = None):
536 if not self.debugmode:
535 if not self.debugmode:
537 return
536 return
538
537
539 import traceback
538 import traceback
540 if msg is not None:
539 if msg is not None:
541 print '====== %s ========' % msg
540 print '====== %s ========' % msg
542 traceback.print_stack()
541 traceback.print_stack()
543
542
544 def check_hotname(self,name):
543 def check_hotname(self,name):
545 if name in self.hotnames:
544 if name in self.hotnames:
546 self.debug_stack( "HotName '%s' caught" % name)
545 self.debug_stack( "HotName '%s' caught" % name)
547
546
548
547
549 def launch_new_instance(user_ns = None,shellclass = None):
548 def launch_new_instance(user_ns = None,shellclass = None):
550 """ Make and start a new ipython instance.
549 """ Make and start a new ipython instance.
551
550
552 This can be called even without having an already initialized
551 This can be called even without having an already initialized
553 ipython session running.
552 ipython session running.
554
553
555 This is also used as the egg entry point for the 'ipython' script.
554 This is also used as the egg entry point for the 'ipython' script.
556
555
557 """
556 """
558 ses = make_session(user_ns,shellclass)
557 ses = make_session(user_ns,shellclass)
559 ses.mainloop()
558 ses.mainloop()
560
559
561
560
562 def make_user_ns(user_ns = None):
561 def make_user_ns(user_ns = None):
563 """Return a valid user interactive namespace.
562 """Return a valid user interactive namespace.
564
563
565 This builds a dict with the minimal information needed to operate as a
564 This builds a dict with the minimal information needed to operate as a
566 valid IPython user namespace, which you can pass to the various embedding
565 valid IPython user namespace, which you can pass to the various embedding
567 classes in ipython.
566 classes in ipython.
568
567
569 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
568 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
570 to make both the local and global namespace objects simultaneously.
569 to make both the local and global namespace objects simultaneously.
571
570
572 :Parameters:
571 :Parameters:
573 user_ns : dict-like, optional
572 user_ns : dict-like, optional
574 The current user namespace. The items in this namespace should be
573 The current user namespace. The items in this namespace should be
575 included in the output. If None, an appropriate blank namespace
574 included in the output. If None, an appropriate blank namespace
576 should be created.
575 should be created.
577
576
578 :Returns:
577 :Returns:
579 A dictionary-like object to be used as the local namespace of the
578 A dictionary-like object to be used as the local namespace of the
580 interpreter.
579 interpreter.
581 """
580 """
582
581
583 raise NotImplementedError
582 raise NotImplementedError
584
583
585
584
586 def make_user_global_ns(ns = None):
585 def make_user_global_ns(ns = None):
587 """Return a valid user global namespace.
586 """Return a valid user global namespace.
588
587
589 Similar to make_user_ns(), but global namespaces are really only needed in
588 Similar to make_user_ns(), but global namespaces are really only needed in
590 embedded applications, where there is a distinction between the user's
589 embedded applications, where there is a distinction between the user's
591 interactive namespace and the global one where ipython is running.
590 interactive namespace and the global one where ipython is running.
592
591
593 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
592 This API is currently deprecated. Use ipapi.make_user_namespaces() instead
594 to make both the local and global namespace objects simultaneously.
593 to make both the local and global namespace objects simultaneously.
595
594
596 :Parameters:
595 :Parameters:
597 ns : dict, optional
596 ns : dict, optional
598 The current user global namespace. The items in this namespace
597 The current user global namespace. The items in this namespace
599 should be included in the output. If None, an appropriate blank
598 should be included in the output. If None, an appropriate blank
600 namespace should be created.
599 namespace should be created.
601
600
602 :Returns:
601 :Returns:
603 A true dict to be used as the global namespace of the interpreter.
602 A true dict to be used as the global namespace of the interpreter.
604 """
603 """
605
604
606 raise NotImplementedError
605 raise NotImplementedError
607
606
608 # Record the true objects in order to be able to test if the user has overridden
607 # Record the true objects in order to be able to test if the user has overridden
609 # these API functions.
608 # these API functions.
610 _make_user_ns = make_user_ns
609 _make_user_ns = make_user_ns
611 _make_user_global_ns = make_user_global_ns
610 _make_user_global_ns = make_user_global_ns
612
611
613
612
614 def make_user_namespaces(user_ns = None,user_global_ns = None):
613 def make_user_namespaces(user_ns = None,user_global_ns = None):
615 """Return a valid local and global user interactive namespaces.
614 """Return a valid local and global user interactive namespaces.
616
615
617 This builds a dict with the minimal information needed to operate as a
616 This builds a dict with the minimal information needed to operate as a
618 valid IPython user namespace, which you can pass to the various embedding
617 valid IPython user namespace, which you can pass to the various embedding
619 classes in ipython. The default implementation returns the same dict for
618 classes in ipython. The default implementation returns the same dict for
620 both the locals and the globals to allow functions to refer to variables in
619 both the locals and the globals to allow functions to refer to variables in
621 the namespace. Customized implementations can return different dicts. The
620 the namespace. Customized implementations can return different dicts. The
622 locals dictionary can actually be anything following the basic mapping
621 locals dictionary can actually be anything following the basic mapping
623 protocol of a dict, but the globals dict must be a true dict, not even
622 protocol of a dict, but the globals dict must be a true dict, not even
624 a subclass. It is recommended that any custom object for the locals
623 a subclass. It is recommended that any custom object for the locals
625 namespace synchronize with the globals dict somehow.
624 namespace synchronize with the globals dict somehow.
626
625
627 Raises TypeError if the provided globals namespace is not a true dict.
626 Raises TypeError if the provided globals namespace is not a true dict.
628
627
629 :Parameters:
628 :Parameters:
630 user_ns : dict-like, optional
629 user_ns : dict-like, optional
631 The current user namespace. The items in this namespace should be
630 The current user namespace. The items in this namespace should be
632 included in the output. If None, an appropriate blank namespace
631 included in the output. If None, an appropriate blank namespace
633 should be created.
632 should be created.
634 user_global_ns : dict, optional
633 user_global_ns : dict, optional
635 The current user global namespace. The items in this namespace
634 The current user global namespace. The items in this namespace
636 should be included in the output. If None, an appropriate blank
635 should be included in the output. If None, an appropriate blank
637 namespace should be created.
636 namespace should be created.
638
637
639 :Returns:
638 :Returns:
640 A tuple pair of dictionary-like object to be used as the local namespace
639 A tuple pair of dictionary-like object to be used as the local namespace
641 of the interpreter and a dict to be used as the global namespace.
640 of the interpreter and a dict to be used as the global namespace.
642 """
641 """
643
642
644 if user_ns is None:
643 if user_ns is None:
645 if make_user_ns is not _make_user_ns:
644 if make_user_ns is not _make_user_ns:
646 # Old API overridden.
645 # Old API overridden.
647 # FIXME: Issue DeprecationWarning, or just let the old API live on?
646 # FIXME: Issue DeprecationWarning, or just let the old API live on?
648 user_ns = make_user_ns(user_ns)
647 user_ns = make_user_ns(user_ns)
649 else:
648 else:
650 # Set __name__ to __main__ to better match the behavior of the
649 # Set __name__ to __main__ to better match the behavior of the
651 # normal interpreter.
650 # normal interpreter.
652 user_ns = {'__name__' :'__main__',
651 user_ns = {'__name__' :'__main__',
653 '__builtins__' : __builtin__,
652 '__builtins__' : __builtin__,
654 }
653 }
655 else:
654 else:
656 user_ns.setdefault('__name__','__main__')
655 user_ns.setdefault('__name__','__main__')
657 user_ns.setdefault('__builtins__',__builtin__)
656 user_ns.setdefault('__builtins__',__builtin__)
658
657
659 if user_global_ns is None:
658 if user_global_ns is None:
660 if make_user_global_ns is not _make_user_global_ns:
659 if make_user_global_ns is not _make_user_global_ns:
661 # Old API overridden.
660 # Old API overridden.
662 user_global_ns = make_user_global_ns(user_global_ns)
661 user_global_ns = make_user_global_ns(user_global_ns)
663 else:
662 else:
664 user_global_ns = user_ns
663 user_global_ns = user_ns
665 if type(user_global_ns) is not dict:
664 if type(user_global_ns) is not dict:
666 raise TypeError("user_global_ns must be a true dict; got %r"
665 raise TypeError("user_global_ns must be a true dict; got %r"
667 % type(user_global_ns))
666 % type(user_global_ns))
668
667
669 return user_ns, user_global_ns
668 return user_ns, user_global_ns
670
669
671
670
672 def make_session(user_ns = None, shellclass = None):
671 def make_session(user_ns = None, shellclass = None):
673 """Makes, but does not launch an IPython session.
672 """Makes, but does not launch an IPython session.
674
673
675 Later on you can call obj.mainloop() on the returned object.
674 Later on you can call obj.mainloop() on the returned object.
676
675
677 Inputs:
676 Inputs:
678
677
679 - user_ns(None): a dict to be used as the user's namespace with initial
678 - user_ns(None): a dict to be used as the user's namespace with initial
680 data.
679 data.
681
680
682 WARNING: This should *not* be run when a session exists already."""
681 WARNING: This should *not* be run when a session exists already."""
683
682
684 import IPython.Shell
683 import IPython.Shell
685 if shellclass is None:
684 if shellclass is None:
686 return IPython.Shell.start(user_ns)
685 return IPython.Shell.start(user_ns)
687 return shellclass(user_ns = user_ns)
686 return shellclass(user_ns = user_ns)
@@ -1,197 +1,197 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 __docformat__ = "restructuredtext en"
3 __docformat__ = "restructuredtext en"
4
4
5 #-------------------------------------------------------------------------------
5 #-------------------------------------------------------------------------------
6 # Copyright (C) 2008 The IPython Development Team
6 # Copyright (C) 2008 The IPython Development Team
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-------------------------------------------------------------------------------
10 #-------------------------------------------------------------------------------
11
11
12 #-------------------------------------------------------------------------------
12 #-------------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-------------------------------------------------------------------------------
14 #-------------------------------------------------------------------------------
15
15
16 import os
16 import os
17 import sys
17 import sys
18
18
19
19
20 # This class is mostly taken from IPython.
20 # This class is mostly taken from IPython.
21 class InputList(list):
21 class InputList(list):
22 """ Class to store user input.
22 """ Class to store user input.
23
23
24 It's basically a list, but slices return a string instead of a list, thus
24 It's basically a list, but slices return a string instead of a list, thus
25 allowing things like (assuming 'In' is an instance):
25 allowing things like (assuming 'In' is an instance):
26
26
27 exec In[4:7]
27 exec In[4:7]
28
28
29 or
29 or
30
30
31 exec In[5:9] + In[14] + In[21:25]
31 exec In[5:9] + In[14] + In[21:25]
32 """
32 """
33
33
34 def __getslice__(self, i, j):
34 def __getslice__(self, i, j):
35 return ''.join(list.__getslice__(self, i, j))
35 return ''.join(list.__getslice__(self, i, j))
36
36
37 def add(self, index, command):
37 def add(self, index, command):
38 """ Add a command to the list with the appropriate index.
38 """ Add a command to the list with the appropriate index.
39
39
40 If the index is greater than the current length of the list, empty
40 If the index is greater than the current length of the list, empty
41 strings are added in between.
41 strings are added in between.
42 """
42 """
43
43
44 length = len(self)
44 length = len(self)
45 if length == index:
45 if length == index:
46 self.append(command)
46 self.append(command)
47 elif length > index:
47 elif length > index:
48 self[index] = command
48 self[index] = command
49 else:
49 else:
50 extras = index - length
50 extras = index - length
51 self.extend([''] * extras)
51 self.extend([''] * extras)
52 self.append(command)
52 self.append(command)
53
53
54
54
55 class Bunch(dict):
55 class Bunch(dict):
56 """ A dictionary that exposes its keys as attributes.
56 """ A dictionary that exposes its keys as attributes.
57 """
57 """
58
58
59 def __init__(self, *args, **kwds):
59 def __init__(self, *args, **kwds):
60 dict.__init__(self, *args, **kwds)
60 dict.__init__(self, *args, **kwds)
61 self.__dict__ = self
61 self.__dict__ = self
62
62
63
63
64 def esc_quotes(strng):
64 def esc_quotes(strng):
65 """ Return the input string with single and double quotes escaped out.
65 """ Return the input string with single and double quotes escaped out.
66 """
66 """
67
67
68 return strng.replace('"', '\\"').replace("'", "\\'")
68 return strng.replace('"', '\\"').replace("'", "\\'")
69
69
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.
78 """
78 """
79
79
80 tail = ''
80 tail = ''
81 tailpadding = ''
81 tailpadding = ''
82 raw = ''
82 raw = ''
83 if "\\" in s:
83 if "\\" in s:
84 raw = 'r'
84 raw = 'r'
85 if s.endswith('\\'):
85 if s.endswith('\\'):
86 tail = '[:-1]'
86 tail = '[:-1]'
87 tailpadding = '_'
87 tailpadding = '_'
88 if '"' not in s:
88 if '"' not in s:
89 quote = '"'
89 quote = '"'
90 elif "'" not in s:
90 elif "'" not in s:
91 quote = "'"
91 quote = "'"
92 elif '"""' not in s and not s.endswith('"'):
92 elif '"""' not in s and not s.endswith('"'):
93 quote = '"""'
93 quote = '"""'
94 elif "'''" not in s and not s.endswith("'"):
94 elif "'''" not in s and not s.endswith("'"):
95 quote = "'''"
95 quote = "'''"
96 else:
96 else:
97 # Give up, backslash-escaped string will do
97 # Give up, backslash-escaped string will do
98 return '"%s"' % esc_quotes(s)
98 return '"%s"' % esc_quotes(s)
99 res = ''.join([raw, quote, s, tailpadding, quote, tail])
99 res = ''.join([raw, quote, s, tailpadding, quote, tail])
100 return res
100 return res
101
101
102 # This function is used by ipython in a lot of places to make system calls.
102 # This function is used by ipython in a lot of places to make system calls.
103 # We need it to be slightly different under win32, due to the vagaries of
103 # We need it to be slightly different under win32, due to the vagaries of
104 # 'network shares'. A win32 override is below.
104 # 'network shares'. A win32 override is below.
105
105
106 def system_shell(cmd, verbose=False, debug=False, header=''):
106 def system_shell(cmd, verbose=False, debug=False, header=''):
107 """ Execute a command in the system shell; always return None.
107 """ Execute a command in the system shell; always return None.
108
108
109 Parameters
109 Parameters
110 ----------
110 ----------
111 cmd : str
111 cmd : str
112 The command to execute.
112 The command to execute.
113 verbose : bool
113 verbose : bool
114 If True, print the command to be executed.
114 If True, print the command to be executed.
115 debug : bool
115 debug : bool
116 Only print, do not actually execute.
116 Only print, do not actually execute.
117 header : str
117 header : str
118 Header to print to screen prior to the executed command. No extra
118 Header to print to screen prior to the executed command. No extra
119 newlines are added.
119 newlines are added.
120
120
121 Description
121 Description
122 -----------
122 -----------
123 This returns None so it can be conveniently used in interactive loops
123 This returns None so it can be conveniently used in interactive loops
124 without getting the return value (typically 0) printed many times.
124 without getting the return value (typically 0) printed many times.
125 """
125 """
126
126
127 if verbose or debug:
127 if verbose or debug:
128 print header + cmd
128 print header + cmd
129
129
130 # Flush stdout so we don't mangle python's buffering.
130 # Flush stdout so we don't mangle python's buffering.
131 sys.stdout.flush()
131 sys.stdout.flush()
132 if not debug:
132 if not debug:
133 os.system(cmd)
133 os.system(cmd)
134
134
135 # Override shell() for win32 to deal with network shares.
135 # Override shell() for win32 to deal with network shares.
136 if os.name in ('nt', 'dos'):
136 if os.name in ('nt', 'dos'):
137
137
138 system_shell_ori = system_shell
138 system_shell_ori = system_shell
139
139
140 def system_shell(cmd, verbose=False, debug=False, header=''):
140 def system_shell(cmd, verbose=False, debug=False, header=''):
141 if os.getcwd().startswith(r"\\"):
141 if os.getcwd().startswith(r"\\"):
142 path = os.getcwd()
142 path = os.getcwd()
143 # Change to c drive (cannot be on UNC-share when issuing os.system,
143 # Change to c drive (cannot be on UNC-share when issuing os.system,
144 # as cmd.exe cannot handle UNC addresses).
144 # as cmd.exe cannot handle UNC addresses).
145 os.chdir("c:")
145 os.chdir("c:")
146 # Issue pushd to the UNC-share and then run the command.
146 # Issue pushd to the UNC-share and then run the command.
147 try:
147 try:
148 system_shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
148 system_shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
149 finally:
149 finally:
150 os.chdir(path)
150 os.chdir(path)
151 else:
151 else:
152 system_shell_ori(cmd,verbose,debug,header)
152 system_shell_ori(cmd,verbose,debug,header)
153
153
154 system_shell.__doc__ = system_shell_ori.__doc__
154 system_shell.__doc__ = system_shell_ori.__doc__
155
155
156 def getoutputerror(cmd, verbose=False, debug=False, header='', split=False):
156 def getoutputerror(cmd, verbose=False, debug=False, header='', split=False):
157 """ Executes a command and returns the output.
157 """ Executes a command and returns the output.
158
158
159 Parameters
159 Parameters
160 ----------
160 ----------
161 cmd : str
161 cmd : str
162 The command to execute.
162 The command to execute.
163 verbose : bool
163 verbose : bool
164 If True, print the command to be executed.
164 If True, print the command to be executed.
165 debug : bool
165 debug : bool
166 Only print, do not actually execute.
166 Only print, do not actually execute.
167 header : str
167 header : str
168 Header to print to screen prior to the executed command. No extra
168 Header to print to screen prior to the executed command. No extra
169 newlines are added.
169 newlines are added.
170 split : bool
170 split : bool
171 If True, return the output as a list split on newlines.
171 If True, return the output as a list split on newlines.
172
172
173 """
173 """
174
174
175 if verbose or debug:
175 if verbose or debug:
176 print header+cmd
176 print header+cmd
177
177
178 if not cmd:
178 if not cmd:
179 # Return empty lists or strings.
179 # Return empty lists or strings.
180 if split:
180 if split:
181 return [], []
181 return [], []
182 else:
182 else:
183 return '', ''
183 return '', ''
184
184
185 if not debug:
185 if not debug:
186 # fixme: use subprocess.
186 # fixme: use subprocess.
187 pin,pout,perr = os.popen3(cmd)
187 pin,pout,perr = os.popen3(cmd)
188 tout = pout.read().rstrip()
188 tout = pout.read().rstrip()
189 terr = perr.read().rstrip()
189 terr = perr.read().rstrip()
190 pin.close()
190 pin.close()
191 pout.close()
191 pout.close()
192 perr.close()
192 perr.close()
193 if split:
193 if split:
194 return tout.split('\n'), terr.split('\n')
194 return tout.split('\n'), terr.split('\n')
195 else:
195 else:
196 return tout, terr
196 return tout, terr
197
197
@@ -1,244 +1,244 b''
1 """Decorators for labeling test objects.
1 """Decorators for labeling test objects.
2
2
3 Decorators that merely return a modified version of the original function
3 Decorators that merely return a modified version of the original function
4 object are straightforward. Decorators that return a new function object need
4 object are straightforward. Decorators that return a new function object need
5 to use nose.tools.make_decorator(original_function)(decorator) in returning the
5 to use nose.tools.make_decorator(original_function)(decorator) in returning the
6 decorator, in order to preserve metadata such as function name, setup and
6 decorator, in order to preserve metadata such as function name, setup and
7 teardown functions and so on - see nose.tools for more information.
7 teardown functions and so on - see nose.tools for more information.
8
8
9 This module provides a set of useful decorators meant to be ready to use in
9 This module provides a set of useful decorators meant to be ready to use in
10 your own tests. See the bottom of the file for the ready-made ones, and if you
10 your own tests. See the bottom of the file for the ready-made ones, and if you
11 find yourself writing a new one that may be of generic use, add it here.
11 find yourself writing a new one that may be of generic use, add it here.
12
12
13 NOTE: This file contains IPython-specific decorators and imports the
13 NOTE: This file contains IPython-specific decorators and imports the
14 numpy.testing.decorators file, which we've copied verbatim. Any of our own
14 numpy.testing.decorators file, which we've copied verbatim. Any of our own
15 code will be added at the bottom if we end up extending this.
15 code will be added at the bottom if we end up extending this.
16 """
16 """
17
17
18 # Stdlib imports
18 # Stdlib imports
19 import inspect
19 import inspect
20 import sys
20 import sys
21
21
22 # Third-party imports
22 # Third-party imports
23
23
24 # This is Michele Simionato's decorator module, also kept verbatim.
24 # This is Michele Simionato's decorator module, also kept verbatim.
25 from decorator_msim import decorator, update_wrapper
25 from decorator_msim import decorator, update_wrapper
26
26
27 # Grab the numpy-specific decorators which we keep in a file that we
27 # Grab the numpy-specific decorators which we keep in a file that we
28 # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy
28 # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy
29 # of numpy.testing.decorators.
29 # of numpy.testing.decorators.
30 from decorators_numpy import *
30 from decorators_numpy import *
31
31
32 ##############################################################################
32 ##############################################################################
33 # Local code begins
33 # Local code begins
34
34
35 # Utility functions
35 # Utility functions
36
36
37 def apply_wrapper(wrapper,func):
37 def apply_wrapper(wrapper,func):
38 """Apply a wrapper to a function for decoration.
38 """Apply a wrapper to a function for decoration.
39
39
40 This mixes Michele Simionato's decorator tool with nose's make_decorator,
40 This mixes Michele Simionato's decorator tool with nose's make_decorator,
41 to apply a wrapper in a decorator so that all nose attributes, as well as
41 to apply a wrapper in a decorator so that all nose attributes, as well as
42 function signature and other properties, survive the decoration cleanly.
42 function signature and other properties, survive the decoration cleanly.
43 This will ensure that wrapped functions can still be well introspected via
43 This will ensure that wrapped functions can still be well introspected via
44 IPython, for example.
44 IPython, for example.
45 """
45 """
46 import nose.tools
46 import nose.tools
47
47
48 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
48 return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
49
49
50
50
51 def make_label_dec(label,ds=None):
51 def make_label_dec(label,ds=None):
52 """Factory function to create a decorator that applies one or more labels.
52 """Factory function to create a decorator that applies one or more labels.
53
53
54 :Parameters:
54 :Parameters:
55 label : string or sequence
55 label : string or sequence
56 One or more labels that will be applied by the decorator to the functions
56 One or more labels that will be applied by the decorator to the functions
57 it decorates. Labels are attributes of the decorated function with their
57 it decorates. Labels are attributes of the decorated function with their
58 value set to True.
58 value set to True.
59
59
60 :Keywords:
60 :Keywords:
61 ds : string
61 ds : string
62 An optional docstring for the resulting decorator. If not given, a
62 An optional docstring for the resulting decorator. If not given, a
63 default docstring is auto-generated.
63 default docstring is auto-generated.
64
64
65 :Returns:
65 :Returns:
66 A decorator.
66 A decorator.
67
67
68 :Examples:
68 :Examples:
69
69
70 A simple labeling decorator:
70 A simple labeling decorator:
71 >>> slow = make_label_dec('slow')
71 >>> slow = make_label_dec('slow')
72 >>> print slow.__doc__
72 >>> print slow.__doc__
73 Labels a test as 'slow'.
73 Labels a test as 'slow'.
74
74
75 And one that uses multiple labels and a custom docstring:
75 And one that uses multiple labels and a custom docstring:
76 >>> rare = make_label_dec(['slow','hard'],
76 >>> rare = make_label_dec(['slow','hard'],
77 ... "Mix labels 'slow' and 'hard' for rare tests.")
77 ... "Mix labels 'slow' and 'hard' for rare tests.")
78 >>> print rare.__doc__
78 >>> print rare.__doc__
79 Mix labels 'slow' and 'hard' for rare tests.
79 Mix labels 'slow' and 'hard' for rare tests.
80
80
81 Now, let's test using this one:
81 Now, let's test using this one:
82 >>> @rare
82 >>> @rare
83 ... def f(): pass
83 ... def f(): pass
84 ...
84 ...
85 >>>
85 >>>
86 >>> f.slow
86 >>> f.slow
87 True
87 True
88 >>> f.hard
88 >>> f.hard
89 True
89 True
90 """
90 """
91
91
92 if isinstance(label,basestring):
92 if isinstance(label,basestring):
93 labels = [label]
93 labels = [label]
94 else:
94 else:
95 labels = label
95 labels = label
96
96
97 # Validate that the given label(s) are OK for use in setattr() by doing a
97 # Validate that the given label(s) are OK for use in setattr() by doing a
98 # dry run on a dummy function.
98 # dry run on a dummy function.
99 tmp = lambda : None
99 tmp = lambda : None
100 for label in labels:
100 for label in labels:
101 setattr(tmp,label,True)
101 setattr(tmp,label,True)
102
102
103 # This is the actual decorator we'll return
103 # This is the actual decorator we'll return
104 def decor(f):
104 def decor(f):
105 for label in labels:
105 for label in labels:
106 setattr(f,label,True)
106 setattr(f,label,True)
107 return f
107 return f
108
108
109 # Apply the user's docstring, or autogenerate a basic one
109 # Apply the user's docstring, or autogenerate a basic one
110 if ds is None:
110 if ds is None:
111 ds = "Labels a test as %r." % label
111 ds = "Labels a test as %r." % label
112 decor.__doc__ = ds
112 decor.__doc__ = ds
113
113
114 return decor
114 return decor
115
115
116
116
117 # Inspired by numpy's skipif, but uses the full apply_wrapper utility to
117 # Inspired by numpy's skipif, but uses the full apply_wrapper utility to
118 # preserve function metadata better and allows the skip condition to be a
118 # preserve function metadata better and allows the skip condition to be a
119 # callable.
119 # callable.
120 def skipif(skip_condition, msg=None):
120 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
128 is useful for tests that may require costly imports, to delay the cost
128 is useful for tests that may require costly imports, to delay the cost
129 until the test suite is actually executed.
129 until the test suite is actually executed.
130 msg : string
130 msg : string
131 Message to give on raising a SkipTest exception
131 Message to give on raising a SkipTest exception
132
132
133 Returns
133 Returns
134 -------
134 -------
135 decorator : function
135 decorator : function
136 Decorator, which, when applied to a function, causes SkipTest
136 Decorator, which, when applied to a function, causes SkipTest
137 to be raised when the skip_condition was True, and the function
137 to be raised when the skip_condition was True, and the function
138 to be called normally otherwise.
138 to be called normally otherwise.
139
139
140 Notes
140 Notes
141 -----
141 -----
142 You will see from the code that we had to further decorate the
142 You will see from the code that we had to further decorate the
143 decorator with the nose.tools.make_decorator function in order to
143 decorator with the nose.tools.make_decorator function in order to
144 transmit function name, and various other metadata.
144 transmit function name, and various other metadata.
145 '''
145 '''
146
146
147 def skip_decorator(f):
147 def skip_decorator(f):
148 # Local import to avoid a hard nose dependency and only incur the
148 # Local import to avoid a hard nose dependency and only incur the
149 # import time overhead at actual test-time.
149 # import time overhead at actual test-time.
150 import nose
150 import nose
151
151
152 # Allow for both boolean or callable skip conditions.
152 # Allow for both boolean or callable skip conditions.
153 if callable(skip_condition):
153 if callable(skip_condition):
154 skip_val = lambda : skip_condition()
154 skip_val = lambda : skip_condition()
155 else:
155 else:
156 skip_val = lambda : skip_condition
156 skip_val = lambda : skip_condition
157
157
158 def get_msg(func,msg=None):
158 def get_msg(func,msg=None):
159 """Skip message with information about function being skipped."""
159 """Skip message with information about function being skipped."""
160 if msg is None: out = 'Test skipped due to test condition.'
160 if msg is None: out = 'Test skipped due to test condition.'
161 else: out = msg
161 else: out = msg
162 return "Skipping test: %s. %s" % (func.__name__,out)
162 return "Skipping test: %s. %s" % (func.__name__,out)
163
163
164 # We need to define *two* skippers because Python doesn't allow both
164 # We need to define *two* skippers because Python doesn't allow both
165 # return with value and yield inside the same function.
165 # return with value and yield inside the same function.
166 def skipper_func(*args, **kwargs):
166 def skipper_func(*args, **kwargs):
167 """Skipper for normal test functions."""
167 """Skipper for normal test functions."""
168 if skip_val():
168 if skip_val():
169 raise nose.SkipTest(get_msg(f,msg))
169 raise nose.SkipTest(get_msg(f,msg))
170 else:
170 else:
171 return f(*args, **kwargs)
171 return f(*args, **kwargs)
172
172
173 def skipper_gen(*args, **kwargs):
173 def skipper_gen(*args, **kwargs):
174 """Skipper for test generators."""
174 """Skipper for test generators."""
175 if skip_val():
175 if skip_val():
176 raise nose.SkipTest(get_msg(f,msg))
176 raise nose.SkipTest(get_msg(f,msg))
177 else:
177 else:
178 for x in f(*args, **kwargs):
178 for x in f(*args, **kwargs):
179 yield x
179 yield x
180
180
181 # Choose the right skipper to use when building the actual generator.
181 # Choose the right skipper to use when building the actual generator.
182 if nose.util.isgenerator(f):
182 if nose.util.isgenerator(f):
183 skipper = skipper_gen
183 skipper = skipper_gen
184 else:
184 else:
185 skipper = skipper_func
185 skipper = skipper_func
186
186
187 return nose.tools.make_decorator(f)(skipper)
187 return nose.tools.make_decorator(f)(skipper)
188
188
189 return skip_decorator
189 return skip_decorator
190
190
191 # A version with the condition set to true, common case just to attacha message
191 # A version with the condition set to true, common case just to attacha message
192 # to a skip decorator
192 # to a skip decorator
193 def skip(msg=None):
193 def skip(msg=None):
194 """Decorator factory - mark a test function for skipping from test suite.
194 """Decorator factory - mark a test function for skipping from test suite.
195
195
196 :Parameters:
196 :Parameters:
197 msg : string
197 msg : string
198 Optional message to be added.
198 Optional message to be added.
199
199
200 :Returns:
200 :Returns:
201 decorator : function
201 decorator : function
202 Decorator, which, when applied to a function, causes SkipTest
202 Decorator, which, when applied to a function, causes SkipTest
203 to be raised, with the optional message added.
203 to be raised, with the optional message added.
204 """
204 """
205
205
206 return skipif(True,msg)
206 return skipif(True,msg)
207
207
208
208
209 #-----------------------------------------------------------------------------
209 #-----------------------------------------------------------------------------
210 # Utility functions for decorators
210 # Utility functions for decorators
211 def numpy_not_available():
211 def numpy_not_available():
212 """Can numpy be imported? Returns true if numpy does NOT import.
212 """Can numpy be imported? Returns true if numpy does NOT import.
213
213
214 This is used to make a decorator to skip tests that require numpy to be
214 This is used to make a decorator to skip tests that require numpy to be
215 available, but delay the 'import numpy' to test execution time.
215 available, but delay the 'import numpy' to test execution time.
216 """
216 """
217 try:
217 try:
218 import numpy
218 import numpy
219 np_not_avail = False
219 np_not_avail = False
220 except ImportError:
220 except ImportError:
221 np_not_avail = True
221 np_not_avail = True
222
222
223 return np_not_avail
223 return np_not_avail
224
224
225 #-----------------------------------------------------------------------------
225 #-----------------------------------------------------------------------------
226 # Decorators for public use
226 # Decorators for public use
227
227
228 skip_doctest = make_label_dec('skip_doctest',
228 skip_doctest = make_label_dec('skip_doctest',
229 """Decorator - mark a function or method for skipping its doctest.
229 """Decorator - mark a function or method for skipping its doctest.
230
230
231 This decorator allows you to mark a function whose docstring you wish to
231 This decorator allows you to mark a function whose docstring you wish to
232 omit from testing, while preserving the docstring for introspection, help,
232 omit from testing, while preserving the docstring for introspection, help,
233 etc.""")
233 etc.""")
234
234
235 # Decorators to skip certain tests on specific platforms.
235 # Decorators to skip certain tests on specific platforms.
236 skip_win32 = skipif(sys.platform=='win32',
236 skip_win32 = skipif(sys.platform=='win32',
237 "This test does not run under Windows")
237 "This test does not run under Windows")
238 skip_linux = skipif(sys.platform=='linux2',"This test does not run under Linux")
238 skip_linux = skipif(sys.platform=='linux2',"This test does not run under Linux")
239 skip_osx = skipif(sys.platform=='darwin',"This test does not run under OS X")
239 skip_osx = skipif(sys.platform=='darwin',"This test does not run under OS X")
240
240
241
241
242 skipif_not_numpy = skipif(numpy_not_available,"This test requires numpy")
242 skipif_not_numpy = skipif(numpy_not_available,"This test requires numpy")
243
243
244 skipknownfailure = skip('This test is known to fail')
244 skipknownfailure = skip('This test is known to fail')
@@ -1,97 +1,97 b''
1 """Decorators for labeling test objects
1 """Decorators for labeling test objects
2
2
3 Decorators that merely return a modified version of the original
3 Decorators that merely return a modified version of the original
4 function object are straightforward. Decorators that return a new
4 function object are straightforward. Decorators that return a new
5 function object need to use
5 function object need to use
6 nose.tools.make_decorator(original_function)(decorator) in returning
6 nose.tools.make_decorator(original_function)(decorator) in returning
7 the decorator, in order to preserve metadata such as function name,
7 the decorator, in order to preserve metadata such as function name,
8 setup and teardown functions and so on - see nose.tools for more
8 setup and teardown functions and so on - see nose.tools for more
9 information.
9 information.
10
10
11 """
11 """
12
12
13 def slow(t):
13 def slow(t):
14 """Labels a test as 'slow'.
14 """Labels a test as 'slow'.
15
15
16 The exact definition of a slow test is obviously both subjective and
16 The exact definition of a slow test is obviously both subjective and
17 hardware-dependent, but in general any individual test that requires more
17 hardware-dependent, but in general any individual test that requires more
18 than a second or two should be labeled as slow (the whole suite consits of
18 than a second or two should be labeled as slow (the whole suite consits of
19 thousands of tests, so even a second is significant)."""
19 thousands of tests, so even a second is significant)."""
20
20
21 t.slow = True
21 t.slow = True
22 return t
22 return t
23
23
24 def setastest(tf=True):
24 def setastest(tf=True):
25 ''' Signals to nose that this function is or is not a test
25 ''' Signals to nose that this function is or is not a test
26
26
27 Parameters
27 Parameters
28 ----------
28 ----------
29 tf : bool
29 tf : bool
30 If True specifies this is a test, not a test otherwise
30 If True specifies this is a test, not a test otherwise
31
31
32 e.g
32 e.g
33 >>> from numpy.testing.decorators import setastest
33 >>> from numpy.testing.decorators import setastest
34 >>> @setastest(False)
34 >>> @setastest(False)
35 ... def func_with_test_in_name(arg1, arg2): pass
35 ... def func_with_test_in_name(arg1, arg2): pass
36 ...
36 ...
37 >>>
37 >>>
38
38
39 This decorator cannot use the nose namespace, because it can be
39 This decorator cannot use the nose namespace, because it can be
40 called from a non-test module. See also istest and nottest in
40 called from a non-test module. See also istest and nottest in
41 nose.tools
41 nose.tools
42
42
43 '''
43 '''
44 def set_test(t):
44 def set_test(t):
45 t.__test__ = tf
45 t.__test__ = tf
46 return t
46 return t
47 return set_test
47 return set_test
48
48
49 def skipif(skip_condition=True, msg=None):
49 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
57 is useful for tests that may require costly imports, to delay the cost
57 is useful for tests that may require costly imports, to delay the cost
58 until the test suite is actually executed.
58 until the test suite is actually executed.
59 msg : string
59 msg : string
60 Message to give on raising a SkipTest exception
60 Message to give on raising a SkipTest exception
61
61
62 Returns
62 Returns
63 -------
63 -------
64 decorator : function
64 decorator : function
65 Decorator, which, when applied to a function, causes SkipTest
65 Decorator, which, when applied to a function, causes SkipTest
66 to be raised when the skip_condition was True, and the function
66 to be raised when the skip_condition was True, and the function
67 to be called normally otherwise.
67 to be called normally otherwise.
68
68
69 Notes
69 Notes
70 -----
70 -----
71 You will see from the code that we had to further decorate the
71 You will see from the code that we had to further decorate the
72 decorator with the nose.tools.make_decorator function in order to
72 decorator with the nose.tools.make_decorator function in order to
73 transmit function name, and various other metadata.
73 transmit function name, and various other metadata.
74 '''
74 '''
75 if msg is None:
75 if msg is None:
76 msg = 'Test skipped due to test condition'
76 msg = 'Test skipped due to test condition'
77 def skip_decorator(f):
77 def skip_decorator(f):
78 # Local import to avoid a hard nose dependency and only incur the
78 # Local import to avoid a hard nose dependency and only incur the
79 # import time overhead at actual test-time.
79 # import time overhead at actual test-time.
80 import nose
80 import nose
81 def skipper(*args, **kwargs):
81 def skipper(*args, **kwargs):
82 if skip_condition:
82 if skip_condition:
83 raise nose.SkipTest, msg
83 raise nose.SkipTest, msg
84 else:
84 else:
85 return f(*args, **kwargs)
85 return f(*args, **kwargs)
86 return nose.tools.make_decorator(f)(skipper)
86 return nose.tools.make_decorator(f)(skipper)
87 return skip_decorator
87 return skip_decorator
88
88
89 def skipknownfailure(f):
89 def skipknownfailure(f):
90 ''' Decorator to raise SkipTest for test known to fail
90 ''' Decorator to raise SkipTest for test known to fail
91 '''
91 '''
92 # Local import to avoid a hard nose dependency and only incur the
92 # Local import to avoid a hard nose dependency and only incur the
93 # import time overhead at actual test-time.
93 # import time overhead at actual test-time.
94 import nose
94 import nose
95 def skipper(*args, **kwargs):
95 def skipper(*args, **kwargs):
96 raise nose.SkipTest, 'This test is known to fail'
96 raise nose.SkipTest, 'This test is known to fail'
97 return nose.tools.make_decorator(f)(skipper)
97 return nose.tools.make_decorator(f)(skipper)
@@ -1,86 +1,91 b''
1 # Makefile for Sphinx documentation
1 # Makefile for Sphinx documentation
2 #
2 #
3
3
4 # You can set these variables from the command line.
4 # You can set these variables from the command line.
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"
18 @echo " html to make standalone HTML files"
19 @echo " html to make standalone HTML files"
19 @echo " pickle to make pickle files (usable by e.g. sphinx-web)"
20 @echo " pickle to make pickle files (usable by e.g. sphinx-web)"
20 @echo " htmlhelp to make HTML files and a HTML help project"
21 @echo " htmlhelp to make HTML files and a HTML help project"
21 @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
22 @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
22 @echo " changes to make an overview over all changed/added/deprecated items"
23 @echo " changes to make an overview over all changed/added/deprecated items"
23 @echo " linkcheck to check all external links for integrity"
24 @echo " linkcheck to check all external links for integrity"
24 @echo
25 @echo
25 @echo "Compound utility targets:"
26 @echo "Compound utility targets:"
26 @echo "pdf latex and then runs the PDF generation"
27 @echo "pdf latex and then runs the PDF generation"
27 @echo "all html and pdf"
28 @echo "all html and pdf"
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
35
36
36 all: html pdf
37 all: html pdf
37
38
38 dist: clean all
39 dist: clean all
39 mkdir -p dist
40 mkdir -p dist
40 ln build/latex/ipython.pdf dist/
41 ln build/latex/ipython.pdf dist/
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
53 @echo
58 @echo
54 @echo "Build finished; now you can process the pickle files or run"
59 @echo "Build finished; now you can process the pickle files or run"
55 @echo " sphinx-web build/pickle"
60 @echo " sphinx-web build/pickle"
56 @echo "to start the sphinx-web server."
61 @echo "to start the sphinx-web server."
57
62
58 web: pickle
63 web: pickle
59
64
60 htmlhelp:
65 htmlhelp:
61 mkdir -p build/htmlhelp build/doctrees
66 mkdir -p build/htmlhelp build/doctrees
62 $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp
67 $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp
63 @echo
68 @echo
64 @echo "Build finished; now you can run HTML Help Workshop with the" \
69 @echo "Build finished; now you can run HTML Help Workshop with the" \
65 ".hhp project file in build/htmlhelp."
70 ".hhp project file in build/htmlhelp."
66
71
67 latex:
72 latex:
68 mkdir -p build/latex build/doctrees
73 mkdir -p build/latex build/doctrees
69 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex
74 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex
70 @echo
75 @echo
71 @echo "Build finished; the LaTeX files are in build/latex."
76 @echo "Build finished; the LaTeX files are in build/latex."
72 @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
77 @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
73 "run these through (pdf)latex."
78 "run these through (pdf)latex."
74
79
75 changes:
80 changes:
76 mkdir -p build/changes build/doctrees
81 mkdir -p build/changes build/doctrees
77 $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes
82 $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes
78 @echo
83 @echo
79 @echo "The overview file is in build/changes."
84 @echo "The overview file is in build/changes."
80
85
81 linkcheck:
86 linkcheck:
82 mkdir -p build/linkcheck build/doctrees
87 mkdir -p build/linkcheck build/doctrees
83 $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck
88 $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck
84 @echo
89 @echo
85 @echo "Link check complete; look for any errors in the above output " \
90 @echo "Link check complete; look for any errors in the above output " \
86 "or in build/linkcheck/output.txt."
91 "or in build/linkcheck/output.txt."
@@ -1,187 +1,191 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 #
2 #
3 # IPython documentation build configuration file.
3 # IPython documentation build configuration file.
4
4
5 # NOTE: This file has been edited manually from the auto-generated one from
5 # NOTE: This file has been edited manually from the auto-generated one from
6 # sphinx. Do NOT delete and re-generate. If any changes from sphinx are
6 # sphinx. Do NOT delete and re-generate. If any changes from sphinx are
7 # needed, generate a scratch one and merge by hand any new fields needed.
7 # needed, generate a scratch one and merge by hand any new fields needed.
8
8
9 #
9 #
10 # This file is execfile()d with the current directory set to its containing dir.
10 # This file is execfile()d with the current directory set to its containing dir.
11 #
11 #
12 # The contents of this file are pickled, so don't put values in the namespace
12 # The contents of this file are pickled, so don't put values in the namespace
13 # that aren't pickleable (module imports are okay, they're removed automatically).
13 # that aren't pickleable (module imports are okay, they're removed automatically).
14 #
14 #
15 # All configuration values have a default value; values that are commented out
15 # All configuration values have a default value; values that are commented out
16 # serve to show the default value.
16 # serve to show the default value.
17
17
18 import sys, os
18 import sys, os
19
19
20 # If your extensions are in another directory, add it here. If the directory
20 # If your extensions are in another directory, add it here. If the directory
21 # is relative to the documentation root, use os.path.abspath to make it
21 # is relative to the documentation root, use os.path.abspath to make it
22 # absolute, like shown here.
22 # absolute, like shown here.
23 sys.path.append(os.path.abspath('../sphinxext'))
23 sys.path.append(os.path.abspath('../sphinxext'))
24
24
25 # Import support for ipython console session syntax highlighting (lives
25 # Import support for ipython console session syntax highlighting (lives
26 # in the sphinxext directory defined above)
26 # in the sphinxext directory defined above)
27 import ipython_console_highlighting
27 import ipython_console_highlighting
28
28
29 # We load the ipython release info into a dict by explicit execution
29 # We load the ipython release info into a dict by explicit execution
30 iprelease = {}
30 iprelease = {}
31 execfile('../../IPython/Release.py',iprelease)
31 execfile('../../IPython/Release.py',iprelease)
32
32
33 # General configuration
33 # General configuration
34 # ---------------------
34 # ---------------------
35
35
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.
45 templates_path = ['_templates']
49 templates_path = ['_templates']
46
50
47 # The suffix of source filenames.
51 # The suffix of source filenames.
48 source_suffix = '.txt'
52 source_suffix = '.txt'
49
53
50 # The master toctree document.
54 # The master toctree document.
51 master_doc = 'index'
55 master_doc = 'index'
52
56
53 # General substitutions.
57 # General substitutions.
54 project = 'IPython'
58 project = 'IPython'
55 copyright = '2008, The IPython Development Team'
59 copyright = '2008, The IPython Development Team'
56
60
57 # The default replacements for |version| and |release|, also used in various
61 # The default replacements for |version| and |release|, also used in various
58 # other places throughout the built documents.
62 # other places throughout the built documents.
59 #
63 #
60 # The full version, including alpha/beta/rc tags.
64 # The full version, including alpha/beta/rc tags.
61 release = iprelease['version']
65 release = iprelease['version']
62 # The short X.Y version.
66 # The short X.Y version.
63 version = '.'.join(release.split('.',2)[:2])
67 version = '.'.join(release.split('.',2)[:2])
64
68
65
69
66 # There are two options for replacing |today|: either, you set today to some
70 # There are two options for replacing |today|: either, you set today to some
67 # non-false value, then it is used:
71 # non-false value, then it is used:
68 #today = ''
72 #today = ''
69 # Else, today_fmt is used as the format for a strftime call.
73 # Else, today_fmt is used as the format for a strftime call.
70 today_fmt = '%B %d, %Y'
74 today_fmt = '%B %d, %Y'
71
75
72 # List of documents that shouldn't be included in the build.
76 # List of documents that shouldn't be included in the build.
73 #unused_docs = []
77 #unused_docs = []
74
78
75 # List of directories, relative to source directories, that shouldn't be searched
79 # List of directories, relative to source directories, that shouldn't be searched
76 # for source files.
80 # for source files.
77 exclude_dirs = ['attic']
81 exclude_dirs = ['attic']
78
82
79 # If true, '()' will be appended to :func: etc. cross-reference text.
83 # If true, '()' will be appended to :func: etc. cross-reference text.
80 #add_function_parentheses = True
84 #add_function_parentheses = True
81
85
82 # If true, the current module name will be prepended to all description
86 # If true, the current module name will be prepended to all description
83 # unit titles (such as .. function::).
87 # unit titles (such as .. function::).
84 #add_module_names = True
88 #add_module_names = True
85
89
86 # If true, sectionauthor and moduleauthor directives will be shown in the
90 # If true, sectionauthor and moduleauthor directives will be shown in the
87 # output. They are ignored by default.
91 # output. They are ignored by default.
88 #show_authors = False
92 #show_authors = False
89
93
90 # The name of the Pygments (syntax highlighting) style to use.
94 # The name of the Pygments (syntax highlighting) style to use.
91 pygments_style = 'sphinx'
95 pygments_style = 'sphinx'
92
96
93
97
94 # Options for HTML output
98 # Options for HTML output
95 # -----------------------
99 # -----------------------
96
100
97 # The style sheet to use for HTML and HTML Help pages. A file of that name
101 # The style sheet to use for HTML and HTML Help pages. A file of that name
98 # must exist either in Sphinx' static/ path, or in one of the custom paths
102 # must exist either in Sphinx' static/ path, or in one of the custom paths
99 # given in html_static_path.
103 # given in html_static_path.
100 html_style = 'default.css'
104 html_style = 'default.css'
101
105
102 # The name for this set of Sphinx documents. If None, it defaults to
106 # The name for this set of Sphinx documents. If None, it defaults to
103 # "<project> v<release> documentation".
107 # "<project> v<release> documentation".
104 #html_title = None
108 #html_title = None
105
109
106 # The name of an image file (within the static path) to place at the top of
110 # The name of an image file (within the static path) to place at the top of
107 # the sidebar.
111 # the sidebar.
108 #html_logo = None
112 #html_logo = None
109
113
110 # Add any paths that contain custom static files (such as style sheets) here,
114 # Add any paths that contain custom static files (such as style sheets) here,
111 # relative to this directory. They are copied after the builtin static files,
115 # relative to this directory. They are copied after the builtin static files,
112 # so a file named "default.css" will overwrite the builtin "default.css".
116 # so a file named "default.css" will overwrite the builtin "default.css".
113 html_static_path = ['_static']
117 html_static_path = ['_static']
114
118
115 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
119 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
116 # using the given strftime format.
120 # using the given strftime format.
117 html_last_updated_fmt = '%b %d, %Y'
121 html_last_updated_fmt = '%b %d, %Y'
118
122
119 # If true, SmartyPants will be used to convert quotes and dashes to
123 # If true, SmartyPants will be used to convert quotes and dashes to
120 # typographically correct entities.
124 # typographically correct entities.
121 #html_use_smartypants = True
125 #html_use_smartypants = True
122
126
123 # Custom sidebar templates, maps document names to template names.
127 # Custom sidebar templates, maps document names to template names.
124 #html_sidebars = {}
128 #html_sidebars = {}
125
129
126 # Additional templates that should be rendered to pages, maps page names to
130 # Additional templates that should be rendered to pages, maps page names to
127 # template names.
131 # template names.
128 #html_additional_pages = {}
132 #html_additional_pages = {}
129
133
130 # If false, no module index is generated.
134 # If false, no module index is generated.
131 #html_use_modindex = True
135 #html_use_modindex = True
132
136
133 # If true, the reST sources are included in the HTML build as _sources/<name>.
137 # If true, the reST sources are included in the HTML build as _sources/<name>.
134 #html_copy_source = True
138 #html_copy_source = True
135
139
136 # If true, an OpenSearch description file will be output, and all pages will
140 # If true, an OpenSearch description file will be output, and all pages will
137 # contain a <link> tag referring to it. The value of this option must be the
141 # contain a <link> tag referring to it. The value of this option must be the
138 # base URL from which the finished HTML is served.
142 # base URL from which the finished HTML is served.
139 #html_use_opensearch = ''
143 #html_use_opensearch = ''
140
144
141 # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
145 # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
142 #html_file_suffix = ''
146 #html_file_suffix = ''
143
147
144 # Output file base name for HTML help builder.
148 # Output file base name for HTML help builder.
145 htmlhelp_basename = 'ipythondoc'
149 htmlhelp_basename = 'ipythondoc'
146
150
147
151
148 # Options for LaTeX output
152 # Options for LaTeX output
149 # ------------------------
153 # ------------------------
150
154
151 # The paper size ('letter' or 'a4').
155 # The paper size ('letter' or 'a4').
152 latex_paper_size = 'letter'
156 latex_paper_size = 'letter'
153
157
154 # The font size ('10pt', '11pt' or '12pt').
158 # The font size ('10pt', '11pt' or '12pt').
155 latex_font_size = '11pt'
159 latex_font_size = '11pt'
156
160
157 # Grouping the document tree into LaTeX files. List of tuples
161 # Grouping the document tree into LaTeX files. List of tuples
158 # (source start file, target name, title, author, document class [howto/manual]).
162 # (source start file, target name, title, author, document class [howto/manual]).
159
163
160 latex_documents = [ ('index', 'ipython.tex', 'IPython Documentation',
164 latex_documents = [ ('index', 'ipython.tex', 'IPython Documentation',
161 ur"""The IPython Development Team""",
165 ur"""The IPython Development Team""",
162 'manual'),
166 'manual'),
163 ]
167 ]
164
168
165 # The name of an image file (relative to this directory) to place at the top of
169 # The name of an image file (relative to this directory) to place at the top of
166 # the title page.
170 # the title page.
167 #latex_logo = None
171 #latex_logo = None
168
172
169 # For "manual" documents, if this is true, then toplevel headings are parts,
173 # For "manual" documents, if this is true, then toplevel headings are parts,
170 # not chapters.
174 # not chapters.
171 #latex_use_parts = False
175 #latex_use_parts = False
172
176
173 # Additional stuff for the LaTeX preamble.
177 # Additional stuff for the LaTeX preamble.
174 #latex_preamble = ''
178 #latex_preamble = ''
175
179
176 # Documents to append as an appendix to all manuals.
180 # Documents to append as an appendix to all manuals.
177 #latex_appendices = []
181 #latex_appendices = []
178
182
179 # If false, no module index is generated.
183 # If false, no module index is generated.
180 #latex_use_modindex = True
184 #latex_use_modindex = True
181
185
182
186
183 # Cleanup
187 # Cleanup
184 # -------
188 # -------
185 # delete release info to avoid pickling errors from sphinx
189 # delete release info to avoid pickling errors from sphinx
186
190
187 del iprelease
191 del iprelease
@@ -1,32 +1,33 b''
1 =====================
1 =====================
2 IPython Documentation
2 IPython Documentation
3 =====================
3 =====================
4
4
5 .. htmlonly::
5 .. htmlonly::
6
6
7 :Release: |release|
7 :Release: |release|
8 :Date: |today|
8 :Date: |today|
9
9
10 Contents:
10 Contents:
11
11
12 .. toctree::
12 .. toctree::
13 :maxdepth: 2
13 :maxdepth: 2
14
14
15 overview.txt
15 overview.txt
16 install/index.txt
16 install/index.txt
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
27
28
28 .. htmlonly::
29 .. htmlonly::
29
30
30 * :ref:`genindex`
31 * :ref:`genindex`
31 * :ref:`modindex`
32 * :ref:`modindex`
32 * :ref:`search`
33 * :ref:`search`
This diff has been collapsed as it changes many lines, (1571 lines changed) Show them Hide them
@@ -1,3162 +1,1599 b''
1 .. IPython documentation master file, created by sphinx-quickstart.py on Mon Mar 24 17:01:34 2008.
1 .. IPython documentation master file, created by sphinx-quickstart.py on Mon Mar 24 17:01:34 2008.
2 You can adapt this file completely to your liking, but it should at least
2 You can adapt this file completely to your liking, but it should at least
3 contain the root 'toctree' directive.
3 contain the root 'toctree' directive.
4
4
5 =================
5 =================
6 IPython reference
6 IPython reference
7 =================
7 =================
8
8
9 .. contents::
9 .. contents::
10
10
11 .. _command_line_options:
11 .. _command_line_options:
12
12
13 Command-line usage
13 Command-line usage
14 ==================
14 ==================
15
15
16 You start IPython with the command::
16 You start IPython with the command::
17
17
18 $ ipython [options] files
18 $ ipython [options] files
19
19
20 If invoked with no options, it executes all the files listed in sequence
20 If invoked with no options, it executes all the files listed in sequence
21 and drops you into the interpreter while still acknowledging any options
21 and drops you into the interpreter while still acknowledging any options
22 you may have set in your ipythonrc file. This behavior is different from
22 you may have set in your ipythonrc file. This behavior is different from
23 standard Python, which when called as python -i will only execute one
23 standard Python, which when called as python -i will only execute one
24 file and ignore your configuration setup.
24 file and ignore your configuration setup.
25
25
26 Please note that some of the configuration options are not available at
26 Please note that some of the configuration options are not available at
27 the command line, simply because they are not practical here. Look into
27 the command line, simply because they are not practical here. Look into
28 your ipythonrc configuration file for details on those. This file
28 your ipythonrc configuration file for details on those. This file
29 typically installed in the $HOME/.ipython directory. For Windows users,
29 typically installed in the $HOME/.ipython directory. For Windows users,
30 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
30 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
31 instances. In the rest of this text, we will refer to this directory as
31 instances. In the rest of this text, we will refer to this directory as
32 IPYTHONDIR.
32 IPYTHONDIR.
33
33
34 .. _Threading options:
34 .. _Threading options:
35
35
36
36
37 Special Threading Options
37 Special Threading Options
38 -------------------------
38 -------------------------
39
39
40 The following special options are ONLY valid at the beginning of the
40 The following special options are ONLY valid at the beginning of the
41 command line, and not later. This is because they control the initial-
41 command line, and not later. This is because they control the initial-
42 ization of ipython itself, before the normal option-handling mechanism
42 ization of ipython itself, before the normal option-handling mechanism
43 is active.
43 is active.
44
44
45 -gthread, -qthread, -q4thread, -wthread, -pylab:
45 -gthread, -qthread, -q4thread, -wthread, -pylab:
46 Only one of these can be given, and it can only be given as
46 Only one of these can be given, and it can only be given as
47 the first option passed to IPython (it will have no effect in
47 the first option passed to IPython (it will have no effect in
48 any other position). They provide threading support for the
48 any other position). They provide threading support for the
49 GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the
49 GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the
50 matplotlib library.
50 matplotlib library.
51
51
52 With any of the first four options, IPython starts running a
52 With any of the first four options, IPython starts running a
53 separate thread for the graphical toolkit's operation, so that
53 separate thread for the graphical toolkit's operation, so that
54 you can open and control graphical elements from within an
54 you can open and control graphical elements from within an
55 IPython command line, without blocking. All four provide
55 IPython command line, without blocking. All four provide
56 essentially the same functionality, respectively for GTK, Qt3,
56 essentially the same functionality, respectively for GTK, Qt3,
57 Qt4 and WXWidgets (via their Python interfaces).
57 Qt4 and WXWidgets (via their Python interfaces).
58
58
59 Note that with -wthread, you can additionally use the
59 Note that with -wthread, you can additionally use the
60 -wxversion option to request a specific version of wx to be
60 -wxversion option to request a specific version of wx to be
61 used. This requires that you have the wxversion Python module
61 used. This requires that you have the wxversion Python module
62 installed, which is part of recent wxPython distributions.
62 installed, which is part of recent wxPython distributions.
63
63
64 If -pylab is given, IPython loads special support for the mat
64 If -pylab is given, IPython loads special support for the mat
65 plotlib library (http://matplotlib.sourceforge.net), allowing
65 plotlib library (http://matplotlib.sourceforge.net), allowing
66 interactive usage of any of its backends as defined in the
66 interactive usage of any of its backends as defined in the
67 user's ~/.matplotlib/matplotlibrc file. It automatically
67 user's ~/.matplotlib/matplotlibrc file. It automatically
68 activates GTK, Qt or WX threading for IPyhton if the choice of
68 activates GTK, Qt or WX threading for IPyhton if the choice of
69 matplotlib backend requires it. It also modifies the %run
69 matplotlib backend requires it. It also modifies the %run
70 command to correctly execute (without blocking) any
70 command to correctly execute (without blocking) any
71 matplotlib-based script which calls show() at the end.
71 matplotlib-based script which calls show() at the end.
72
72
73 -tk
73 -tk
74 The -g/q/q4/wthread options, and -pylab (if matplotlib is
74 The -g/q/q4/wthread options, and -pylab (if matplotlib is
75 configured to use GTK, Qt3, Qt4 or WX), will normally block Tk
75 configured to use GTK, Qt3, Qt4 or WX), will normally block Tk
76 graphical interfaces. This means that when either GTK, Qt or WX
76 graphical interfaces. This means that when either GTK, Qt or WX
77 threading is active, any attempt to open a Tk GUI will result in a
77 threading is active, any attempt to open a Tk GUI will result in a
78 dead window, and possibly cause the Python interpreter to crash.
78 dead window, and possibly cause the Python interpreter to crash.
79 An extra option, -tk, is available to address this issue. It can
79 An extra option, -tk, is available to address this issue. It can
80 only be given as a second option after any of the above (-gthread,
80 only be given as a second option after any of the above (-gthread,
81 -wthread or -pylab).
81 -wthread or -pylab).
82
82
83 If -tk is given, IPython will try to coordinate Tk threading
83 If -tk is given, IPython will try to coordinate Tk threading
84 with GTK, Qt or WX. This is however potentially unreliable, and
84 with GTK, Qt or WX. This is however potentially unreliable, and
85 you will have to test on your platform and Python configuration to
85 you will have to test on your platform and Python configuration to
86 determine whether it works for you. Debian users have reported
86 determine whether it works for you. Debian users have reported
87 success, apparently due to the fact that Debian builds all of Tcl,
87 success, apparently due to the fact that Debian builds all of Tcl,
88 Tk, Tkinter and Python with pthreads support. Under other Linux
88 Tk, Tkinter and Python with pthreads support. Under other Linux
89 environments (such as Fedora Core 2/3), this option has caused
89 environments (such as Fedora Core 2/3), this option has caused
90 random crashes and lockups of the Python interpreter. Under other
90 random crashes and lockups of the Python interpreter. Under other
91 operating systems (Mac OSX and Windows), you'll need to try it to
91 operating systems (Mac OSX and Windows), you'll need to try it to
92 find out, since currently no user reports are available.
92 find out, since currently no user reports are available.
93
93
94 There is unfortunately no way for IPython to determine at run time
94 There is unfortunately no way for IPython to determine at run time
95 whether -tk will work reliably or not, so you will need to do some
95 whether -tk will work reliably or not, so you will need to do some
96 experiments before relying on it for regular work.
96 experiments before relying on it for regular work.
97
97
98
98
99
99
100 Regular Options
100 Regular Options
101 ---------------
101 ---------------
102
102
103 After the above threading options have been given, regular options can
103 After the above threading options have been given, regular options can
104 follow in any order. All options can be abbreviated to their shortest
104 follow in any order. All options can be abbreviated to their shortest
105 non-ambiguous form and are case-sensitive. One or two dashes can be
105 non-ambiguous form and are case-sensitive. One or two dashes can be
106 used. Some options have an alternate short form, indicated after a ``|``.
106 used. Some options have an alternate short form, indicated after a ``|``.
107
107
108 Most options can also be set from your ipythonrc configuration file. See
108 Most options can also be set from your ipythonrc configuration file. See
109 the provided example for more details on what the options do. Options
109 the provided example for more details on what the options do. Options
110 given at the command line override the values set in the ipythonrc file.
110 given at the command line override the values set in the ipythonrc file.
111
111
112 All options with a [no] prepended can be specified in negated form
112 All options with a [no] prepended can be specified in negated form
113 (-nooption instead of -option) to turn the feature off.
113 (-nooption instead of -option) to turn the feature off.
114
114
115 -help print a help message and exit.
115 -help print a help message and exit.
116
116
117 -pylab
117 -pylab
118 this can only be given as the first option passed to IPython
118 this can only be given as the first option passed to IPython
119 (it will have no effect in any other position). It adds
119 (it will have no effect in any other position). It adds
120 special support for the matplotlib library
120 special support for the matplotlib library
121 (http://matplotlib.sourceforge.ne), allowing interactive usage
121 (http://matplotlib.sourceforge.ne), allowing interactive usage
122 of any of its backends as defined in the user's .matplotlibrc
122 of any of its backends as defined in the user's .matplotlibrc
123 file. It automatically activates GTK or WX threading for
123 file. It automatically activates GTK or WX threading for
124 IPyhton if the choice of matplotlib backend requires it. It
124 IPyhton if the choice of matplotlib backend requires it. It
125 also modifies the %run command to correctly execute (without
125 also modifies the %run command to correctly execute (without
126 blocking) any matplotlib-based script which calls show() at
126 blocking) any matplotlib-based script which calls show() at
127 the end. See `Matplotlib support`_ for more details.
127 the end. See `Matplotlib support`_ for more details.
128
128
129 -autocall <val>
129 -autocall <val>
130 Make IPython automatically call any callable object even if you
130 Make IPython automatically call any callable object even if you
131 didn't type explicit parentheses. For example, 'str 43' becomes
131 didn't type explicit parentheses. For example, 'str 43' becomes
132 'str(43)' automatically. The value can be '0' to disable the feature,
132 'str(43)' automatically. The value can be '0' to disable the feature,
133 '1' for smart autocall, where it is not applied if there are no more
133 '1' for smart autocall, where it is not applied if there are no more
134 arguments on the line, and '2' for full autocall, where all callable
134 arguments on the line, and '2' for full autocall, where all callable
135 objects are automatically called (even if no arguments are
135 objects are automatically called (even if no arguments are
136 present). The default is '1'.
136 present). The default is '1'.
137
137
138 -[no]autoindent
138 -[no]autoindent
139 Turn automatic indentation on/off.
139 Turn automatic indentation on/off.
140
140
141 -[no]automagic
141 -[no]automagic
142 make magic commands automatic (without needing their first character
142 make magic commands automatic (without needing their first character
143 to be %). Type %magic at the IPython prompt for more information.
143 to be %). Type %magic at the IPython prompt for more information.
144
144
145 -[no]autoedit_syntax
145 -[no]autoedit_syntax
146 When a syntax error occurs after editing a file, automatically
146 When a syntax error occurs after editing a file, automatically
147 open the file to the trouble causing line for convenient
147 open the file to the trouble causing line for convenient
148 fixing.
148 fixing.
149
149
150 -[no]banner Print the initial information banner (default on).
150 -[no]banner Print the initial information banner (default on).
151
151
152 -c <command>
152 -c <command>
153 execute the given command string. This is similar to the -c
153 execute the given command string. This is similar to the -c
154 option in the normal Python interpreter.
154 option in the normal Python interpreter.
155
155
156 -cache_size, cs <n>
156 -cache_size, cs <n>
157 size of the output cache (maximum number of entries to hold in
157 size of the output cache (maximum number of entries to hold in
158 memory). The default is 1000, you can change it permanently in your
158 memory). The default is 1000, you can change it permanently in your
159 config file. Setting it to 0 completely disables the caching system,
159 config file. Setting it to 0 completely disables the caching system,
160 and the minimum value accepted is 20 (if you provide a value less than
160 and the minimum value accepted is 20 (if you provide a value less than
161 20, it is reset to 0 and a warning is issued) This limit is defined
161 20, it is reset to 0 and a warning is issued) This limit is defined
162 because otherwise you'll spend more time re-flushing a too small cache
162 because otherwise you'll spend more time re-flushing a too small cache
163 than working.
163 than working.
164
164
165 -classic, cl
165 -classic, cl
166 Gives IPython a similar feel to the classic Python
166 Gives IPython a similar feel to the classic Python
167 prompt.
167 prompt.
168
168
169 -colors <scheme>
169 -colors <scheme>
170 Color scheme for prompts and exception reporting. Currently
170 Color scheme for prompts and exception reporting. Currently
171 implemented: NoColor, Linux and LightBG.
171 implemented: NoColor, Linux and LightBG.
172
172
173 -[no]color_info
173 -[no]color_info
174 IPython can display information about objects via a set of functions,
174 IPython can display information about objects via a set of functions,
175 and optionally can use colors for this, syntax highlighting source
175 and optionally can use colors for this, syntax highlighting source
176 code and various other elements. However, because this information is
176 code and various other elements. However, because this information is
177 passed through a pager (like 'less') and many pagers get confused with
177 passed through a pager (like 'less') and many pagers get confused with
178 color codes, this option is off by default. You can test it and turn
178 color codes, this option is off by default. You can test it and turn
179 it on permanently in your ipythonrc file if it works for you. As a
179 it on permanently in your ipythonrc file if it works for you. As a
180 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
180 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
181 that in RedHat 7.2 doesn't.
181 that in RedHat 7.2 doesn't.
182
182
183 Test it and turn it on permanently if it works with your
183 Test it and turn it on permanently if it works with your
184 system. The magic function %color_info allows you to toggle this
184 system. The magic function %color_info allows you to toggle this
185 interactively for testing.
185 interactively for testing.
186
186
187 -[no]debug
187 -[no]debug
188 Show information about the loading process. Very useful to pin down
188 Show information about the loading process. Very useful to pin down
189 problems with your configuration files or to get details about
189 problems with your configuration files or to get details about
190 session restores.
190 session restores.
191
191
192 -[no]deep_reload:
192 -[no]deep_reload:
193 IPython can use the deep_reload module which reloads changes in
193 IPython can use the deep_reload module which reloads changes in
194 modules recursively (it replaces the reload() function, so you don't
194 modules recursively (it replaces the reload() function, so you don't
195 need to change anything to use it). deep_reload() forces a full
195 need to change anything to use it). deep_reload() forces a full
196 reload of modules whose code may have changed, which the default
196 reload of modules whose code may have changed, which the default
197 reload() function does not.
197 reload() function does not.
198
198
199 When deep_reload is off, IPython will use the normal reload(),
199 When deep_reload is off, IPython will use the normal reload(),
200 but deep_reload will still be available as dreload(). This
200 but deep_reload will still be available as dreload(). This
201 feature is off by default [which means that you have both
201 feature is off by default [which means that you have both
202 normal reload() and dreload()].
202 normal reload() and dreload()].
203
203
204 -editor <name>
204 -editor <name>
205 Which editor to use with the %edit command. By default,
205 Which editor to use with the %edit command. By default,
206 IPython will honor your EDITOR environment variable (if not
206 IPython will honor your EDITOR environment variable (if not
207 set, vi is the Unix default and notepad the Windows one).
207 set, vi is the Unix default and notepad the Windows one).
208 Since this editor is invoked on the fly by IPython and is
208 Since this editor is invoked on the fly by IPython and is
209 meant for editing small code snippets, you may want to use a
209 meant for editing small code snippets, you may want to use a
210 small, lightweight editor here (in case your default EDITOR is
210 small, lightweight editor here (in case your default EDITOR is
211 something like Emacs).
211 something like Emacs).
212
212
213 -ipythondir <name>
213 -ipythondir <name>
214 name of your IPython configuration directory IPYTHONDIR. This
214 name of your IPython configuration directory IPYTHONDIR. This
215 can also be specified through the environment variable
215 can also be specified through the environment variable
216 IPYTHONDIR.
216 IPYTHONDIR.
217
217
218 -log, l
218 -log, l
219 generate a log file of all input. The file is named
219 generate a log file of all input. The file is named
220 ipython_log.py in your current directory (which prevents logs
220 ipython_log.py in your current directory (which prevents logs
221 from multiple IPython sessions from trampling each other). You
221 from multiple IPython sessions from trampling each other). You
222 can use this to later restore a session by loading your
222 can use this to later restore a session by loading your
223 logfile as a file to be executed with option -logplay (see
223 logfile as a file to be executed with option -logplay (see
224 below).
224 below).
225
225
226 -logfile, lf <name> specify the name of your logfile.
226 -logfile, lf <name> specify the name of your logfile.
227
227
228 -logplay, lp <name>
228 -logplay, lp <name>
229
229
230 you can replay a previous log. For restoring a session as close as
230 you can replay a previous log. For restoring a session as close as
231 possible to the state you left it in, use this option (don't just run
231 possible to the state you left it in, use this option (don't just run
232 the logfile). With -logplay, IPython will try to reconstruct the
232 the logfile). With -logplay, IPython will try to reconstruct the
233 previous working environment in full, not just execute the commands in
233 previous working environment in full, not just execute the commands in
234 the logfile.
234 the logfile.
235
235
236 When a session is restored, logging is automatically turned on
236 When a session is restored, logging is automatically turned on
237 again with the name of the logfile it was invoked with (it is
237 again with the name of the logfile it was invoked with (it is
238 read from the log header). So once you've turned logging on for
238 read from the log header). So once you've turned logging on for
239 a session, you can quit IPython and reload it as many times as
239 a session, you can quit IPython and reload it as many times as
240 you want and it will continue to log its history and restore
240 you want and it will continue to log its history and restore
241 from the beginning every time.
241 from the beginning every time.
242
242
243 Caveats: there are limitations in this option. The history
243 Caveats: there are limitations in this option. The history
244 variables _i*,_* and _dh don't get restored properly. In the
244 variables _i*,_* and _dh don't get restored properly. In the
245 future we will try to implement full session saving by writing
245 future we will try to implement full session saving by writing
246 and retrieving a 'snapshot' of the memory state of IPython. But
246 and retrieving a 'snapshot' of the memory state of IPython. But
247 our first attempts failed because of inherent limitations of
247 our first attempts failed because of inherent limitations of
248 Python's Pickle module, so this may have to wait.
248 Python's Pickle module, so this may have to wait.
249
249
250 -[no]messages
250 -[no]messages
251 Print messages which IPython collects about its startup
251 Print messages which IPython collects about its startup
252 process (default on).
252 process (default on).
253
253
254 -[no]pdb
254 -[no]pdb
255 Automatically call the pdb debugger after every uncaught
255 Automatically call the pdb debugger after every uncaught
256 exception. If you are used to debugging using pdb, this puts
256 exception. If you are used to debugging using pdb, this puts
257 you automatically inside of it after any call (either in
257 you automatically inside of it after any call (either in
258 IPython or in code called by it) which triggers an exception
258 IPython or in code called by it) which triggers an exception
259 which goes uncaught.
259 which goes uncaught.
260
260
261 -pydb
261 -pydb
262 Makes IPython use the third party "pydb" package as debugger,
262 Makes IPython use the third party "pydb" package as debugger,
263 instead of pdb. Requires that pydb is installed.
263 instead of pdb. Requires that pydb is installed.
264
264
265 -[no]pprint
265 -[no]pprint
266 ipython can optionally use the pprint (pretty printer) module
266 ipython can optionally use the pprint (pretty printer) module
267 for displaying results. pprint tends to give a nicer display
267 for displaying results. pprint tends to give a nicer display
268 of nested data structures. If you like it, you can turn it on
268 of nested data structures. If you like it, you can turn it on
269 permanently in your config file (default off).
269 permanently in your config file (default off).
270
270
271 -profile, p <name>
271 -profile, p <name>
272
272
273 assume that your config file is ipythonrc-<name> or
273 assume that your config file is ipythonrc-<name> or
274 ipy_profile_<name>.py (looks in current dir first, then in
274 ipy_profile_<name>.py (looks in current dir first, then in
275 IPYTHONDIR). This is a quick way to keep and load multiple
275 IPYTHONDIR). This is a quick way to keep and load multiple
276 config files for different tasks, especially if you use the
276 config files for different tasks, especially if you use the
277 include option of config files. You can keep a basic
277 include option of config files. You can keep a basic
278 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
278 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
279 include this one and load extra things for particular
279 include this one and load extra things for particular
280 tasks. For example:
280 tasks. For example:
281
281
282 1. $HOME/.ipython/ipythonrc : load basic things you always want.
282 1. $HOME/.ipython/ipythonrc : load basic things you always want.
283 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
283 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
284 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
284 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
285
285
286 Since it is possible to create an endless loop by having
286 Since it is possible to create an endless loop by having
287 circular file inclusions, IPython will stop if it reaches 15
287 circular file inclusions, IPython will stop if it reaches 15
288 recursive inclusions.
288 recursive inclusions.
289
289
290 -prompt_in1, pi1 <string>
290 -prompt_in1, pi1 <string>
291
291
292 Specify the string used for input prompts. Note that if you are using
292 Specify the string used for input prompts. Note that if you are using
293 numbered prompts, the number is represented with a '\#' in the
293 numbered prompts, the number is represented with a '\#' in the
294 string. Don't forget to quote strings with spaces embedded in
294 string. Don't forget to quote strings with spaces embedded in
295 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
295 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
296 discusses in detail all the available escapes to customize your
296 discusses in detail all the available escapes to customize your
297 prompts.
297 prompts.
298
298
299 -prompt_in2, pi2 <string>
299 -prompt_in2, pi2 <string>
300 Similar to the previous option, but used for the continuation
300 Similar to the previous option, but used for the continuation
301 prompts. The special sequence '\D' is similar to '\#', but
301 prompts. The special sequence '\D' is similar to '\#', but
302 with all digits replaced dots (so you can have your
302 with all digits replaced dots (so you can have your
303 continuation prompt aligned with your input prompt). Default:
303 continuation prompt aligned with your input prompt). Default:
304 ' .\D.:' (note three spaces at the start for alignment with
304 ' .\D.:' (note three spaces at the start for alignment with
305 'In [\#]').
305 'In [\#]').
306
306
307 -prompt_out,po <string>
307 -prompt_out,po <string>
308 String used for output prompts, also uses numbers like
308 String used for output prompts, also uses numbers like
309 prompt_in1. Default: 'Out[\#]:'
309 prompt_in1. Default: 'Out[\#]:'
310
310
311 -quick start in bare bones mode (no config file loaded).
311 -quick start in bare bones mode (no config file loaded).
312
312
313 -rcfile <name>
313 -rcfile <name>
314 name of your IPython resource configuration file. Normally
314 name of your IPython resource configuration file. Normally
315 IPython loads ipythonrc (from current directory) or
315 IPython loads ipythonrc (from current directory) or
316 IPYTHONDIR/ipythonrc.
316 IPYTHONDIR/ipythonrc.
317
317
318 If the loading of your config file fails, IPython starts with
318 If the loading of your config file fails, IPython starts with
319 a bare bones configuration (no modules loaded at all).
319 a bare bones configuration (no modules loaded at all).
320
320
321 -[no]readline
321 -[no]readline
322 use the readline library, which is needed to support name
322 use the readline library, which is needed to support name
323 completion and command history, among other things. It is
323 completion and command history, among other things. It is
324 enabled by default, but may cause problems for users of
324 enabled by default, but may cause problems for users of
325 X/Emacs in Python comint or shell buffers.
325 X/Emacs in Python comint or shell buffers.
326
326
327 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
327 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
328 IPython's readline and syntax coloring fine, only 'emacs' (M-x
328 IPython's readline and syntax coloring fine, only 'emacs' (M-x
329 shell and C-c !) buffers do not.
329 shell and C-c !) buffers do not.
330
330
331 -screen_length, sl <n>
331 -screen_length, sl <n>
332 number of lines of your screen. This is used to control
332 number of lines of your screen. This is used to control
333 printing of very long strings. Strings longer than this number
333 printing of very long strings. Strings longer than this number
334 of lines will be sent through a pager instead of directly
334 of lines will be sent through a pager instead of directly
335 printed.
335 printed.
336
336
337 The default value for this is 0, which means IPython will
337 The default value for this is 0, which means IPython will
338 auto-detect your screen size every time it needs to print certain
338 auto-detect your screen size every time it needs to print certain
339 potentially long strings (this doesn't change the behavior of the
339 potentially long strings (this doesn't change the behavior of the
340 'print' keyword, it's only triggered internally). If for some
340 'print' keyword, it's only triggered internally). If for some
341 reason this isn't working well (it needs curses support), specify
341 reason this isn't working well (it needs curses support), specify
342 it yourself. Otherwise don't change the default.
342 it yourself. Otherwise don't change the default.
343
343
344 -separate_in, si <string>
344 -separate_in, si <string>
345
345
346 separator before input prompts.
346 separator before input prompts.
347 Default: '\n'
347 Default: '\n'
348
348
349 -separate_out, so <string>
349 -separate_out, so <string>
350 separator before output prompts.
350 separator before output prompts.
351 Default: nothing.
351 Default: nothing.
352
352
353 -separate_out2, so2
353 -separate_out2, so2
354 separator after output prompts.
354 separator after output prompts.
355 Default: nothing.
355 Default: nothing.
356 For these three options, use the value 0 to specify no separator.
356 For these three options, use the value 0 to specify no separator.
357
357
358 -nosep
358 -nosep
359 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
359 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
360 0'. Simply removes all input/output separators.
360 0'. Simply removes all input/output separators.
361
361
362 -upgrade
362 -upgrade
363 allows you to upgrade your IPYTHONDIR configuration when you
363 allows you to upgrade your IPYTHONDIR configuration when you
364 install a new version of IPython. Since new versions may
364 install a new version of IPython. Since new versions may
365 include new command line options or example files, this copies
365 include new command line options or example files, this copies
366 updated ipythonrc-type files. However, it backs up (with a
366 updated ipythonrc-type files. However, it backs up (with a
367 .old extension) all files which it overwrites so that you can
367 .old extension) all files which it overwrites so that you can
368 merge back any customizations you might have in your personal
368 merge back any customizations you might have in your personal
369 files. Note that you should probably use %upgrade instead,
369 files. Note that you should probably use %upgrade instead,
370 it's a safer alternative.
370 it's a safer alternative.
371
371
372
372
373 -Version print version information and exit.
373 -Version print version information and exit.
374
374
375 -wxversion <string>
375 -wxversion <string>
376 Select a specific version of wxPython (used in conjunction
376 Select a specific version of wxPython (used in conjunction
377 with -wthread). Requires the wxversion module, part of recent
377 with -wthread). Requires the wxversion module, part of recent
378 wxPython distributions
378 wxPython distributions
379
379
380 -xmode <modename>
380 -xmode <modename>
381
381
382 Mode for exception reporting.
382 Mode for exception reporting.
383
383
384 Valid modes: Plain, Context and Verbose.
384 Valid modes: Plain, Context and Verbose.
385
385
386 * Plain: similar to python's normal traceback printing.
386 * Plain: similar to python's normal traceback printing.
387 * Context: prints 5 lines of context source code around each
387 * Context: prints 5 lines of context source code around each
388 line in the traceback.
388 line in the traceback.
389 * Verbose: similar to Context, but additionally prints the
389 * Verbose: similar to Context, but additionally prints the
390 variables currently visible where the exception happened
390 variables currently visible where the exception happened
391 (shortening their strings if too long). This can potentially be
391 (shortening their strings if too long). This can potentially be
392 very slow, if you happen to have a huge data structure whose
392 very slow, if you happen to have a huge data structure whose
393 string representation is complex to compute. Your computer may
393 string representation is complex to compute. Your computer may
394 appear to freeze for a while with cpu usage at 100%. If this
394 appear to freeze for a while with cpu usage at 100%. If this
395 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
395 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
396 more than once).
396 more than once).
397
397
398 Interactive use
398 Interactive use
399 ===============
399 ===============
400
400
401 Warning: IPython relies on the existence of a global variable called
401 Warning: IPython relies on the existence of a global variable called
402 _ip which controls the shell itself. If you redefine _ip to anything,
402 _ip which controls the shell itself. If you redefine _ip to anything,
403 bizarre behavior will quickly occur.
403 bizarre behavior will quickly occur.
404
404
405 Other than the above warning, IPython is meant to work as a drop-in
405 Other than the above warning, IPython is meant to work as a drop-in
406 replacement for the standard interactive interpreter. As such, any code
406 replacement for the standard interactive interpreter. As such, any code
407 which is valid python should execute normally under IPython (cases where
407 which is valid python should execute normally under IPython (cases where
408 this is not true should be reported as bugs). It does, however, offer
408 this is not true should be reported as bugs). It does, however, offer
409 many features which are not available at a standard python prompt. What
409 many features which are not available at a standard python prompt. What
410 follows is a list of these.
410 follows is a list of these.
411
411
412
412
413 Caution for Windows users
413 Caution for Windows users
414 -------------------------
414 -------------------------
415
415
416 Windows, unfortunately, uses the '\' character as a path
416 Windows, unfortunately, uses the '\' character as a path
417 separator. This is a terrible choice, because '\' also represents the
417 separator. This is a terrible choice, because '\' also represents the
418 escape character in most modern programming languages, including
418 escape character in most modern programming languages, including
419 Python. For this reason, using '/' character is recommended if you
419 Python. For this reason, using '/' character is recommended if you
420 have problems with ``\``. However, in Windows commands '/' flags
420 have problems with ``\``. However, in Windows commands '/' flags
421 options, so you can not use it for the root directory. This means that
421 options, so you can not use it for the root directory. This means that
422 paths beginning at the root must be typed in a contrived manner like:
422 paths beginning at the root must be typed in a contrived manner like:
423 ``%copy \opt/foo/bar.txt \tmp``
423 ``%copy \opt/foo/bar.txt \tmp``
424
424
425 .. _magic:
425 .. _magic:
426
426
427 Magic command system
427 Magic command system
428 --------------------
428 --------------------
429
429
430 IPython will treat any line whose first character is a % as a special
430 IPython will treat any line whose first character is a % as a special
431 call to a 'magic' function. These allow you to control the behavior of
431 call to a 'magic' function. These allow you to control the behavior of
432 IPython itself, plus a lot of system-type features. They are all
432 IPython itself, plus a lot of system-type features. They are all
433 prefixed with a % character, but parameters are given without
433 prefixed with a % character, but parameters are given without
434 parentheses or quotes.
434 parentheses or quotes.
435
435
436 Example: typing '%cd mydir' (without the quotes) changes you working
436 Example: typing '%cd mydir' (without the quotes) changes you working
437 directory to 'mydir', if it exists.
437 directory to 'mydir', if it exists.
438
438
439 If you have 'automagic' enabled (in your ipythonrc file, via the command
439 If you have 'automagic' enabled (in your ipythonrc file, via the command
440 line option -automagic or with the %automagic function), you don't need
440 line option -automagic or with the %automagic function), you don't need
441 to type in the % explicitly. IPython will scan its internal list of
441 to type in the % explicitly. IPython will scan its internal list of
442 magic functions and call one if it exists. With automagic on you can
442 magic functions and call one if it exists. With automagic on you can
443 then just type 'cd mydir' to go to directory 'mydir'. The automagic
443 then just type 'cd mydir' to go to directory 'mydir'. The automagic
444 system has the lowest possible precedence in name searches, so defining
444 system has the lowest possible precedence in name searches, so defining
445 an identifier with the same name as an existing magic function will
445 an identifier with the same name as an existing magic function will
446 shadow it for automagic use. You can still access the shadowed magic
446 shadow it for automagic use. You can still access the shadowed magic
447 function by explicitly using the % character at the beginning of the line.
447 function by explicitly using the % character at the beginning of the line.
448
448
449 An example (with automagic on) should clarify all this::
449 An example (with automagic on) should clarify all this::
450
450
451 In [1]: cd ipython # %cd is called by automagic
451 In [1]: cd ipython # %cd is called by automagic
452
452
453 /home/fperez/ipython
453 /home/fperez/ipython
454
454
455 In [2]: cd=1 # now cd is just a variable
455 In [2]: cd=1 # now cd is just a variable
456
456
457 In [3]: cd .. # and doesn't work as a function anymore
457 In [3]: cd .. # and doesn't work as a function anymore
458
458
459 ------------------------------
459 ------------------------------
460
460
461 File "<console>", line 1
461 File "<console>", line 1
462
462
463 cd ..
463 cd ..
464
464
465 ^
465 ^
466
466
467 SyntaxError: invalid syntax
467 SyntaxError: invalid syntax
468
468
469 In [4]: %cd .. # but %cd always works
469 In [4]: %cd .. # but %cd always works
470
470
471 /home/fperez
471 /home/fperez
472
472
473 In [5]: del cd # if you remove the cd variable
473 In [5]: del cd # if you remove the cd variable
474
474
475 In [6]: cd ipython # automagic can work again
475 In [6]: cd ipython # automagic can work again
476
476
477 /home/fperez/ipython
477 /home/fperez/ipython
478
478
479 You can define your own magic functions to extend the system. The
479 You can define your own magic functions to extend the system. The
480 following example defines a new magic command, %impall::
480 following example defines a new magic command, %impall::
481
481
482 import IPython.ipapi
482 import IPython.ipapi
483
483
484 ip = IPython.ipapi.get()
484 ip = IPython.ipapi.get()
485
485
486 def doimp(self, arg):
486 def doimp(self, arg):
487
487
488 ip = self.api
488 ip = self.api
489
489
490 ip.ex("import %s; reload(%s); from %s import *" % (
490 ip.ex("import %s; reload(%s); from %s import *" % (
491
491
492 arg,arg,arg)
492 arg,arg,arg)
493
493
494 )
494 )
495
495
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
505 Type %magic for more information, including a list of all available
505 Type %magic for more information, including a list of all available
506 magic functions at any time and their docstrings. You can also type
506 magic functions at any time and their docstrings. You can also type
507 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
507 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
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 ----------------------------------
2080
517
2081 As of Python 2.1, a help system is available with access to object docstrings
518 As of Python 2.1, a help system is available with access to object docstrings
2082 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
519 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
2083 also type help(object) to obtain information about a given object, and
520 also type help(object) to obtain information about a given object, and
2084 help('keyword') for information on a keyword. As noted :ref:`here
521 help('keyword') for information on a keyword. As noted :ref:`here
2085 <accessing_help>`, you need to properly configure your environment variable
522 <accessing_help>`, you need to properly configure your environment variable
2086 PYTHONDOCS for this feature to work correctly.
523 PYTHONDOCS for this feature to work correctly.
2087
524
2088 .. _dynamic_object_info:
525 .. _dynamic_object_info:
2089
526
2090 Dynamic object information
527 Dynamic object information
2091 --------------------------
528 --------------------------
2092
529
2093 Typing ?word or word? prints detailed information about an object. If
530 Typing ?word or word? prints detailed information about an object. If
2094 certain strings in the object are too long (docstrings, code, etc.) they
531 certain strings in the object are too long (docstrings, code, etc.) they
2095 get snipped in the center for brevity. This system gives access variable
532 get snipped in the center for brevity. This system gives access variable
2096 types and values, full source code for any object (if available),
533 types and values, full source code for any object (if available),
2097 function prototypes and other useful information.
534 function prototypes and other useful information.
2098
535
2099 Typing ??word or word?? gives access to the full information without
536 Typing ??word or word?? gives access to the full information without
2100 snipping long strings. Long strings are sent to the screen through the
537 snipping long strings. Long strings are sent to the screen through the
2101 less pager if longer than the screen and printed otherwise. On systems
538 less pager if longer than the screen and printed otherwise. On systems
2102 lacking the less command, IPython uses a very basic internal pager.
539 lacking the less command, IPython uses a very basic internal pager.
2103
540
2104 The following magic functions are particularly useful for gathering
541 The following magic functions are particularly useful for gathering
2105 information about your working environment. You can get more details by
542 information about your working environment. You can get more details by
2106 typing %magic or querying them individually (use %function_name? with or
543 typing %magic or querying them individually (use %function_name? with or
2107 without the %), this is just a summary:
544 without the %), this is just a summary:
2108
545
2109 * **%pdoc <object>**: Print (or run through a pager if too long) the
546 * **%pdoc <object>**: Print (or run through a pager if too long) the
2110 docstring for an object. If the given object is a class, it will
547 docstring for an object. If the given object is a class, it will
2111 print both the class and the constructor docstrings.
548 print both the class and the constructor docstrings.
2112 * **%pdef <object>**: Print the definition header for any callable
549 * **%pdef <object>**: Print the definition header for any callable
2113 object. If the object is a class, print the constructor information.
550 object. If the object is a class, print the constructor information.
2114 * **%psource <object>**: Print (or run through a pager if too long)
551 * **%psource <object>**: Print (or run through a pager if too long)
2115 the source code for an object.
552 the source code for an object.
2116 * **%pfile <object>**: Show the entire source file where an object was
553 * **%pfile <object>**: Show the entire source file where an object was
2117 defined via a pager, opening it at the line where the object
554 defined via a pager, opening it at the line where the object
2118 definition begins.
555 definition begins.
2119 * **%who/%whos**: These functions give information about identifiers
556 * **%who/%whos**: These functions give information about identifiers
2120 you have defined interactively (not things you loaded or defined
557 you have defined interactively (not things you loaded or defined
2121 in your configuration files). %who just prints a list of
558 in your configuration files). %who just prints a list of
2122 identifiers and %whos prints a table with some basic details about
559 identifiers and %whos prints a table with some basic details about
2123 each identifier.
560 each identifier.
2124
561
2125 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
562 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
2126 %pdef, %psource) give you access to documentation even on things which
563 %pdef, %psource) give you access to documentation even on things which
2127 are not really defined as separate identifiers. Try for example typing
564 are not really defined as separate identifiers. Try for example typing
2128 {}.get? or after doing import os, type os.path.abspath??.
565 {}.get? or after doing import os, type os.path.abspath??.
2129
566
2130
567
2131 .. _readline:
568 .. _readline:
2132
569
2133 Readline-based features
570 Readline-based features
2134 -----------------------
571 -----------------------
2135
572
2136 These features require the GNU readline library, so they won't work if
573 These features require the GNU readline library, so they won't work if
2137 your Python installation lacks readline support. We will first describe
574 your Python installation lacks readline support. We will first describe
2138 the default behavior IPython uses, and then how to change it to suit
575 the default behavior IPython uses, and then how to change it to suit
2139 your preferences.
576 your preferences.
2140
577
2141
578
2142 Command line completion
579 Command line completion
2143 +++++++++++++++++++++++
580 +++++++++++++++++++++++
2144
581
2145 At any time, hitting TAB will complete any available python commands or
582 At any time, hitting TAB will complete any available python commands or
2146 variable names, and show you a list of the possible completions if
583 variable names, and show you a list of the possible completions if
2147 there's no unambiguous one. It will also complete filenames in the
584 there's no unambiguous one. It will also complete filenames in the
2148 current directory if no python names match what you've typed so far.
585 current directory if no python names match what you've typed so far.
2149
586
2150
587
2151 Search command history
588 Search command history
2152 ++++++++++++++++++++++
589 ++++++++++++++++++++++
2153
590
2154 IPython provides two ways for searching through previous input and thus
591 IPython provides two ways for searching through previous input and thus
2155 reduce the need for repetitive typing:
592 reduce the need for repetitive typing:
2156
593
2157 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
594 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
2158 (next,down) to search through only the history items that match
595 (next,down) to search through only the history items that match
2159 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
596 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
2160 prompt, they just behave like normal arrow keys.
597 prompt, they just behave like normal arrow keys.
2161 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
598 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
2162 searches your history for lines that contain what you've typed so
599 searches your history for lines that contain what you've typed so
2163 far, completing as much as it can.
600 far, completing as much as it can.
2164
601
2165
602
2166 Persistent command history across sessions
603 Persistent command history across sessions
2167 ++++++++++++++++++++++++++++++++++++++++++
604 ++++++++++++++++++++++++++++++++++++++++++
2168
605
2169 IPython will save your input history when it leaves and reload it next
606 IPython will save your input history when it leaves and reload it next
2170 time you restart it. By default, the history file is named
607 time you restart it. By default, the history file is named
2171 $IPYTHONDIR/history, but if you've loaded a named profile,
608 $IPYTHONDIR/history, but if you've loaded a named profile,
2172 '-PROFILE_NAME' is appended to the name. This allows you to keep
609 '-PROFILE_NAME' is appended to the name. This allows you to keep
2173 separate histories related to various tasks: commands related to
610 separate histories related to various tasks: commands related to
2174 numerical work will not be clobbered by a system shell history, for
611 numerical work will not be clobbered by a system shell history, for
2175 example.
612 example.
2176
613
2177
614
2178 Autoindent
615 Autoindent
2179 ++++++++++
616 ++++++++++
2180
617
2181 IPython can recognize lines ending in ':' and indent the next line,
618 IPython can recognize lines ending in ':' and indent the next line,
2182 while also un-indenting automatically after 'raise' or 'return'.
619 while also un-indenting automatically after 'raise' or 'return'.
2183
620
2184 This feature uses the readline library, so it will honor your ~/.inputrc
621 This feature uses the readline library, so it will honor your ~/.inputrc
2185 configuration (or whatever file your INPUTRC variable points to). Adding
622 configuration (or whatever file your INPUTRC variable points to). Adding
2186 the following lines to your .inputrc file can make indenting/unindenting
623 the following lines to your .inputrc file can make indenting/unindenting
2187 more convenient (M-i indents, M-u unindents)::
624 more convenient (M-i indents, M-u unindents)::
2188
625
2189 $if Python
626 $if Python
2190 "\M-i": " "
627 "\M-i": " "
2191 "\M-u": "\d\d\d\d"
628 "\M-u": "\d\d\d\d"
2192 $endif
629 $endif
2193
630
2194 Note that there are 4 spaces between the quote marks after "M-i" above.
631 Note that there are 4 spaces between the quote marks after "M-i" above.
2195
632
2196 Warning: this feature is ON by default, but it can cause problems with
633 Warning: this feature is ON by default, but it can cause problems with
2197 the pasting of multi-line indented code (the pasted code gets
634 the pasting of multi-line indented code (the pasted code gets
2198 re-indented on each line). A magic function %autoindent allows you to
635 re-indented on each line). A magic function %autoindent allows you to
2199 toggle it on/off at runtime. You can also disable it permanently on in
636 toggle it on/off at runtime. You can also disable it permanently on in
2200 your ipythonrc file (set autoindent 0).
637 your ipythonrc file (set autoindent 0).
2201
638
2202
639
2203 Customizing readline behavior
640 Customizing readline behavior
2204 +++++++++++++++++++++++++++++
641 +++++++++++++++++++++++++++++
2205
642
2206 All these features are based on the GNU readline library, which has an
643 All these features are based on the GNU readline library, which has an
2207 extremely customizable interface. Normally, readline is configured via a
644 extremely customizable interface. Normally, readline is configured via a
2208 file which defines the behavior of the library; the details of the
645 file which defines the behavior of the library; the details of the
2209 syntax for this can be found in the readline documentation available
646 syntax for this can be found in the readline documentation available
2210 with your system or on the Internet. IPython doesn't read this file (if
647 with your system or on the Internet. IPython doesn't read this file (if
2211 it exists) directly, but it does support passing to readline valid
648 it exists) directly, but it does support passing to readline valid
2212 options via a simple interface. In brief, you can customize readline by
649 options via a simple interface. In brief, you can customize readline by
2213 setting the following options in your ipythonrc configuration file (note
650 setting the following options in your ipythonrc configuration file (note
2214 that these options can not be specified at the command line):
651 that these options can not be specified at the command line):
2215
652
2216 * **readline_parse_and_bind**: this option can appear as many times as
653 * **readline_parse_and_bind**: this option can appear as many times as
2217 you want, each time defining a string to be executed via a
654 you want, each time defining a string to be executed via a
2218 readline.parse_and_bind() command. The syntax for valid commands
655 readline.parse_and_bind() command. The syntax for valid commands
2219 of this kind can be found by reading the documentation for the GNU
656 of this kind can be found by reading the documentation for the GNU
2220 readline library, as these commands are of the kind which readline
657 readline library, as these commands are of the kind which readline
2221 accepts in its configuration file.
658 accepts in its configuration file.
2222 * **readline_remove_delims**: a string of characters to be removed
659 * **readline_remove_delims**: a string of characters to be removed
2223 from the default word-delimiters list used by readline, so that
660 from the default word-delimiters list used by readline, so that
2224 completions may be performed on strings which contain them. Do not
661 completions may be performed on strings which contain them. Do not
2225 change the default value unless you know what you're doing.
662 change the default value unless you know what you're doing.
2226 * **readline_omit__names**: when tab-completion is enabled, hitting
663 * **readline_omit__names**: when tab-completion is enabled, hitting
2227 <tab> after a '.' in a name will complete all attributes of an
664 <tab> after a '.' in a name will complete all attributes of an
2228 object, including all the special methods whose names include
665 object, including all the special methods whose names include
2229 double underscores (like __getitem__ or __class__). If you'd
666 double underscores (like __getitem__ or __class__). If you'd
2230 rather not see these names by default, you can set this option to
667 rather not see these names by default, you can set this option to
2231 1. Note that even when this option is set, you can still see those
668 1. Note that even when this option is set, you can still see those
2232 names by explicitly typing a _ after the period and hitting <tab>:
669 names by explicitly typing a _ after the period and hitting <tab>:
2233 'name._<tab>' will always complete attribute names starting with '_'.
670 'name._<tab>' will always complete attribute names starting with '_'.
2234
671
2235 This option is off by default so that new users see all
672 This option is off by default so that new users see all
2236 attributes of any objects they are dealing with.
673 attributes of any objects they are dealing with.
2237
674
2238 You will find the default values along with a corresponding detailed
675 You will find the default values along with a corresponding detailed
2239 explanation in your ipythonrc file.
676 explanation in your ipythonrc file.
2240
677
2241
678
2242 Session logging and restoring
679 Session logging and restoring
2243 -----------------------------
680 -----------------------------
2244
681
2245 You can log all input from a session either by starting IPython with the
682 You can log all input from a session either by starting IPython with the
2246 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
683 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
2247 or by activating the logging at any moment with the magic function %logstart.
684 or by activating the logging at any moment with the magic function %logstart.
2248
685
2249 Log files can later be reloaded with the -logplay option and IPython
686 Log files can later be reloaded with the -logplay option and IPython
2250 will attempt to 'replay' the log by executing all the lines in it, thus
687 will attempt to 'replay' the log by executing all the lines in it, thus
2251 restoring the state of a previous session. This feature is not quite
688 restoring the state of a previous session. This feature is not quite
2252 perfect, but can still be useful in many cases.
689 perfect, but can still be useful in many cases.
2253
690
2254 The log files can also be used as a way to have a permanent record of
691 The log files can also be used as a way to have a permanent record of
2255 any code you wrote while experimenting. Log files are regular text files
692 any code you wrote while experimenting. Log files are regular text files
2256 which you can later open in your favorite text editor to extract code or
693 which you can later open in your favorite text editor to extract code or
2257 to 'clean them up' before using them to replay a session.
694 to 'clean them up' before using them to replay a session.
2258
695
2259 The %logstart function for activating logging in mid-session is used as
696 The %logstart function for activating logging in mid-session is used as
2260 follows:
697 follows:
2261
698
2262 %logstart [log_name [log_mode]]
699 %logstart [log_name [log_mode]]
2263
700
2264 If no name is given, it defaults to a file named 'log' in your
701 If no name is given, it defaults to a file named 'log' in your
2265 IPYTHONDIR directory, in 'rotate' mode (see below).
702 IPYTHONDIR directory, in 'rotate' mode (see below).
2266
703
2267 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
704 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
2268 history up to that point and then continues logging.
705 history up to that point and then continues logging.
2269
706
2270 %logstart takes a second optional parameter: logging mode. This can be
707 %logstart takes a second optional parameter: logging mode. This can be
2271 one of (note that the modes are given unquoted):
708 one of (note that the modes are given unquoted):
2272
709
2273 * [over:] overwrite existing log_name.
710 * [over:] overwrite existing log_name.
2274 * [backup:] rename (if exists) to log_name~ and start log_name.
711 * [backup:] rename (if exists) to log_name~ and start log_name.
2275 * [append:] well, that says it.
712 * [append:] well, that says it.
2276 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
713 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
2277
714
2278 The %logoff and %logon functions allow you to temporarily stop and
715 The %logoff and %logon functions allow you to temporarily stop and
2279 resume logging to a file which had previously been started with
716 resume logging to a file which had previously been started with
2280 %logstart. They will fail (with an explanation) if you try to use them
717 %logstart. They will fail (with an explanation) if you try to use them
2281 before logging has been started.
718 before logging has been started.
2282
719
2283 .. _system_shell_access:
720 .. _system_shell_access:
2284
721
2285 System shell access
722 System shell access
2286 -------------------
723 -------------------
2287
724
2288 Any input line beginning with a ! character is passed verbatim (minus
725 Any input line beginning with a ! character is passed verbatim (minus
2289 the !, of course) to the underlying operating system. For example,
726 the !, of course) to the underlying operating system. For example,
2290 typing !ls will run 'ls' in the current directory.
727 typing !ls will run 'ls' in the current directory.
2291
728
2292 Manual capture of command output
729 Manual capture of command output
2293 --------------------------------
730 --------------------------------
2294
731
2295 If the input line begins with two exclamation marks, !!, the command is
732 If the input line begins with two exclamation marks, !!, the command is
2296 executed but its output is captured and returned as a python list, split
733 executed but its output is captured and returned as a python list, split
2297 on newlines. Any output sent by the subprocess to standard error is
734 on newlines. Any output sent by the subprocess to standard error is
2298 printed separately, so that the resulting list only captures standard
735 printed separately, so that the resulting list only captures standard
2299 output. The !! syntax is a shorthand for the %sx magic command.
736 output. The !! syntax is a shorthand for the %sx magic command.
2300
737
2301 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
738 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
2302 but allowing more fine-grained control of the capture details, and
739 but allowing more fine-grained control of the capture details, and
2303 storing the result directly into a named variable. The direct use of
740 storing the result directly into a named variable. The direct use of
2304 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
741 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
2305 instead.
742 instead.
2306
743
2307 IPython also allows you to expand the value of python variables when
744 IPython also allows you to expand the value of python variables when
2308 making system calls. Any python variable or expression which you prepend
745 making system calls. Any python variable or expression which you prepend
2309 with $ will get expanded before the system call is made::
746 with $ will get expanded before the system call is made::
2310
747
2311 In [1]: pyvar='Hello world'
748 In [1]: pyvar='Hello world'
2312 In [2]: !echo "A python variable: $pyvar"
749 In [2]: !echo "A python variable: $pyvar"
2313 A python variable: Hello world
750 A python variable: Hello world
2314
751
2315 If you want the shell to actually see a literal $, you need to type it
752 If you want the shell to actually see a literal $, you need to type it
2316 twice::
753 twice::
2317
754
2318 In [3]: !echo "A system variable: $$HOME"
755 In [3]: !echo "A system variable: $$HOME"
2319 A system variable: /home/fperez
756 A system variable: /home/fperez
2320
757
2321 You can pass arbitrary expressions, though you'll need to delimit them
758 You can pass arbitrary expressions, though you'll need to delimit them
2322 with {} if there is ambiguity as to the extent of the expression::
759 with {} if there is ambiguity as to the extent of the expression::
2323
760
2324 In [5]: x=10
761 In [5]: x=10
2325 In [6]: y=20
762 In [6]: y=20
2326 In [13]: !echo $x+y
763 In [13]: !echo $x+y
2327 10+y
764 10+y
2328 In [7]: !echo ${x+y}
765 In [7]: !echo ${x+y}
2329 30
766 30
2330
767
2331 Even object attributes can be expanded::
768 Even object attributes can be expanded::
2332
769
2333 In [12]: !echo $sys.argv
770 In [12]: !echo $sys.argv
2334 [/home/fperez/usr/bin/ipython]
771 [/home/fperez/usr/bin/ipython]
2335
772
2336
773
2337 System command aliases
774 System command aliases
2338 ----------------------
775 ----------------------
2339
776
2340 The %alias magic function and the alias option in the ipythonrc
777 The %alias magic function and the alias option in the ipythonrc
2341 configuration file allow you to define magic functions which are in fact
778 configuration file allow you to define magic functions which are in fact
2342 system shell commands. These aliases can have parameters.
779 system shell commands. These aliases can have parameters.
2343
780
2344 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
781 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2345
782
2346 Then, typing '%alias_name params' will execute the system command 'cmd
783 Then, typing '%alias_name params' will execute the system command 'cmd
2347 params' (from your underlying operating system).
784 params' (from your underlying operating system).
2348
785
2349 You can also define aliases with parameters using %s specifiers (one per
786 You can also define aliases with parameters using %s specifiers (one per
2350 parameter). The following example defines the %parts function as an
787 parameter). The following example defines the %parts function as an
2351 alias to the command 'echo first %s second %s' where each %s will be
788 alias to the command 'echo first %s second %s' where each %s will be
2352 replaced by a positional parameter to the call to %parts::
789 replaced by a positional parameter to the call to %parts::
2353
790
2354 In [1]: alias parts echo first %s second %s
791 In [1]: alias parts echo first %s second %s
2355 In [2]: %parts A B
792 In [2]: %parts A B
2356 first A second B
793 first A second B
2357 In [3]: %parts A
794 In [3]: %parts A
2358 Incorrect number of arguments: 2 expected.
795 Incorrect number of arguments: 2 expected.
2359 parts is an alias to: 'echo first %s second %s'
796 parts is an alias to: 'echo first %s second %s'
2360
797
2361 If called with no parameters, %alias prints the table of currently
798 If called with no parameters, %alias prints the table of currently
2362 defined aliases.
799 defined aliases.
2363
800
2364 The %rehash/rehashx magics allow you to load your entire $PATH as
801 The %rehash/rehashx magics allow you to load your entire $PATH as
2365 ipython aliases. See their respective docstrings (or sec. 6.2
802 ipython aliases. See their respective docstrings (or sec. 6.2
2366 <#sec:magic> for further details).
803 <#sec:magic> for further details).
2367
804
2368
805
2369 .. _dreload:
806 .. _dreload:
2370
807
2371 Recursive reload
808 Recursive reload
2372 ----------------
809 ----------------
2373
810
2374 The dreload function does a recursive reload of a module: changes made
811 The dreload function does a recursive reload of a module: changes made
2375 to the module since you imported will actually be available without
812 to the module since you imported will actually be available without
2376 having to exit.
813 having to exit.
2377
814
2378
815
2379 Verbose and colored exception traceback printouts
816 Verbose and colored exception traceback printouts
2380 -------------------------------------------------
817 -------------------------------------------------
2381
818
2382 IPython provides the option to see very detailed exception tracebacks,
819 IPython provides the option to see very detailed exception tracebacks,
2383 which can be especially useful when debugging large programs. You can
820 which can be especially useful when debugging large programs. You can
2384 run any Python file with the %run function to benefit from these
821 run any Python file with the %run function to benefit from these
2385 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
822 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
2386 be colored (if your terminal supports it) which makes them much easier
823 be colored (if your terminal supports it) which makes them much easier
2387 to parse visually.
824 to parse visually.
2388
825
2389 See the magic xmode and colors functions for details (just type %magic).
826 See the magic xmode and colors functions for details (just type %magic).
2390
827
2391 These features are basically a terminal version of Ka-Ping Yee's cgitb
828 These features are basically a terminal version of Ka-Ping Yee's cgitb
2392 module, now part of the standard Python library.
829 module, now part of the standard Python library.
2393
830
2394
831
2395 .. _input_caching:
832 .. _input_caching:
2396
833
2397 Input caching system
834 Input caching system
2398 --------------------
835 --------------------
2399
836
2400 IPython offers numbered prompts (In/Out) with input and output caching.
837 IPython offers numbered prompts (In/Out) with input and output caching.
2401 All input is saved and can be retrieved as variables (besides the usual
838 All input is saved and can be retrieved as variables (besides the usual
2402 arrow key recall).
839 arrow key recall).
2403
840
2404 The following GLOBAL variables always exist (so don't overwrite them!):
841 The following GLOBAL variables always exist (so don't overwrite them!):
2405 _i: stores previous input. _ii: next previous. _iii: next-next previous.
842 _i: stores previous input. _ii: next previous. _iii: next-next previous.
2406 _ih : a list of all input _ih[n] is the input from line n and this list
843 _ih : a list of all input _ih[n] is the input from line n and this list
2407 is aliased to the global variable In. If you overwrite In with a
844 is aliased to the global variable In. If you overwrite In with a
2408 variable of your own, you can remake the assignment to the internal list
845 variable of your own, you can remake the assignment to the internal list
2409 with a simple 'In=_ih'.
846 with a simple 'In=_ih'.
2410
847
2411 Additionally, global variables named _i<n> are dynamically created (<n>
848 Additionally, global variables named _i<n> are dynamically created (<n>
2412 being the prompt counter), such that
849 being the prompt counter), such that
2413 _i<n> == _ih[<n>] == In[<n>].
850 _i<n> == _ih[<n>] == In[<n>].
2414
851
2415 For example, what you typed at prompt 14 is available as _i14, _ih[14]
852 For example, what you typed at prompt 14 is available as _i14, _ih[14]
2416 and In[14].
853 and In[14].
2417
854
2418 This allows you to easily cut and paste multi line interactive prompts
855 This allows you to easily cut and paste multi line interactive prompts
2419 by printing them out: they print like a clean string, without prompt
856 by printing them out: they print like a clean string, without prompt
2420 characters. You can also manipulate them like regular variables (they
857 characters. You can also manipulate them like regular variables (they
2421 are strings), modify or exec them (typing 'exec _i9' will re-execute the
858 are strings), modify or exec them (typing 'exec _i9' will re-execute the
2422 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
859 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
2423 9 through 13 and line 18).
860 9 through 13 and line 18).
2424
861
2425 You can also re-execute multiple lines of input easily by using the
862 You can also re-execute multiple lines of input easily by using the
2426 magic %macro function (which automates the process and allows
863 magic %macro function (which automates the process and allows
2427 re-execution without having to type 'exec' every time). The macro system
864 re-execution without having to type 'exec' every time). The macro system
2428 also allows you to re-execute previous lines which include magic
865 also allows you to re-execute previous lines which include magic
2429 function calls (which require special processing). Type %macro? or see
866 function calls (which require special processing). Type %macro? or see
2430 sec. 6.2 <#sec:magic> for more details on the macro system.
867 sec. 6.2 <#sec:magic> for more details on the macro system.
2431
868
2432 A history function %hist allows you to see any part of your input
869 A history function %hist allows you to see any part of your input
2433 history by printing a range of the _i variables.
870 history by printing a range of the _i variables.
2434
871
2435 .. _output_caching:
872 .. _output_caching:
2436
873
2437 Output caching system
874 Output caching system
2438 ---------------------
875 ---------------------
2439
876
2440 For output that is returned from actions, a system similar to the input
877 For output that is returned from actions, a system similar to the input
2441 cache exists but using _ instead of _i. Only actions that produce a
878 cache exists but using _ instead of _i. Only actions that produce a
2442 result (NOT assignments, for example) are cached. If you are familiar
879 result (NOT assignments, for example) are cached. If you are familiar
2443 with Mathematica, IPython's _ variables behave exactly like
880 with Mathematica, IPython's _ variables behave exactly like
2444 Mathematica's % variables.
881 Mathematica's % variables.
2445
882
2446 The following GLOBAL variables always exist (so don't overwrite them!):
883 The following GLOBAL variables always exist (so don't overwrite them!):
2447
884
2448 * [_] (a single underscore) : stores previous output, like Python's
885 * [_] (a single underscore) : stores previous output, like Python's
2449 default interpreter.
886 default interpreter.
2450 * [__] (two underscores): next previous.
887 * [__] (two underscores): next previous.
2451 * [___] (three underscores): next-next previous.
888 * [___] (three underscores): next-next previous.
2452
889
2453 Additionally, global variables named _<n> are dynamically created (<n>
890 Additionally, global variables named _<n> are dynamically created (<n>
2454 being the prompt counter), such that the result of output <n> is always
891 being the prompt counter), such that the result of output <n> is always
2455 available as _<n> (don't use the angle brackets, just the number, e.g.
892 available as _<n> (don't use the angle brackets, just the number, e.g.
2456 _21).
893 _21).
2457
894
2458 These global variables are all stored in a global dictionary (not a
895 These global variables are all stored in a global dictionary (not a
2459 list, since it only has entries for lines which returned a result)
896 list, since it only has entries for lines which returned a result)
2460 available under the names _oh and Out (similar to _ih and In). So the
897 available under the names _oh and Out (similar to _ih and In). So the
2461 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
898 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
2462 accidentally overwrite the Out variable you can recover it by typing
899 accidentally overwrite the Out variable you can recover it by typing
2463 'Out=_oh' at the prompt.
900 'Out=_oh' at the prompt.
2464
901
2465 This system obviously can potentially put heavy memory demands on your
902 This system obviously can potentially put heavy memory demands on your
2466 system, since it prevents Python's garbage collector from removing any
903 system, since it prevents Python's garbage collector from removing any
2467 previously computed results. You can control how many results are kept
904 previously computed results. You can control how many results are kept
2468 in memory with the option (at the command line or in your ipythonrc
905 in memory with the option (at the command line or in your ipythonrc
2469 file) cache_size. If you set it to 0, the whole system is completely
906 file) cache_size. If you set it to 0, the whole system is completely
2470 disabled and the prompts revert to the classic '>>>' of normal Python.
907 disabled and the prompts revert to the classic '>>>' of normal Python.
2471
908
2472
909
2473 Directory history
910 Directory history
2474 -----------------
911 -----------------
2475
912
2476 Your history of visited directories is kept in the global list _dh, and
913 Your history of visited directories is kept in the global list _dh, and
2477 the magic %cd command can be used to go to any entry in that list. The
914 the magic %cd command can be used to go to any entry in that list. The
2478 %dhist command allows you to view this history. do ``cd -<TAB`` to
915 %dhist command allows you to view this history. do ``cd -<TAB`` to
2479 conventiently view the directory history.
916 conventiently view the directory history.
2480
917
2481
918
2482 Automatic parentheses and quotes
919 Automatic parentheses and quotes
2483 --------------------------------
920 --------------------------------
2484
921
2485 These features were adapted from Nathan Gray's LazyPython. They are
922 These features were adapted from Nathan Gray's LazyPython. They are
2486 meant to allow less typing for common situations.
923 meant to allow less typing for common situations.
2487
924
2488
925
2489 Automatic parentheses
926 Automatic parentheses
2490 ---------------------
927 ---------------------
2491
928
2492 Callable objects (i.e. functions, methods, etc) can be invoked like this
929 Callable objects (i.e. functions, methods, etc) can be invoked like this
2493 (notice the commas between the arguments)::
930 (notice the commas between the arguments)::
2494
931
2495 >>> callable_ob arg1, arg2, arg3
932 >>> callable_ob arg1, arg2, arg3
2496
933
2497 and the input will be translated to this::
934 and the input will be translated to this::
2498
935
2499 -> callable_ob(arg1, arg2, arg3)
936 -> callable_ob(arg1, arg2, arg3)
2500
937
2501 You can force automatic parentheses by using '/' as the first character
938 You can force automatic parentheses by using '/' as the first character
2502 of a line. For example::
939 of a line. For example::
2503
940
2504 >>> /globals # becomes 'globals()'
941 >>> /globals # becomes 'globals()'
2505
942
2506 Note that the '/' MUST be the first character on the line! This won't work::
943 Note that the '/' MUST be the first character on the line! This won't work::
2507
944
2508 >>> print /globals # syntax error
945 >>> print /globals # syntax error
2509
946
2510 In most cases the automatic algorithm should work, so you should rarely
947 In most cases the automatic algorithm should work, so you should rarely
2511 need to explicitly invoke /. One notable exception is if you are trying
948 need to explicitly invoke /. One notable exception is if you are trying
2512 to call a function with a list of tuples as arguments (the parenthesis
949 to call a function with a list of tuples as arguments (the parenthesis
2513 will confuse IPython)::
950 will confuse IPython)::
2514
951
2515 In [1]: zip (1,2,3),(4,5,6) # won't work
952 In [1]: zip (1,2,3),(4,5,6) # won't work
2516
953
2517 but this will work::
954 but this will work::
2518
955
2519 In [2]: /zip (1,2,3),(4,5,6)
956 In [2]: /zip (1,2,3),(4,5,6)
2520 ---> zip ((1,2,3),(4,5,6))
957 ---> zip ((1,2,3),(4,5,6))
2521 Out[2]= [(1, 4), (2, 5), (3, 6)]
958 Out[2]= [(1, 4), (2, 5), (3, 6)]
2522
959
2523 IPython tells you that it has altered your command line by displaying
960 IPython tells you that it has altered your command line by displaying
2524 the new command line preceded by ->. e.g.::
961 the new command line preceded by ->. e.g.::
2525
962
2526 In [18]: callable list
963 In [18]: callable list
2527 ----> callable (list)
964 ----> callable (list)
2528
965
2529
966
2530 Automatic quoting
967 Automatic quoting
2531 -----------------
968 -----------------
2532
969
2533 You can force automatic quoting of a function's arguments by using ','
970 You can force automatic quoting of a function's arguments by using ','
2534 or ';' as the first character of a line. For example::
971 or ';' as the first character of a line. For example::
2535
972
2536 >>> ,my_function /home/me # becomes my_function("/home/me")
973 >>> ,my_function /home/me # becomes my_function("/home/me")
2537
974
2538 If you use ';' instead, the whole argument is quoted as a single string
975 If you use ';' instead, the whole argument is quoted as a single string
2539 (while ',' splits on whitespace)::
976 (while ',' splits on whitespace)::
2540
977
2541 >>> ,my_function a b c # becomes my_function("a","b","c")
978 >>> ,my_function a b c # becomes my_function("a","b","c")
2542
979
2543 >>> ;my_function a b c # becomes my_function("a b c")
980 >>> ;my_function a b c # becomes my_function("a b c")
2544
981
2545 Note that the ',' or ';' MUST be the first character on the line! This
982 Note that the ',' or ';' MUST be the first character on the line! This
2546 won't work::
983 won't work::
2547
984
2548 >>> x = ,my_function /home/me # syntax error
985 >>> x = ,my_function /home/me # syntax error
2549
986
2550 IPython as your default Python environment
987 IPython as your default Python environment
2551 ==========================================
988 ==========================================
2552
989
2553 Python honors the environment variable PYTHONSTARTUP and will execute at
990 Python honors the environment variable PYTHONSTARTUP and will execute at
2554 startup the file referenced by this variable. If you put at the end of
991 startup the file referenced by this variable. If you put at the end of
2555 this file the following two lines of code::
992 this file the following two lines of code::
2556
993
2557 import IPython
994 import IPython
2558 IPython.Shell.IPShell().mainloop(sys_exit=1)
995 IPython.Shell.IPShell().mainloop(sys_exit=1)
2559
996
2560 then IPython will be your working environment anytime you start Python.
997 then IPython will be your working environment anytime you start Python.
2561 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
998 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
2562 it finishes, otherwise you'll be back at the normal Python '>>>'
999 it finishes, otherwise you'll be back at the normal Python '>>>'
2563 prompt.
1000 prompt.
2564
1001
2565 This is probably useful to developers who manage multiple Python
1002 This is probably useful to developers who manage multiple Python
2566 versions and don't want to have correspondingly multiple IPython
1003 versions and don't want to have correspondingly multiple IPython
2567 versions. Note that in this mode, there is no way to pass IPython any
1004 versions. Note that in this mode, there is no way to pass IPython any
2568 command-line options, as those are trapped first by Python itself.
1005 command-line options, as those are trapped first by Python itself.
2569
1006
2570 .. _Embedding:
1007 .. _Embedding:
2571
1008
2572 Embedding IPython
1009 Embedding IPython
2573 =================
1010 =================
2574
1011
2575 It is possible to start an IPython instance inside your own Python
1012 It is possible to start an IPython instance inside your own Python
2576 programs. This allows you to evaluate dynamically the state of your
1013 programs. This allows you to evaluate dynamically the state of your
2577 code, operate with your variables, analyze them, etc. Note however that
1014 code, operate with your variables, analyze them, etc. Note however that
2578 any changes you make to values while in the shell do not propagate back
1015 any changes you make to values while in the shell do not propagate back
2579 to the running code, so it is safe to modify your values because you
1016 to the running code, so it is safe to modify your values because you
2580 won't break your code in bizarre ways by doing so.
1017 won't break your code in bizarre ways by doing so.
2581
1018
2582 This feature allows you to easily have a fully functional python
1019 This feature allows you to easily have a fully functional python
2583 environment for doing object introspection anywhere in your code with a
1020 environment for doing object introspection anywhere in your code with a
2584 simple function call. In some cases a simple print statement is enough,
1021 simple function call. In some cases a simple print statement is enough,
2585 but if you need to do more detailed analysis of a code fragment this
1022 but if you need to do more detailed analysis of a code fragment this
2586 feature can be very valuable.
1023 feature can be very valuable.
2587
1024
2588 It can also be useful in scientific computing situations where it is
1025 It can also be useful in scientific computing situations where it is
2589 common to need to do some automatic, computationally intensive part and
1026 common to need to do some automatic, computationally intensive part and
2590 then stop to look at data, plots, etc.
1027 then stop to look at data, plots, etc.
2591 Opening an IPython instance will give you full access to your data and
1028 Opening an IPython instance will give you full access to your data and
2592 functions, and you can resume program execution once you are done with
1029 functions, and you can resume program execution once you are done with
2593 the interactive part (perhaps to stop again later, as many times as
1030 the interactive part (perhaps to stop again later, as many times as
2594 needed).
1031 needed).
2595
1032
2596 The following code snippet is the bare minimum you need to include in
1033 The following code snippet is the bare minimum you need to include in
2597 your Python programs for this to work (detailed examples follow later)::
1034 your Python programs for this to work (detailed examples follow later)::
2598
1035
2599 from IPython.Shell import IPShellEmbed
1036 from IPython.Shell import IPShellEmbed
2600
1037
2601 ipshell = IPShellEmbed()
1038 ipshell = IPShellEmbed()
2602
1039
2603 ipshell() # this call anywhere in your program will start IPython
1040 ipshell() # this call anywhere in your program will start IPython
2604
1041
2605 You can run embedded instances even in code which is itself being run at
1042 You can run embedded instances even in code which is itself being run at
2606 the IPython interactive prompt with '%run <filename>'. Since it's easy
1043 the IPython interactive prompt with '%run <filename>'. Since it's easy
2607 to get lost as to where you are (in your top-level IPython or in your
1044 to get lost as to where you are (in your top-level IPython or in your
2608 embedded one), it's a good idea in such cases to set the in/out prompts
1045 embedded one), it's a good idea in such cases to set the in/out prompts
2609 to something different for the embedded instances. The code examples
1046 to something different for the embedded instances. The code examples
2610 below illustrate this.
1047 below illustrate this.
2611
1048
2612 You can also have multiple IPython instances in your program and open
1049 You can also have multiple IPython instances in your program and open
2613 them separately, for example with different options for data
1050 them separately, for example with different options for data
2614 presentation. If you close and open the same instance multiple times,
1051 presentation. If you close and open the same instance multiple times,
2615 its prompt counters simply continue from each execution to the next.
1052 its prompt counters simply continue from each execution to the next.
2616
1053
2617 Please look at the docstrings in the Shell.py module for more details on
1054 Please look at the docstrings in the Shell.py module for more details on
2618 the use of this system.
1055 the use of this system.
2619
1056
2620 The following sample file illustrating how to use the embedding
1057 The following sample file illustrating how to use the embedding
2621 functionality is provided in the examples directory as example-embed.py.
1058 functionality is provided in the examples directory as example-embed.py.
2622 It should be fairly self-explanatory::
1059 It should be fairly self-explanatory::
2623
1060
2624
1061
2625 #!/usr/bin/env python
1062 #!/usr/bin/env python
2626
1063
2627 """An example of how to embed an IPython shell into a running program.
1064 """An example of how to embed an IPython shell into a running program.
2628
1065
2629 Please see the documentation in the IPython.Shell module for more details.
1066 Please see the documentation in the IPython.Shell module for more details.
2630
1067
2631 The accompanying file example-embed-short.py has quick code fragments for
1068 The accompanying file example-embed-short.py has quick code fragments for
2632 embedding which you can cut and paste in your code once you understand how
1069 embedding which you can cut and paste in your code once you understand how
2633 things work.
1070 things work.
2634
1071
2635 The code in this file is deliberately extra-verbose, meant for learning."""
1072 The code in this file is deliberately extra-verbose, meant for learning."""
2636
1073
2637 # The basics to get you going:
1074 # The basics to get you going:
2638
1075
2639 # IPython sets the __IPYTHON__ variable so you can know if you have nested
1076 # IPython sets the __IPYTHON__ variable so you can know if you have nested
2640 # copies running.
1077 # copies running.
2641
1078
2642 # Try running this code both at the command line and from inside IPython (with
1079 # Try running this code both at the command line and from inside IPython (with
2643 # %run example-embed.py)
1080 # %run example-embed.py)
2644 try:
1081 try:
2645 __IPYTHON__
1082 __IPYTHON__
2646 except NameError:
1083 except NameError:
2647 nested = 0
1084 nested = 0
2648 args = ['']
1085 args = ['']
2649 else:
1086 else:
2650 print "Running nested copies of IPython."
1087 print "Running nested copies of IPython."
2651 print "The prompts for the nested copy have been modified"
1088 print "The prompts for the nested copy have been modified"
2652 nested = 1
1089 nested = 1
2653 # what the embedded instance will see as sys.argv:
1090 # what the embedded instance will see as sys.argv:
2654 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
1091 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
2655 '-po','Out<\\#>: ','-nosep']
1092 '-po','Out<\\#>: ','-nosep']
2656
1093
2657 # First import the embeddable shell class
1094 # First import the embeddable shell class
2658 from IPython.Shell import IPShellEmbed
1095 from IPython.Shell import IPShellEmbed
2659
1096
2660 # Now create an instance of the embeddable shell. The first argument is a
1097 # Now create an instance of the embeddable shell. The first argument is a
2661 # string with options exactly as you would type them if you were starting
1098 # string with options exactly as you would type them if you were starting
2662 # IPython at the system command line. Any parameters you want to define for
1099 # IPython at the system command line. Any parameters you want to define for
2663 # configuration can thus be specified here.
1100 # configuration can thus be specified here.
2664 ipshell = IPShellEmbed(args,
1101 ipshell = IPShellEmbed(args,
2665 banner = 'Dropping into IPython',
1102 banner = 'Dropping into IPython',
2666 exit_msg = 'Leaving Interpreter, back to program.')
1103 exit_msg = 'Leaving Interpreter, back to program.')
2667
1104
2668 # Make a second instance, you can have as many as you want.
1105 # Make a second instance, you can have as many as you want.
2669 if nested:
1106 if nested:
2670 args[1] = 'In2<\\#>'
1107 args[1] = 'In2<\\#>'
2671 else:
1108 else:
2672 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
1109 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
2673 '-po','Out<\\#>: ','-nosep']
1110 '-po','Out<\\#>: ','-nosep']
2674 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
1111 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
2675
1112
2676 print '\nHello. This is printed from the main controller program.\n'
1113 print '\nHello. This is printed from the main controller program.\n'
2677
1114
2678 # You can then call ipshell() anywhere you need it (with an optional
1115 # You can then call ipshell() anywhere you need it (with an optional
2679 # message):
1116 # message):
2680 ipshell('***Called from top level. '
1117 ipshell('***Called from top level. '
2681 'Hit Ctrl-D to exit interpreter and continue program.\n'
1118 'Hit Ctrl-D to exit interpreter and continue program.\n'
2682 'Note that if you use %kill_embedded, you can fully deactivate\n'
1119 'Note that if you use %kill_embedded, you can fully deactivate\n'
2683 'This embedded instance so it will never turn on again')
1120 'This embedded instance so it will never turn on again')
2684
1121
2685 print '\nBack in caller program, moving along...\n'
1122 print '\nBack in caller program, moving along...\n'
2686
1123
2687 #---------------------------------------------------------------------------
1124 #---------------------------------------------------------------------------
2688 # More details:
1125 # More details:
2689
1126
2690 # IPShellEmbed instances don't print the standard system banner and
1127 # IPShellEmbed instances don't print the standard system banner and
2691 # messages. The IPython banner (which actually may contain initialization
1128 # messages. The IPython banner (which actually may contain initialization
2692 # messages) is available as <instance>.IP.BANNER in case you want it.
1129 # messages) is available as <instance>.IP.BANNER in case you want it.
2693
1130
2694 # IPShellEmbed instances print the following information everytime they
1131 # IPShellEmbed instances print the following information everytime they
2695 # start:
1132 # start:
2696
1133
2697 # - A global startup banner.
1134 # - A global startup banner.
2698
1135
2699 # - A call-specific header string, which you can use to indicate where in the
1136 # - A call-specific header string, which you can use to indicate where in the
2700 # execution flow the shell is starting.
1137 # execution flow the shell is starting.
2701
1138
2702 # They also print an exit message every time they exit.
1139 # They also print an exit message every time they exit.
2703
1140
2704 # Both the startup banner and the exit message default to None, and can be set
1141 # Both the startup banner and the exit message default to None, and can be set
2705 # either at the instance constructor or at any other time with the
1142 # either at the instance constructor or at any other time with the
2706 # set_banner() and set_exit_msg() methods.
1143 # set_banner() and set_exit_msg() methods.
2707
1144
2708 # The shell instance can be also put in 'dummy' mode globally or on a per-call
1145 # The shell instance can be also put in 'dummy' mode globally or on a per-call
2709 # basis. This gives you fine control for debugging without having to change
1146 # basis. This gives you fine control for debugging without having to change
2710 # code all over the place.
1147 # code all over the place.
2711
1148
2712 # The code below illustrates all this.
1149 # The code below illustrates all this.
2713
1150
2714
1151
2715 # This is how the global banner and exit_msg can be reset at any point
1152 # This is how the global banner and exit_msg can be reset at any point
2716 ipshell.set_banner('Entering interpreter - New Banner')
1153 ipshell.set_banner('Entering interpreter - New Banner')
2717 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
1154 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
2718
1155
2719 def foo(m):
1156 def foo(m):
2720 s = 'spam'
1157 s = 'spam'
2721 ipshell('***In foo(). Try @whos, or print s or m:')
1158 ipshell('***In foo(). Try @whos, or print s or m:')
2722 print 'foo says m = ',m
1159 print 'foo says m = ',m
2723
1160
2724 def bar(n):
1161 def bar(n):
2725 s = 'eggs'
1162 s = 'eggs'
2726 ipshell('***In bar(). Try @whos, or print s or n:')
1163 ipshell('***In bar(). Try @whos, or print s or n:')
2727 print 'bar says n = ',n
1164 print 'bar says n = ',n
2728
1165
2729 # Some calls to the above functions which will trigger IPython:
1166 # Some calls to the above functions which will trigger IPython:
2730 print 'Main program calling foo("eggs")\n'
1167 print 'Main program calling foo("eggs")\n'
2731 foo('eggs')
1168 foo('eggs')
2732
1169
2733 # The shell can be put in 'dummy' mode where calls to it silently return. This
1170 # The shell can be put in 'dummy' mode where calls to it silently return. This
2734 # allows you, for example, to globally turn off debugging for a program with a
1171 # allows you, for example, to globally turn off debugging for a program with a
2735 # single call.
1172 # single call.
2736 ipshell.set_dummy_mode(1)
1173 ipshell.set_dummy_mode(1)
2737 print '\nTrying to call IPython which is now "dummy":'
1174 print '\nTrying to call IPython which is now "dummy":'
2738 ipshell()
1175 ipshell()
2739 print 'Nothing happened...'
1176 print 'Nothing happened...'
2740 # The global 'dummy' mode can still be overridden for a single call
1177 # The global 'dummy' mode can still be overridden for a single call
2741 print '\nOverriding dummy mode manually:'
1178 print '\nOverriding dummy mode manually:'
2742 ipshell(dummy=0)
1179 ipshell(dummy=0)
2743
1180
2744 # Reactivate the IPython shell
1181 # Reactivate the IPython shell
2745 ipshell.set_dummy_mode(0)
1182 ipshell.set_dummy_mode(0)
2746
1183
2747 print 'You can even have multiple embedded instances:'
1184 print 'You can even have multiple embedded instances:'
2748 ipshell2()
1185 ipshell2()
2749
1186
2750 print '\nMain program calling bar("spam")\n'
1187 print '\nMain program calling bar("spam")\n'
2751 bar('spam')
1188 bar('spam')
2752
1189
2753 print 'Main program finished. Bye!'
1190 print 'Main program finished. Bye!'
2754
1191
2755 #********************** End of file <example-embed.py> ***********************
1192 #********************** End of file <example-embed.py> ***********************
2756
1193
2757 Once you understand how the system functions, you can use the following
1194 Once you understand how the system functions, you can use the following
2758 code fragments in your programs which are ready for cut and paste::
1195 code fragments in your programs which are ready for cut and paste::
2759
1196
2760
1197
2761 """Quick code snippets for embedding IPython into other programs.
1198 """Quick code snippets for embedding IPython into other programs.
2762
1199
2763 See example-embed.py for full details, this file has the bare minimum code for
1200 See example-embed.py for full details, this file has the bare minimum code for
2764 cut and paste use once you understand how to use the system."""
1201 cut and paste use once you understand how to use the system."""
2765
1202
2766 #---------------------------------------------------------------------------
1203 #---------------------------------------------------------------------------
2767 # This code loads IPython but modifies a few things if it detects it's running
1204 # This code loads IPython but modifies a few things if it detects it's running
2768 # embedded in another IPython session (helps avoid confusion)
1205 # embedded in another IPython session (helps avoid confusion)
2769
1206
2770 try:
1207 try:
2771 __IPYTHON__
1208 __IPYTHON__
2772 except NameError:
1209 except NameError:
2773 argv = ['']
1210 argv = ['']
2774 banner = exit_msg = ''
1211 banner = exit_msg = ''
2775 else:
1212 else:
2776 # Command-line options for IPython (a list like sys.argv)
1213 # Command-line options for IPython (a list like sys.argv)
2777 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
1214 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
2778 banner = '*** Nested interpreter ***'
1215 banner = '*** Nested interpreter ***'
2779 exit_msg = '*** Back in main IPython ***'
1216 exit_msg = '*** Back in main IPython ***'
2780
1217
2781 # First import the embeddable shell class
1218 # First import the embeddable shell class
2782 from IPython.Shell import IPShellEmbed
1219 from IPython.Shell import IPShellEmbed
2783 # Now create the IPython shell instance. Put ipshell() anywhere in your code
1220 # Now create the IPython shell instance. Put ipshell() anywhere in your code
2784 # where you want it to open.
1221 # where you want it to open.
2785 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
1222 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
2786
1223
2787 #---------------------------------------------------------------------------
1224 #---------------------------------------------------------------------------
2788 # This code will load an embeddable IPython shell always with no changes for
1225 # This code will load an embeddable IPython shell always with no changes for
2789 # nested embededings.
1226 # nested embededings.
2790
1227
2791 from IPython.Shell import IPShellEmbed
1228 from IPython.Shell import IPShellEmbed
2792 ipshell = IPShellEmbed()
1229 ipshell = IPShellEmbed()
2793 # Now ipshell() will open IPython anywhere in the code.
1230 # Now ipshell() will open IPython anywhere in the code.
2794
1231
2795 #---------------------------------------------------------------------------
1232 #---------------------------------------------------------------------------
2796 # This code loads an embeddable shell only if NOT running inside
1233 # This code loads an embeddable shell only if NOT running inside
2797 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
1234 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
2798 # dummy function.
1235 # dummy function.
2799
1236
2800 try:
1237 try:
2801 __IPYTHON__
1238 __IPYTHON__
2802 except NameError:
1239 except NameError:
2803 from IPython.Shell import IPShellEmbed
1240 from IPython.Shell import IPShellEmbed
2804 ipshell = IPShellEmbed()
1241 ipshell = IPShellEmbed()
2805 # Now ipshell() will open IPython anywhere in the code
1242 # Now ipshell() will open IPython anywhere in the code
2806 else:
1243 else:
2807 # Define a dummy ipshell() so the same code doesn't crash inside an
1244 # Define a dummy ipshell() so the same code doesn't crash inside an
2808 # interactive IPython
1245 # interactive IPython
2809 def ipshell(): pass
1246 def ipshell(): pass
2810
1247
2811 #******************* End of file <example-embed-short.py> ********************
1248 #******************* End of file <example-embed-short.py> ********************
2812
1249
2813 Using the Python debugger (pdb)
1250 Using the Python debugger (pdb)
2814 ===============================
1251 ===============================
2815
1252
2816 Running entire programs via pdb
1253 Running entire programs via pdb
2817 -------------------------------
1254 -------------------------------
2818
1255
2819 pdb, the Python debugger, is a powerful interactive debugger which
1256 pdb, the Python debugger, is a powerful interactive debugger which
2820 allows you to step through code, set breakpoints, watch variables,
1257 allows you to step through code, set breakpoints, watch variables,
2821 etc. IPython makes it very easy to start any script under the control
1258 etc. IPython makes it very easy to start any script under the control
2822 of pdb, regardless of whether you have wrapped it into a 'main()'
1259 of pdb, regardless of whether you have wrapped it into a 'main()'
2823 function or not. For this, simply type '%run -d myscript' at an
1260 function or not. For this, simply type '%run -d myscript' at an
2824 IPython prompt. See the %run command's documentation (via '%run?' or
1261 IPython prompt. See the %run command's documentation (via '%run?' or
2825 in Sec. magic_ for more details, including how to control where pdb
1262 in Sec. magic_ for more details, including how to control where pdb
2826 will stop execution first.
1263 will stop execution first.
2827
1264
2828 For more information on the use of the pdb debugger, read the included
1265 For more information on the use of the pdb debugger, read the included
2829 pdb.doc file (part of the standard Python distribution). On a stock
1266 pdb.doc file (part of the standard Python distribution). On a stock
2830 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1267 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
2831 easiest way to read it is by using the help() function of the pdb module
1268 easiest way to read it is by using the help() function of the pdb module
2832 as follows (in an IPython prompt):
1269 as follows (in an IPython prompt):
2833
1270
2834 In [1]: import pdb
1271 In [1]: import pdb
2835 In [2]: pdb.help()
1272 In [2]: pdb.help()
2836
1273
2837 This will load the pdb.doc document in a file viewer for you automatically.
1274 This will load the pdb.doc document in a file viewer for you automatically.
2838
1275
2839
1276
2840 Automatic invocation of pdb on exceptions
1277 Automatic invocation of pdb on exceptions
2841 -----------------------------------------
1278 -----------------------------------------
2842
1279
2843 IPython, if started with the -pdb option (or if the option is set in
1280 IPython, if started with the -pdb option (or if the option is set in
2844 your rc file) can call the Python pdb debugger every time your code
1281 your rc file) can call the Python pdb debugger every time your code
2845 triggers an uncaught exception. This feature
1282 triggers an uncaught exception. This feature
2846 can also be toggled at any time with the %pdb magic command. This can be
1283 can also be toggled at any time with the %pdb magic command. This can be
2847 extremely useful in order to find the origin of subtle bugs, because pdb
1284 extremely useful in order to find the origin of subtle bugs, because pdb
2848 opens up at the point in your code which triggered the exception, and
1285 opens up at the point in your code which triggered the exception, and
2849 while your program is at this point 'dead', all the data is still
1286 while your program is at this point 'dead', all the data is still
2850 available and you can walk up and down the stack frame and understand
1287 available and you can walk up and down the stack frame and understand
2851 the origin of the problem.
1288 the origin of the problem.
2852
1289
2853 Furthermore, you can use these debugging facilities both with the
1290 Furthermore, you can use these debugging facilities both with the
2854 embedded IPython mode and without IPython at all. For an embedded shell
1291 embedded IPython mode and without IPython at all. For an embedded shell
2855 (see sec. Embedding_), simply call the constructor with
1292 (see sec. Embedding_), simply call the constructor with
2856 '-pdb' in the argument string and automatically pdb will be called if an
1293 '-pdb' in the argument string and automatically pdb will be called if an
2857 uncaught exception is triggered by your code.
1294 uncaught exception is triggered by your code.
2858
1295
2859 For stand-alone use of the feature in your programs which do not use
1296 For stand-alone use of the feature in your programs which do not use
2860 IPython at all, put the following lines toward the top of your 'main'
1297 IPython at all, put the following lines toward the top of your 'main'
2861 routine::
1298 routine::
2862
1299
2863 import sys,IPython.ultraTB
1300 import sys,IPython.ultraTB
2864 sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
1301 sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
2865 color_scheme='Linux', call_pdb=1)
1302 color_scheme='Linux', call_pdb=1)
2866
1303
2867 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1304 The mode keyword can be either 'Verbose' or 'Plain', giving either very
2868 detailed or normal tracebacks respectively. The color_scheme keyword can
1305 detailed or normal tracebacks respectively. The color_scheme keyword can
2869 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1306 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
2870 options which can be set in IPython with -colors and -xmode.
1307 options which can be set in IPython with -colors and -xmode.
2871
1308
2872 This will give any of your programs detailed, colored tracebacks with
1309 This will give any of your programs detailed, colored tracebacks with
2873 automatic invocation of pdb.
1310 automatic invocation of pdb.
2874
1311
2875
1312
2876 Extensions for syntax processing
1313 Extensions for syntax processing
2877 ================================
1314 ================================
2878
1315
2879 This isn't for the faint of heart, because the potential for breaking
1316 This isn't for the faint of heart, because the potential for breaking
2880 things is quite high. But it can be a very powerful and useful feature.
1317 things is quite high. But it can be a very powerful and useful feature.
2881 In a nutshell, you can redefine the way IPython processes the user input
1318 In a nutshell, you can redefine the way IPython processes the user input
2882 line to accept new, special extensions to the syntax without needing to
1319 line to accept new, special extensions to the syntax without needing to
2883 change any of IPython's own code.
1320 change any of IPython's own code.
2884
1321
2885 In the IPython/Extensions directory you will find some examples
1322 In the IPython/Extensions directory you will find some examples
2886 supplied, which we will briefly describe now. These can be used 'as is'
1323 supplied, which we will briefly describe now. These can be used 'as is'
2887 (and both provide very useful functionality), or you can use them as a
1324 (and both provide very useful functionality), or you can use them as a
2888 starting point for writing your own extensions.
1325 starting point for writing your own extensions.
2889
1326
2890
1327
2891 Pasting of code starting with '>>> ' or '... '
1328 Pasting of code starting with '>>> ' or '... '
2892 ----------------------------------------------
1329 ----------------------------------------------
2893
1330
2894 In the python tutorial it is common to find code examples which have
1331 In the python tutorial it is common to find code examples which have
2895 been taken from real python sessions. The problem with those is that all
1332 been taken from real python sessions. The problem with those is that all
2896 the lines begin with either '>>> ' or '... ', which makes it impossible
1333 the lines begin with either '>>> ' or '... ', which makes it impossible
2897 to paste them all at once. One must instead do a line by line manual
1334 to paste them all at once. One must instead do a line by line manual
2898 copying, carefully removing the leading extraneous characters.
1335 copying, carefully removing the leading extraneous characters.
2899
1336
2900 This extension identifies those starting characters and removes them
1337 This extension identifies those starting characters and removes them
2901 from the input automatically, so that one can paste multi-line examples
1338 from the input automatically, so that one can paste multi-line examples
2902 directly into IPython, saving a lot of time. Please look at the file
1339 directly into IPython, saving a lot of time. Please look at the file
2903 InterpreterPasteInput.py in the IPython/Extensions directory for details
1340 InterpreterPasteInput.py in the IPython/Extensions directory for details
2904 on how this is done.
1341 on how this is done.
2905
1342
2906 IPython comes with a special profile enabling this feature, called
1343 IPython comes with a special profile enabling this feature, called
2907 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1344 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
2908 will be available. In a normal IPython session you can activate the
1345 will be available. In a normal IPython session you can activate the
2909 feature by importing the corresponding module with:
1346 feature by importing the corresponding module with:
2910 In [1]: import IPython.Extensions.InterpreterPasteInput
1347 In [1]: import IPython.Extensions.InterpreterPasteInput
2911
1348
2912 The following is a 'screenshot' of how things work when this extension
1349 The following is a 'screenshot' of how things work when this extension
2913 is on, copying an example from the standard tutorial::
1350 is on, copying an example from the standard tutorial::
2914
1351
2915 IPython profile: tutorial
1352 IPython profile: tutorial
2916
1353
2917 *** Pasting of code with ">>>" or "..." has been enabled.
1354 *** Pasting of code with ">>>" or "..." has been enabled.
2918
1355
2919 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1356 In [1]: >>> def fib2(n): # return Fibonacci series up to n
2920 ...: ... """Return a list containing the Fibonacci series up to
1357 ...: ... """Return a list containing the Fibonacci series up to
2921 n."""
1358 n."""
2922 ...: ... result = []
1359 ...: ... result = []
2923 ...: ... a, b = 0, 1
1360 ...: ... a, b = 0, 1
2924 ...: ... while b < n:
1361 ...: ... while b < n:
2925 ...: ... result.append(b) # see below
1362 ...: ... result.append(b) # see below
2926 ...: ... a, b = b, a+b
1363 ...: ... a, b = b, a+b
2927 ...: ... return result
1364 ...: ... return result
2928 ...:
1365 ...:
2929
1366
2930 In [2]: fib2(10)
1367 In [2]: fib2(10)
2931 Out[2]: [1, 1, 2, 3, 5, 8]
1368 Out[2]: [1, 1, 2, 3, 5, 8]
2932
1369
2933 Note that as currently written, this extension does not recognize
1370 Note that as currently written, this extension does not recognize
2934 IPython's prompts for pasting. Those are more complicated, since the
1371 IPython's prompts for pasting. Those are more complicated, since the
2935 user can change them very easily, they involve numbers and can vary in
1372 user can change them very easily, they involve numbers and can vary in
2936 length. One could however extract all the relevant information from the
1373 length. One could however extract all the relevant information from the
2937 IPython instance and build an appropriate regular expression. This is
1374 IPython instance and build an appropriate regular expression. This is
2938 left as an exercise for the reader.
1375 left as an exercise for the reader.
2939
1376
2940
1377
2941 Input of physical quantities with units
1378 Input of physical quantities with units
2942 ---------------------------------------
1379 ---------------------------------------
2943
1380
2944 The module PhysicalQInput allows a simplified form of input for physical
1381 The module PhysicalQInput allows a simplified form of input for physical
2945 quantities with units. This file is meant to be used in conjunction with
1382 quantities with units. This file is meant to be used in conjunction with
2946 the PhysicalQInteractive module (in the same directory) and
1383 the PhysicalQInteractive module (in the same directory) and
2947 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1384 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
2948 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1385 (http://dirac.cnrs-orleans.fr/ScientificPython/).
2949
1386
2950 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1387 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
2951 but these must be declared as instances of a class. For example, to
1388 but these must be declared as instances of a class. For example, to
2952 define v as a velocity of 3 m/s, normally you would write::
1389 define v as a velocity of 3 m/s, normally you would write::
2953
1390
2954 In [1]: v = PhysicalQuantity(3,'m/s')
1391 In [1]: v = PhysicalQuantity(3,'m/s')
2955
1392
2956 Using the PhysicalQ_Input extension this can be input instead as:
1393 Using the PhysicalQ_Input extension this can be input instead as:
2957 In [1]: v = 3 m/s
1394 In [1]: v = 3 m/s
2958 which is much more convenient for interactive use (even though it is
1395 which is much more convenient for interactive use (even though it is
2959 blatantly invalid Python syntax).
1396 blatantly invalid Python syntax).
2960
1397
2961 The physics profile supplied with IPython (enabled via 'ipython -p
1398 The physics profile supplied with IPython (enabled via 'ipython -p
2962 physics') uses these extensions, which you can also activate with:
1399 physics') uses these extensions, which you can also activate with:
2963
1400
2964 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1401 from math import * # math MUST be imported BEFORE PhysicalQInteractive
2965 from IPython.Extensions.PhysicalQInteractive import *
1402 from IPython.Extensions.PhysicalQInteractive import *
2966 import IPython.Extensions.PhysicalQInput
1403 import IPython.Extensions.PhysicalQInput
2967
1404
2968
1405
2969 Threading support
1406 Threading support
2970 =================
1407 =================
2971
1408
2972 WARNING: The threading support is still somewhat experimental, and it
1409 WARNING: The threading support is still somewhat experimental, and it
2973 has only seen reasonable testing under Linux. Threaded code is
1410 has only seen reasonable testing under Linux. Threaded code is
2974 particularly tricky to debug, and it tends to show extremely
1411 particularly tricky to debug, and it tends to show extremely
2975 platform-dependent behavior. Since I only have access to Linux machines,
1412 platform-dependent behavior. Since I only have access to Linux machines,
2976 I will have to rely on user's experiences and assistance for this area
1413 I will have to rely on user's experiences and assistance for this area
2977 of IPython to improve under other platforms.
1414 of IPython to improve under other platforms.
2978
1415
2979 IPython, via the -gthread , -qthread, -q4thread and -wthread options
1416 IPython, via the -gthread , -qthread, -q4thread and -wthread options
2980 (described in Sec. `Threading options`_), can run in
1417 (described in Sec. `Threading options`_), can run in
2981 multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications
1418 multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications
2982 respectively. These GUI toolkits need to control the python main loop of
1419 respectively. These GUI toolkits need to control the python main loop of
2983 execution, so under a normal Python interpreter, starting a pyGTK, Qt3,
1420 execution, so under a normal Python interpreter, starting a pyGTK, Qt3,
2984 Qt4 or WXPython application will immediately freeze the shell.
1421 Qt4 or WXPython application will immediately freeze the shell.
2985
1422
2986 IPython, with one of these options (you can only use one at a time),
1423 IPython, with one of these options (you can only use one at a time),
2987 separates the graphical loop and IPython's code execution run into
1424 separates the graphical loop and IPython's code execution run into
2988 different threads. This allows you to test interactively (with %run, for
1425 different threads. This allows you to test interactively (with %run, for
2989 example) your GUI code without blocking.
1426 example) your GUI code without blocking.
2990
1427
2991 A nice mini-tutorial on using IPython along with the Qt Designer
1428 A nice mini-tutorial on using IPython along with the Qt Designer
2992 application is available at the SciPy wiki:
1429 application is available at the SciPy wiki:
2993 http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer.
1430 http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer.
2994
1431
2995
1432
2996 Tk issues
1433 Tk issues
2997 ---------
1434 ---------
2998
1435
2999 As indicated in Sec. `Threading options`_, a special -tk option is
1436 As indicated in Sec. `Threading options`_, a special -tk option is
3000 provided to try and allow Tk graphical applications to coexist
1437 provided to try and allow Tk graphical applications to coexist
3001 interactively with WX, Qt or GTK ones. Whether this works at all,
1438 interactively with WX, Qt or GTK ones. Whether this works at all,
3002 however, is very platform and configuration dependent. Please
1439 however, is very platform and configuration dependent. Please
3003 experiment with simple test cases before committing to using this
1440 experiment with simple test cases before committing to using this
3004 combination of Tk and GTK/Qt/WX threading in a production environment.
1441 combination of Tk and GTK/Qt/WX threading in a production environment.
3005
1442
3006
1443
3007 I/O pitfalls
1444 I/O pitfalls
3008 ------------
1445 ------------
3009
1446
3010 Be mindful that the Python interpreter switches between threads every
1447 Be mindful that the Python interpreter switches between threads every
3011 $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This
1448 $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This
3012 value can be read by using the sys.getcheckinterval() function, and it
1449 value can be read by using the sys.getcheckinterval() function, and it
3013 can be reset via sys.setcheckinterval(N). This switching of threads can
1450 can be reset via sys.setcheckinterval(N). This switching of threads can
3014 cause subtly confusing effects if one of your threads is doing file I/O.
1451 cause subtly confusing effects if one of your threads is doing file I/O.
3015 In text mode, most systems only flush file buffers when they encounter a
1452 In text mode, most systems only flush file buffers when they encounter a
3016 '\n'. An instruction as simple as::
1453 '\n'. An instruction as simple as::
3017
1454
3018 print >> filehandle, ''hello world''
1455 print >> filehandle, ''hello world''
3019
1456
3020 actually consists of several bytecodes, so it is possible that the
1457 actually consists of several bytecodes, so it is possible that the
3021 newline does not reach your file before the next thread switch.
1458 newline does not reach your file before the next thread switch.
3022 Similarly, if you are writing to a file in binary mode, the file won't
1459 Similarly, if you are writing to a file in binary mode, the file won't
3023 be flushed until the buffer fills, and your other thread may see
1460 be flushed until the buffer fills, and your other thread may see
3024 apparently truncated files.
1461 apparently truncated files.
3025
1462
3026 For this reason, if you are using IPython's thread support and have (for
1463 For this reason, if you are using IPython's thread support and have (for
3027 example) a GUI application which will read data generated by files
1464 example) a GUI application which will read data generated by files
3028 written to from the IPython thread, the safest approach is to open all
1465 written to from the IPython thread, the safest approach is to open all
3029 of your files in unbuffered mode (the third argument to the file/open
1466 of your files in unbuffered mode (the third argument to the file/open
3030 function is the buffering value)::
1467 function is the buffering value)::
3031
1468
3032 filehandle = open(filename,mode,0)
1469 filehandle = open(filename,mode,0)
3033
1470
3034 This is obviously a brute force way of avoiding race conditions with the
1471 This is obviously a brute force way of avoiding race conditions with the
3035 file buffering. If you want to do it cleanly, and you have a resource
1472 file buffering. If you want to do it cleanly, and you have a resource
3036 which is being shared by the interactive IPython loop and your GUI
1473 which is being shared by the interactive IPython loop and your GUI
3037 thread, you should really handle it with thread locking and
1474 thread, you should really handle it with thread locking and
3038 syncrhonization properties. The Python documentation discusses these.
1475 syncrhonization properties. The Python documentation discusses these.
3039
1476
3040 .. _interactive_demos:
1477 .. _interactive_demos:
3041
1478
3042 Interactive demos with IPython
1479 Interactive demos with IPython
3043 ==============================
1480 ==============================
3044
1481
3045 IPython ships with a basic system for running scripts interactively in
1482 IPython ships with a basic system for running scripts interactively in
3046 sections, useful when presenting code to audiences. A few tags embedded
1483 sections, useful when presenting code to audiences. A few tags embedded
3047 in comments (so that the script remains valid Python code) divide a file
1484 in comments (so that the script remains valid Python code) divide a file
3048 into separate blocks, and the demo can be run one block at a time, with
1485 into separate blocks, and the demo can be run one block at a time, with
3049 IPython printing (with syntax highlighting) the block before executing
1486 IPython printing (with syntax highlighting) the block before executing
3050 it, and returning to the interactive prompt after each block. The
1487 it, and returning to the interactive prompt after each block. The
3051 interactive namespace is updated after each block is run with the
1488 interactive namespace is updated after each block is run with the
3052 contents of the demo's namespace.
1489 contents of the demo's namespace.
3053
1490
3054 This allows you to show a piece of code, run it and then execute
1491 This allows you to show a piece of code, run it and then execute
3055 interactively commands based on the variables just created. Once you
1492 interactively commands based on the variables just created. Once you
3056 want to continue, you simply execute the next block of the demo. The
1493 want to continue, you simply execute the next block of the demo. The
3057 following listing shows the markup necessary for dividing a script into
1494 following listing shows the markup necessary for dividing a script into
3058 sections for execution as a demo::
1495 sections for execution as a demo::
3059
1496
3060
1497
3061 """A simple interactive demo to illustrate the use of IPython's Demo class.
1498 """A simple interactive demo to illustrate the use of IPython's Demo class.
3062
1499
3063 Any python script can be run as a demo, but that does little more than showing
1500 Any python script can be run as a demo, but that does little more than showing
3064 it on-screen, syntax-highlighted in one shot. If you add a little simple
1501 it on-screen, syntax-highlighted in one shot. If you add a little simple
3065 markup, you can stop at specified intervals and return to the ipython prompt,
1502 markup, you can stop at specified intervals and return to the ipython prompt,
3066 resuming execution later.
1503 resuming execution later.
3067 """
1504 """
3068
1505
3069 print 'Hello, welcome to an interactive IPython demo.'
1506 print 'Hello, welcome to an interactive IPython demo.'
3070 print 'Executing this block should require confirmation before proceeding,'
1507 print 'Executing this block should require confirmation before proceeding,'
3071 print 'unless auto_all has been set to true in the demo object'
1508 print 'unless auto_all has been set to true in the demo object'
3072
1509
3073 # The mark below defines a block boundary, which is a point where IPython will
1510 # The mark below defines a block boundary, which is a point where IPython will
3074 # stop execution and return to the interactive prompt.
1511 # stop execution and return to the interactive prompt.
3075 # Note that in actual interactive execution,
1512 # Note that in actual interactive execution,
3076 # <demo> --- stop ---
1513 # <demo> --- stop ---
3077
1514
3078 x = 1
1515 x = 1
3079 y = 2
1516 y = 2
3080
1517
3081 # <demo> --- stop ---
1518 # <demo> --- stop ---
3082
1519
3083 # the mark below makes this block as silent
1520 # the mark below makes this block as silent
3084 # <demo> silent
1521 # <demo> silent
3085
1522
3086 print 'This is a silent block, which gets executed but not printed.'
1523 print 'This is a silent block, which gets executed but not printed.'
3087
1524
3088 # <demo> --- stop ---
1525 # <demo> --- stop ---
3089 # <demo> auto
1526 # <demo> auto
3090 print 'This is an automatic block.'
1527 print 'This is an automatic block.'
3091 print 'It is executed without asking for confirmation, but printed.'
1528 print 'It is executed without asking for confirmation, but printed.'
3092 z = x+y
1529 z = x+y
3093
1530
3094 print 'z=',x
1531 print 'z=',x
3095
1532
3096 # <demo> --- stop ---
1533 # <demo> --- stop ---
3097 # This is just another normal block.
1534 # This is just another normal block.
3098 print 'z is now:', z
1535 print 'z is now:', z
3099
1536
3100 print 'bye!'
1537 print 'bye!'
3101
1538
3102 In order to run a file as a demo, you must first make a Demo object out
1539 In order to run a file as a demo, you must first make a Demo object out
3103 of it. If the file is named myscript.py, the following code will make a
1540 of it. If the file is named myscript.py, the following code will make a
3104 demo::
1541 demo::
3105
1542
3106 from IPython.demo import Demo
1543 from IPython.demo import Demo
3107
1544
3108 mydemo = Demo('myscript.py')
1545 mydemo = Demo('myscript.py')
3109
1546
3110 This creates the mydemo object, whose blocks you run one at a time by
1547 This creates the mydemo object, whose blocks you run one at a time by
3111 simply calling the object with no arguments. If you have autocall active
1548 simply calling the object with no arguments. If you have autocall active
3112 in IPython (the default), all you need to do is type::
1549 in IPython (the default), all you need to do is type::
3113
1550
3114 mydemo
1551 mydemo
3115
1552
3116 and IPython will call it, executing each block. Demo objects can be
1553 and IPython will call it, executing each block. Demo objects can be
3117 restarted, you can move forward or back skipping blocks, re-execute the
1554 restarted, you can move forward or back skipping blocks, re-execute the
3118 last block, etc. Simply use the Tab key on a demo object to see its
1555 last block, etc. Simply use the Tab key on a demo object to see its
3119 methods, and call '?' on them to see their docstrings for more usage
1556 methods, and call '?' on them to see their docstrings for more usage
3120 details. In addition, the demo module itself contains a comprehensive
1557 details. In addition, the demo module itself contains a comprehensive
3121 docstring, which you can access via::
1558 docstring, which you can access via::
3122
1559
3123 from IPython import demo
1560 from IPython import demo
3124
1561
3125 demo?
1562 demo?
3126
1563
3127 Limitations: It is important to note that these demos are limited to
1564 Limitations: It is important to note that these demos are limited to
3128 fairly simple uses. In particular, you can not put division marks in
1565 fairly simple uses. In particular, you can not put division marks in
3129 indented code (loops, if statements, function definitions, etc.)
1566 indented code (loops, if statements, function definitions, etc.)
3130 Supporting something like this would basically require tracking the
1567 Supporting something like this would basically require tracking the
3131 internal execution state of the Python interpreter, so only top-level
1568 internal execution state of the Python interpreter, so only top-level
3132 divisions are allowed. If you want to be able to open an IPython
1569 divisions are allowed. If you want to be able to open an IPython
3133 instance at an arbitrary point in a program, you can use IPython's
1570 instance at an arbitrary point in a program, you can use IPython's
3134 embedding facilities, described in detail in Sec. 9
1571 embedding facilities, described in detail in Sec. 9
3135
1572
3136
1573
3137 .. _Matplotlib support:
1574 .. _Matplotlib support:
3138
1575
3139 Plotting with matplotlib
1576 Plotting with matplotlib
3140 ========================
1577 ========================
3141
1578
3142 The matplotlib library (http://matplotlib.sourceforge.net
1579 The matplotlib library (http://matplotlib.sourceforge.net
3143 http://matplotlib.sourceforge.net) provides high quality 2D plotting for
1580 http://matplotlib.sourceforge.net) provides high quality 2D plotting for
3144 Python. Matplotlib can produce plots on screen using a variety of GUI
1581 Python. Matplotlib can produce plots on screen using a variety of GUI
3145 toolkits, including Tk, GTK and WXPython. It also provides a number of
1582 toolkits, including Tk, GTK and WXPython. It also provides a number of
3146 commands useful for scientific computing, all with a syntax compatible
1583 commands useful for scientific computing, all with a syntax compatible
3147 with that of the popular Matlab program.
1584 with that of the popular Matlab program.
3148
1585
3149 IPython accepts the special option -pylab (see :ref:`here
1586 IPython accepts the special option -pylab (see :ref:`here
3150 <command_line_options>`). This configures it to support matplotlib, honoring
1587 <command_line_options>`). This configures it to support matplotlib, honoring
3151 the settings in the .matplotlibrc file. IPython will detect the user's choice
1588 the settings in the .matplotlibrc file. IPython will detect the user's choice
3152 of matplotlib GUI backend, and automatically select the proper threading model
1589 of matplotlib GUI backend, and automatically select the proper threading model
3153 to prevent blocking. It also sets matplotlib in interactive mode and modifies
1590 to prevent blocking. It also sets matplotlib in interactive mode and modifies
3154 %run slightly, so that any matplotlib-based script can be executed using %run
1591 %run slightly, so that any matplotlib-based script can be executed using %run
3155 and the final show() command does not block the interactive shell.
1592 and the final show() command does not block the interactive shell.
3156
1593
3157 The -pylab option must be given first in order for IPython to configure its
1594 The -pylab option must be given first in order for IPython to configure its
3158 threading mode. However, you can still issue other options afterwards. This
1595 threading mode. However, you can still issue other options afterwards. This
3159 allows you to have a matplotlib-based environment customized with additional
1596 allows you to have a matplotlib-based environment customized with additional
3160 modules using the standard IPython profile mechanism (see :ref:`here
1597 modules using the standard IPython profile mechanism (see :ref:`here
3161 <profiles>`): ``ipython -pylab -p myprofile`` will load the profile defined in
1598 <profiles>`): ``ipython -pylab -p myprofile`` will load the profile defined in
3162 ipythonrc-myprofile after configuring matplotlib.
1599 ipythonrc-myprofile after configuring matplotlib.
@@ -1,423 +1,407 b''
1 """
1 """
2 Defines a docutils directive for inserting inheritance diagrams.
2 Defines a docutils directive for inserting inheritance diagrams.
3
3
4 Provide the directive with one or more classes or modules (separated
4 Provide the directive with one or more classes or modules (separated
5 by whitespace). For modules, all of the classes in that module will
5 by whitespace). For modules, all of the classes in that module will
6 be used.
6 be used.
7
7
8 Example::
8 Example::
9
9
10 Given the following classes:
10 Given the following classes:
11
11
12 class A: pass
12 class A: pass
13 class B(A): pass
13 class B(A): pass
14 class C(A): pass
14 class C(A): pass
15 class D(B, C): pass
15 class D(B, C): pass
16 class E(B): pass
16 class E(B): pass
17
17
18 .. inheritance-diagram: D E
18 .. inheritance-diagram: D E
19
19
20 Produces a graph like the following:
20 Produces a graph like the following:
21
21
22 A
22 A
23 / \
23 / \
24 B C
24 B C
25 / \ /
25 / \ /
26 E D
26 E D
27
27
28 The graph is inserted as a PNG+image map into HTML and a PDF in
28 The graph is inserted as a PNG+image map into HTML and a PDF in
29 LaTeX.
29 LaTeX.
30 """
30 """
31
31
32 import inspect
32 import inspect
33 import os
33 import os
34 import re
34 import re
35 import subprocess
35 import subprocess
36 try:
36 try:
37 from hashlib import md5
37 from hashlib import md5
38 except ImportError:
38 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
50 class InheritanceGraph(object):
59 class InheritanceGraph(object):
51 """
60 """
52 Given a list of classes, determines the set of classes that
61 Given a list of classes, determines the set of classes that
53 they inherit from all the way to the root "object", and then
62 they inherit from all the way to the root "object", and then
54 is able to generate a graphviz dot graph from them.
63 is able to generate a graphviz dot graph from them.
55 """
64 """
56 def __init__(self, class_names, show_builtins=False):
65 def __init__(self, class_names, show_builtins=False):
57 """
66 """
58 *class_names* is a list of child classes to show bases from.
67 *class_names* is a list of child classes to show bases from.
59
68
60 If *show_builtins* is True, then Python builtins will be shown
69 If *show_builtins* is True, then Python builtins will be shown
61 in the graph.
70 in the graph.
62 """
71 """
63 self.class_names = class_names
72 self.class_names = class_names
64 self.classes = self._import_classes(class_names)
73 self.classes = self._import_classes(class_names)
65 self.all_classes = self._all_classes(self.classes)
74 self.all_classes = self._all_classes(self.classes)
66 if len(self.all_classes) == 0:
75 if len(self.all_classes) == 0:
67 raise ValueError("No classes found for inheritance diagram")
76 raise ValueError("No classes found for inheritance diagram")
68 self.show_builtins = show_builtins
77 self.show_builtins = show_builtins
69
78
70 py_sig_re = re.compile(r'''^([\w.]*\.)? # class names
79 py_sig_re = re.compile(r'''^([\w.]*\.)? # class names
71 (\w+) \s* $ # optionally arguments
80 (\w+) \s* $ # optionally arguments
72 ''', re.VERBOSE)
81 ''', re.VERBOSE)
73
82
74 def _import_class_or_module(self, name):
83 def _import_class_or_module(self, name):
75 """
84 """
76 Import a class using its fully-qualified *name*.
85 Import a class using its fully-qualified *name*.
77 """
86 """
78 try:
87 try:
79 path, base = self.py_sig_re.match(name).groups()
88 path, base = self.py_sig_re.match(name).groups()
80 except:
89 except:
81 raise ValueError(
90 raise ValueError(
82 "Invalid class or module '%s' specified for inheritance diagram" % name)
91 "Invalid class or module '%s' specified for inheritance diagram" % name)
83 fullname = (path or '') + base
92 fullname = (path or '') + base
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)
95
108
96 try:
109 try:
97 todoc = module
110 todoc = module
98 for comp in fullname.split('.')[1:]:
111 for comp in fullname.split('.')[1:]:
99 todoc = getattr(todoc, comp)
112 todoc = getattr(todoc, comp)
100 except AttributeError:
113 except AttributeError:
101 raise ValueError(
114 raise ValueError(
102 "Could not find class or module '%s' specified for inheritance diagram" % name)
115 "Could not find class or module '%s' specified for inheritance diagram" % name)
103
116
104 # If a class, just return it
117 # If a class, just return it
105 if inspect.isclass(todoc):
118 if inspect.isclass(todoc):
106 return [todoc]
119 return [todoc]
107 elif inspect.ismodule(todoc):
120 elif inspect.ismodule(todoc):
108 classes = []
121 classes = []
109 for cls in todoc.__dict__.values():
122 for cls in todoc.__dict__.values():
110 if inspect.isclass(cls) and cls.__module__ == todoc.__name__:
123 if inspect.isclass(cls) and cls.__module__ == todoc.__name__:
111 classes.append(cls)
124 classes.append(cls)
112 return classes
125 return classes
113 raise ValueError(
126 raise ValueError(
114 "'%s' does not resolve to a class or module" % name)
127 "'%s' does not resolve to a class or module" % name)
115
128
116 def _import_classes(self, class_names):
129 def _import_classes(self, class_names):
117 """
130 """
118 Import a list of classes.
131 Import a list of classes.
119 """
132 """
120 classes = []
133 classes = []
121 for name in class_names:
134 for name in class_names:
122 classes.extend(self._import_class_or_module(name))
135 classes.extend(self._import_class_or_module(name))
123 return classes
136 return classes
124
137
125 def _all_classes(self, classes):
138 def _all_classes(self, classes):
126 """
139 """
127 Return a list of all classes that are ancestors of *classes*.
140 Return a list of all classes that are ancestors of *classes*.
128 """
141 """
129 all_classes = {}
142 all_classes = {}
130
143
131 def recurse(cls):
144 def recurse(cls):
132 all_classes[cls] = None
145 all_classes[cls] = None
133 for c in cls.__bases__:
146 for c in cls.__bases__:
134 if c not in all_classes:
147 if c not in all_classes:
135 recurse(c)
148 recurse(c)
136
149
137 for cls in classes:
150 for cls in classes:
138 recurse(cls)
151 recurse(cls)
139
152
140 return all_classes.keys()
153 return all_classes.keys()
141
154
142 def class_name(self, cls, parts=0):
155 def class_name(self, cls, parts=0):
143 """
156 """
144 Given a class object, return a fully-qualified name. This
157 Given a class object, return a fully-qualified name. This
145 works for things I've tested in matplotlib so far, but may not
158 works for things I've tested in matplotlib so far, but may not
146 be completely general.
159 be completely general.
147 """
160 """
148 module = cls.__module__
161 module = cls.__module__
149 if module == '__builtin__':
162 if module == '__builtin__':
150 fullname = cls.__name__
163 fullname = cls.__name__
151 else:
164 else:
152 fullname = "%s.%s" % (module, cls.__name__)
165 fullname = "%s.%s" % (module, cls.__name__)
153 if parts == 0:
166 if parts == 0:
154 return fullname
167 return fullname
155 name_parts = fullname.split('.')
168 name_parts = fullname.split('.')
156 return '.'.join(name_parts[-parts:])
169 return '.'.join(name_parts[-parts:])
157
170
158 def get_all_class_names(self):
171 def get_all_class_names(self):
159 """
172 """
160 Get all of the class names involved in the graph.
173 Get all of the class names involved in the graph.
161 """
174 """
162 return [self.class_name(x) for x in self.all_classes]
175 return [self.class_name(x) for x in self.all_classes]
163
176
164 # These are the default options for graphviz
177 # These are the default options for graphviz
165 default_graph_options = {
178 default_graph_options = {
166 "rankdir": "LR",
179 "rankdir": "LR",
167 "size": '"8.0, 12.0"'
180 "size": '"8.0, 12.0"'
168 }
181 }
169 default_node_options = {
182 default_node_options = {
170 "shape": "box",
183 "shape": "box",
171 "fontsize": 10,
184 "fontsize": 10,
172 "height": 0.25,
185 "height": 0.25,
173 "fontname": "Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",
186 "fontname": "Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",
174 "style": '"setlinewidth(0.5)"'
187 "style": '"setlinewidth(0.5)"'
175 }
188 }
176 default_edge_options = {
189 default_edge_options = {
177 "arrowsize": 0.5,
190 "arrowsize": 0.5,
178 "style": '"setlinewidth(0.5)"'
191 "style": '"setlinewidth(0.5)"'
179 }
192 }
180
193
181 def _format_node_options(self, options):
194 def _format_node_options(self, options):
182 return ','.join(["%s=%s" % x for x in options.items()])
195 return ','.join(["%s=%s" % x for x in options.items()])
183 def _format_graph_options(self, options):
196 def _format_graph_options(self, options):
184 return ''.join(["%s=%s;\n" % x for x in options.items()])
197 return ''.join(["%s=%s;\n" % x for x in options.items()])
185
198
186 def generate_dot(self, fd, name, parts=0, urls={},
199 def generate_dot(self, fd, name, parts=0, urls={},
187 graph_options={}, node_options={},
200 graph_options={}, node_options={},
188 edge_options={}):
201 edge_options={}):
189 """
202 """
190 Generate a graphviz dot graph from the classes that
203 Generate a graphviz dot graph from the classes that
191 were passed in to __init__.
204 were passed in to __init__.
192
205
193 *fd* is a Python file-like object to write to.
206 *fd* is a Python file-like object to write to.
194
207
195 *name* is the name of the graph
208 *name* is the name of the graph
196
209
197 *urls* is a dictionary mapping class names to http urls
210 *urls* is a dictionary mapping class names to http urls
198
211
199 *graph_options*, *node_options*, *edge_options* are
212 *graph_options*, *node_options*, *edge_options* are
200 dictionaries containing key/value pairs to pass on as graphviz
213 dictionaries containing key/value pairs to pass on as graphviz
201 properties.
214 properties.
202 """
215 """
203 g_options = self.default_graph_options.copy()
216 g_options = self.default_graph_options.copy()
204 g_options.update(graph_options)
217 g_options.update(graph_options)
205 n_options = self.default_node_options.copy()
218 n_options = self.default_node_options.copy()
206 n_options.update(node_options)
219 n_options.update(node_options)
207 e_options = self.default_edge_options.copy()
220 e_options = self.default_edge_options.copy()
208 e_options.update(edge_options)
221 e_options.update(edge_options)
209
222
210 fd.write('digraph %s {\n' % name)
223 fd.write('digraph %s {\n' % name)
211 fd.write(self._format_graph_options(g_options))
224 fd.write(self._format_graph_options(g_options))
212
225
213 for cls in self.all_classes:
226 for cls in self.all_classes:
214 if not self.show_builtins and cls in __builtins__.values():
227 if not self.show_builtins and cls in __builtins__.values():
215 continue
228 continue
216
229
217 name = self.class_name(cls, parts)
230 name = self.class_name(cls, parts)
218
231
219 # Write the node
232 # Write the node
220 this_node_options = n_options.copy()
233 this_node_options = n_options.copy()
221 url = urls.get(self.class_name(cls))
234 url = urls.get(self.class_name(cls))
222 if url is not None:
235 if url is not None:
223 this_node_options['URL'] = '"%s"' % url
236 this_node_options['URL'] = '"%s"' % url
224 fd.write(' "%s" [%s];\n' %
237 fd.write(' "%s" [%s];\n' %
225 (name, self._format_node_options(this_node_options)))
238 (name, self._format_node_options(this_node_options)))
226
239
227 # Write the edges
240 # Write the edges
228 for base in cls.__bases__:
241 for base in cls.__bases__:
229 if not self.show_builtins and base in __builtins__.values():
242 if not self.show_builtins and base in __builtins__.values():
230 continue
243 continue
231
244
232 base_name = self.class_name(base, parts)
245 base_name = self.class_name(base, parts)
233 fd.write(' "%s" -> "%s" [%s];\n' %
246 fd.write(' "%s" -> "%s" [%s];\n' %
234 (base_name, name,
247 (base_name, name,
235 self._format_node_options(e_options)))
248 self._format_node_options(e_options)))
236 fd.write('}\n')
249 fd.write('}\n')
237
250
238 def run_dot(self, args, name, parts=0, urls={},
251 def run_dot(self, args, name, parts=0, urls={},
239 graph_options={}, node_options={}, edge_options={}):
252 graph_options={}, node_options={}, edge_options={}):
240 """
253 """
241 Run graphviz 'dot' over this graph, returning whatever 'dot'
254 Run graphviz 'dot' over this graph, returning whatever 'dot'
242 writes to stdout.
255 writes to stdout.
243
256
244 *args* will be passed along as commandline arguments.
257 *args* will be passed along as commandline arguments.
245
258
246 *name* is the name of the graph
259 *name* is the name of the graph
247
260
248 *urls* is a dictionary mapping class names to http urls
261 *urls* is a dictionary mapping class names to http urls
249
262
250 Raises DotException for any of the many os and
263 Raises DotException for any of the many os and
251 installation-related errors that may occur.
264 installation-related errors that may occur.
252 """
265 """
253 try:
266 try:
254 dot = subprocess.Popen(['dot'] + list(args),
267 dot = subprocess.Popen(['dot'] + list(args),
255 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
268 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
256 close_fds=True)
269 close_fds=True)
257 except OSError:
270 except OSError:
258 raise DotException("Could not execute 'dot'. Are you sure you have 'graphviz' installed?")
271 raise DotException("Could not execute 'dot'. Are you sure you have 'graphviz' installed?")
259 except ValueError:
272 except ValueError:
260 raise DotException("'dot' called with invalid arguments")
273 raise DotException("'dot' called with invalid arguments")
261 except:
274 except:
262 raise DotException("Unexpected error calling 'dot'")
275 raise DotException("Unexpected error calling 'dot'")
263
276
264 self.generate_dot(dot.stdin, name, parts, urls, graph_options,
277 self.generate_dot(dot.stdin, name, parts, urls, graph_options,
265 node_options, edge_options)
278 node_options, edge_options)
266 dot.stdin.close()
279 dot.stdin.close()
267 result = dot.stdout.read()
280 result = dot.stdout.read()
268 returncode = dot.wait()
281 returncode = dot.wait()
269 if returncode != 0:
282 if returncode != 0:
270 raise DotException("'dot' returned the errorcode %d" % returncode)
283 raise DotException("'dot' returned the errorcode %d" % returncode)
271 return result
284 return result
272
285
273 class inheritance_diagram(Body, Element):
286 class inheritance_diagram(Body, Element):
274 """
287 """
275 A docutils node to use as a placeholder for the inheritance
288 A docutils node to use as a placeholder for the inheritance
276 diagram.
289 diagram.
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
289 # Create xref nodes for each target of the graph's image map and
306 # Create xref nodes for each target of the graph's image map and
290 # add them to the doc tree so that Sphinx can resolve the
307 # add them to the doc tree so that Sphinx can resolve the
291 # references to real URLs later. These nodes will eventually be
308 # references to real URLs later. These nodes will eventually be
292 # removed from the doctree after we're done with them.
309 # removed from the doctree after we're done with them.
293 for name in graph.get_all_class_names():
310 for name in graph.get_all_class_names():
294 refnodes, x = xfileref_role(
311 refnodes, x = xfileref_role(
295 'class', ':class:`%s`' % name, name, 0, state)
312 'class', ':class:`%s`' % name, name, 0, state)
296 node.extend(refnodes)
313 node.extend(refnodes)
297 # Store the graph object so we can use it to generate the
314 # Store the graph object so we can use it to generate the
298 # dot file later
315 # dot file later
299 node['graph'] = graph
316 node['graph'] = graph
300 # Store the original content for use as a hash
317 # Store the original content for use as a hash
301 node['parts'] = options.get('parts', 0)
318 node['parts'] = options.get('parts', 0)
302 node['content'] = " ".join(class_names)
319 node['content'] = " ".join(class_names)
303 return [node]
320 return [node]
304
321
305 def get_graph_hash(node):
322 def get_graph_hash(node):
306 return md5(node['content'] + str(node['parts'])).hexdigest()[-10:]
323 return md5(node['content'] + str(node['parts'])).hexdigest()[-10:]
307
324
308 def html_output_graph(self, node):
325 def html_output_graph(self, node):
309 """
326 """
310 Output the graph for HTML. This will insert a PNG with clickable
327 Output the graph for HTML. This will insert a PNG with clickable
311 image map.
328 image map.
312 """
329 """
313 graph = node['graph']
330 graph = node['graph']
314 parts = node['parts']
331 parts = node['parts']
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 = {}
330 for child in node:
344 for child in node:
331 if child.get('refuri') is not None:
345 if child.get('refuri') is not None:
332 urls[child['reftitle']] = child.get('refuri')
346 urls[child['reftitle']] = child.get('refuri')
333 elif child.get('refid') is not None:
347 elif child.get('refid') is not None:
334 urls[child['reftitle']] = '#' + child.get('refid')
348 urls[child['reftitle']] = '#' + child.get('refid')
335
349
336 # These arguments to dot will save a PNG file to disk and write
350 # These arguments to dot will save a PNG file to disk and write
337 # an HTML image map to stdout.
351 # an HTML image map to stdout.
338 image_map = graph.run_dot(['-Tpng', '-o%s' % png_path, '-Tcmapx'],
352 image_map = graph.run_dot(['-Tpng', '-o%s' % png_path, '-Tcmapx'],
339 name, parts, urls)
353 name, parts, urls)
340 return ('<img src="%s/%s.png" usemap="#%s" class="inheritance"/>%s' %
354 return ('<img src="%s/%s.png" usemap="#%s" class="inheritance"/>%s' %
341 (path, name, name, image_map))
355 (path, name, name, image_map))
342
356
343 def latex_output_graph(self, node):
357 def latex_output_graph(self, node):
344 """
358 """
345 Output the graph for LaTeX. This will insert a PDF.
359 Output the graph for LaTeX. This will insert a PDF.
346 """
360 """
347 graph = node['graph']
361 graph = node['graph']
348 parts = node['parts']
362 parts = node['parts']
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 """
360 This is just a wrapper around html/latex_output_graph to make it
377 This is just a wrapper around html/latex_output_graph to make it
361 easier to handle errors and insert warnings.
378 easier to handle errors and insert warnings.
362 """
379 """
363 def visitor(self, node):
380 def visitor(self, node):
364 try:
381 try:
365 content = inner_func(self, node)
382 content = inner_func(self, node)
366 except DotException, e:
383 except DotException, e:
367 # Insert the exception as a warning in the document
384 # Insert the exception as a warning in the document
368 warning = self.document.reporter.warning(str(e), line=node.line)
385 warning = self.document.reporter.warning(str(e), line=node.line)
369 warning.parent = node
386 warning.parent = node
370 node.children = [warning]
387 node.children = [warning]
371 else:
388 else:
372 source = self.document.attributes['source']
389 source = self.document.attributes['source']
373 self.body.append(content)
390 self.body.append(content)
374 node.children = []
391 node.children = []
375 return visitor
392 return visitor
376
393
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,75 +1,98 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'
19
33
20 In [2]: a
34 In [2]: a
21 Out[2]: 'foo'
35 Out[2]: 'foo'
22
36
23 In [3]: print a
37 In [3]: print a
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']
31 input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)")
52 input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)")
32 output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)")
53 output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)")
33 continue_prompt = re.compile(" \.\.\.+:")
54 continue_prompt = re.compile(" \.\.\.+:")
34 tb_start = re.compile("\-+")
55 tb_start = re.compile("\-+")
35
56
36 def get_tokens_unprocessed(self, text):
57 def get_tokens_unprocessed(self, text):
37 pylexer = PythonLexer(**self.options)
58 pylexer = PythonLexer(**self.options)
38 tblexer = PythonTracebackLexer(**self.options)
59 tblexer = PythonTracebackLexer(**self.options)
39
60
40 curcode = ''
61 curcode = ''
41 insertions = []
62 insertions = []
42 for match in line_re.finditer(text):
63 for match in line_re.finditer(text):
43 line = match.group()
64 line = match.group()
44 input_prompt = self.input_prompt.match(line)
65 input_prompt = self.input_prompt.match(line)
45 continue_prompt = self.continue_prompt.match(line.rstrip())
66 continue_prompt = self.continue_prompt.match(line.rstrip())
46 output_prompt = self.output_prompt.match(line)
67 output_prompt = self.output_prompt.match(line)
47 if line.startswith("#"):
68 if line.startswith("#"):
48 insertions.append((len(curcode),
69 insertions.append((len(curcode),
49 [(0, Comment, line)]))
70 [(0, Comment, line)]))
50 elif input_prompt is not None:
71 elif input_prompt is not None:
51 insertions.append((len(curcode),
72 insertions.append((len(curcode),
52 [(0, Generic.Prompt, input_prompt.group())]))
73 [(0, Generic.Prompt, input_prompt.group())]))
53 curcode += line[input_prompt.end():]
74 curcode += line[input_prompt.end():]
54 elif continue_prompt is not None:
75 elif continue_prompt is not None:
55 insertions.append((len(curcode),
76 insertions.append((len(curcode),
56 [(0, Generic.Prompt, continue_prompt.group())]))
77 [(0, Generic.Prompt, continue_prompt.group())]))
57 curcode += line[continue_prompt.end():]
78 curcode += line[continue_prompt.end():]
58 elif output_prompt is not None:
79 elif output_prompt is not None:
59 insertions.append((len(curcode),
80 insertions.append((len(curcode),
60 [(0, Generic.Output, output_prompt.group())]))
81 [(0, Generic.Output, output_prompt.group())]))
61 curcode += line[output_prompt.end():]
82 curcode += line[output_prompt.end():]
62 else:
83 else:
63 if curcode:
84 if curcode:
64 for item in do_insertions(insertions,
85 for item in do_insertions(insertions,
65 pylexer.get_tokens_unprocessed(curcode)):
86 pylexer.get_tokens_unprocessed(curcode)):
66 yield item
87 yield item
67 curcode = ''
88 curcode = ''
68 insertions = []
89 insertions = []
69 yield match.start(), Generic.Output, line
90 yield match.start(), Generic.Output, line
70 if curcode:
91 if curcode:
71 for item in do_insertions(insertions,
92 for item in do_insertions(insertions,
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