Show More
@@ -0,0 +1,33 | |||
|
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 | |||
|
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 |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
@@ -0,0 +1,246 | |||
|
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 | |||
|
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 | |||
|
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 | |||
|
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 | |||
|
1 | 1 | """Word completion for IPython. |
|
2 | 2 | |
|
3 | 3 | This module is a fork of the rlcompleter module in the Python standard |
|
4 | 4 | library. The original enhancements made to rlcompleter have been sent |
|
5 | 5 | upstream and were accepted as of Python 2.3, but we need a lot more |
|
6 | 6 | functionality specific to IPython, so this module will continue to live as an |
|
7 | 7 | IPython-specific utility. |
|
8 | 8 | |
|
9 | --------------------------------------------------------------------------- | |
|
10 | 9 | Original rlcompleter documentation: |
|
11 | 10 | |
|
12 | 11 | This requires the latest extension to the readline module (the |
|
13 | 12 | completes keywords, built-ins and globals in __main__; when completing |
|
14 | 13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
15 | 14 | completes its attributes. |
|
16 | 15 | |
|
17 | 16 | It's very cool to do "import string" type "string.", hit the |
|
18 | 17 | completion key (twice), and see the list of names defined by the |
|
19 | 18 | string module! |
|
20 | 19 | |
|
21 | 20 | Tip: to use the tab key as the completion key, call |
|
22 | 21 | |
|
23 | 22 | readline.parse_and_bind("tab: complete") |
|
24 | 23 | |
|
25 | 24 | Notes: |
|
26 | 25 | |
|
27 | 26 | - Exceptions raised by the completer function are *ignored* (and |
|
28 | 27 | generally cause the completion to fail). This is a feature -- since |
|
29 | 28 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
30 | 29 | traceback wouldn't work well without some complicated hoopla to save, |
|
31 | 30 | reset and restore the tty state. |
|
32 | 31 | |
|
33 | 32 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
34 | 33 | application defined code to be executed if an object with a |
|
35 | 34 | __getattr__ hook is found. Since it is the responsibility of the |
|
36 | 35 | application (or the user) to enable this feature, I consider this an |
|
37 | 36 | acceptable risk. More complicated expressions (e.g. function calls or |
|
38 | 37 | indexing operations) are *not* evaluated. |
|
39 | 38 | |
|
40 | 39 | - GNU readline is also used by the built-in functions input() and |
|
41 | 40 | raw_input(), and thus these also benefit/suffer from the completer |
|
42 | 41 | features. Clearly an interactive application can benefit by |
|
43 | 42 | specifying its own completer function and using raw_input() for all |
|
44 | 43 | its input. |
|
45 | 44 | |
|
46 | 45 | - When the original stdin is not a tty device, GNU readline is never |
|
47 | 46 | used, and this module (and the readline module) are silently inactive. |
|
48 | 47 | |
|
49 | 48 | """ |
|
50 | 49 | |
|
51 | 50 | #***************************************************************************** |
|
52 | 51 | # |
|
53 | 52 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
54 | 53 | # module which is part of the standard Python distribution, I assume that the |
|
55 | 54 | # proper procedure is to maintain its copyright as belonging to the Python |
|
56 | 55 | # Software Foundation (in addition to my own, for all new code). |
|
57 | 56 | # |
|
58 | 57 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
59 | 58 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
60 | 59 | # |
|
61 | 60 | # Distributed under the terms of the BSD License. The full license is in |
|
62 | 61 | # the file COPYING, distributed as part of this software. |
|
63 | 62 | # |
|
64 | 63 | #***************************************************************************** |
|
65 | 64 | |
|
66 | 65 | import __builtin__ |
|
67 | 66 | import __main__ |
|
68 | 67 | import glob |
|
69 | 68 | import keyword |
|
70 | 69 | import os |
|
71 | 70 | import re |
|
72 | 71 | import shlex |
|
73 | 72 | import sys |
|
74 | 73 | import IPython.rlineimpl as readline |
|
75 | 74 | import itertools |
|
76 | 75 | from IPython.ipstruct import Struct |
|
77 | 76 | from IPython import ipapi |
|
78 | 77 | from IPython import generics |
|
79 | 78 | import types |
|
80 | 79 | |
|
81 | 80 | # Python 2.4 offers sets as a builtin |
|
82 | 81 | try: |
|
83 | 82 | set() |
|
84 | 83 | except NameError: |
|
85 | 84 | from sets import Set as set |
|
86 | 85 | |
|
87 | 86 | from IPython.genutils import debugx, dir2 |
|
88 | 87 | |
|
89 | 88 | __all__ = ['Completer','IPCompleter'] |
|
90 | 89 | |
|
91 | 90 | class Completer: |
|
92 | 91 | def __init__(self,namespace=None,global_namespace=None): |
|
93 | 92 | """Create a new completer for the command line. |
|
94 | 93 | |
|
95 | 94 | Completer([namespace,global_namespace]) -> completer instance. |
|
96 | 95 | |
|
97 | 96 | If unspecified, the default namespace where completions are performed |
|
98 | 97 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
99 | 98 | given as dictionaries. |
|
100 | 99 | |
|
101 | 100 | An optional second namespace can be given. This allows the completer |
|
102 | 101 | to handle cases where both the local and global scopes need to be |
|
103 | 102 | distinguished. |
|
104 | 103 | |
|
105 | 104 | Completer instances should be used as the completion mechanism of |
|
106 | 105 | readline via the set_completer() call: |
|
107 | 106 | |
|
108 | 107 | readline.set_completer(Completer(my_namespace).complete) |
|
109 | 108 | """ |
|
110 | 109 | |
|
111 | 110 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
112 | 111 | # specific namespace or to use __main__.__dict__. This will allow us |
|
113 | 112 | # to bind to __main__.__dict__ at completion time, not now. |
|
114 | 113 | if namespace is None: |
|
115 | 114 | self.use_main_ns = 1 |
|
116 | 115 | else: |
|
117 | 116 | self.use_main_ns = 0 |
|
118 | 117 | self.namespace = namespace |
|
119 | 118 | |
|
120 | 119 | # The global namespace, if given, can be bound directly |
|
121 | 120 | if global_namespace is None: |
|
122 | 121 | self.global_namespace = {} |
|
123 | 122 | else: |
|
124 | 123 | self.global_namespace = global_namespace |
|
125 | 124 | |
|
126 | 125 | def complete(self, text, state): |
|
127 | 126 | """Return the next possible completion for 'text'. |
|
128 | 127 | |
|
129 | 128 | This is called successively with state == 0, 1, 2, ... until it |
|
130 | 129 | returns None. The completion should begin with 'text'. |
|
131 | 130 | |
|
132 | 131 | """ |
|
133 | 132 | if self.use_main_ns: |
|
134 | 133 | self.namespace = __main__.__dict__ |
|
135 | 134 | |
|
136 | 135 | if state == 0: |
|
137 | 136 | if "." in text: |
|
138 | 137 | self.matches = self.attr_matches(text) |
|
139 | 138 | else: |
|
140 | 139 | self.matches = self.global_matches(text) |
|
141 | 140 | try: |
|
142 | 141 | return self.matches[state] |
|
143 | 142 | except IndexError: |
|
144 | 143 | return None |
|
145 | 144 | |
|
146 | 145 | def global_matches(self, text): |
|
147 | 146 | """Compute matches when text is a simple name. |
|
148 | 147 | |
|
149 | 148 | Return a list of all keywords, built-in functions and names currently |
|
150 | 149 | defined in self.namespace or self.global_namespace that match. |
|
151 | 150 | |
|
152 | 151 | """ |
|
153 | 152 | matches = [] |
|
154 | 153 | match_append = matches.append |
|
155 | 154 | n = len(text) |
|
156 | 155 | for lst in [keyword.kwlist, |
|
157 | 156 | __builtin__.__dict__.keys(), |
|
158 | 157 | self.namespace.keys(), |
|
159 | 158 | self.global_namespace.keys()]: |
|
160 | 159 | for word in lst: |
|
161 | 160 | if word[:n] == text and word != "__builtins__": |
|
162 | 161 | match_append(word) |
|
163 | 162 | return matches |
|
164 | 163 | |
|
165 | 164 | def attr_matches(self, text): |
|
166 | 165 | """Compute matches when text contains a dot. |
|
167 | 166 | |
|
168 | 167 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
169 | 168 | evaluatable in self.namespace or self.global_namespace, it will be |
|
170 | 169 | evaluated and its attributes (as revealed by dir()) are used as |
|
171 | 170 | possible completions. (For class instances, class members are are |
|
172 | 171 | also considered.) |
|
173 | 172 | |
|
174 | 173 | WARNING: this can still invoke arbitrary C code, if an object |
|
175 | 174 | with a __getattr__ hook is evaluated. |
|
176 | 175 | |
|
177 | 176 | """ |
|
178 | 177 | import re |
|
179 | 178 | |
|
180 | 179 | # Another option, seems to work great. Catches things like ''.<tab> |
|
181 | 180 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
182 | 181 | |
|
183 | 182 | if not m: |
|
184 | 183 | return [] |
|
185 | 184 | |
|
186 | 185 | expr, attr = m.group(1, 3) |
|
187 | 186 | try: |
|
188 | 187 | obj = eval(expr, self.namespace) |
|
189 | 188 | except: |
|
190 | 189 | try: |
|
191 | 190 | obj = eval(expr, self.global_namespace) |
|
192 | 191 | except: |
|
193 | 192 | return [] |
|
194 | 193 | |
|
195 | 194 | words = dir2(obj) |
|
196 | 195 | |
|
197 | 196 | try: |
|
198 | 197 | words = generics.complete_object(obj, words) |
|
199 | 198 | except ipapi.TryNext: |
|
200 | 199 | pass |
|
201 | 200 | # Build match list to return |
|
202 | 201 | n = len(attr) |
|
203 | 202 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
204 | 203 | return res |
|
205 | 204 | |
|
206 | 205 | class IPCompleter(Completer): |
|
207 | 206 | """Extension of the completer class with IPython-specific features""" |
|
208 | 207 | |
|
209 | 208 | def __init__(self,shell,namespace=None,global_namespace=None, |
|
210 | 209 | omit__names=0,alias_table=None): |
|
211 | 210 | """IPCompleter() -> completer |
|
212 | 211 | |
|
213 | 212 | Return a completer object suitable for use by the readline library |
|
214 | 213 | via readline.set_completer(). |
|
215 | 214 | |
|
216 | 215 | Inputs: |
|
217 | 216 | |
|
218 | 217 | - shell: a pointer to the ipython shell itself. This is needed |
|
219 | 218 | because this completer knows about magic functions, and those can |
|
220 | 219 | only be accessed via the ipython instance. |
|
221 | 220 | |
|
222 | 221 | - namespace: an optional dict where completions are performed. |
|
223 | 222 | |
|
224 | 223 | - global_namespace: secondary optional dict for completions, to |
|
225 | 224 | handle cases (such as IPython embedded inside functions) where |
|
226 | 225 | both Python scopes are visible. |
|
227 | 226 | |
|
228 | 227 | - The optional omit__names parameter sets the completer to omit the |
|
229 | 228 | 'magic' names (__magicname__) for python objects unless the text |
|
230 | 229 | to be completed explicitly starts with one or more underscores. |
|
231 | 230 | |
|
232 | 231 | - If alias_table is supplied, it should be a dictionary of aliases |
|
233 | 232 | to complete. """ |
|
234 | 233 | |
|
235 | 234 | Completer.__init__(self,namespace,global_namespace) |
|
236 | 235 | self.magic_prefix = shell.name+'.magic_' |
|
237 | 236 | self.magic_escape = shell.ESC_MAGIC |
|
238 | 237 | self.readline = readline |
|
239 | 238 | delims = self.readline.get_completer_delims() |
|
240 | 239 | delims = delims.replace(self.magic_escape,'') |
|
241 | 240 | self.readline.set_completer_delims(delims) |
|
242 | 241 | self.get_line_buffer = self.readline.get_line_buffer |
|
243 | 242 | self.get_endidx = self.readline.get_endidx |
|
244 | 243 | self.omit__names = omit__names |
|
245 | 244 | self.merge_completions = shell.rc.readline_merge_completions |
|
246 | 245 | if alias_table is None: |
|
247 | 246 | alias_table = {} |
|
248 | 247 | self.alias_table = alias_table |
|
249 | 248 | # Regexp to split filenames with spaces in them |
|
250 | 249 | self.space_name_re = re.compile(r'([^\\] )') |
|
251 | 250 | # Hold a local ref. to glob.glob for speed |
|
252 | 251 | self.glob = glob.glob |
|
253 | 252 | |
|
254 | 253 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
255 | 254 | # buffers, to avoid completion problems. |
|
256 | 255 | term = os.environ.get('TERM','xterm') |
|
257 | 256 | self.dumb_terminal = term in ['dumb','emacs'] |
|
258 | 257 | |
|
259 | 258 | # Special handling of backslashes needed in win32 platforms |
|
260 | 259 | if sys.platform == "win32": |
|
261 | 260 | self.clean_glob = self._clean_glob_win32 |
|
262 | 261 | else: |
|
263 | 262 | self.clean_glob = self._clean_glob |
|
264 | 263 | self.matchers = [self.python_matches, |
|
265 | 264 | self.file_matches, |
|
266 | 265 | self.alias_matches, |
|
267 | 266 | self.python_func_kw_matches] |
|
268 | 267 | |
|
269 | 268 | |
|
270 | 269 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
271 | 270 | def all_completions(self, text): |
|
272 | 271 | """Return all possible completions for the benefit of emacs.""" |
|
273 | 272 | |
|
274 | 273 | completions = [] |
|
275 | 274 | comp_append = completions.append |
|
276 | 275 | try: |
|
277 | 276 | for i in xrange(sys.maxint): |
|
278 | 277 | res = self.complete(text, i) |
|
279 | 278 | |
|
280 | 279 | if not res: break |
|
281 | 280 | |
|
282 | 281 | comp_append(res) |
|
283 | 282 | #XXX workaround for ``notDefined.<tab>`` |
|
284 | 283 | except NameError: |
|
285 | 284 | pass |
|
286 | 285 | return completions |
|
287 | 286 | # /end Alex Schmolck code. |
|
288 | 287 | |
|
289 | 288 | def _clean_glob(self,text): |
|
290 | 289 | return self.glob("%s*" % text) |
|
291 | 290 | |
|
292 | 291 | def _clean_glob_win32(self,text): |
|
293 | 292 | return [f.replace("\\","/") |
|
294 | 293 | for f in self.glob("%s*" % text)] |
|
295 | 294 | |
|
296 | 295 | def file_matches(self, text): |
|
297 | 296 | """Match filenames, expanding ~USER type strings. |
|
298 | 297 | |
|
299 | 298 | Most of the seemingly convoluted logic in this completer is an |
|
300 | 299 | attempt to handle filenames with spaces in them. And yet it's not |
|
301 | 300 | quite perfect, because Python's readline doesn't expose all of the |
|
302 | 301 | GNU readline details needed for this to be done correctly. |
|
303 | 302 | |
|
304 | 303 | For a filename with a space in it, the printed completions will be |
|
305 | 304 | only the parts after what's already been typed (instead of the |
|
306 | 305 | full completions, as is normally done). I don't think with the |
|
307 | 306 | current (as of Python 2.3) Python readline it's possible to do |
|
308 | 307 | better.""" |
|
309 | 308 | |
|
310 | 309 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
311 | 310 | |
|
312 | 311 | # chars that require escaping with backslash - i.e. chars |
|
313 | 312 | # that readline treats incorrectly as delimiters, but we |
|
314 | 313 | # don't want to treat as delimiters in filename matching |
|
315 | 314 | # when escaped with backslash |
|
316 | 315 | |
|
317 | 316 | if sys.platform == 'win32': |
|
318 | 317 | protectables = ' ' |
|
319 | 318 | else: |
|
320 | 319 | protectables = ' ()' |
|
321 | 320 | |
|
322 | 321 | if text.startswith('!'): |
|
323 | 322 | text = text[1:] |
|
324 | 323 | text_prefix = '!' |
|
325 | 324 | else: |
|
326 | 325 | text_prefix = '' |
|
327 | 326 | |
|
328 | 327 | def protect_filename(s): |
|
329 | 328 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
330 | 329 | for ch in s]) |
|
331 | 330 | |
|
332 | 331 | def single_dir_expand(matches): |
|
333 | 332 | "Recursively expand match lists containing a single dir." |
|
334 | 333 | |
|
335 | 334 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
336 | 335 | # Takes care of links to directories also. Use '/' |
|
337 | 336 | # explicitly, even under Windows, so that name completions |
|
338 | 337 | # don't end up escaped. |
|
339 | 338 | d = matches[0] |
|
340 | 339 | if d[-1] in ['/','\\']: |
|
341 | 340 | d = d[:-1] |
|
342 | 341 | |
|
343 | 342 | subdirs = os.listdir(d) |
|
344 | 343 | if subdirs: |
|
345 | 344 | matches = [ (d + '/' + p) for p in subdirs] |
|
346 | 345 | return single_dir_expand(matches) |
|
347 | 346 | else: |
|
348 | 347 | return matches |
|
349 | 348 | else: |
|
350 | 349 | return matches |
|
351 | 350 | |
|
352 | 351 | lbuf = self.lbuf |
|
353 | 352 | open_quotes = 0 # track strings with open quotes |
|
354 | 353 | try: |
|
355 | 354 | lsplit = shlex.split(lbuf)[-1] |
|
356 | 355 | except ValueError: |
|
357 | 356 | # typically an unmatched ", or backslash without escaped char. |
|
358 | 357 | if lbuf.count('"')==1: |
|
359 | 358 | open_quotes = 1 |
|
360 | 359 | lsplit = lbuf.split('"')[-1] |
|
361 | 360 | elif lbuf.count("'")==1: |
|
362 | 361 | open_quotes = 1 |
|
363 | 362 | lsplit = lbuf.split("'")[-1] |
|
364 | 363 | else: |
|
365 | 364 | return [] |
|
366 | 365 | except IndexError: |
|
367 | 366 | # tab pressed on empty line |
|
368 | 367 | lsplit = "" |
|
369 | 368 | |
|
370 | 369 | if lsplit != protect_filename(lsplit): |
|
371 | 370 | # if protectables are found, do matching on the whole escaped |
|
372 | 371 | # name |
|
373 | 372 | has_protectables = 1 |
|
374 | 373 | text0,text = text,lsplit |
|
375 | 374 | else: |
|
376 | 375 | has_protectables = 0 |
|
377 | 376 | text = os.path.expanduser(text) |
|
378 | 377 | |
|
379 | 378 | if text == "": |
|
380 | 379 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
381 | 380 | |
|
382 | 381 | m0 = self.clean_glob(text.replace('\\','')) |
|
383 | 382 | if has_protectables: |
|
384 | 383 | # If we had protectables, we need to revert our changes to the |
|
385 | 384 | # beginning of filename so that we don't double-write the part |
|
386 | 385 | # of the filename we have so far |
|
387 | 386 | len_lsplit = len(lsplit) |
|
388 | 387 | matches = [text_prefix + text0 + |
|
389 | 388 | protect_filename(f[len_lsplit:]) for f in m0] |
|
390 | 389 | else: |
|
391 | 390 | if open_quotes: |
|
392 | 391 | # if we have a string with an open quote, we don't need to |
|
393 | 392 | # protect the names at all (and we _shouldn't_, as it |
|
394 | 393 | # would cause bugs when the filesystem call is made). |
|
395 | 394 | matches = m0 |
|
396 | 395 | else: |
|
397 | 396 | matches = [text_prefix + |
|
398 | 397 | protect_filename(f) for f in m0] |
|
399 | 398 | |
|
400 | 399 | #print 'mm',matches # dbg |
|
401 | 400 | return single_dir_expand(matches) |
|
402 | 401 | |
|
403 | 402 | def alias_matches(self, text): |
|
404 | 403 | """Match internal system aliases""" |
|
405 | 404 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg |
|
406 | 405 | |
|
407 | 406 | # if we are not in the first 'item', alias matching |
|
408 | 407 | # doesn't make sense - unless we are starting with 'sudo' command. |
|
409 | 408 | if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'): |
|
410 | 409 | return [] |
|
411 | 410 | text = os.path.expanduser(text) |
|
412 | 411 | aliases = self.alias_table.keys() |
|
413 | 412 | if text == "": |
|
414 | 413 | return aliases |
|
415 | 414 | else: |
|
416 | 415 | return [alias for alias in aliases if alias.startswith(text)] |
|
417 | 416 | |
|
418 | 417 | def python_matches(self,text): |
|
419 | 418 | """Match attributes or global python names""" |
|
420 | 419 | |
|
421 | 420 | #print 'Completer->python_matches, txt=<%s>' % text # dbg |
|
422 | 421 | if "." in text: |
|
423 | 422 | try: |
|
424 | 423 | matches = self.attr_matches(text) |
|
425 | 424 | if text.endswith('.') and self.omit__names: |
|
426 | 425 | if self.omit__names == 1: |
|
427 | 426 | # true if txt is _not_ a __ name, false otherwise: |
|
428 | 427 | no__name = (lambda txt: |
|
429 | 428 | re.match(r'.*\.__.*?__',txt) is None) |
|
430 | 429 | else: |
|
431 | 430 | # true if txt is _not_ a _ name, false otherwise: |
|
432 | 431 | no__name = (lambda txt: |
|
433 | 432 | re.match(r'.*\._.*?',txt) is None) |
|
434 | 433 | matches = filter(no__name, matches) |
|
435 | 434 | except NameError: |
|
436 | 435 | # catches <undefined attributes>.<tab> |
|
437 | 436 | matches = [] |
|
438 | 437 | else: |
|
439 | 438 | matches = self.global_matches(text) |
|
440 | 439 | # this is so completion finds magics when automagic is on: |
|
441 | 440 | if (matches == [] and |
|
442 | 441 | not text.startswith(os.sep) and |
|
443 | 442 | not ' ' in self.lbuf): |
|
444 | 443 | matches = self.attr_matches(self.magic_prefix+text) |
|
445 | 444 | return matches |
|
446 | 445 | |
|
447 | 446 | def _default_arguments(self, obj): |
|
448 | 447 | """Return the list of default arguments of obj if it is callable, |
|
449 | 448 | or empty list otherwise.""" |
|
450 | 449 | |
|
451 | 450 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
452 | 451 | # for classes, check for __init__,__new__ |
|
453 | 452 | if inspect.isclass(obj): |
|
454 | 453 | obj = (getattr(obj,'__init__',None) or |
|
455 | 454 | getattr(obj,'__new__',None)) |
|
456 | 455 | # for all others, check if they are __call__able |
|
457 | 456 | elif hasattr(obj, '__call__'): |
|
458 | 457 | obj = obj.__call__ |
|
459 | 458 | # XXX: is there a way to handle the builtins ? |
|
460 | 459 | try: |
|
461 | 460 | args,_,_1,defaults = inspect.getargspec(obj) |
|
462 | 461 | if defaults: |
|
463 | 462 | return args[-len(defaults):] |
|
464 | 463 | except TypeError: pass |
|
465 | 464 | return [] |
|
466 | 465 | |
|
467 | 466 | def python_func_kw_matches(self,text): |
|
468 | 467 | """Match named parameters (kwargs) of the last open function""" |
|
469 | 468 | |
|
470 | 469 | if "." in text: # a parameter cannot be dotted |
|
471 | 470 | return [] |
|
472 | 471 | try: regexp = self.__funcParamsRegex |
|
473 | 472 | except AttributeError: |
|
474 | 473 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
475 | 474 | '.*?' | # single quoted strings or |
|
476 | 475 | ".*?" | # double quoted strings or |
|
477 | 476 | \w+ | # identifier |
|
478 | 477 | \S # other characters |
|
479 | 478 | ''', re.VERBOSE | re.DOTALL) |
|
480 | 479 | # 1. find the nearest identifier that comes before an unclosed |
|
481 | 480 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
482 | 481 | tokens = regexp.findall(self.get_line_buffer()) |
|
483 | 482 | tokens.reverse() |
|
484 | 483 | iterTokens = iter(tokens); openPar = 0 |
|
485 | 484 | for token in iterTokens: |
|
486 | 485 | if token == ')': |
|
487 | 486 | openPar -= 1 |
|
488 | 487 | elif token == '(': |
|
489 | 488 | openPar += 1 |
|
490 | 489 | if openPar > 0: |
|
491 | 490 | # found the last unclosed parenthesis |
|
492 | 491 | break |
|
493 | 492 | else: |
|
494 | 493 | return [] |
|
495 | 494 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
496 | 495 | ids = [] |
|
497 | 496 | isId = re.compile(r'\w+$').match |
|
498 | 497 | while True: |
|
499 | 498 | try: |
|
500 | 499 | ids.append(iterTokens.next()) |
|
501 | 500 | if not isId(ids[-1]): |
|
502 | 501 | ids.pop(); break |
|
503 | 502 | if not iterTokens.next() == '.': |
|
504 | 503 | break |
|
505 | 504 | except StopIteration: |
|
506 | 505 | break |
|
507 | 506 | # lookup the candidate callable matches either using global_matches |
|
508 | 507 | # or attr_matches for dotted names |
|
509 | 508 | if len(ids) == 1: |
|
510 | 509 | callableMatches = self.global_matches(ids[0]) |
|
511 | 510 | else: |
|
512 | 511 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
513 | 512 | argMatches = [] |
|
514 | 513 | for callableMatch in callableMatches: |
|
515 | 514 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
516 | 515 | self.namespace)) |
|
517 | 516 | except: continue |
|
518 | 517 | for namedArg in namedArgs: |
|
519 | 518 | if namedArg.startswith(text): |
|
520 | 519 | argMatches.append("%s=" %namedArg) |
|
521 | 520 | return argMatches |
|
522 | 521 | |
|
523 | 522 | def dispatch_custom_completer(self,text): |
|
524 | 523 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg |
|
525 | 524 | line = self.full_lbuf |
|
526 | 525 | if not line.strip(): |
|
527 | 526 | return None |
|
528 | 527 | |
|
529 | 528 | event = Struct() |
|
530 | 529 | event.line = line |
|
531 | 530 | event.symbol = text |
|
532 | 531 | cmd = line.split(None,1)[0] |
|
533 | 532 | event.command = cmd |
|
534 | 533 | #print "\ncustom:{%s]\n" % event # dbg |
|
535 | 534 | |
|
536 | 535 | # for foo etc, try also to find completer for %foo |
|
537 | 536 | if not cmd.startswith(self.magic_escape): |
|
538 | 537 | try_magic = self.custom_completers.s_matches( |
|
539 | 538 | self.magic_escape + cmd) |
|
540 | 539 | else: |
|
541 | 540 | try_magic = [] |
|
542 | 541 | |
|
543 | 542 | |
|
544 | 543 | for c in itertools.chain( |
|
545 | 544 | self.custom_completers.s_matches(cmd), |
|
546 | 545 | try_magic, |
|
547 | 546 | self.custom_completers.flat_matches(self.lbuf)): |
|
548 | 547 | #print "try",c # dbg |
|
549 | 548 | try: |
|
550 | 549 | res = c(event) |
|
551 | 550 | # first, try case sensitive match |
|
552 | 551 | withcase = [r for r in res if r.startswith(text)] |
|
553 | 552 | if withcase: |
|
554 | 553 | return withcase |
|
555 | 554 | # if none, then case insensitive ones are ok too |
|
556 | 555 | return [r for r in res if r.lower().startswith(text.lower())] |
|
557 | 556 | except ipapi.TryNext: |
|
558 | 557 | pass |
|
559 | 558 | |
|
560 | 559 | return None |
|
561 | 560 | |
|
562 | 561 | def complete(self, text, state,line_buffer=None): |
|
563 | 562 | """Return the next possible completion for 'text'. |
|
564 | 563 | |
|
565 | 564 | This is called successively with state == 0, 1, 2, ... until it |
|
566 | 565 | returns None. The completion should begin with 'text'. |
|
567 | 566 | |
|
568 | 567 | :Keywords: |
|
569 | 568 | - line_buffer: string |
|
570 | 569 | If not given, the completer attempts to obtain the current line buffer |
|
571 | 570 | via readline. This keyword allows clients which are requesting for |
|
572 | 571 | text completions in non-readline contexts to inform the completer of |
|
573 | 572 | the entire text. |
|
574 | 573 | """ |
|
575 | 574 | |
|
576 | 575 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
577 | 576 | |
|
578 | 577 | # if there is only a tab on a line with only whitespace, instead |
|
579 | 578 | # of the mostly useless 'do you want to see all million |
|
580 | 579 | # completions' message, just do the right thing and give the user |
|
581 | 580 | # his tab! Incidentally, this enables pasting of tabbed text from |
|
582 | 581 | # an editor (as long as autoindent is off). |
|
583 | 582 | |
|
584 | 583 | # It should be noted that at least pyreadline still shows |
|
585 | 584 | # file completions - is there a way around it? |
|
586 | 585 | |
|
587 | 586 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we |
|
588 | 587 | # don't interfere with their own tab-completion mechanism. |
|
589 | 588 | if line_buffer is None: |
|
590 | 589 | self.full_lbuf = self.get_line_buffer() |
|
591 | 590 | else: |
|
592 | 591 | self.full_lbuf = line_buffer |
|
593 | 592 | |
|
594 | 593 | if not (self.dumb_terminal or self.full_lbuf.strip()): |
|
595 | 594 | self.readline.insert_text('\t') |
|
596 | 595 | return None |
|
597 | 596 | |
|
598 | 597 | magic_escape = self.magic_escape |
|
599 | 598 | magic_prefix = self.magic_prefix |
|
600 | 599 | |
|
601 | 600 | self.lbuf = self.full_lbuf[:self.get_endidx()] |
|
602 | 601 | |
|
603 | 602 | try: |
|
604 | 603 | if text.startswith(magic_escape): |
|
605 | 604 | text = text.replace(magic_escape,magic_prefix) |
|
606 | 605 | elif text.startswith('~'): |
|
607 | 606 | text = os.path.expanduser(text) |
|
608 | 607 | if state == 0: |
|
609 | 608 | custom_res = self.dispatch_custom_completer(text) |
|
610 | 609 | if custom_res is not None: |
|
611 | 610 | # did custom completers produce something? |
|
612 | 611 | self.matches = custom_res |
|
613 | 612 | else: |
|
614 | 613 | # Extend the list of completions with the results of each |
|
615 | 614 | # matcher, so we return results to the user from all |
|
616 | 615 | # namespaces. |
|
617 | 616 | if self.merge_completions: |
|
618 | 617 | self.matches = [] |
|
619 | 618 | for matcher in self.matchers: |
|
620 | 619 | self.matches.extend(matcher(text)) |
|
621 | 620 | else: |
|
622 | 621 | for matcher in self.matchers: |
|
623 | 622 | self.matches = matcher(text) |
|
624 | 623 | if self.matches: |
|
625 | 624 | break |
|
626 | 625 | def uniq(alist): |
|
627 | 626 | set = {} |
|
628 | 627 | return [set.setdefault(e,e) for e in alist if e not in set] |
|
629 | 628 | self.matches = uniq(self.matches) |
|
630 | 629 | try: |
|
631 | 630 | ret = self.matches[state].replace(magic_prefix,magic_escape) |
|
632 | 631 | return ret |
|
633 | 632 | except IndexError: |
|
634 | 633 | return None |
|
635 | 634 | except: |
|
636 | 635 | #from IPython.ultraTB import AutoFormattedTB; # dbg |
|
637 | 636 | #tb=AutoFormattedTB('Verbose');tb() #dbg |
|
638 | 637 | |
|
639 | 638 | # If completion fails, don't annoy the user. |
|
640 | 639 | return None |
@@ -1,2164 +1,2164 | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | General purpose utilities. |
|
4 | 4 | |
|
5 | 5 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
6 | 6 | these things are also convenient when working at the command line. |
|
7 | 7 | |
|
8 | 8 | $Id: genutils.py 2998 2008-01-31 10:06:04Z vivainio $""" |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #***************************************************************************** |
|
16 | 16 | |
|
17 | 17 | from IPython import Release |
|
18 | 18 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
19 | 19 | __license__ = Release.license |
|
20 | 20 | |
|
21 | 21 | #**************************************************************************** |
|
22 | 22 | # required modules from the Python standard library |
|
23 | 23 | import __main__ |
|
24 | 24 | import commands |
|
25 | 25 | try: |
|
26 | 26 | import doctest |
|
27 | 27 | except ImportError: |
|
28 | 28 | pass |
|
29 | 29 | import os |
|
30 | 30 | import platform |
|
31 | 31 | import re |
|
32 | 32 | import shlex |
|
33 | 33 | import shutil |
|
34 | 34 | import subprocess |
|
35 | 35 | import sys |
|
36 | 36 | import tempfile |
|
37 | 37 | import time |
|
38 | 38 | import types |
|
39 | 39 | import warnings |
|
40 | 40 | |
|
41 | 41 | # Curses and termios are Unix-only modules |
|
42 | 42 | try: |
|
43 | 43 | import curses |
|
44 | 44 | # We need termios as well, so if its import happens to raise, we bail on |
|
45 | 45 | # using curses altogether. |
|
46 | 46 | import termios |
|
47 | 47 | except ImportError: |
|
48 | 48 | USE_CURSES = False |
|
49 | 49 | else: |
|
50 | 50 | # Curses on Solaris may not be complete, so we can't use it there |
|
51 | 51 | USE_CURSES = hasattr(curses,'initscr') |
|
52 | 52 | |
|
53 | 53 | # Other IPython utilities |
|
54 | 54 | import IPython |
|
55 | 55 | from IPython.Itpl import Itpl,itpl,printpl |
|
56 | 56 | from IPython import DPyGetOpt, platutils |
|
57 | 57 | from IPython.generics import result_display |
|
58 | 58 | import IPython.ipapi |
|
59 | 59 | from IPython.external.path import path |
|
60 | 60 | if os.name == "nt": |
|
61 | 61 | from IPython.winconsole import get_console_size |
|
62 | 62 | |
|
63 | 63 | try: |
|
64 | 64 | set |
|
65 | 65 | except: |
|
66 | 66 | from sets import Set as set |
|
67 | 67 | |
|
68 | 68 | |
|
69 | 69 | #**************************************************************************** |
|
70 | 70 | # Exceptions |
|
71 | 71 | class Error(Exception): |
|
72 | 72 | """Base class for exceptions in this module.""" |
|
73 | 73 | pass |
|
74 | 74 | |
|
75 | 75 | #---------------------------------------------------------------------------- |
|
76 | 76 | class IOStream: |
|
77 | 77 | def __init__(self,stream,fallback): |
|
78 | 78 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
79 | 79 | stream = fallback |
|
80 | 80 | self.stream = stream |
|
81 | 81 | self._swrite = stream.write |
|
82 | 82 | self.flush = stream.flush |
|
83 | 83 | |
|
84 | 84 | def write(self,data): |
|
85 | 85 | try: |
|
86 | 86 | self._swrite(data) |
|
87 | 87 | except: |
|
88 | 88 | try: |
|
89 | 89 | # print handles some unicode issues which may trip a plain |
|
90 | 90 | # write() call. Attempt to emulate write() by using a |
|
91 | 91 | # trailing comma |
|
92 | 92 | print >> self.stream, data, |
|
93 | 93 | except: |
|
94 | 94 | # if we get here, something is seriously broken. |
|
95 | 95 | print >> sys.stderr, \ |
|
96 | 96 | 'ERROR - failed to write data to stream:', self.stream |
|
97 | 97 | |
|
98 | 98 | def close(self): |
|
99 | 99 | pass |
|
100 | 100 | |
|
101 | 101 | |
|
102 | 102 | class IOTerm: |
|
103 | 103 | """ Term holds the file or file-like objects for handling I/O operations. |
|
104 | 104 | |
|
105 | 105 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
106 | 106 | Windows they can can replaced to allow editing the strings before they are |
|
107 | 107 | displayed.""" |
|
108 | 108 | |
|
109 | 109 | # In the future, having IPython channel all its I/O operations through |
|
110 | 110 | # this class will make it easier to embed it into other environments which |
|
111 | 111 | # are not a normal terminal (such as a GUI-based shell) |
|
112 | 112 | def __init__(self,cin=None,cout=None,cerr=None): |
|
113 | 113 | self.cin = IOStream(cin,sys.stdin) |
|
114 | 114 | self.cout = IOStream(cout,sys.stdout) |
|
115 | 115 | self.cerr = IOStream(cerr,sys.stderr) |
|
116 | 116 | |
|
117 | 117 | # Global variable to be used for all I/O |
|
118 | 118 | Term = IOTerm() |
|
119 | 119 | |
|
120 | 120 | import IPython.rlineimpl as readline |
|
121 | 121 | # Remake Term to use the readline i/o facilities |
|
122 | 122 | if sys.platform == 'win32' and readline.have_readline: |
|
123 | 123 | |
|
124 | 124 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) |
|
125 | 125 | |
|
126 | 126 | |
|
127 | 127 | #**************************************************************************** |
|
128 | 128 | # Generic warning/error printer, used by everything else |
|
129 | 129 | def warn(msg,level=2,exit_val=1): |
|
130 | 130 | """Standard warning printer. Gives formatting consistency. |
|
131 | 131 | |
|
132 | 132 | Output is sent to Term.cerr (sys.stderr by default). |
|
133 | 133 | |
|
134 | 134 | Options: |
|
135 | 135 | |
|
136 | 136 | -level(2): allows finer control: |
|
137 | 137 | 0 -> Do nothing, dummy function. |
|
138 | 138 | 1 -> Print message. |
|
139 | 139 | 2 -> Print 'WARNING:' + message. (Default level). |
|
140 | 140 | 3 -> Print 'ERROR:' + message. |
|
141 | 141 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
142 | 142 | |
|
143 | 143 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
144 | 144 | warning. Ignored for all other levels.""" |
|
145 | 145 | |
|
146 | 146 | if level>0: |
|
147 | 147 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
148 | 148 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
149 | 149 | if level == 4: |
|
150 | 150 | print >> Term.cerr,'Exiting.\n' |
|
151 | 151 | sys.exit(exit_val) |
|
152 | 152 | |
|
153 | 153 | def info(msg): |
|
154 | 154 | """Equivalent to warn(msg,level=1).""" |
|
155 | 155 | |
|
156 | 156 | warn(msg,level=1) |
|
157 | 157 | |
|
158 | 158 | def error(msg): |
|
159 | 159 | """Equivalent to warn(msg,level=3).""" |
|
160 | 160 | |
|
161 | 161 | warn(msg,level=3) |
|
162 | 162 | |
|
163 | 163 | def fatal(msg,exit_val=1): |
|
164 | 164 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
165 | 165 | |
|
166 | 166 | warn(msg,exit_val=exit_val,level=4) |
|
167 | 167 | |
|
168 | 168 | #--------------------------------------------------------------------------- |
|
169 | 169 | # Debugging routines |
|
170 | 170 | # |
|
171 | 171 | def debugx(expr,pre_msg=''): |
|
172 | 172 | """Print the value of an expression from the caller's frame. |
|
173 | 173 | |
|
174 | 174 | Takes an expression, evaluates it in the caller's frame and prints both |
|
175 | 175 | the given expression and the resulting value (as well as a debug mark |
|
176 | 176 | indicating the name of the calling function. The input must be of a form |
|
177 | 177 | suitable for eval(). |
|
178 | 178 | |
|
179 | 179 | An optional message can be passed, which will be prepended to the printed |
|
180 | 180 | expr->value pair.""" |
|
181 | 181 | |
|
182 | 182 | cf = sys._getframe(1) |
|
183 | 183 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, |
|
184 | 184 | eval(expr,cf.f_globals,cf.f_locals)) |
|
185 | 185 | |
|
186 | 186 | # deactivate it by uncommenting the following line, which makes it a no-op |
|
187 | 187 | #def debugx(expr,pre_msg=''): pass |
|
188 | 188 | |
|
189 | 189 | #---------------------------------------------------------------------------- |
|
190 | 190 | StringTypes = types.StringTypes |
|
191 | 191 | |
|
192 | 192 | # Basic timing functionality |
|
193 | 193 | |
|
194 | 194 | # If possible (Unix), use the resource module instead of time.clock() |
|
195 | 195 | try: |
|
196 | 196 | import resource |
|
197 | 197 | def clocku(): |
|
198 | 198 | """clocku() -> floating point number |
|
199 | 199 | |
|
200 | 200 | Return the *USER* CPU time in seconds since the start of the process. |
|
201 | 201 | This is done via a call to resource.getrusage, so it avoids the |
|
202 | 202 | wraparound problems in time.clock().""" |
|
203 | 203 | |
|
204 | 204 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
205 | 205 | |
|
206 | 206 | def clocks(): |
|
207 | 207 | """clocks() -> floating point number |
|
208 | 208 | |
|
209 | 209 | Return the *SYSTEM* CPU time in seconds since the start of the process. |
|
210 | 210 | This is done via a call to resource.getrusage, so it avoids the |
|
211 | 211 | wraparound problems in time.clock().""" |
|
212 | 212 | |
|
213 | 213 | return resource.getrusage(resource.RUSAGE_SELF)[1] |
|
214 | 214 | |
|
215 | 215 | def clock(): |
|
216 | 216 | """clock() -> floating point number |
|
217 | 217 | |
|
218 | 218 | Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of |
|
219 | 219 | the process. This is done via a call to resource.getrusage, so it |
|
220 | 220 | avoids the wraparound problems in time.clock().""" |
|
221 | 221 | |
|
222 | 222 | u,s = resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
223 | 223 | return u+s |
|
224 | 224 | |
|
225 | 225 | def clock2(): |
|
226 | 226 | """clock2() -> (t_user,t_system) |
|
227 | 227 | |
|
228 | 228 | Similar to clock(), but return a tuple of user/system times.""" |
|
229 | 229 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
230 | 230 | |
|
231 | 231 | except ImportError: |
|
232 | 232 | # There is no distinction of user/system time under windows, so we just use |
|
233 | 233 | # time.clock() for everything... |
|
234 | 234 | clocku = clocks = clock = time.clock |
|
235 | 235 | def clock2(): |
|
236 | 236 | """Under windows, system CPU time can't be measured. |
|
237 | 237 | |
|
238 | 238 | This just returns clock() and zero.""" |
|
239 | 239 | return time.clock(),0.0 |
|
240 | 240 | |
|
241 | 241 | def timings_out(reps,func,*args,**kw): |
|
242 | 242 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
243 | 243 | |
|
244 | 244 | Execute a function reps times, return a tuple with the elapsed total |
|
245 | 245 | CPU time in seconds, the time per call and the function's output. |
|
246 | 246 | |
|
247 | 247 | Under Unix, the return value is the sum of user+system time consumed by |
|
248 | 248 | the process, computed via the resource module. This prevents problems |
|
249 | 249 | related to the wraparound effect which the time.clock() function has. |
|
250 | 250 | |
|
251 | 251 | Under Windows the return value is in wall clock seconds. See the |
|
252 | 252 | documentation for the time module for more details.""" |
|
253 | 253 | |
|
254 | 254 | reps = int(reps) |
|
255 | 255 | assert reps >=1, 'reps must be >= 1' |
|
256 | 256 | if reps==1: |
|
257 | 257 | start = clock() |
|
258 | 258 | out = func(*args,**kw) |
|
259 | 259 | tot_time = clock()-start |
|
260 | 260 | else: |
|
261 | 261 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
262 | 262 | start = clock() |
|
263 | 263 | for dummy in rng: func(*args,**kw) |
|
264 | 264 | out = func(*args,**kw) # one last time |
|
265 | 265 | tot_time = clock()-start |
|
266 | 266 | av_time = tot_time / reps |
|
267 | 267 | return tot_time,av_time,out |
|
268 | 268 | |
|
269 | 269 | def timings(reps,func,*args,**kw): |
|
270 | 270 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
271 | 271 | |
|
272 | 272 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
273 | 273 | time in seconds and the time per call. These are just the first two values |
|
274 | 274 | in timings_out().""" |
|
275 | 275 | |
|
276 | 276 | return timings_out(reps,func,*args,**kw)[0:2] |
|
277 | 277 | |
|
278 | 278 | def timing(func,*args,**kw): |
|
279 | 279 | """timing(func,*args,**kw) -> t_total |
|
280 | 280 | |
|
281 | 281 | Execute a function once, return the elapsed total CPU time in |
|
282 | 282 | seconds. This is just the first value in timings_out().""" |
|
283 | 283 | |
|
284 | 284 | return timings_out(1,func,*args,**kw)[0] |
|
285 | 285 | |
|
286 | 286 | #**************************************************************************** |
|
287 | 287 | # file and system |
|
288 | 288 | |
|
289 | 289 | def arg_split(s,posix=False): |
|
290 | 290 | """Split a command line's arguments in a shell-like manner. |
|
291 | 291 | |
|
292 | 292 | This is a modified version of the standard library's shlex.split() |
|
293 | 293 | function, but with a default of posix=False for splitting, so that quotes |
|
294 | 294 | in inputs are respected.""" |
|
295 | 295 | |
|
296 | 296 | # XXX - there may be unicode-related problems here!!! I'm not sure that |
|
297 | 297 | # shlex is truly unicode-safe, so it might be necessary to do |
|
298 | 298 | # |
|
299 | 299 | # s = s.encode(sys.stdin.encoding) |
|
300 | 300 | # |
|
301 | 301 | # first, to ensure that shlex gets a normal string. Input from anyone who |
|
302 | 302 | # knows more about unicode and shlex than I would be good to have here... |
|
303 | 303 | lex = shlex.shlex(s, posix=posix) |
|
304 | 304 | lex.whitespace_split = True |
|
305 | 305 | return list(lex) |
|
306 | 306 | |
|
307 | 307 | def system(cmd,verbose=0,debug=0,header=''): |
|
308 | 308 | """Execute a system command, return its exit status. |
|
309 | 309 | |
|
310 | 310 | Options: |
|
311 | 311 | |
|
312 | 312 | - verbose (0): print the command to be executed. |
|
313 | 313 | |
|
314 | 314 | - debug (0): only print, do not actually execute. |
|
315 | 315 | |
|
316 | 316 | - header (''): Header to print on screen prior to the executed command (it |
|
317 | 317 | is only prepended to the command, no newlines are added). |
|
318 | 318 | |
|
319 | 319 | Note: a stateful version of this function is available through the |
|
320 | 320 | SystemExec class.""" |
|
321 | 321 | |
|
322 | 322 | stat = 0 |
|
323 | 323 | if verbose or debug: print header+cmd |
|
324 | 324 | sys.stdout.flush() |
|
325 | 325 | if not debug: stat = os.system(cmd) |
|
326 | 326 | return stat |
|
327 | 327 | |
|
328 | 328 | def abbrev_cwd(): |
|
329 | 329 | """ Return abbreviated version of cwd, e.g. d:mydir """ |
|
330 | 330 | cwd = os.getcwd().replace('\\','/') |
|
331 | 331 | drivepart = '' |
|
332 | 332 | tail = cwd |
|
333 | 333 | if sys.platform == 'win32': |
|
334 | 334 | if len(cwd) < 4: |
|
335 | 335 | return cwd |
|
336 | 336 | drivepart,tail = os.path.splitdrive(cwd) |
|
337 | 337 | |
|
338 | 338 | |
|
339 | 339 | parts = tail.split('/') |
|
340 | 340 | if len(parts) > 2: |
|
341 | 341 | tail = '/'.join(parts[-2:]) |
|
342 | 342 | |
|
343 | 343 | return (drivepart + ( |
|
344 | 344 | cwd == '/' and '/' or tail)) |
|
345 | 345 | |
|
346 | 346 | |
|
347 | 347 | # This function is used by ipython in a lot of places to make system calls. |
|
348 | 348 | # We need it to be slightly different under win32, due to the vagaries of |
|
349 | 349 | # 'network shares'. A win32 override is below. |
|
350 | 350 | |
|
351 | 351 | def shell(cmd,verbose=0,debug=0,header=''): |
|
352 | 352 | """Execute a command in the system shell, always return None. |
|
353 | 353 | |
|
354 | 354 | Options: |
|
355 | 355 | |
|
356 | 356 | - verbose (0): print the command to be executed. |
|
357 | 357 | |
|
358 | 358 | - debug (0): only print, do not actually execute. |
|
359 | 359 | |
|
360 | 360 | - header (''): Header to print on screen prior to the executed command (it |
|
361 | 361 | is only prepended to the command, no newlines are added). |
|
362 | 362 | |
|
363 | 363 | Note: this is similar to genutils.system(), but it returns None so it can |
|
364 | 364 | be conveniently used in interactive loops without getting the return value |
|
365 | 365 | (typically 0) printed many times.""" |
|
366 | 366 | |
|
367 | 367 | stat = 0 |
|
368 | 368 | if verbose or debug: print header+cmd |
|
369 | 369 | # flush stdout so we don't mangle python's buffering |
|
370 | 370 | sys.stdout.flush() |
|
371 | 371 | |
|
372 | 372 | if not debug: |
|
373 | 373 | platutils.set_term_title("IPy " + cmd) |
|
374 | 374 | os.system(cmd) |
|
375 | 375 | platutils.set_term_title("IPy " + abbrev_cwd()) |
|
376 | 376 | |
|
377 | 377 | # override shell() for win32 to deal with network shares |
|
378 | 378 | if os.name in ('nt','dos'): |
|
379 | 379 | |
|
380 | 380 | shell_ori = shell |
|
381 | 381 | |
|
382 | 382 | def shell(cmd,verbose=0,debug=0,header=''): |
|
383 | 383 | if os.getcwd().startswith(r"\\"): |
|
384 | 384 | path = os.getcwd() |
|
385 | 385 | # change to c drive (cannot be on UNC-share when issuing os.system, |
|
386 | 386 | # as cmd.exe cannot handle UNC addresses) |
|
387 | 387 | os.chdir("c:") |
|
388 | 388 | # issue pushd to the UNC-share and then run the command |
|
389 | 389 | try: |
|
390 | 390 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) |
|
391 | 391 | finally: |
|
392 | 392 | os.chdir(path) |
|
393 | 393 | else: |
|
394 | 394 | shell_ori(cmd,verbose,debug,header) |
|
395 | 395 | |
|
396 | 396 | shell.__doc__ = shell_ori.__doc__ |
|
397 | 397 | |
|
398 | 398 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
399 | 399 | """Dummy substitute for perl's backquotes. |
|
400 | 400 | |
|
401 | 401 | Executes a command and returns the output. |
|
402 | 402 | |
|
403 | 403 | Accepts the same arguments as system(), plus: |
|
404 | 404 | |
|
405 | 405 | - split(0): if true, the output is returned as a list split on newlines. |
|
406 | 406 | |
|
407 | 407 | Note: a stateful version of this function is available through the |
|
408 | 408 | SystemExec class. |
|
409 | 409 | |
|
410 | 410 | This is pretty much deprecated and rarely used, |
|
411 | 411 | genutils.getoutputerror may be what you need. |
|
412 | 412 | |
|
413 | 413 | """ |
|
414 | 414 | |
|
415 | 415 | if verbose or debug: print header+cmd |
|
416 | 416 | if not debug: |
|
417 | 417 | output = os.popen(cmd).read() |
|
418 | 418 | # stipping last \n is here for backwards compat. |
|
419 | 419 | if output.endswith('\n'): |
|
420 | 420 | output = output[:-1] |
|
421 | 421 | if split: |
|
422 | 422 | return output.split('\n') |
|
423 | 423 | else: |
|
424 | 424 | return output |
|
425 | 425 | |
|
426 | 426 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
427 | 427 | """Return (standard output,standard error) of executing cmd in a shell. |
|
428 | 428 | |
|
429 | 429 | Accepts the same arguments as system(), plus: |
|
430 | 430 | |
|
431 | 431 | - split(0): if true, each of stdout/err is returned as a list split on |
|
432 | 432 | newlines. |
|
433 | 433 | |
|
434 | 434 | Note: a stateful version of this function is available through the |
|
435 | 435 | SystemExec class.""" |
|
436 | 436 | |
|
437 | 437 | if verbose or debug: print header+cmd |
|
438 | 438 | if not cmd: |
|
439 | 439 | if split: |
|
440 | 440 | return [],[] |
|
441 | 441 | else: |
|
442 | 442 | return '','' |
|
443 | 443 | if not debug: |
|
444 | 444 | pin,pout,perr = os.popen3(cmd) |
|
445 | 445 | tout = pout.read().rstrip() |
|
446 | 446 | terr = perr.read().rstrip() |
|
447 | 447 | pin.close() |
|
448 | 448 | pout.close() |
|
449 | 449 | perr.close() |
|
450 | 450 | if split: |
|
451 | 451 | return tout.split('\n'),terr.split('\n') |
|
452 | 452 | else: |
|
453 | 453 | return tout,terr |
|
454 | 454 | |
|
455 | 455 | # for compatibility with older naming conventions |
|
456 | 456 | xsys = system |
|
457 | 457 | bq = getoutput |
|
458 | 458 | |
|
459 | 459 | class SystemExec: |
|
460 | 460 | """Access the system and getoutput functions through a stateful interface. |
|
461 | 461 | |
|
462 | 462 | Note: here we refer to the system and getoutput functions from this |
|
463 | 463 | library, not the ones from the standard python library. |
|
464 | 464 | |
|
465 | 465 | This class offers the system and getoutput functions as methods, but the |
|
466 | 466 | verbose, debug and header parameters can be set for the instance (at |
|
467 | 467 | creation time or later) so that they don't need to be specified on each |
|
468 | 468 | call. |
|
469 | 469 | |
|
470 | 470 | For efficiency reasons, there's no way to override the parameters on a |
|
471 | 471 | per-call basis other than by setting instance attributes. If you need |
|
472 | 472 | local overrides, it's best to directly call system() or getoutput(). |
|
473 | 473 | |
|
474 | 474 | The following names are provided as alternate options: |
|
475 | 475 | - xsys: alias to system |
|
476 | 476 | - bq: alias to getoutput |
|
477 | 477 | |
|
478 | 478 | An instance can then be created as: |
|
479 | 479 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
480 | 480 | """ |
|
481 | 481 | |
|
482 | 482 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
483 | 483 | """Specify the instance's values for verbose, debug and header.""" |
|
484 | 484 | setattr_list(self,'verbose debug header split') |
|
485 | 485 | |
|
486 | 486 | def system(self,cmd): |
|
487 | 487 | """Stateful interface to system(), with the same keyword parameters.""" |
|
488 | 488 | |
|
489 | 489 | system(cmd,self.verbose,self.debug,self.header) |
|
490 | 490 | |
|
491 | 491 | def shell(self,cmd): |
|
492 | 492 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
493 | 493 | |
|
494 | 494 | shell(cmd,self.verbose,self.debug,self.header) |
|
495 | 495 | |
|
496 | 496 | xsys = system # alias |
|
497 | 497 | |
|
498 | 498 | def getoutput(self,cmd): |
|
499 | 499 | """Stateful interface to getoutput().""" |
|
500 | 500 | |
|
501 | 501 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
502 | 502 | |
|
503 | 503 | def getoutputerror(self,cmd): |
|
504 | 504 | """Stateful interface to getoutputerror().""" |
|
505 | 505 | |
|
506 | 506 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
507 | 507 | |
|
508 | 508 | bq = getoutput # alias |
|
509 | 509 | |
|
510 | 510 | #----------------------------------------------------------------------------- |
|
511 | 511 | def mutex_opts(dict,ex_op): |
|
512 | 512 | """Check for presence of mutually exclusive keys in a dict. |
|
513 | 513 | |
|
514 | 514 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
515 | 515 | for op1,op2 in ex_op: |
|
516 | 516 | if op1 in dict and op2 in dict: |
|
517 | 517 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
518 | 518 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
519 | 519 | |
|
520 | 520 | #----------------------------------------------------------------------------- |
|
521 | 521 | def get_py_filename(name): |
|
522 | 522 | """Return a valid python filename in the current directory. |
|
523 | 523 | |
|
524 | 524 | If the given name is not a file, it adds '.py' and searches again. |
|
525 | 525 | Raises IOError with an informative message if the file isn't found.""" |
|
526 | 526 | |
|
527 | 527 | name = os.path.expanduser(name) |
|
528 | 528 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
529 | 529 | name += '.py' |
|
530 | 530 | if os.path.isfile(name): |
|
531 | 531 | return name |
|
532 | 532 | else: |
|
533 | 533 | raise IOError,'File `%s` not found.' % name |
|
534 | 534 | |
|
535 | 535 | #----------------------------------------------------------------------------- |
|
536 | 536 | def filefind(fname,alt_dirs = None): |
|
537 | 537 | """Return the given filename either in the current directory, if it |
|
538 | 538 | exists, or in a specified list of directories. |
|
539 | 539 | |
|
540 | 540 | ~ expansion is done on all file and directory names. |
|
541 | 541 | |
|
542 | 542 | Upon an unsuccessful search, raise an IOError exception.""" |
|
543 | 543 | |
|
544 | 544 | if alt_dirs is None: |
|
545 | 545 | try: |
|
546 | 546 | alt_dirs = get_home_dir() |
|
547 | 547 | except HomeDirError: |
|
548 | 548 | alt_dirs = os.getcwd() |
|
549 | 549 | search = [fname] + list_strings(alt_dirs) |
|
550 | 550 | search = map(os.path.expanduser,search) |
|
551 | 551 | #print 'search list for',fname,'list:',search # dbg |
|
552 | 552 | fname = search[0] |
|
553 | 553 | if os.path.isfile(fname): |
|
554 | 554 | return fname |
|
555 | 555 | for direc in search[1:]: |
|
556 | 556 | testname = os.path.join(direc,fname) |
|
557 | 557 | #print 'testname',testname # dbg |
|
558 | 558 | if os.path.isfile(testname): |
|
559 | 559 | return testname |
|
560 | 560 | raise IOError,'File' + `fname` + \ |
|
561 | 561 | ' not found in current or supplied directories:' + `alt_dirs` |
|
562 | 562 | |
|
563 | 563 | #---------------------------------------------------------------------------- |
|
564 | 564 | def file_read(filename): |
|
565 | 565 | """Read a file and close it. Returns the file source.""" |
|
566 | 566 | fobj = open(filename,'r'); |
|
567 | 567 | source = fobj.read(); |
|
568 | 568 | fobj.close() |
|
569 | 569 | return source |
|
570 | 570 | |
|
571 | 571 | def file_readlines(filename): |
|
572 | 572 | """Read a file and close it. Returns the file source using readlines().""" |
|
573 | 573 | fobj = open(filename,'r'); |
|
574 | 574 | lines = fobj.readlines(); |
|
575 | 575 | fobj.close() |
|
576 | 576 | return lines |
|
577 | 577 | |
|
578 | 578 | #---------------------------------------------------------------------------- |
|
579 | 579 | def target_outdated(target,deps): |
|
580 | 580 | """Determine whether a target is out of date. |
|
581 | 581 | |
|
582 | 582 | target_outdated(target,deps) -> 1/0 |
|
583 | 583 | |
|
584 | 584 | deps: list of filenames which MUST exist. |
|
585 | 585 | target: single filename which may or may not exist. |
|
586 | 586 | |
|
587 | 587 | If target doesn't exist or is older than any file listed in deps, return |
|
588 | 588 | true, otherwise return false. |
|
589 | 589 | """ |
|
590 | 590 | try: |
|
591 | 591 | target_time = os.path.getmtime(target) |
|
592 | 592 | except os.error: |
|
593 | 593 | return 1 |
|
594 | 594 | for dep in deps: |
|
595 | 595 | dep_time = os.path.getmtime(dep) |
|
596 | 596 | if dep_time > target_time: |
|
597 | 597 | #print "For target",target,"Dep failed:",dep # dbg |
|
598 | 598 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
599 | 599 | return 1 |
|
600 | 600 | return 0 |
|
601 | 601 | |
|
602 | 602 | #----------------------------------------------------------------------------- |
|
603 | 603 | def target_update(target,deps,cmd): |
|
604 | 604 | """Update a target with a given command given a list of dependencies. |
|
605 | 605 | |
|
606 | 606 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
607 | 607 | |
|
608 | 608 | This is just a wrapper around target_outdated() which calls the given |
|
609 | 609 | command if target is outdated.""" |
|
610 | 610 | |
|
611 | 611 | if target_outdated(target,deps): |
|
612 | 612 | xsys(cmd) |
|
613 | 613 | |
|
614 | 614 | #---------------------------------------------------------------------------- |
|
615 | 615 | def unquote_ends(istr): |
|
616 | 616 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
617 | 617 | |
|
618 | 618 | if not istr: |
|
619 | 619 | return istr |
|
620 | 620 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
621 | 621 | (istr[0]=='"' and istr[-1]=='"'): |
|
622 | 622 | return istr[1:-1] |
|
623 | 623 | else: |
|
624 | 624 | return istr |
|
625 | 625 | |
|
626 | 626 | #---------------------------------------------------------------------------- |
|
627 | 627 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
628 | 628 | """ Process command-line options and arguments. |
|
629 | 629 | |
|
630 | 630 | Arguments: |
|
631 | 631 | |
|
632 | 632 | - argv: list of arguments, typically sys.argv. |
|
633 | 633 | |
|
634 | 634 | - names: list of option names. See DPyGetOpt docs for details on options |
|
635 | 635 | syntax. |
|
636 | 636 | |
|
637 | 637 | - defaults: dict of default values. |
|
638 | 638 | |
|
639 | 639 | - usage: optional usage notice to print if a wrong argument is passed. |
|
640 | 640 | |
|
641 | 641 | Return a dict of options and a list of free arguments.""" |
|
642 | 642 | |
|
643 | 643 | getopt = DPyGetOpt.DPyGetOpt() |
|
644 | 644 | getopt.setIgnoreCase(0) |
|
645 | 645 | getopt.parseConfiguration(names) |
|
646 | 646 | |
|
647 | 647 | try: |
|
648 | 648 | getopt.processArguments(argv) |
|
649 | 649 | except DPyGetOpt.ArgumentError, exc: |
|
650 | 650 | print usage |
|
651 | 651 | warn('"%s"' % exc,level=4) |
|
652 | 652 | |
|
653 | 653 | defaults.update(getopt.optionValues) |
|
654 | 654 | args = getopt.freeValues |
|
655 | 655 | |
|
656 | 656 | return defaults,args |
|
657 | 657 | |
|
658 | 658 | #---------------------------------------------------------------------------- |
|
659 | 659 | def optstr2types(ostr): |
|
660 | 660 | """Convert a string of option names to a dict of type mappings. |
|
661 | 661 | |
|
662 | 662 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
663 | 663 | |
|
664 | 664 | This is used to get the types of all the options in a string formatted |
|
665 | 665 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
666 | 666 | which are strings (they need no further conversion). This function's main |
|
667 | 667 | use is to get a typemap for use with read_dict(). |
|
668 | 668 | """ |
|
669 | 669 | |
|
670 | 670 | typeconv = {None:'',int:'',float:''} |
|
671 | 671 | typemap = {'s':None,'i':int,'f':float} |
|
672 | 672 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
673 | 673 | |
|
674 | 674 | for w in ostr.split(): |
|
675 | 675 | oname,alias,otype = opt_re.match(w).groups() |
|
676 | 676 | if otype == '' or alias == '!': # simple switches are integers too |
|
677 | 677 | otype = 'i' |
|
678 | 678 | typeconv[typemap[otype]] += oname + ' ' |
|
679 | 679 | return typeconv |
|
680 | 680 | |
|
681 | 681 | #---------------------------------------------------------------------------- |
|
682 | 682 | def read_dict(filename,type_conv=None,**opt): |
|
683 | 683 | r"""Read a dictionary of key=value pairs from an input file, optionally |
|
684 | 684 | performing conversions on the resulting values. |
|
685 | 685 | |
|
686 | 686 | read_dict(filename,type_conv,**opt) -> dict |
|
687 | 687 | |
|
688 | 688 | Only one value per line is accepted, the format should be |
|
689 | 689 | # optional comments are ignored |
|
690 | 690 | key value\n |
|
691 | 691 | |
|
692 | 692 | Args: |
|
693 | 693 | |
|
694 | 694 | - type_conv: A dictionary specifying which keys need to be converted to |
|
695 | 695 | which types. By default all keys are read as strings. This dictionary |
|
696 | 696 | should have as its keys valid conversion functions for strings |
|
697 | 697 | (int,long,float,complex, or your own). The value for each key |
|
698 | 698 | (converter) should be a whitespace separated string containing the names |
|
699 | 699 | of all the entries in the file to be converted using that function. For |
|
700 | 700 | keys to be left alone, use None as the conversion function (only needed |
|
701 | 701 | with purge=1, see below). |
|
702 | 702 | |
|
703 | 703 | - opt: dictionary with extra options as below (default in parens) |
|
704 | 704 | |
|
705 | 705 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
706 | 706 | of the dictionary to be returned. If purge is going to be used, the |
|
707 | 707 | set of keys to be left as strings also has to be explicitly specified |
|
708 | 708 | using the (non-existent) conversion function None. |
|
709 | 709 | |
|
710 | 710 | fs(None): field separator. This is the key/value separator to be used |
|
711 | 711 | when parsing the file. The None default means any whitespace [behavior |
|
712 | 712 | of string.split()]. |
|
713 | 713 | |
|
714 | 714 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
715 | 715 | |
|
716 | 716 | warn(1): warning level if requested keys are not found in file. |
|
717 | 717 | - 0: silently ignore. |
|
718 | 718 | - 1: inform but proceed. |
|
719 | 719 | - 2: raise KeyError exception. |
|
720 | 720 | |
|
721 | 721 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
722 | 722 | |
|
723 | 723 | unique([]): list of keys (or space separated string) which can't be |
|
724 | 724 | repeated. If one such key is found in the file, each new instance |
|
725 | 725 | overwrites the previous one. For keys not listed here, the behavior is |
|
726 | 726 | to make a list of all appearances. |
|
727 | 727 | |
|
728 | 728 | Example: |
|
729 | 729 | |
|
730 | 730 | If the input file test.ini contains (we put it in a string to keep the test |
|
731 | 731 | self-contained): |
|
732 | 732 | |
|
733 | 733 | >>> test_ini = '''\ |
|
734 | 734 | ... i 3 |
|
735 | 735 | ... x 4.5 |
|
736 | 736 | ... y 5.5 |
|
737 | 737 | ... s hi ho''' |
|
738 | 738 | |
|
739 | 739 | Then we can use it as follows: |
|
740 | 740 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
741 | 741 | |
|
742 | 742 | >>> d = read_dict(test_ini) |
|
743 | 743 | |
|
744 | 744 | >>> sorted(d.items()) |
|
745 | 745 | [('i', '3'), ('s', 'hi ho'), ('x', '4.5'), ('y', '5.5')] |
|
746 | 746 | |
|
747 | 747 | >>> d = read_dict(test_ini,type_conv) |
|
748 | 748 | |
|
749 | 749 | >>> sorted(d.items()) |
|
750 | 750 | [('i', 3), ('s', 'hi ho'), ('x', 4.5), ('y', '5.5')] |
|
751 | 751 | |
|
752 | 752 | >>> d = read_dict(test_ini,type_conv,purge=True) |
|
753 | 753 | |
|
754 | 754 | >>> sorted(d.items()) |
|
755 | 755 | [('i', 3), ('s', 'hi ho'), ('x', 4.5)] |
|
756 | 756 | """ |
|
757 | 757 | |
|
758 | 758 | # starting config |
|
759 | 759 | opt.setdefault('purge',0) |
|
760 | 760 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
761 | 761 | opt.setdefault('strip',0) |
|
762 | 762 | opt.setdefault('warn',1) |
|
763 | 763 | opt.setdefault('no_empty',0) |
|
764 | 764 | opt.setdefault('unique','') |
|
765 | 765 | if type(opt['unique']) in StringTypes: |
|
766 | 766 | unique_keys = qw(opt['unique']) |
|
767 | 767 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
768 | 768 | unique_keys = opt['unique'] |
|
769 | 769 | else: |
|
770 | 770 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
771 | 771 | |
|
772 | 772 | dict = {} |
|
773 | 773 | |
|
774 | 774 | # first read in table of values as strings |
|
775 | 775 | if '\n' in filename: |
|
776 | 776 | lines = filename.splitlines() |
|
777 | 777 | file = None |
|
778 | 778 | else: |
|
779 | 779 | file = open(filename,'r') |
|
780 | 780 | lines = file.readlines() |
|
781 | 781 | for line in lines: |
|
782 | 782 | line = line.strip() |
|
783 | 783 | if len(line) and line[0]=='#': continue |
|
784 | 784 | if len(line)>0: |
|
785 | 785 | lsplit = line.split(opt['fs'],1) |
|
786 | 786 | try: |
|
787 | 787 | key,val = lsplit |
|
788 | 788 | except ValueError: |
|
789 | 789 | key,val = lsplit[0],'' |
|
790 | 790 | key = key.strip() |
|
791 | 791 | if opt['strip']: val = val.strip() |
|
792 | 792 | if val == "''" or val == '""': val = '' |
|
793 | 793 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
794 | 794 | continue |
|
795 | 795 | # if a key is found more than once in the file, build a list |
|
796 | 796 | # unless it's in the 'unique' list. In that case, last found in file |
|
797 | 797 | # takes precedence. User beware. |
|
798 | 798 | try: |
|
799 | 799 | if dict[key] and key in unique_keys: |
|
800 | 800 | dict[key] = val |
|
801 | 801 | elif type(dict[key]) is types.ListType: |
|
802 | 802 | dict[key].append(val) |
|
803 | 803 | else: |
|
804 | 804 | dict[key] = [dict[key],val] |
|
805 | 805 | except KeyError: |
|
806 | 806 | dict[key] = val |
|
807 | 807 | # purge if requested |
|
808 | 808 | if opt['purge']: |
|
809 | 809 | accepted_keys = qwflat(type_conv.values()) |
|
810 | 810 | for key in dict.keys(): |
|
811 | 811 | if key in accepted_keys: continue |
|
812 | 812 | del(dict[key]) |
|
813 | 813 | # now convert if requested |
|
814 | 814 | if type_conv==None: return dict |
|
815 | 815 | conversions = type_conv.keys() |
|
816 | 816 | try: conversions.remove(None) |
|
817 | 817 | except: pass |
|
818 | 818 | for convert in conversions: |
|
819 | 819 | for val in qw(type_conv[convert]): |
|
820 | 820 | try: |
|
821 | 821 | dict[val] = convert(dict[val]) |
|
822 | 822 | except KeyError,e: |
|
823 | 823 | if opt['warn'] == 0: |
|
824 | 824 | pass |
|
825 | 825 | elif opt['warn'] == 1: |
|
826 | 826 | print >>sys.stderr, 'Warning: key',val,\ |
|
827 | 827 | 'not found in file',filename |
|
828 | 828 | elif opt['warn'] == 2: |
|
829 | 829 | raise KeyError,e |
|
830 | 830 | else: |
|
831 | 831 | raise ValueError,'Warning level must be 0,1 or 2' |
|
832 | 832 | |
|
833 | 833 | return dict |
|
834 | 834 | |
|
835 | 835 | #---------------------------------------------------------------------------- |
|
836 | 836 | def flag_calls(func): |
|
837 | 837 | """Wrap a function to detect and flag when it gets called. |
|
838 | 838 | |
|
839 | 839 | This is a decorator which takes a function and wraps it in a function with |
|
840 | 840 | a 'called' attribute. wrapper.called is initialized to False. |
|
841 | 841 | |
|
842 | 842 | The wrapper.called attribute is set to False right before each call to the |
|
843 | 843 | wrapped function, so if the call fails it remains False. After the call |
|
844 | 844 | completes, wrapper.called is set to True and the output is returned. |
|
845 | 845 | |
|
846 | 846 | Testing for truth in wrapper.called allows you to determine if a call to |
|
847 | 847 | func() was attempted and succeeded.""" |
|
848 | 848 | |
|
849 | 849 | def wrapper(*args,**kw): |
|
850 | 850 | wrapper.called = False |
|
851 | 851 | out = func(*args,**kw) |
|
852 | 852 | wrapper.called = True |
|
853 | 853 | return out |
|
854 | 854 | |
|
855 | 855 | wrapper.called = False |
|
856 | 856 | wrapper.__doc__ = func.__doc__ |
|
857 | 857 | return wrapper |
|
858 | 858 | |
|
859 | 859 | #---------------------------------------------------------------------------- |
|
860 | 860 | def dhook_wrap(func,*a,**k): |
|
861 | 861 | """Wrap a function call in a sys.displayhook controller. |
|
862 | 862 | |
|
863 | 863 | Returns a wrapper around func which calls func, with all its arguments and |
|
864 | 864 | keywords unmodified, using the default sys.displayhook. Since IPython |
|
865 | 865 | modifies sys.displayhook, it breaks the behavior of certain systems that |
|
866 | 866 | rely on the default behavior, notably doctest. |
|
867 | 867 | """ |
|
868 | 868 | |
|
869 | 869 | def f(*a,**k): |
|
870 | 870 | |
|
871 | 871 | dhook_s = sys.displayhook |
|
872 | 872 | sys.displayhook = sys.__displayhook__ |
|
873 | 873 | try: |
|
874 | 874 | out = func(*a,**k) |
|
875 | 875 | finally: |
|
876 | 876 | sys.displayhook = dhook_s |
|
877 | 877 | |
|
878 | 878 | return out |
|
879 | 879 | |
|
880 | 880 | f.__doc__ = func.__doc__ |
|
881 | 881 | return f |
|
882 | 882 | |
|
883 | 883 | #---------------------------------------------------------------------------- |
|
884 | 884 | def doctest_reload(): |
|
885 | 885 | """Properly reload doctest to reuse it interactively. |
|
886 | 886 | |
|
887 | 887 | This routine: |
|
888 | 888 | |
|
889 | 889 | - reloads doctest |
|
890 | 890 | |
|
891 | 891 | - resets its global 'master' attribute to None, so that multiple uses of |
|
892 | 892 | the module interactively don't produce cumulative reports. |
|
893 | 893 | |
|
894 | 894 | - Monkeypatches its core test runner method to protect it from IPython's |
|
895 | 895 | modified displayhook. Doctest expects the default displayhook behavior |
|
896 | 896 | deep down, so our modification breaks it completely. For this reason, a |
|
897 | 897 | hard monkeypatch seems like a reasonable solution rather than asking |
|
898 | 898 | users to manually use a different doctest runner when under IPython.""" |
|
899 | 899 | |
|
900 | 900 | import doctest |
|
901 | 901 | reload(doctest) |
|
902 | 902 | doctest.master=None |
|
903 | 903 | |
|
904 | 904 | try: |
|
905 | 905 | doctest.DocTestRunner |
|
906 | 906 | except AttributeError: |
|
907 | 907 | # This is only for python 2.3 compatibility, remove once we move to |
|
908 | 908 | # 2.4 only. |
|
909 | 909 | pass |
|
910 | 910 | else: |
|
911 | 911 | doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run) |
|
912 | 912 | |
|
913 | 913 | #---------------------------------------------------------------------------- |
|
914 | 914 | class HomeDirError(Error): |
|
915 | 915 | pass |
|
916 | 916 | |
|
917 | 917 | def get_home_dir(): |
|
918 | 918 | """Return the closest possible equivalent to a 'home' directory. |
|
919 | 919 | |
|
920 | 920 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
921 | 921 | |
|
922 | 922 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
923 | 923 | raised for all other OSes. """ |
|
924 | 924 | |
|
925 | 925 | isdir = os.path.isdir |
|
926 | 926 | env = os.environ |
|
927 | 927 | |
|
928 | 928 | # first, check py2exe distribution root directory for _ipython. |
|
929 | 929 | # This overrides all. Normally does not exist. |
|
930 | 930 | |
|
931 | 931 | if '\\library.zip\\' in IPython.__file__.lower(): |
|
932 | 932 | root, rest = IPython.__file__.lower().split('library.zip') |
|
933 | 933 | if isdir(root + '_ipython'): |
|
934 | 934 | os.environ["IPYKITROOT"] = root.rstrip('\\') |
|
935 | 935 | return root |
|
936 | 936 | |
|
937 | 937 | try: |
|
938 | 938 | homedir = env['HOME'] |
|
939 | 939 | if not isdir(homedir): |
|
940 | 940 | # in case a user stuck some string which does NOT resolve to a |
|
941 | 941 | # valid path, it's as good as if we hadn't foud it |
|
942 | 942 | raise KeyError |
|
943 | 943 | return homedir |
|
944 | 944 | except KeyError: |
|
945 | 945 | if os.name == 'posix': |
|
946 | 946 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
947 | 947 | elif os.name == 'nt': |
|
948 | 948 | # For some strange reason, win9x returns 'nt' for os.name. |
|
949 | 949 | try: |
|
950 | 950 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
951 | 951 | if not isdir(homedir): |
|
952 | 952 | homedir = os.path.join(env['USERPROFILE']) |
|
953 | 953 | if not isdir(homedir): |
|
954 | 954 | raise HomeDirError |
|
955 | 955 | return homedir |
|
956 | 956 | except: |
|
957 | 957 | try: |
|
958 | 958 | # Use the registry to get the 'My Documents' folder. |
|
959 | 959 | import _winreg as wreg |
|
960 | 960 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
961 | 961 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
962 | 962 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
963 | 963 | key.Close() |
|
964 | 964 | if not isdir(homedir): |
|
965 | 965 | e = ('Invalid "Personal" folder registry key ' |
|
966 | 966 | 'typically "My Documents".\n' |
|
967 | 967 | 'Value: %s\n' |
|
968 | 968 | 'This is not a valid directory on your system.' % |
|
969 | 969 | homedir) |
|
970 | 970 | raise HomeDirError(e) |
|
971 | 971 | return homedir |
|
972 | 972 | except HomeDirError: |
|
973 | 973 | raise |
|
974 | 974 | except: |
|
975 | 975 | return 'C:\\' |
|
976 | 976 | elif os.name == 'dos': |
|
977 | 977 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
978 | 978 | return 'C:\\' |
|
979 | 979 | else: |
|
980 | 980 | raise HomeDirError,'support for your operating system not implemented.' |
|
981 | 981 | |
|
982 | 982 | |
|
983 | 983 | def get_ipython_dir(): |
|
984 | 984 | """Get the IPython directory for this platform and user. |
|
985 | 985 | |
|
986 | 986 | This uses the logic in `get_home_dir` to find the home directory |
|
987 | 987 | and the adds either .ipython or _ipython to the end of the path. |
|
988 | 988 | """ |
|
989 | 989 | if os.name == 'posix': |
|
990 | 990 | ipdir_def = '.ipython' |
|
991 | 991 | else: |
|
992 | 992 | ipdir_def = '_ipython' |
|
993 | 993 | home_dir = get_home_dir() |
|
994 | 994 | ipdir = os.path.abspath(os.environ.get('IPYTHONDIR', |
|
995 | 995 | os.path.join(home_dir,ipdir_def))) |
|
996 | 996 | return ipdir |
|
997 | 997 | |
|
998 | 998 | def get_security_dir(): |
|
999 | 999 | """Get the IPython security directory. |
|
1000 | 1000 | |
|
1001 | 1001 | This directory is the default location for all security related files, |
|
1002 | 1002 | including SSL/TLS certificates and FURL files. |
|
1003 | 1003 | |
|
1004 | 1004 | If the directory does not exist, it is created with 0700 permissions. |
|
1005 | 1005 | If it exists, permissions are set to 0700. |
|
1006 | 1006 | """ |
|
1007 | 1007 | security_dir = os.path.join(get_ipython_dir(), 'security') |
|
1008 | 1008 | if not os.path.isdir(security_dir): |
|
1009 | 1009 | os.mkdir(security_dir, 0700) |
|
1010 | 1010 | else: |
|
1011 | 1011 | os.chmod(security_dir, 0700) |
|
1012 | 1012 | return security_dir |
|
1013 | 1013 | |
|
1014 | 1014 | #**************************************************************************** |
|
1015 | 1015 | # strings and text |
|
1016 | 1016 | |
|
1017 | 1017 | class LSString(str): |
|
1018 | 1018 | """String derivative with a special access attributes. |
|
1019 | 1019 | |
|
1020 | 1020 | These are normal strings, but with the special attributes: |
|
1021 | 1021 | |
|
1022 | 1022 | .l (or .list) : value as list (split on newlines). |
|
1023 | 1023 | .n (or .nlstr): original value (the string itself). |
|
1024 | 1024 | .s (or .spstr): value as whitespace-separated string. |
|
1025 | 1025 | .p (or .paths): list of path objects |
|
1026 | 1026 | |
|
1027 | 1027 | Any values which require transformations are computed only once and |
|
1028 | 1028 | cached. |
|
1029 | 1029 | |
|
1030 | 1030 | Such strings are very useful to efficiently interact with the shell, which |
|
1031 | 1031 | typically only understands whitespace-separated options for commands.""" |
|
1032 | 1032 | |
|
1033 | 1033 | def get_list(self): |
|
1034 | 1034 | try: |
|
1035 | 1035 | return self.__list |
|
1036 | 1036 | except AttributeError: |
|
1037 | 1037 | self.__list = self.split('\n') |
|
1038 | 1038 | return self.__list |
|
1039 | 1039 | |
|
1040 | 1040 | l = list = property(get_list) |
|
1041 | 1041 | |
|
1042 | 1042 | def get_spstr(self): |
|
1043 | 1043 | try: |
|
1044 | 1044 | return self.__spstr |
|
1045 | 1045 | except AttributeError: |
|
1046 | 1046 | self.__spstr = self.replace('\n',' ') |
|
1047 | 1047 | return self.__spstr |
|
1048 | 1048 | |
|
1049 | 1049 | s = spstr = property(get_spstr) |
|
1050 | 1050 | |
|
1051 | 1051 | def get_nlstr(self): |
|
1052 | 1052 | return self |
|
1053 | 1053 | |
|
1054 | 1054 | n = nlstr = property(get_nlstr) |
|
1055 | 1055 | |
|
1056 | 1056 | def get_paths(self): |
|
1057 | 1057 | try: |
|
1058 | 1058 | return self.__paths |
|
1059 | 1059 | except AttributeError: |
|
1060 | 1060 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
1061 | 1061 | return self.__paths |
|
1062 | 1062 | |
|
1063 | 1063 | p = paths = property(get_paths) |
|
1064 | 1064 | |
|
1065 | 1065 | def print_lsstring(arg): |
|
1066 | 1066 | """ Prettier (non-repr-like) and more informative printer for LSString """ |
|
1067 | 1067 | print "LSString (.p, .n, .l, .s available). Value:" |
|
1068 | 1068 | print arg |
|
1069 | 1069 | |
|
1070 | 1070 | print_lsstring = result_display.when_type(LSString)(print_lsstring) |
|
1071 | 1071 | |
|
1072 | 1072 | #---------------------------------------------------------------------------- |
|
1073 | 1073 | class SList(list): |
|
1074 | 1074 | """List derivative with a special access attributes. |
|
1075 | 1075 | |
|
1076 | 1076 | These are normal lists, but with the special attributes: |
|
1077 | 1077 | |
|
1078 | 1078 | .l (or .list) : value as list (the list itself). |
|
1079 | 1079 | .n (or .nlstr): value as a string, joined on newlines. |
|
1080 | 1080 | .s (or .spstr): value as a string, joined on spaces. |
|
1081 | 1081 | .p (or .paths): list of path objects |
|
1082 | 1082 | |
|
1083 | 1083 | Any values which require transformations are computed only once and |
|
1084 | 1084 | cached.""" |
|
1085 | 1085 | |
|
1086 | 1086 | def get_list(self): |
|
1087 | 1087 | return self |
|
1088 | 1088 | |
|
1089 | 1089 | l = list = property(get_list) |
|
1090 | 1090 | |
|
1091 | 1091 | def get_spstr(self): |
|
1092 | 1092 | try: |
|
1093 | 1093 | return self.__spstr |
|
1094 | 1094 | except AttributeError: |
|
1095 | 1095 | self.__spstr = ' '.join(self) |
|
1096 | 1096 | return self.__spstr |
|
1097 | 1097 | |
|
1098 | 1098 | s = spstr = property(get_spstr) |
|
1099 | 1099 | |
|
1100 | 1100 | def get_nlstr(self): |
|
1101 | 1101 | try: |
|
1102 | 1102 | return self.__nlstr |
|
1103 | 1103 | except AttributeError: |
|
1104 | 1104 | self.__nlstr = '\n'.join(self) |
|
1105 | 1105 | return self.__nlstr |
|
1106 | 1106 | |
|
1107 | 1107 | n = nlstr = property(get_nlstr) |
|
1108 | 1108 | |
|
1109 | 1109 | def get_paths(self): |
|
1110 | 1110 | try: |
|
1111 | 1111 | return self.__paths |
|
1112 | 1112 | except AttributeError: |
|
1113 | 1113 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
1114 | 1114 | return self.__paths |
|
1115 | 1115 | |
|
1116 | 1116 | p = paths = property(get_paths) |
|
1117 | 1117 | |
|
1118 | 1118 | def grep(self, pattern, prune = False, field = None): |
|
1119 | 1119 | """ Return all strings matching 'pattern' (a regex or callable) |
|
1120 | 1120 | |
|
1121 | 1121 | This is case-insensitive. If prune is true, return all items |
|
1122 | 1122 | NOT matching the pattern. |
|
1123 | 1123 | |
|
1124 | 1124 | If field is specified, the match must occur in the specified |
|
1125 | 1125 | whitespace-separated field. |
|
1126 | 1126 | |
|
1127 | 1127 | Examples:: |
|
1128 | 1128 | |
|
1129 | 1129 | a.grep( lambda x: x.startswith('C') ) |
|
1130 | 1130 | a.grep('Cha.*log', prune=1) |
|
1131 | 1131 | a.grep('chm', field=-1) |
|
1132 | 1132 | """ |
|
1133 | 1133 | |
|
1134 | 1134 | def match_target(s): |
|
1135 | 1135 | if field is None: |
|
1136 | 1136 | return s |
|
1137 | 1137 | parts = s.split() |
|
1138 | 1138 | try: |
|
1139 | 1139 | tgt = parts[field] |
|
1140 | 1140 | return tgt |
|
1141 | 1141 | except IndexError: |
|
1142 | 1142 | return "" |
|
1143 | 1143 | |
|
1144 | 1144 | if isinstance(pattern, basestring): |
|
1145 | 1145 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) |
|
1146 | 1146 | else: |
|
1147 | 1147 | pred = pattern |
|
1148 | 1148 | if not prune: |
|
1149 | 1149 | return SList([el for el in self if pred(match_target(el))]) |
|
1150 | 1150 | else: |
|
1151 | 1151 | return SList([el for el in self if not pred(match_target(el))]) |
|
1152 | 1152 | def fields(self, *fields): |
|
1153 | 1153 | """ Collect whitespace-separated fields from string list |
|
1154 | 1154 | |
|
1155 | 1155 | Allows quick awk-like usage of string lists. |
|
1156 | 1156 | |
|
1157 | 1157 | Example data (in var a, created by 'a = !ls -l'):: |
|
1158 | 1158 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog |
|
1159 | 1159 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython |
|
1160 | 1160 | |
|
1161 | 1161 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] |
|
1162 | 1162 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] |
|
1163 | 1163 | (note the joining by space). |
|
1164 | 1164 | a.fields(-1) is ['ChangeLog', 'IPython'] |
|
1165 | 1165 | |
|
1166 | 1166 | IndexErrors are ignored. |
|
1167 | 1167 | |
|
1168 | 1168 | Without args, fields() just split()'s the strings. |
|
1169 | 1169 | """ |
|
1170 | 1170 | if len(fields) == 0: |
|
1171 | 1171 | return [el.split() for el in self] |
|
1172 | 1172 | |
|
1173 | 1173 | res = SList() |
|
1174 | 1174 | for el in [f.split() for f in self]: |
|
1175 | 1175 | lineparts = [] |
|
1176 | 1176 | |
|
1177 | 1177 | for fd in fields: |
|
1178 | 1178 | try: |
|
1179 | 1179 | lineparts.append(el[fd]) |
|
1180 | 1180 | except IndexError: |
|
1181 | 1181 | pass |
|
1182 | 1182 | if lineparts: |
|
1183 | 1183 | res.append(" ".join(lineparts)) |
|
1184 | 1184 | |
|
1185 | 1185 | return res |
|
1186 | 1186 | def sort(self,field= None, nums = False): |
|
1187 | 1187 | """ sort by specified fields (see fields()) |
|
1188 | 1188 | |
|
1189 | 1189 | Example:: |
|
1190 | 1190 | a.sort(1, nums = True) |
|
1191 | 1191 | |
|
1192 | 1192 | Sorts a by second field, in numerical order (so that 21 > 3) |
|
1193 | 1193 | |
|
1194 | 1194 | """ |
|
1195 | 1195 | |
|
1196 | 1196 | #decorate, sort, undecorate |
|
1197 | 1197 | if field is not None: |
|
1198 | 1198 | dsu = [[SList([line]).fields(field), line] for line in self] |
|
1199 | 1199 | else: |
|
1200 | 1200 | dsu = [[line, line] for line in self] |
|
1201 | 1201 | if nums: |
|
1202 | 1202 | for i in range(len(dsu)): |
|
1203 | 1203 | numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) |
|
1204 | 1204 | try: |
|
1205 | 1205 | n = int(numstr) |
|
1206 | 1206 | except ValueError: |
|
1207 | 1207 | n = 0; |
|
1208 | 1208 | dsu[i][0] = n |
|
1209 | 1209 | |
|
1210 | 1210 | |
|
1211 | 1211 | dsu.sort() |
|
1212 | 1212 | return SList([t[1] for t in dsu]) |
|
1213 | 1213 | |
|
1214 | 1214 | def print_slist(arg): |
|
1215 | 1215 | """ Prettier (non-repr-like) and more informative printer for SList """ |
|
1216 | 1216 | print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" |
|
1217 | 1217 | if hasattr(arg, 'hideonce') and arg.hideonce: |
|
1218 | 1218 | arg.hideonce = False |
|
1219 | 1219 | return |
|
1220 | 1220 | |
|
1221 | 1221 | nlprint(arg) |
|
1222 | 1222 | |
|
1223 | 1223 | print_slist = result_display.when_type(SList)(print_slist) |
|
1224 | 1224 | |
|
1225 | 1225 | |
|
1226 | 1226 | |
|
1227 | 1227 | #---------------------------------------------------------------------------- |
|
1228 | 1228 | def esc_quotes(strng): |
|
1229 | 1229 | """Return the input string with single and double quotes escaped out""" |
|
1230 | 1230 | |
|
1231 | 1231 | return strng.replace('"','\\"').replace("'","\\'") |
|
1232 | 1232 | |
|
1233 | 1233 | #---------------------------------------------------------------------------- |
|
1234 | 1234 | def make_quoted_expr(s): |
|
1235 | 1235 | """Return string s in appropriate quotes, using raw string if possible. |
|
1236 | 1236 | |
|
1237 | Effectively this turns string: cd \ao\ao\ | |
|
1238 | to: r"cd \ao\ao\_"[:-1] | |
|
1239 | ||
|
1240 | Note the use of raw string and padding at the end to allow trailing backslash. | |
|
1237 | XXX - example removed because it caused encoding errors in documentation | |
|
1238 | generation. We need a new example that doesn't contain invalid chars. | |
|
1241 | 1239 | |
|
1240 | Note the use of raw string and padding at the end to allow trailing | |
|
1241 | backslash. | |
|
1242 | 1242 | """ |
|
1243 | 1243 | |
|
1244 | 1244 | tail = '' |
|
1245 | 1245 | tailpadding = '' |
|
1246 | 1246 | raw = '' |
|
1247 | 1247 | if "\\" in s: |
|
1248 | 1248 | raw = 'r' |
|
1249 | 1249 | if s.endswith('\\'): |
|
1250 | 1250 | tail = '[:-1]' |
|
1251 | 1251 | tailpadding = '_' |
|
1252 | 1252 | if '"' not in s: |
|
1253 | 1253 | quote = '"' |
|
1254 | 1254 | elif "'" not in s: |
|
1255 | 1255 | quote = "'" |
|
1256 | 1256 | elif '"""' not in s and not s.endswith('"'): |
|
1257 | 1257 | quote = '"""' |
|
1258 | 1258 | elif "'''" not in s and not s.endswith("'"): |
|
1259 | 1259 | quote = "'''" |
|
1260 | 1260 | else: |
|
1261 | 1261 | # give up, backslash-escaped string will do |
|
1262 | 1262 | return '"%s"' % esc_quotes(s) |
|
1263 | 1263 | res = raw + quote + s + tailpadding + quote + tail |
|
1264 | 1264 | return res |
|
1265 | 1265 | |
|
1266 | 1266 | |
|
1267 | 1267 | #---------------------------------------------------------------------------- |
|
1268 | 1268 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
1269 | 1269 | """Take multiple lines of input. |
|
1270 | 1270 | |
|
1271 | 1271 | A list with each line of input as a separate element is returned when a |
|
1272 | 1272 | termination string is entered (defaults to a single '.'). Input can also |
|
1273 | 1273 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
1274 | 1274 | |
|
1275 | 1275 | Lines of input which end in \\ are joined into single entries (and a |
|
1276 | 1276 | secondary continuation prompt is issued as long as the user terminates |
|
1277 | 1277 | lines with \\). This allows entering very long strings which are still |
|
1278 | 1278 | meant to be treated as single entities. |
|
1279 | 1279 | """ |
|
1280 | 1280 | |
|
1281 | 1281 | try: |
|
1282 | 1282 | if header: |
|
1283 | 1283 | header += '\n' |
|
1284 | 1284 | lines = [raw_input(header + ps1)] |
|
1285 | 1285 | except EOFError: |
|
1286 | 1286 | return [] |
|
1287 | 1287 | terminate = [terminate_str] |
|
1288 | 1288 | try: |
|
1289 | 1289 | while lines[-1:] != terminate: |
|
1290 | 1290 | new_line = raw_input(ps1) |
|
1291 | 1291 | while new_line.endswith('\\'): |
|
1292 | 1292 | new_line = new_line[:-1] + raw_input(ps2) |
|
1293 | 1293 | lines.append(new_line) |
|
1294 | 1294 | |
|
1295 | 1295 | return lines[:-1] # don't return the termination command |
|
1296 | 1296 | except EOFError: |
|
1297 | 1297 | |
|
1298 | 1298 | return lines |
|
1299 | 1299 | |
|
1300 | 1300 | #---------------------------------------------------------------------------- |
|
1301 | 1301 | def raw_input_ext(prompt='', ps2='... '): |
|
1302 | 1302 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
1303 | 1303 | |
|
1304 | 1304 | line = raw_input(prompt) |
|
1305 | 1305 | while line.endswith('\\'): |
|
1306 | 1306 | line = line[:-1] + raw_input(ps2) |
|
1307 | 1307 | return line |
|
1308 | 1308 | |
|
1309 | 1309 | #---------------------------------------------------------------------------- |
|
1310 | 1310 | def ask_yes_no(prompt,default=None): |
|
1311 | 1311 | """Asks a question and returns a boolean (y/n) answer. |
|
1312 | 1312 | |
|
1313 | 1313 | If default is given (one of 'y','n'), it is used if the user input is |
|
1314 | 1314 | empty. Otherwise the question is repeated until an answer is given. |
|
1315 | 1315 | |
|
1316 | 1316 | An EOF is treated as the default answer. If there is no default, an |
|
1317 | 1317 | exception is raised to prevent infinite loops. |
|
1318 | 1318 | |
|
1319 | 1319 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
1320 | 1320 | |
|
1321 | 1321 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
1322 | 1322 | ans = None |
|
1323 | 1323 | while ans not in answers.keys(): |
|
1324 | 1324 | try: |
|
1325 | 1325 | ans = raw_input(prompt+' ').lower() |
|
1326 | 1326 | if not ans: # response was an empty string |
|
1327 | 1327 | ans = default |
|
1328 | 1328 | except KeyboardInterrupt: |
|
1329 | 1329 | pass |
|
1330 | 1330 | except EOFError: |
|
1331 | 1331 | if default in answers.keys(): |
|
1332 | 1332 | ans = default |
|
1333 | 1333 | |
|
1334 | 1334 | else: |
|
1335 | 1335 | raise |
|
1336 | 1336 | |
|
1337 | 1337 | return answers[ans] |
|
1338 | 1338 | |
|
1339 | 1339 | #---------------------------------------------------------------------------- |
|
1340 | 1340 | def marquee(txt='',width=78,mark='*'): |
|
1341 | 1341 | """Return the input string centered in a 'marquee'.""" |
|
1342 | 1342 | if not txt: |
|
1343 | 1343 | return (mark*width)[:width] |
|
1344 | 1344 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
1345 | 1345 | if nmark < 0: nmark =0 |
|
1346 | 1346 | marks = mark*nmark |
|
1347 | 1347 | return '%s %s %s' % (marks,txt,marks) |
|
1348 | 1348 | |
|
1349 | 1349 | #---------------------------------------------------------------------------- |
|
1350 | 1350 | class EvalDict: |
|
1351 | 1351 | """ |
|
1352 | 1352 | Emulate a dict which evaluates its contents in the caller's frame. |
|
1353 | 1353 | |
|
1354 | 1354 | Usage: |
|
1355 | 1355 | >>> number = 19 |
|
1356 | 1356 | |
|
1357 | 1357 | >>> text = "python" |
|
1358 | 1358 | |
|
1359 | 1359 | >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
1360 | 1360 | Python 2.1 rules! |
|
1361 | 1361 | """ |
|
1362 | 1362 | |
|
1363 | 1363 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
1364 | 1364 | # modified (shorter) version of: |
|
1365 | 1365 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
1366 | 1366 | # Skip Montanaro (skip@pobox.com). |
|
1367 | 1367 | |
|
1368 | 1368 | def __getitem__(self, name): |
|
1369 | 1369 | frame = sys._getframe(1) |
|
1370 | 1370 | return eval(name, frame.f_globals, frame.f_locals) |
|
1371 | 1371 | |
|
1372 | 1372 | EvalString = EvalDict # for backwards compatibility |
|
1373 | 1373 | #---------------------------------------------------------------------------- |
|
1374 | 1374 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
1375 | 1375 | """Similar to Perl's qw() operator, but with some more options. |
|
1376 | 1376 | |
|
1377 | 1377 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
1378 | 1378 | |
|
1379 | 1379 | words can also be a list itself, and with flat=1, the output will be |
|
1380 | 1380 | recursively flattened. |
|
1381 | 1381 | |
|
1382 | 1382 | Examples: |
|
1383 | 1383 | |
|
1384 | 1384 | >>> qw('1 2') |
|
1385 | 1385 | ['1', '2'] |
|
1386 | 1386 | |
|
1387 | 1387 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1388 | 1388 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1389 | 1389 | |
|
1390 | 1390 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1391 | 1391 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] |
|
1392 | 1392 | """ |
|
1393 | 1393 | |
|
1394 | 1394 | if type(words) in StringTypes: |
|
1395 | 1395 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1396 | 1396 | if word and not word.isspace() ] |
|
1397 | 1397 | if flat: |
|
1398 | 1398 | return flatten(map(qw,words,[1]*len(words))) |
|
1399 | 1399 | return map(qw,words) |
|
1400 | 1400 | |
|
1401 | 1401 | #---------------------------------------------------------------------------- |
|
1402 | 1402 | def qwflat(words,sep=None,maxsplit=-1): |
|
1403 | 1403 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1404 | 1404 | return qw(words,1,sep,maxsplit) |
|
1405 | 1405 | |
|
1406 | 1406 | #---------------------------------------------------------------------------- |
|
1407 | 1407 | def qw_lol(indata): |
|
1408 | 1408 | """qw_lol('a b') -> [['a','b']], |
|
1409 | 1409 | otherwise it's just a call to qw(). |
|
1410 | 1410 | |
|
1411 | 1411 | We need this to make sure the modules_some keys *always* end up as a |
|
1412 | 1412 | list of lists.""" |
|
1413 | 1413 | |
|
1414 | 1414 | if type(indata) in StringTypes: |
|
1415 | 1415 | return [qw(indata)] |
|
1416 | 1416 | else: |
|
1417 | 1417 | return qw(indata) |
|
1418 | 1418 | |
|
1419 | 1419 | #----------------------------------------------------------------------------- |
|
1420 | 1420 | def list_strings(arg): |
|
1421 | 1421 | """Always return a list of strings, given a string or list of strings |
|
1422 | 1422 | as input.""" |
|
1423 | 1423 | |
|
1424 | 1424 | if type(arg) in StringTypes: return [arg] |
|
1425 | 1425 | else: return arg |
|
1426 | 1426 | |
|
1427 | 1427 | #---------------------------------------------------------------------------- |
|
1428 | 1428 | def grep(pat,list,case=1): |
|
1429 | 1429 | """Simple minded grep-like function. |
|
1430 | 1430 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1431 | 1431 | |
|
1432 | 1432 | It only does simple string matching, with no support for regexps. Use the |
|
1433 | 1433 | option case=0 for case-insensitive matching.""" |
|
1434 | 1434 | |
|
1435 | 1435 | # This is pretty crude. At least it should implement copying only references |
|
1436 | 1436 | # to the original data in case it's big. Now it copies the data for output. |
|
1437 | 1437 | out=[] |
|
1438 | 1438 | if case: |
|
1439 | 1439 | for term in list: |
|
1440 | 1440 | if term.find(pat)>-1: out.append(term) |
|
1441 | 1441 | else: |
|
1442 | 1442 | lpat=pat.lower() |
|
1443 | 1443 | for term in list: |
|
1444 | 1444 | if term.lower().find(lpat)>-1: out.append(term) |
|
1445 | 1445 | |
|
1446 | 1446 | if len(out): return out |
|
1447 | 1447 | else: return None |
|
1448 | 1448 | |
|
1449 | 1449 | #---------------------------------------------------------------------------- |
|
1450 | 1450 | def dgrep(pat,*opts): |
|
1451 | 1451 | """Return grep() on dir()+dir(__builtins__). |
|
1452 | 1452 | |
|
1453 | 1453 | A very common use of grep() when working interactively.""" |
|
1454 | 1454 | |
|
1455 | 1455 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1456 | 1456 | |
|
1457 | 1457 | #---------------------------------------------------------------------------- |
|
1458 | 1458 | def idgrep(pat): |
|
1459 | 1459 | """Case-insensitive dgrep()""" |
|
1460 | 1460 | |
|
1461 | 1461 | return dgrep(pat,0) |
|
1462 | 1462 | |
|
1463 | 1463 | #---------------------------------------------------------------------------- |
|
1464 | 1464 | def igrep(pat,list): |
|
1465 | 1465 | """Synonym for case-insensitive grep.""" |
|
1466 | 1466 | |
|
1467 | 1467 | return grep(pat,list,case=0) |
|
1468 | 1468 | |
|
1469 | 1469 | #---------------------------------------------------------------------------- |
|
1470 | 1470 | def indent(str,nspaces=4,ntabs=0): |
|
1471 | 1471 | """Indent a string a given number of spaces or tabstops. |
|
1472 | 1472 | |
|
1473 | 1473 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1474 | 1474 | """ |
|
1475 | 1475 | if str is None: |
|
1476 | 1476 | return |
|
1477 | 1477 | ind = '\t'*ntabs+' '*nspaces |
|
1478 | 1478 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1479 | 1479 | if outstr.endswith(os.linesep+ind): |
|
1480 | 1480 | return outstr[:-len(ind)] |
|
1481 | 1481 | else: |
|
1482 | 1482 | return outstr |
|
1483 | 1483 | |
|
1484 | 1484 | #----------------------------------------------------------------------------- |
|
1485 | 1485 | def native_line_ends(filename,backup=1): |
|
1486 | 1486 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1487 | 1487 | |
|
1488 | 1488 | If the optional backup argument is given as false, no backup of the |
|
1489 | 1489 | original file is left. """ |
|
1490 | 1490 | |
|
1491 | 1491 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1492 | 1492 | |
|
1493 | 1493 | bak_filename = filename + backup_suffixes[os.name] |
|
1494 | 1494 | |
|
1495 | 1495 | original = open(filename).read() |
|
1496 | 1496 | shutil.copy2(filename,bak_filename) |
|
1497 | 1497 | try: |
|
1498 | 1498 | new = open(filename,'wb') |
|
1499 | 1499 | new.write(os.linesep.join(original.splitlines())) |
|
1500 | 1500 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1501 | 1501 | new.close() |
|
1502 | 1502 | except: |
|
1503 | 1503 | os.rename(bak_filename,filename) |
|
1504 | 1504 | if not backup: |
|
1505 | 1505 | try: |
|
1506 | 1506 | os.remove(bak_filename) |
|
1507 | 1507 | except: |
|
1508 | 1508 | pass |
|
1509 | 1509 | |
|
1510 | 1510 | #---------------------------------------------------------------------------- |
|
1511 | 1511 | def get_pager_cmd(pager_cmd = None): |
|
1512 | 1512 | """Return a pager command. |
|
1513 | 1513 | |
|
1514 | 1514 | Makes some attempts at finding an OS-correct one.""" |
|
1515 | 1515 | |
|
1516 | 1516 | if os.name == 'posix': |
|
1517 | 1517 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1518 | 1518 | elif os.name in ['nt','dos']: |
|
1519 | 1519 | default_pager_cmd = 'type' |
|
1520 | 1520 | |
|
1521 | 1521 | if pager_cmd is None: |
|
1522 | 1522 | try: |
|
1523 | 1523 | pager_cmd = os.environ['PAGER'] |
|
1524 | 1524 | except: |
|
1525 | 1525 | pager_cmd = default_pager_cmd |
|
1526 | 1526 | return pager_cmd |
|
1527 | 1527 | |
|
1528 | 1528 | #----------------------------------------------------------------------------- |
|
1529 | 1529 | def get_pager_start(pager,start): |
|
1530 | 1530 | """Return the string for paging files with an offset. |
|
1531 | 1531 | |
|
1532 | 1532 | This is the '+N' argument which less and more (under Unix) accept. |
|
1533 | 1533 | """ |
|
1534 | 1534 | |
|
1535 | 1535 | if pager in ['less','more']: |
|
1536 | 1536 | if start: |
|
1537 | 1537 | start_string = '+' + str(start) |
|
1538 | 1538 | else: |
|
1539 | 1539 | start_string = '' |
|
1540 | 1540 | else: |
|
1541 | 1541 | start_string = '' |
|
1542 | 1542 | return start_string |
|
1543 | 1543 | |
|
1544 | 1544 | #---------------------------------------------------------------------------- |
|
1545 | 1545 | # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch() |
|
1546 | 1546 | if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': |
|
1547 | 1547 | import msvcrt |
|
1548 | 1548 | def page_more(): |
|
1549 | 1549 | """ Smart pausing between pages |
|
1550 | 1550 | |
|
1551 | 1551 | @return: True if need print more lines, False if quit |
|
1552 | 1552 | """ |
|
1553 | 1553 | Term.cout.write('---Return to continue, q to quit--- ') |
|
1554 | 1554 | ans = msvcrt.getch() |
|
1555 | 1555 | if ans in ("q", "Q"): |
|
1556 | 1556 | result = False |
|
1557 | 1557 | else: |
|
1558 | 1558 | result = True |
|
1559 | 1559 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) |
|
1560 | 1560 | return result |
|
1561 | 1561 | else: |
|
1562 | 1562 | def page_more(): |
|
1563 | 1563 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1564 | 1564 | if ans.lower().startswith('q'): |
|
1565 | 1565 | return False |
|
1566 | 1566 | else: |
|
1567 | 1567 | return True |
|
1568 | 1568 | |
|
1569 | 1569 | esc_re = re.compile(r"(\x1b[^m]+m)") |
|
1570 | 1570 | |
|
1571 | 1571 | def page_dumb(strng,start=0,screen_lines=25): |
|
1572 | 1572 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1573 | 1573 | |
|
1574 | 1574 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1575 | 1575 | mode.""" |
|
1576 | 1576 | |
|
1577 | 1577 | out_ln = strng.splitlines()[start:] |
|
1578 | 1578 | screens = chop(out_ln,screen_lines-1) |
|
1579 | 1579 | if len(screens) == 1: |
|
1580 | 1580 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1581 | 1581 | else: |
|
1582 | 1582 | last_escape = "" |
|
1583 | 1583 | for scr in screens[0:-1]: |
|
1584 | 1584 | hunk = os.linesep.join(scr) |
|
1585 | 1585 | print >>Term.cout, last_escape + hunk |
|
1586 | 1586 | if not page_more(): |
|
1587 | 1587 | return |
|
1588 | 1588 | esc_list = esc_re.findall(hunk) |
|
1589 | 1589 | if len(esc_list) > 0: |
|
1590 | 1590 | last_escape = esc_list[-1] |
|
1591 | 1591 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) |
|
1592 | 1592 | |
|
1593 | 1593 | #---------------------------------------------------------------------------- |
|
1594 | 1594 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1595 | 1595 | """Print a string, piping through a pager after a certain length. |
|
1596 | 1596 | |
|
1597 | 1597 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1598 | 1598 | terminal screen (total lines minus lines you need to reserve to show other |
|
1599 | 1599 | information). |
|
1600 | 1600 | |
|
1601 | 1601 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1602 | 1602 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1603 | 1603 | printing, paging after that. That is, if you want auto-detection but need |
|
1604 | 1604 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1605 | 1605 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1606 | 1606 | |
|
1607 | 1607 | If a string won't fit in the allowed lines, it is sent through the |
|
1608 | 1608 | specified pager command. If none given, look for PAGER in the environment, |
|
1609 | 1609 | and ultimately default to less. |
|
1610 | 1610 | |
|
1611 | 1611 | If no system pager works, the string is sent through a 'dumb pager' |
|
1612 | 1612 | written in python, very simplistic. |
|
1613 | 1613 | """ |
|
1614 | 1614 | |
|
1615 | 1615 | # Some routines may auto-compute start offsets incorrectly and pass a |
|
1616 | 1616 | # negative value. Offset to 0 for robustness. |
|
1617 | 1617 | start = max(0,start) |
|
1618 | 1618 | |
|
1619 | 1619 | # first, try the hook |
|
1620 | 1620 | ip = IPython.ipapi.get() |
|
1621 | 1621 | if ip: |
|
1622 | 1622 | try: |
|
1623 | 1623 | ip.IP.hooks.show_in_pager(strng) |
|
1624 | 1624 | return |
|
1625 | 1625 | except IPython.ipapi.TryNext: |
|
1626 | 1626 | pass |
|
1627 | 1627 | |
|
1628 | 1628 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1629 | 1629 | TERM = os.environ.get('TERM','dumb') |
|
1630 | 1630 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1631 | 1631 | print strng |
|
1632 | 1632 | return |
|
1633 | 1633 | # chop off the topmost part of the string we don't want to see |
|
1634 | 1634 | str_lines = strng.split(os.linesep)[start:] |
|
1635 | 1635 | str_toprint = os.linesep.join(str_lines) |
|
1636 | 1636 | num_newlines = len(str_lines) |
|
1637 | 1637 | len_str = len(str_toprint) |
|
1638 | 1638 | |
|
1639 | 1639 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1640 | 1640 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1641 | 1641 | # terminals. If someone later feels like refining it, it's not hard. |
|
1642 | 1642 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1643 | 1643 | |
|
1644 | 1644 | if os.name == "nt": |
|
1645 | 1645 | screen_lines_def = get_console_size(defaulty=25)[1] |
|
1646 | 1646 | else: |
|
1647 | 1647 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1648 | 1648 | |
|
1649 | 1649 | # auto-determine screen size |
|
1650 | 1650 | if screen_lines <= 0: |
|
1651 | 1651 | if TERM=='xterm': |
|
1652 | 1652 | use_curses = USE_CURSES |
|
1653 | 1653 | else: |
|
1654 | 1654 | # curses causes problems on many terminals other than xterm. |
|
1655 | 1655 | use_curses = False |
|
1656 | 1656 | if use_curses: |
|
1657 | 1657 | # There is a bug in curses, where *sometimes* it fails to properly |
|
1658 | 1658 | # initialize, and then after the endwin() call is made, the |
|
1659 | 1659 | # terminal is left in an unusable state. Rather than trying to |
|
1660 | 1660 | # check everytime for this (by requesting and comparing termios |
|
1661 | 1661 | # flags each time), we just save the initial terminal state and |
|
1662 | 1662 | # unconditionally reset it every time. It's cheaper than making |
|
1663 | 1663 | # the checks. |
|
1664 | 1664 | term_flags = termios.tcgetattr(sys.stdout) |
|
1665 | 1665 | scr = curses.initscr() |
|
1666 | 1666 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1667 | 1667 | curses.endwin() |
|
1668 | 1668 | # Restore terminal state in case endwin() didn't. |
|
1669 | 1669 | termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags) |
|
1670 | 1670 | # Now we have what we needed: the screen size in rows/columns |
|
1671 | 1671 | screen_lines += screen_lines_real |
|
1672 | 1672 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1673 | 1673 | #screen_cols,'columns.' # dbg |
|
1674 | 1674 | else: |
|
1675 | 1675 | screen_lines += screen_lines_def |
|
1676 | 1676 | |
|
1677 | 1677 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1678 | 1678 | if numlines <= screen_lines : |
|
1679 | 1679 | #print '*** normal print' # dbg |
|
1680 | 1680 | print >>Term.cout, str_toprint |
|
1681 | 1681 | else: |
|
1682 | 1682 | # Try to open pager and default to internal one if that fails. |
|
1683 | 1683 | # All failure modes are tagged as 'retval=1', to match the return |
|
1684 | 1684 | # value of a failed system command. If any intermediate attempt |
|
1685 | 1685 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1686 | 1686 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1687 | 1687 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1688 | 1688 | if os.name == 'nt': |
|
1689 | 1689 | if pager_cmd.startswith('type'): |
|
1690 | 1690 | # The default WinXP 'type' command is failing on complex strings. |
|
1691 | 1691 | retval = 1 |
|
1692 | 1692 | else: |
|
1693 | 1693 | tmpname = tempfile.mktemp('.txt') |
|
1694 | 1694 | tmpfile = file(tmpname,'wt') |
|
1695 | 1695 | tmpfile.write(strng) |
|
1696 | 1696 | tmpfile.close() |
|
1697 | 1697 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1698 | 1698 | if os.system(cmd): |
|
1699 | 1699 | retval = 1 |
|
1700 | 1700 | else: |
|
1701 | 1701 | retval = None |
|
1702 | 1702 | os.remove(tmpname) |
|
1703 | 1703 | else: |
|
1704 | 1704 | try: |
|
1705 | 1705 | retval = None |
|
1706 | 1706 | # if I use popen4, things hang. No idea why. |
|
1707 | 1707 | #pager,shell_out = os.popen4(pager_cmd) |
|
1708 | 1708 | pager = os.popen(pager_cmd,'w') |
|
1709 | 1709 | pager.write(strng) |
|
1710 | 1710 | pager.close() |
|
1711 | 1711 | retval = pager.close() # success returns None |
|
1712 | 1712 | except IOError,msg: # broken pipe when user quits |
|
1713 | 1713 | if msg.args == (32,'Broken pipe'): |
|
1714 | 1714 | retval = None |
|
1715 | 1715 | else: |
|
1716 | 1716 | retval = 1 |
|
1717 | 1717 | except OSError: |
|
1718 | 1718 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1719 | 1719 | retval = 1 |
|
1720 | 1720 | if retval is not None: |
|
1721 | 1721 | page_dumb(strng,screen_lines=screen_lines) |
|
1722 | 1722 | |
|
1723 | 1723 | #---------------------------------------------------------------------------- |
|
1724 | 1724 | def page_file(fname,start = 0, pager_cmd = None): |
|
1725 | 1725 | """Page a file, using an optional pager command and starting line. |
|
1726 | 1726 | """ |
|
1727 | 1727 | |
|
1728 | 1728 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1729 | 1729 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1730 | 1730 | |
|
1731 | 1731 | try: |
|
1732 | 1732 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1733 | 1733 | raise EnvironmentError |
|
1734 | 1734 | xsys(pager_cmd + ' ' + fname) |
|
1735 | 1735 | except: |
|
1736 | 1736 | try: |
|
1737 | 1737 | if start > 0: |
|
1738 | 1738 | start -= 1 |
|
1739 | 1739 | page(open(fname).read(),start) |
|
1740 | 1740 | except: |
|
1741 | 1741 | print 'Unable to show file',`fname` |
|
1742 | 1742 | |
|
1743 | 1743 | |
|
1744 | 1744 | #---------------------------------------------------------------------------- |
|
1745 | 1745 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1746 | 1746 | """Print a string snipping the midsection to fit in width. |
|
1747 | 1747 | |
|
1748 | 1748 | print_full: mode control: |
|
1749 | 1749 | - 0: only snip long strings |
|
1750 | 1750 | - 1: send to page() directly. |
|
1751 | 1751 | - 2: snip long strings and ask for full length viewing with page() |
|
1752 | 1752 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1753 | 1753 | |
|
1754 | 1754 | if print_full == 1: |
|
1755 | 1755 | page(header+str) |
|
1756 | 1756 | return 0 |
|
1757 | 1757 | |
|
1758 | 1758 | print header, |
|
1759 | 1759 | if len(str) < width: |
|
1760 | 1760 | print str |
|
1761 | 1761 | snip = 0 |
|
1762 | 1762 | else: |
|
1763 | 1763 | whalf = int((width -5)/2) |
|
1764 | 1764 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1765 | 1765 | snip = 1 |
|
1766 | 1766 | if snip and print_full == 2: |
|
1767 | 1767 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1768 | 1768 | page(str) |
|
1769 | 1769 | return snip |
|
1770 | 1770 | |
|
1771 | 1771 | #**************************************************************************** |
|
1772 | 1772 | # lists, dicts and structures |
|
1773 | 1773 | |
|
1774 | 1774 | def belong(candidates,checklist): |
|
1775 | 1775 | """Check whether a list of items appear in a given list of options. |
|
1776 | 1776 | |
|
1777 | 1777 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1778 | 1778 | |
|
1779 | 1779 | return [x in checklist for x in candidates] |
|
1780 | 1780 | |
|
1781 | 1781 | #---------------------------------------------------------------------------- |
|
1782 | 1782 | def uniq_stable(elems): |
|
1783 | 1783 | """uniq_stable(elems) -> list |
|
1784 | 1784 | |
|
1785 | 1785 | Return from an iterable, a list of all the unique elements in the input, |
|
1786 | 1786 | but maintaining the order in which they first appear. |
|
1787 | 1787 | |
|
1788 | 1788 | A naive solution to this problem which just makes a dictionary with the |
|
1789 | 1789 | elements as keys fails to respect the stability condition, since |
|
1790 | 1790 | dictionaries are unsorted by nature. |
|
1791 | 1791 | |
|
1792 | 1792 | Note: All elements in the input must be valid dictionary keys for this |
|
1793 | 1793 | routine to work, as it internally uses a dictionary for efficiency |
|
1794 | 1794 | reasons.""" |
|
1795 | 1795 | |
|
1796 | 1796 | unique = [] |
|
1797 | 1797 | unique_dict = {} |
|
1798 | 1798 | for nn in elems: |
|
1799 | 1799 | if nn not in unique_dict: |
|
1800 | 1800 | unique.append(nn) |
|
1801 | 1801 | unique_dict[nn] = None |
|
1802 | 1802 | return unique |
|
1803 | 1803 | |
|
1804 | 1804 | #---------------------------------------------------------------------------- |
|
1805 | 1805 | class NLprinter: |
|
1806 | 1806 | """Print an arbitrarily nested list, indicating index numbers. |
|
1807 | 1807 | |
|
1808 | 1808 | An instance of this class called nlprint is available and callable as a |
|
1809 | 1809 | function. |
|
1810 | 1810 | |
|
1811 | 1811 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1812 | 1812 | and using 'sep' to separate the index from the value. """ |
|
1813 | 1813 | |
|
1814 | 1814 | def __init__(self): |
|
1815 | 1815 | self.depth = 0 |
|
1816 | 1816 | |
|
1817 | 1817 | def __call__(self,lst,pos='',**kw): |
|
1818 | 1818 | """Prints the nested list numbering levels.""" |
|
1819 | 1819 | kw.setdefault('indent',' ') |
|
1820 | 1820 | kw.setdefault('sep',': ') |
|
1821 | 1821 | kw.setdefault('start',0) |
|
1822 | 1822 | kw.setdefault('stop',len(lst)) |
|
1823 | 1823 | # we need to remove start and stop from kw so they don't propagate |
|
1824 | 1824 | # into a recursive call for a nested list. |
|
1825 | 1825 | start = kw['start']; del kw['start'] |
|
1826 | 1826 | stop = kw['stop']; del kw['stop'] |
|
1827 | 1827 | if self.depth == 0 and 'header' in kw.keys(): |
|
1828 | 1828 | print kw['header'] |
|
1829 | 1829 | |
|
1830 | 1830 | for idx in range(start,stop): |
|
1831 | 1831 | elem = lst[idx] |
|
1832 | 1832 | if type(elem)==type([]): |
|
1833 | 1833 | self.depth += 1 |
|
1834 | 1834 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1835 | 1835 | self.depth -= 1 |
|
1836 | 1836 | else: |
|
1837 | 1837 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1838 | 1838 | |
|
1839 | 1839 | nlprint = NLprinter() |
|
1840 | 1840 | #---------------------------------------------------------------------------- |
|
1841 | 1841 | def all_belong(candidates,checklist): |
|
1842 | 1842 | """Check whether a list of items ALL appear in a given list of options. |
|
1843 | 1843 | |
|
1844 | 1844 | Returns a single 1 or 0 value.""" |
|
1845 | 1845 | |
|
1846 | 1846 | return 1-(0 in [x in checklist for x in candidates]) |
|
1847 | 1847 | |
|
1848 | 1848 | #---------------------------------------------------------------------------- |
|
1849 | 1849 | def sort_compare(lst1,lst2,inplace = 1): |
|
1850 | 1850 | """Sort and compare two lists. |
|
1851 | 1851 | |
|
1852 | 1852 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1853 | 1853 | to avoid that (at the cost of temporary copy creation).""" |
|
1854 | 1854 | if not inplace: |
|
1855 | 1855 | lst1 = lst1[:] |
|
1856 | 1856 | lst2 = lst2[:] |
|
1857 | 1857 | lst1.sort(); lst2.sort() |
|
1858 | 1858 | return lst1 == lst2 |
|
1859 | 1859 | |
|
1860 | 1860 | #---------------------------------------------------------------------------- |
|
1861 | 1861 | def list2dict(lst): |
|
1862 | 1862 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1863 | 1863 | |
|
1864 | 1864 | dic = {} |
|
1865 | 1865 | for k,v in lst: dic[k] = v |
|
1866 | 1866 | return dic |
|
1867 | 1867 | |
|
1868 | 1868 | #---------------------------------------------------------------------------- |
|
1869 | 1869 | def list2dict2(lst,default=''): |
|
1870 | 1870 | """Takes a list and turns it into a dict. |
|
1871 | 1871 | Much slower than list2dict, but more versatile. This version can take |
|
1872 | 1872 | lists with sublists of arbitrary length (including sclars).""" |
|
1873 | 1873 | |
|
1874 | 1874 | dic = {} |
|
1875 | 1875 | for elem in lst: |
|
1876 | 1876 | if type(elem) in (types.ListType,types.TupleType): |
|
1877 | 1877 | size = len(elem) |
|
1878 | 1878 | if size == 0: |
|
1879 | 1879 | pass |
|
1880 | 1880 | elif size == 1: |
|
1881 | 1881 | dic[elem] = default |
|
1882 | 1882 | else: |
|
1883 | 1883 | k,v = elem[0], elem[1:] |
|
1884 | 1884 | if len(v) == 1: v = v[0] |
|
1885 | 1885 | dic[k] = v |
|
1886 | 1886 | else: |
|
1887 | 1887 | dic[elem] = default |
|
1888 | 1888 | return dic |
|
1889 | 1889 | |
|
1890 | 1890 | #---------------------------------------------------------------------------- |
|
1891 | 1891 | def flatten(seq): |
|
1892 | 1892 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1893 | 1893 | |
|
1894 | 1894 | return [x for subseq in seq for x in subseq] |
|
1895 | 1895 | |
|
1896 | 1896 | #---------------------------------------------------------------------------- |
|
1897 | 1897 | def get_slice(seq,start=0,stop=None,step=1): |
|
1898 | 1898 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1899 | 1899 | if stop == None: |
|
1900 | 1900 | stop = len(seq) |
|
1901 | 1901 | item = lambda i: seq[i] |
|
1902 | 1902 | return map(item,xrange(start,stop,step)) |
|
1903 | 1903 | |
|
1904 | 1904 | #---------------------------------------------------------------------------- |
|
1905 | 1905 | def chop(seq,size): |
|
1906 | 1906 | """Chop a sequence into chunks of the given size.""" |
|
1907 | 1907 | chunk = lambda i: seq[i:i+size] |
|
1908 | 1908 | return map(chunk,xrange(0,len(seq),size)) |
|
1909 | 1909 | |
|
1910 | 1910 | #---------------------------------------------------------------------------- |
|
1911 | 1911 | # with is a keyword as of python 2.5, so this function is renamed to withobj |
|
1912 | 1912 | # from its old 'with' name. |
|
1913 | 1913 | def with_obj(object, **args): |
|
1914 | 1914 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1915 | 1915 | |
|
1916 | 1916 | Example: |
|
1917 | 1917 | with_obj(jim, |
|
1918 | 1918 | born = 1960, |
|
1919 | 1919 | haircolour = 'Brown', |
|
1920 | 1920 | eyecolour = 'Green') |
|
1921 | 1921 | |
|
1922 | 1922 | Credit: Greg Ewing, in |
|
1923 | 1923 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. |
|
1924 | 1924 | |
|
1925 | 1925 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' |
|
1926 | 1926 | has become a keyword for Python 2.5, so we had to rename it.""" |
|
1927 | 1927 | |
|
1928 | 1928 | object.__dict__.update(args) |
|
1929 | 1929 | |
|
1930 | 1930 | #---------------------------------------------------------------------------- |
|
1931 | 1931 | def setattr_list(obj,alist,nspace = None): |
|
1932 | 1932 | """Set a list of attributes for an object taken from a namespace. |
|
1933 | 1933 | |
|
1934 | 1934 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1935 | 1935 | alist with their values taken from nspace, which must be a dict (something |
|
1936 | 1936 | like locals() will often do) If nspace isn't given, locals() of the |
|
1937 | 1937 | *caller* is used, so in most cases you can omit it. |
|
1938 | 1938 | |
|
1939 | 1939 | Note that alist can be given as a string, which will be automatically |
|
1940 | 1940 | split into a list on whitespace. If given as a list, it must be a list of |
|
1941 | 1941 | *strings* (the variable names themselves), not of variables.""" |
|
1942 | 1942 | |
|
1943 | 1943 | # this grabs the local variables from the *previous* call frame -- that is |
|
1944 | 1944 | # the locals from the function that called setattr_list(). |
|
1945 | 1945 | # - snipped from weave.inline() |
|
1946 | 1946 | if nspace is None: |
|
1947 | 1947 | call_frame = sys._getframe().f_back |
|
1948 | 1948 | nspace = call_frame.f_locals |
|
1949 | 1949 | |
|
1950 | 1950 | if type(alist) in StringTypes: |
|
1951 | 1951 | alist = alist.split() |
|
1952 | 1952 | for attr in alist: |
|
1953 | 1953 | val = eval(attr,nspace) |
|
1954 | 1954 | setattr(obj,attr,val) |
|
1955 | 1955 | |
|
1956 | 1956 | #---------------------------------------------------------------------------- |
|
1957 | 1957 | def getattr_list(obj,alist,*args): |
|
1958 | 1958 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1959 | 1959 | |
|
1960 | 1960 | Get a list of named attributes for an object. When a default argument is |
|
1961 | 1961 | given, it is returned when the attribute doesn't exist; without it, an |
|
1962 | 1962 | exception is raised in that case. |
|
1963 | 1963 | |
|
1964 | 1964 | Note that alist can be given as a string, which will be automatically |
|
1965 | 1965 | split into a list on whitespace. If given as a list, it must be a list of |
|
1966 | 1966 | *strings* (the variable names themselves), not of variables.""" |
|
1967 | 1967 | |
|
1968 | 1968 | if type(alist) in StringTypes: |
|
1969 | 1969 | alist = alist.split() |
|
1970 | 1970 | if args: |
|
1971 | 1971 | if len(args)==1: |
|
1972 | 1972 | default = args[0] |
|
1973 | 1973 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1974 | 1974 | else: |
|
1975 | 1975 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1976 | 1976 | else: |
|
1977 | 1977 | return map(lambda attr: getattr(obj,attr),alist) |
|
1978 | 1978 | |
|
1979 | 1979 | #---------------------------------------------------------------------------- |
|
1980 | 1980 | def map_method(method,object_list,*argseq,**kw): |
|
1981 | 1981 | """map_method(method,object_list,*args,**kw) -> list |
|
1982 | 1982 | |
|
1983 | 1983 | Return a list of the results of applying the methods to the items of the |
|
1984 | 1984 | argument sequence(s). If more than one sequence is given, the method is |
|
1985 | 1985 | called with an argument list consisting of the corresponding item of each |
|
1986 | 1986 | sequence. All sequences must be of the same length. |
|
1987 | 1987 | |
|
1988 | 1988 | Keyword arguments are passed verbatim to all objects called. |
|
1989 | 1989 | |
|
1990 | 1990 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1991 | 1991 | |
|
1992 | 1992 | out_list = [] |
|
1993 | 1993 | idx = 0 |
|
1994 | 1994 | for object in object_list: |
|
1995 | 1995 | try: |
|
1996 | 1996 | handler = getattr(object, method) |
|
1997 | 1997 | except AttributeError: |
|
1998 | 1998 | out_list.append(None) |
|
1999 | 1999 | else: |
|
2000 | 2000 | if argseq: |
|
2001 | 2001 | args = map(lambda lst:lst[idx],argseq) |
|
2002 | 2002 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
2003 | 2003 | out_list.append(handler(args,**kw)) |
|
2004 | 2004 | else: |
|
2005 | 2005 | out_list.append(handler(**kw)) |
|
2006 | 2006 | idx += 1 |
|
2007 | 2007 | return out_list |
|
2008 | 2008 | |
|
2009 | 2009 | #---------------------------------------------------------------------------- |
|
2010 | 2010 | def get_class_members(cls): |
|
2011 | 2011 | ret = dir(cls) |
|
2012 | 2012 | if hasattr(cls,'__bases__'): |
|
2013 | 2013 | for base in cls.__bases__: |
|
2014 | 2014 | ret.extend(get_class_members(base)) |
|
2015 | 2015 | return ret |
|
2016 | 2016 | |
|
2017 | 2017 | #---------------------------------------------------------------------------- |
|
2018 | 2018 | def dir2(obj): |
|
2019 | 2019 | """dir2(obj) -> list of strings |
|
2020 | 2020 | |
|
2021 | 2021 | Extended version of the Python builtin dir(), which does a few extra |
|
2022 | 2022 | checks, and supports common objects with unusual internals that confuse |
|
2023 | 2023 | dir(), such as Traits and PyCrust. |
|
2024 | 2024 | |
|
2025 | 2025 | This version is guaranteed to return only a list of true strings, whereas |
|
2026 | 2026 | dir() returns anything that objects inject into themselves, even if they |
|
2027 | 2027 | are later not really valid for attribute access (many extension libraries |
|
2028 | 2028 | have such bugs). |
|
2029 | 2029 | """ |
|
2030 | 2030 | |
|
2031 | 2031 | # Start building the attribute list via dir(), and then complete it |
|
2032 | 2032 | # with a few extra special-purpose calls. |
|
2033 | 2033 | words = dir(obj) |
|
2034 | 2034 | |
|
2035 | 2035 | if hasattr(obj,'__class__'): |
|
2036 | 2036 | words.append('__class__') |
|
2037 | 2037 | words.extend(get_class_members(obj.__class__)) |
|
2038 | 2038 | #if '__base__' in words: 1/0 |
|
2039 | 2039 | |
|
2040 | 2040 | # Some libraries (such as traits) may introduce duplicates, we want to |
|
2041 | 2041 | # track and clean this up if it happens |
|
2042 | 2042 | may_have_dupes = False |
|
2043 | 2043 | |
|
2044 | 2044 | # this is the 'dir' function for objects with Enthought's traits |
|
2045 | 2045 | if hasattr(obj, 'trait_names'): |
|
2046 | 2046 | try: |
|
2047 | 2047 | words.extend(obj.trait_names()) |
|
2048 | 2048 | may_have_dupes = True |
|
2049 | 2049 | except TypeError: |
|
2050 | 2050 | # This will happen if `obj` is a class and not an instance. |
|
2051 | 2051 | pass |
|
2052 | 2052 | |
|
2053 | 2053 | # Support for PyCrust-style _getAttributeNames magic method. |
|
2054 | 2054 | if hasattr(obj, '_getAttributeNames'): |
|
2055 | 2055 | try: |
|
2056 | 2056 | words.extend(obj._getAttributeNames()) |
|
2057 | 2057 | may_have_dupes = True |
|
2058 | 2058 | except TypeError: |
|
2059 | 2059 | # `obj` is a class and not an instance. Ignore |
|
2060 | 2060 | # this error. |
|
2061 | 2061 | pass |
|
2062 | 2062 | |
|
2063 | 2063 | if may_have_dupes: |
|
2064 | 2064 | # eliminate possible duplicates, as some traits may also |
|
2065 | 2065 | # appear as normal attributes in the dir() call. |
|
2066 | 2066 | words = list(set(words)) |
|
2067 | 2067 | words.sort() |
|
2068 | 2068 | |
|
2069 | 2069 | # filter out non-string attributes which may be stuffed by dir() calls |
|
2070 | 2070 | # and poor coding in third-party modules |
|
2071 | 2071 | return [w for w in words if isinstance(w, basestring)] |
|
2072 | 2072 | |
|
2073 | 2073 | #---------------------------------------------------------------------------- |
|
2074 | 2074 | def import_fail_info(mod_name,fns=None): |
|
2075 | 2075 | """Inform load failure for a module.""" |
|
2076 | 2076 | |
|
2077 | 2077 | if fns == None: |
|
2078 | 2078 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
2079 | 2079 | else: |
|
2080 | 2080 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
2081 | 2081 | |
|
2082 | 2082 | #---------------------------------------------------------------------------- |
|
2083 | 2083 | # Proposed popitem() extension, written as a method |
|
2084 | 2084 | |
|
2085 | 2085 | |
|
2086 | 2086 | class NotGiven: pass |
|
2087 | 2087 | |
|
2088 | 2088 | def popkey(dct,key,default=NotGiven): |
|
2089 | 2089 | """Return dct[key] and delete dct[key]. |
|
2090 | 2090 | |
|
2091 | 2091 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
2092 | 2092 | KeyError. """ |
|
2093 | 2093 | |
|
2094 | 2094 | try: |
|
2095 | 2095 | val = dct[key] |
|
2096 | 2096 | except KeyError: |
|
2097 | 2097 | if default is NotGiven: |
|
2098 | 2098 | raise |
|
2099 | 2099 | else: |
|
2100 | 2100 | return default |
|
2101 | 2101 | else: |
|
2102 | 2102 | del dct[key] |
|
2103 | 2103 | return val |
|
2104 | 2104 | |
|
2105 | 2105 | def wrap_deprecated(func, suggest = '<nothing>'): |
|
2106 | 2106 | def newFunc(*args, **kwargs): |
|
2107 | 2107 | warnings.warn("Call to deprecated function %s, use %s instead" % |
|
2108 | 2108 | ( func.__name__, suggest), |
|
2109 | 2109 | category=DeprecationWarning, |
|
2110 | 2110 | stacklevel = 2) |
|
2111 | 2111 | return func(*args, **kwargs) |
|
2112 | 2112 | return newFunc |
|
2113 | 2113 | |
|
2114 | 2114 | |
|
2115 | 2115 | def _num_cpus_unix(): |
|
2116 | 2116 | """Return the number of active CPUs on a Unix system.""" |
|
2117 | 2117 | return os.sysconf("SC_NPROCESSORS_ONLN") |
|
2118 | 2118 | |
|
2119 | 2119 | |
|
2120 | 2120 | def _num_cpus_darwin(): |
|
2121 | 2121 | """Return the number of active CPUs on a Darwin system.""" |
|
2122 | 2122 | p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) |
|
2123 | 2123 | return p.stdout.read() |
|
2124 | 2124 | |
|
2125 | 2125 | |
|
2126 | 2126 | def _num_cpus_windows(): |
|
2127 | 2127 | """Return the number of active CPUs on a Windows system.""" |
|
2128 | 2128 | return os.environ.get("NUMBER_OF_PROCESSORS") |
|
2129 | 2129 | |
|
2130 | 2130 | |
|
2131 | 2131 | def num_cpus(): |
|
2132 | 2132 | """Return the effective number of CPUs in the system as an integer. |
|
2133 | 2133 | |
|
2134 | 2134 | This cross-platform function makes an attempt at finding the total number of |
|
2135 | 2135 | available CPUs in the system, as returned by various underlying system and |
|
2136 | 2136 | python calls. |
|
2137 | 2137 | |
|
2138 | 2138 | If it can't find a sensible answer, it returns 1 (though an error *may* make |
|
2139 | 2139 | it return a large positive number that's actually incorrect). |
|
2140 | 2140 | """ |
|
2141 | 2141 | |
|
2142 | 2142 | # Many thanks to the Parallel Python project (http://www.parallelpython.com) |
|
2143 | 2143 | # for the names of the keys we needed to look up for this function. This |
|
2144 | 2144 | # code was inspired by their equivalent function. |
|
2145 | 2145 | |
|
2146 | 2146 | ncpufuncs = {'Linux':_num_cpus_unix, |
|
2147 | 2147 | 'Darwin':_num_cpus_darwin, |
|
2148 | 2148 | 'Windows':_num_cpus_windows, |
|
2149 | 2149 | # On Vista, python < 2.5.2 has a bug and returns 'Microsoft' |
|
2150 | 2150 | # See http://bugs.python.org/issue1082 for details. |
|
2151 | 2151 | 'Microsoft':_num_cpus_windows, |
|
2152 | 2152 | } |
|
2153 | 2153 | |
|
2154 | 2154 | ncpufunc = ncpufuncs.get(platform.system(), |
|
2155 | 2155 | # default to unix version (Solaris, AIX, etc) |
|
2156 | 2156 | _num_cpus_unix) |
|
2157 | 2157 | |
|
2158 | 2158 | try: |
|
2159 | 2159 | ncpus = max(1,int(ncpufunc())) |
|
2160 | 2160 | except: |
|
2161 | 2161 | ncpus = 1 |
|
2162 | 2162 | return ncpus |
|
2163 | 2163 | |
|
2164 | 2164 | #*************************** end of file <genutils.py> ********************** |
@@ -1,687 +1,686 | |||
|
1 | 1 | """IPython customization API |
|
2 | 2 | |
|
3 | 3 | Your one-stop module for configuring & extending ipython |
|
4 | 4 | |
|
5 | 5 | The API will probably break when ipython 1.0 is released, but so |
|
6 | 6 | will the other configuration method (rc files). |
|
7 | 7 | |
|
8 | 8 | All names prefixed by underscores are for internal use, not part |
|
9 | 9 | of the public api. |
|
10 | 10 | |
|
11 | 11 | Below is an example that you can just put to a module and import from ipython. |
|
12 | 12 | |
|
13 | 13 | A good practice is to install the config script below as e.g. |
|
14 | 14 | |
|
15 | 15 | ~/.ipython/my_private_conf.py |
|
16 | 16 | |
|
17 | 17 | And do |
|
18 | 18 | |
|
19 | 19 | import_mod my_private_conf |
|
20 | 20 | |
|
21 | 21 | in ~/.ipython/ipythonrc |
|
22 | 22 | |
|
23 | 23 | That way the module is imported at startup and you can have all your |
|
24 | 24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME |
|
25 | 25 | stuff) in there. |
|
26 | 26 | |
|
27 | ----------------------------------------------- | |
|
28 | 27 | import IPython.ipapi |
|
29 | 28 | ip = IPython.ipapi.get() |
|
30 | 29 | |
|
31 | 30 | def ankka_f(self, arg): |
|
32 | 31 | print 'Ankka',self,'says uppercase:',arg.upper() |
|
33 | 32 | |
|
34 | 33 | ip.expose_magic('ankka',ankka_f) |
|
35 | 34 | |
|
36 | 35 | ip.magic('alias sayhi echo "Testing, hi ok"') |
|
37 | 36 | ip.magic('alias helloworld echo "Hello world"') |
|
38 | 37 | ip.system('pwd') |
|
39 | 38 | |
|
40 | 39 | ip.ex('import re') |
|
41 | 40 | ip.ex(''' |
|
42 | 41 | def funcci(a,b): |
|
43 | 42 | print a+b |
|
44 | 43 | print funcci(3,4) |
|
45 | 44 | ''') |
|
46 | 45 | ip.ex('funcci(348,9)') |
|
47 | 46 | |
|
48 | 47 | def jed_editor(self,filename, linenum=None): |
|
49 | 48 | print 'Calling my own editor, jed ... via hook!' |
|
50 | 49 | import os |
|
51 | 50 | if linenum is None: linenum = 0 |
|
52 | 51 | os.system('jed +%d %s' % (linenum, filename)) |
|
53 | 52 | print 'exiting jed' |
|
54 | 53 | |
|
55 | 54 | ip.set_hook('editor',jed_editor) |
|
56 | 55 | |
|
57 | 56 | o = ip.options |
|
58 | 57 | o.autocall = 2 # FULL autocall mode |
|
59 | 58 | |
|
60 | 59 | print 'done!' |
|
61 | 60 | """ |
|
62 | 61 | |
|
63 | 62 | #----------------------------------------------------------------------------- |
|
64 | 63 | # Modules and globals |
|
65 | 64 | |
|
66 | 65 | # stdlib imports |
|
67 | 66 | import __builtin__ |
|
68 | 67 | import sys |
|
69 | 68 | |
|
70 | 69 | # contains the most recently instantiated IPApi |
|
71 | 70 | _RECENT_IP = None |
|
72 | 71 | |
|
73 | 72 | #----------------------------------------------------------------------------- |
|
74 | 73 | # Code begins |
|
75 | 74 | |
|
76 | 75 | class TryNext(Exception): |
|
77 | 76 | """Try next hook exception. |
|
78 | 77 | |
|
79 | 78 | Raise this in your hook function to indicate that the next hook handler |
|
80 | 79 | should be used to handle the operation. If you pass arguments to the |
|
81 | 80 | constructor those arguments will be used by the next hook instead of the |
|
82 | 81 | original ones. |
|
83 | 82 | """ |
|
84 | 83 | |
|
85 | 84 | def __init__(self, *args, **kwargs): |
|
86 | 85 | self.args = args |
|
87 | 86 | self.kwargs = kwargs |
|
88 | 87 | |
|
89 | 88 | |
|
90 | 89 | class UsageError(Exception): |
|
91 | 90 | """ Error in magic function arguments, etc. |
|
92 | 91 | |
|
93 | 92 | Something that probably won't warrant a full traceback, but should |
|
94 | 93 | nevertheless interrupt a macro / batch file. |
|
95 | 94 | """ |
|
96 | 95 | |
|
97 | 96 | |
|
98 | 97 | class IPyAutocall: |
|
99 | 98 | """ Instances of this class are always autocalled |
|
100 | 99 | |
|
101 | 100 | This happens regardless of 'autocall' variable state. Use this to |
|
102 | 101 | develop macro-like mechanisms. |
|
103 | 102 | """ |
|
104 | 103 | |
|
105 | 104 | def set_ip(self,ip): |
|
106 | 105 | """ Will be used to set _ip point to current ipython instance b/f call |
|
107 | 106 | |
|
108 | 107 | Override this method if you don't want this to happen. |
|
109 | 108 | |
|
110 | 109 | """ |
|
111 | 110 | self._ip = ip |
|
112 | 111 | |
|
113 | 112 | |
|
114 | 113 | class IPythonNotRunning: |
|
115 | 114 | """Dummy do-nothing class. |
|
116 | 115 | |
|
117 | 116 | Instances of this class return a dummy attribute on all accesses, which |
|
118 | 117 | can be called and warns. This makes it easier to write scripts which use |
|
119 | 118 | the ipapi.get() object for informational purposes to operate both with and |
|
120 | 119 | without ipython. Obviously code which uses the ipython object for |
|
121 | 120 | computations will not work, but this allows a wider range of code to |
|
122 | 121 | transparently work whether ipython is being used or not.""" |
|
123 | 122 | |
|
124 | 123 | def __init__(self,warn=True): |
|
125 | 124 | if warn: |
|
126 | 125 | self.dummy = self._dummy_warn |
|
127 | 126 | else: |
|
128 | 127 | self.dummy = self._dummy_silent |
|
129 | 128 | |
|
130 | 129 | def __str__(self): |
|
131 | 130 | return "<IPythonNotRunning>" |
|
132 | 131 | |
|
133 | 132 | __repr__ = __str__ |
|
134 | 133 | |
|
135 | 134 | def __getattr__(self,name): |
|
136 | 135 | return self.dummy |
|
137 | 136 | |
|
138 | 137 | def _dummy_warn(self,*args,**kw): |
|
139 | 138 | """Dummy function, which doesn't do anything but warn.""" |
|
140 | 139 | |
|
141 | 140 | print ("IPython is not running, this is a dummy no-op function") |
|
142 | 141 | |
|
143 | 142 | def _dummy_silent(self,*args,**kw): |
|
144 | 143 | """Dummy function, which doesn't do anything and emits no warnings.""" |
|
145 | 144 | pass |
|
146 | 145 | |
|
147 | 146 | |
|
148 | 147 | def get(allow_dummy=False,dummy_warn=True): |
|
149 | 148 | """Get an IPApi object. |
|
150 | 149 | |
|
151 | 150 | If allow_dummy is true, returns an instance of IPythonNotRunning |
|
152 | 151 | instead of None if not running under IPython. |
|
153 | 152 | |
|
154 | 153 | If dummy_warn is false, the dummy instance will be completely silent. |
|
155 | 154 | |
|
156 | 155 | Running this should be the first thing you do when writing extensions that |
|
157 | 156 | can be imported as normal modules. You can then direct all the |
|
158 | 157 | configuration operations against the returned object. |
|
159 | 158 | """ |
|
160 | 159 | global _RECENT_IP |
|
161 | 160 | if allow_dummy and not _RECENT_IP: |
|
162 | 161 | _RECENT_IP = IPythonNotRunning(dummy_warn) |
|
163 | 162 | return _RECENT_IP |
|
164 | 163 | |
|
165 | 164 | |
|
166 | 165 | class IPApi(object): |
|
167 | 166 | """ The actual API class for configuring IPython |
|
168 | 167 | |
|
169 | 168 | You should do all of the IPython configuration by getting an IPApi object |
|
170 | 169 | with IPython.ipapi.get() and using the attributes and methods of the |
|
171 | 170 | returned object.""" |
|
172 | 171 | |
|
173 | 172 | def __init__(self,ip): |
|
174 | 173 | |
|
175 | 174 | global _RECENT_IP |
|
176 | 175 | |
|
177 | 176 | # All attributes exposed here are considered to be the public API of |
|
178 | 177 | # IPython. As needs dictate, some of these may be wrapped as |
|
179 | 178 | # properties. |
|
180 | 179 | |
|
181 | 180 | self.magic = ip.ipmagic |
|
182 | 181 | |
|
183 | 182 | self.system = ip.system |
|
184 | 183 | |
|
185 | 184 | self.set_hook = ip.set_hook |
|
186 | 185 | |
|
187 | 186 | self.set_custom_exc = ip.set_custom_exc |
|
188 | 187 | |
|
189 | 188 | self.user_ns = ip.user_ns |
|
190 | 189 | self.user_ns['_ip'] = self |
|
191 | 190 | |
|
192 | 191 | self.set_crash_handler = ip.set_crash_handler |
|
193 | 192 | |
|
194 | 193 | # Session-specific data store, which can be used to store |
|
195 | 194 | # data that should persist through the ipython session. |
|
196 | 195 | self.meta = ip.meta |
|
197 | 196 | |
|
198 | 197 | # The ipython instance provided |
|
199 | 198 | self.IP = ip |
|
200 | 199 | |
|
201 | 200 | self.extensions = {} |
|
202 | 201 | |
|
203 | 202 | self.dbg = DebugTools(self) |
|
204 | 203 | |
|
205 | 204 | _RECENT_IP = self |
|
206 | 205 | |
|
207 | 206 | # Use a property for some things which are added to the instance very |
|
208 | 207 | # late. I don't have time right now to disentangle the initialization |
|
209 | 208 | # order issues, so a property lets us delay item extraction while |
|
210 | 209 | # providing a normal attribute API. |
|
211 | 210 | def get_db(self): |
|
212 | 211 | """A handle to persistent dict-like database (a PickleShareDB object)""" |
|
213 | 212 | return self.IP.db |
|
214 | 213 | |
|
215 | 214 | db = property(get_db,None,None,get_db.__doc__) |
|
216 | 215 | |
|
217 | 216 | def get_options(self): |
|
218 | 217 | """All configurable variables.""" |
|
219 | 218 | |
|
220 | 219 | # catch typos by disabling new attribute creation. If new attr creation |
|
221 | 220 | # is in fact wanted (e.g. when exposing new options), do |
|
222 | 221 | # allow_new_attr(True) for the received rc struct. |
|
223 | 222 | |
|
224 | 223 | self.IP.rc.allow_new_attr(False) |
|
225 | 224 | return self.IP.rc |
|
226 | 225 | |
|
227 | 226 | options = property(get_options,None,None,get_options.__doc__) |
|
228 | 227 | |
|
229 | 228 | def expose_magic(self,magicname, func): |
|
230 | 229 | """Expose own function as magic function for ipython |
|
231 | 230 | |
|
232 | 231 | def foo_impl(self,parameter_s=''): |
|
233 | 232 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
234 | 233 | print 'Magic function. Passed parameter is between < >:' |
|
235 | 234 | print '<%s>' % parameter_s |
|
236 | 235 | print 'The self object is:',self |
|
237 | 236 | |
|
238 | 237 | ipapi.expose_magic('foo',foo_impl) |
|
239 | 238 | """ |
|
240 | 239 | |
|
241 | 240 | import new |
|
242 | 241 | im = new.instancemethod(func,self.IP, self.IP.__class__) |
|
243 | 242 | old = getattr(self.IP, "magic_" + magicname, None) |
|
244 | 243 | if old: |
|
245 | 244 | self.dbg.debug_stack("Magic redefinition '%s', old %s" % |
|
246 | 245 | (magicname,old) ) |
|
247 | 246 | |
|
248 | 247 | setattr(self.IP, "magic_" + magicname, im) |
|
249 | 248 | |
|
250 | 249 | def ex(self,cmd): |
|
251 | 250 | """ Execute a normal python statement in user namespace """ |
|
252 | 251 | exec cmd in self.user_ns |
|
253 | 252 | |
|
254 | 253 | def ev(self,expr): |
|
255 | 254 | """ Evaluate python expression expr in user namespace |
|
256 | 255 | |
|
257 | 256 | Returns the result of evaluation""" |
|
258 | 257 | return eval(expr,self.user_ns) |
|
259 | 258 | |
|
260 | 259 | def runlines(self,lines): |
|
261 | 260 | """ Run the specified lines in interpreter, honoring ipython directives. |
|
262 | 261 | |
|
263 | 262 | This allows %magic and !shell escape notations. |
|
264 | 263 | |
|
265 | 264 | Takes either all lines in one string or list of lines. |
|
266 | 265 | """ |
|
267 | 266 | |
|
268 | 267 | def cleanup_ipy_script(script): |
|
269 | 268 | """ Make a script safe for _ip.runlines() |
|
270 | 269 | |
|
271 | 270 | - Removes empty lines Suffixes all indented blocks that end with |
|
272 | 271 | - unindented lines with empty lines |
|
273 | 272 | """ |
|
274 | 273 | |
|
275 | 274 | res = [] |
|
276 | 275 | lines = script.splitlines() |
|
277 | 276 | |
|
278 | 277 | level = 0 |
|
279 | 278 | for l in lines: |
|
280 | 279 | lstripped = l.lstrip() |
|
281 | 280 | stripped = l.strip() |
|
282 | 281 | if not stripped: |
|
283 | 282 | continue |
|
284 | 283 | newlevel = len(l) - len(lstripped) |
|
285 | 284 | def is_secondary_block_start(s): |
|
286 | 285 | if not s.endswith(':'): |
|
287 | 286 | return False |
|
288 | 287 | if (s.startswith('elif') or |
|
289 | 288 | s.startswith('else') or |
|
290 | 289 | s.startswith('except') or |
|
291 | 290 | s.startswith('finally')): |
|
292 | 291 | return True |
|
293 | 292 | |
|
294 | 293 | if level > 0 and newlevel == 0 and \ |
|
295 | 294 | not is_secondary_block_start(stripped): |
|
296 | 295 | # add empty line |
|
297 | 296 | res.append('') |
|
298 | 297 | |
|
299 | 298 | res.append(l) |
|
300 | 299 | level = newlevel |
|
301 | 300 | return '\n'.join(res) + '\n' |
|
302 | 301 | |
|
303 | 302 | if isinstance(lines,basestring): |
|
304 | 303 | script = lines |
|
305 | 304 | else: |
|
306 | 305 | script = '\n'.join(lines) |
|
307 | 306 | clean=cleanup_ipy_script(script) |
|
308 | 307 | # print "_ip.runlines() script:\n",clean # dbg |
|
309 | 308 | self.IP.runlines(clean) |
|
310 | 309 | |
|
311 | 310 | def to_user_ns(self,vars, interactive = True): |
|
312 | 311 | """Inject a group of variables into the IPython user namespace. |
|
313 | 312 | |
|
314 | 313 | Inputs: |
|
315 | 314 | |
|
316 | 315 | - vars: string with variable names separated by whitespace, or a |
|
317 | 316 | dict with name/value pairs. |
|
318 | 317 | |
|
319 | 318 | - interactive: if True (default), the var will be listed with |
|
320 | 319 | %whos et. al. |
|
321 | 320 | |
|
322 | 321 | This utility routine is meant to ease interactive debugging work, |
|
323 | 322 | where you want to easily propagate some internal variable in your code |
|
324 | 323 | up to the interactive namespace for further exploration. |
|
325 | 324 | |
|
326 | 325 | When you run code via %run, globals in your script become visible at |
|
327 | 326 | the interactive prompt, but this doesn't happen for locals inside your |
|
328 | 327 | own functions and methods. Yet when debugging, it is common to want |
|
329 | 328 | to explore some internal variables further at the interactive propmt. |
|
330 | 329 | |
|
331 | 330 | Examples: |
|
332 | 331 | |
|
333 | 332 | To use this, you first must obtain a handle on the ipython object as |
|
334 | 333 | indicated above, via: |
|
335 | 334 | |
|
336 | 335 | import IPython.ipapi |
|
337 | 336 | ip = IPython.ipapi.get() |
|
338 | 337 | |
|
339 | 338 | Once this is done, inside a routine foo() where you want to expose |
|
340 | 339 | variables x and y, you do the following: |
|
341 | 340 | |
|
342 | 341 | def foo(): |
|
343 | 342 | ... |
|
344 | 343 | x = your_computation() |
|
345 | 344 | y = something_else() |
|
346 | 345 | |
|
347 | 346 | # This pushes x and y to the interactive prompt immediately, even |
|
348 | 347 | # if this routine crashes on the next line after: |
|
349 | 348 | ip.to_user_ns('x y') |
|
350 | 349 | ... |
|
351 | 350 | |
|
352 | 351 | # To expose *ALL* the local variables from the function, use: |
|
353 | 352 | ip.to_user_ns(locals()) |
|
354 | 353 | |
|
355 | 354 | ... |
|
356 | 355 | # return |
|
357 | 356 | |
|
358 | 357 | |
|
359 | 358 | If you need to rename variables, the dict input makes it easy. For |
|
360 | 359 | example, this call exposes variables 'foo' as 'x' and 'bar' as 'y' |
|
361 | 360 | in IPython user namespace: |
|
362 | 361 | |
|
363 | 362 | ip.to_user_ns(dict(x=foo,y=bar)) |
|
364 | 363 | """ |
|
365 | 364 | |
|
366 | 365 | # print 'vars given:',vars # dbg |
|
367 | 366 | |
|
368 | 367 | # We need a dict of name/value pairs to do namespace updates. |
|
369 | 368 | if isinstance(vars,dict): |
|
370 | 369 | # If a dict was given, no need to change anything. |
|
371 | 370 | vdict = vars |
|
372 | 371 | elif isinstance(vars,basestring): |
|
373 | 372 | # If a string with names was given, get the caller's frame to |
|
374 | 373 | # evaluate the given names in |
|
375 | 374 | cf = sys._getframe(1) |
|
376 | 375 | vdict = {} |
|
377 | 376 | for name in vars.split(): |
|
378 | 377 | try: |
|
379 | 378 | vdict[name] = eval(name,cf.f_globals,cf.f_locals) |
|
380 | 379 | except: |
|
381 | 380 | print ('could not get var. %s from %s' % |
|
382 | 381 | (name,cf.f_code.co_name)) |
|
383 | 382 | else: |
|
384 | 383 | raise ValueError('vars must be a string or a dict') |
|
385 | 384 | |
|
386 | 385 | # Propagate variables to user namespace |
|
387 | 386 | self.user_ns.update(vdict) |
|
388 | 387 | |
|
389 | 388 | # And configure interactive visibility |
|
390 | 389 | config_ns = self.IP.user_config_ns |
|
391 | 390 | if interactive: |
|
392 | 391 | for name,val in vdict.iteritems(): |
|
393 | 392 | config_ns.pop(name,None) |
|
394 | 393 | else: |
|
395 | 394 | for name,val in vdict.iteritems(): |
|
396 | 395 | config_ns[name] = val |
|
397 | 396 | |
|
398 | 397 | def expand_alias(self,line): |
|
399 | 398 | """ Expand an alias in the command line |
|
400 | 399 | |
|
401 | 400 | Returns the provided command line, possibly with the first word |
|
402 | 401 | (command) translated according to alias expansion rules. |
|
403 | 402 | |
|
404 | 403 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
405 | 404 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
406 | 405 | """ |
|
407 | 406 | |
|
408 | 407 | pre,fn,rest = self.IP.split_user_input(line) |
|
409 | 408 | res = pre + self.IP.expand_aliases(fn,rest) |
|
410 | 409 | return res |
|
411 | 410 | |
|
412 | 411 | def itpl(self, s, depth = 1): |
|
413 | 412 | """ Expand Itpl format string s. |
|
414 | 413 | |
|
415 | 414 | Only callable from command line (i.e. prefilter results); |
|
416 | 415 | If you use in your scripts, you need to use a bigger depth! |
|
417 | 416 | """ |
|
418 | 417 | return self.IP.var_expand(s, depth) |
|
419 | 418 | |
|
420 | 419 | def defalias(self, name, cmd): |
|
421 | 420 | """ Define a new alias |
|
422 | 421 | |
|
423 | 422 | _ip.defalias('bb','bldmake bldfiles') |
|
424 | 423 | |
|
425 | 424 | Creates a new alias named 'bb' in ipython user namespace |
|
426 | 425 | """ |
|
427 | 426 | |
|
428 | 427 | self.dbg.check_hotname(name) |
|
429 | 428 | |
|
430 | 429 | if name in self.IP.alias_table: |
|
431 | 430 | self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')" |
|
432 | 431 | % (name, cmd, self.IP.alias_table[name])) |
|
433 | 432 | |
|
434 | 433 | if callable(cmd): |
|
435 | 434 | self.IP.alias_table[name] = cmd |
|
436 | 435 | import IPython.shadowns |
|
437 | 436 | setattr(IPython.shadowns, name,cmd) |
|
438 | 437 | return |
|
439 | 438 | |
|
440 | 439 | if isinstance(cmd,basestring): |
|
441 | 440 | nargs = cmd.count('%s') |
|
442 | 441 | if nargs>0 and cmd.find('%l')>=0: |
|
443 | 442 | raise Exception('The %s and %l specifiers are mutually ' |
|
444 | 443 | 'exclusive in alias definitions.') |
|
445 | 444 | |
|
446 | 445 | self.IP.alias_table[name] = (nargs,cmd) |
|
447 | 446 | return |
|
448 | 447 | |
|
449 | 448 | # just put it in - it's probably (0,'foo') |
|
450 | 449 | self.IP.alias_table[name] = cmd |
|
451 | 450 | |
|
452 | 451 | def defmacro(self, *args): |
|
453 | 452 | """ Define a new macro |
|
454 | 453 | |
|
455 | 454 | 2 forms of calling: |
|
456 | 455 | |
|
457 | 456 | mac = _ip.defmacro('print "hello"\nprint "world"') |
|
458 | 457 | |
|
459 | 458 | (doesn't put the created macro on user namespace) |
|
460 | 459 | |
|
461 | 460 | _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb') |
|
462 | 461 | |
|
463 | 462 | (creates a macro named 'build' in user namespace) |
|
464 | 463 | """ |
|
465 | 464 | |
|
466 | 465 | import IPython.macro |
|
467 | 466 | |
|
468 | 467 | if len(args) == 1: |
|
469 | 468 | return IPython.macro.Macro(args[0]) |
|
470 | 469 | elif len(args) == 2: |
|
471 | 470 | self.user_ns[args[0]] = IPython.macro.Macro(args[1]) |
|
472 | 471 | else: |
|
473 | 472 | return Exception("_ip.defmacro must be called with 1 or 2 arguments") |
|
474 | 473 | |
|
475 | 474 | def set_next_input(self, s): |
|
476 | 475 | """ Sets the 'default' input string for the next command line. |
|
477 | 476 | |
|
478 | 477 | Requires readline. |
|
479 | 478 | |
|
480 | 479 | Example: |
|
481 | 480 | |
|
482 | 481 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
483 | 482 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
484 | 483 | """ |
|
485 | 484 | |
|
486 | 485 | self.IP.rl_next_input = s |
|
487 | 486 | |
|
488 | 487 | def load(self, mod): |
|
489 | 488 | """ Load an extension. |
|
490 | 489 | |
|
491 | 490 | Some modules should (or must) be 'load()':ed, rather than just imported. |
|
492 | 491 | |
|
493 | 492 | Loading will do: |
|
494 | 493 | |
|
495 | 494 | - run init_ipython(ip) |
|
496 | 495 | - run ipython_firstrun(ip) |
|
497 | 496 | """ |
|
498 | 497 | |
|
499 | 498 | if mod in self.extensions: |
|
500 | 499 | # just to make sure we don't init it twice |
|
501 | 500 | # note that if you 'load' a module that has already been |
|
502 | 501 | # imported, init_ipython gets run anyway |
|
503 | 502 | |
|
504 | 503 | return self.extensions[mod] |
|
505 | 504 | __import__(mod) |
|
506 | 505 | m = sys.modules[mod] |
|
507 | 506 | if hasattr(m,'init_ipython'): |
|
508 | 507 | m.init_ipython(self) |
|
509 | 508 | |
|
510 | 509 | if hasattr(m,'ipython_firstrun'): |
|
511 | 510 | already_loaded = self.db.get('firstrun_done', set()) |
|
512 | 511 | if mod not in already_loaded: |
|
513 | 512 | m.ipython_firstrun(self) |
|
514 | 513 | already_loaded.add(mod) |
|
515 | 514 | self.db['firstrun_done'] = already_loaded |
|
516 | 515 | |
|
517 | 516 | self.extensions[mod] = m |
|
518 | 517 | return m |
|
519 | 518 | |
|
520 | 519 | |
|
521 | 520 | class DebugTools: |
|
522 | 521 | """ Used for debugging mishaps in api usage |
|
523 | 522 | |
|
524 | 523 | So far, tracing redefinitions is supported. |
|
525 | 524 | """ |
|
526 | 525 | |
|
527 | 526 | def __init__(self, ip): |
|
528 | 527 | self.ip = ip |
|
529 | 528 | self.debugmode = False |
|
530 | 529 | self.hotnames = set() |
|
531 | 530 | |
|
532 | 531 | def hotname(self, name_to_catch): |
|
533 | 532 | self.hotnames.add(name_to_catch) |
|
534 | 533 | |
|
535 | 534 | def debug_stack(self, msg = None): |
|
536 | 535 | if not self.debugmode: |
|
537 | 536 | return |
|
538 | 537 | |
|
539 | 538 | import traceback |
|
540 | 539 | if msg is not None: |
|
541 | 540 | print '====== %s ========' % msg |
|
542 | 541 | traceback.print_stack() |
|
543 | 542 | |
|
544 | 543 | def check_hotname(self,name): |
|
545 | 544 | if name in self.hotnames: |
|
546 | 545 | self.debug_stack( "HotName '%s' caught" % name) |
|
547 | 546 | |
|
548 | 547 | |
|
549 | 548 | def launch_new_instance(user_ns = None,shellclass = None): |
|
550 | 549 | """ Make and start a new ipython instance. |
|
551 | 550 | |
|
552 | 551 | This can be called even without having an already initialized |
|
553 | 552 | ipython session running. |
|
554 | 553 | |
|
555 | 554 | This is also used as the egg entry point for the 'ipython' script. |
|
556 | 555 | |
|
557 | 556 | """ |
|
558 | 557 | ses = make_session(user_ns,shellclass) |
|
559 | 558 | ses.mainloop() |
|
560 | 559 | |
|
561 | 560 | |
|
562 | 561 | def make_user_ns(user_ns = None): |
|
563 | 562 | """Return a valid user interactive namespace. |
|
564 | 563 | |
|
565 | 564 | This builds a dict with the minimal information needed to operate as a |
|
566 | 565 | valid IPython user namespace, which you can pass to the various embedding |
|
567 | 566 | classes in ipython. |
|
568 | 567 | |
|
569 | 568 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead |
|
570 | 569 | to make both the local and global namespace objects simultaneously. |
|
571 | 570 | |
|
572 | 571 | :Parameters: |
|
573 | 572 | user_ns : dict-like, optional |
|
574 | 573 | The current user namespace. The items in this namespace should be |
|
575 | 574 | included in the output. If None, an appropriate blank namespace |
|
576 | 575 | should be created. |
|
577 | 576 | |
|
578 | 577 | :Returns: |
|
579 | 578 | A dictionary-like object to be used as the local namespace of the |
|
580 | 579 | interpreter. |
|
581 | 580 | """ |
|
582 | 581 | |
|
583 | 582 | raise NotImplementedError |
|
584 | 583 | |
|
585 | 584 | |
|
586 | 585 | def make_user_global_ns(ns = None): |
|
587 | 586 | """Return a valid user global namespace. |
|
588 | 587 | |
|
589 | 588 | Similar to make_user_ns(), but global namespaces are really only needed in |
|
590 | 589 | embedded applications, where there is a distinction between the user's |
|
591 | 590 | interactive namespace and the global one where ipython is running. |
|
592 | 591 | |
|
593 | 592 | This API is currently deprecated. Use ipapi.make_user_namespaces() instead |
|
594 | 593 | to make both the local and global namespace objects simultaneously. |
|
595 | 594 | |
|
596 | 595 | :Parameters: |
|
597 | 596 | ns : dict, optional |
|
598 | 597 | The current user global namespace. The items in this namespace |
|
599 | 598 | should be included in the output. If None, an appropriate blank |
|
600 | 599 | namespace should be created. |
|
601 | 600 | |
|
602 | 601 | :Returns: |
|
603 | 602 | A true dict to be used as the global namespace of the interpreter. |
|
604 | 603 | """ |
|
605 | 604 | |
|
606 | 605 | raise NotImplementedError |
|
607 | 606 | |
|
608 | 607 | # Record the true objects in order to be able to test if the user has overridden |
|
609 | 608 | # these API functions. |
|
610 | 609 | _make_user_ns = make_user_ns |
|
611 | 610 | _make_user_global_ns = make_user_global_ns |
|
612 | 611 | |
|
613 | 612 | |
|
614 | 613 | def make_user_namespaces(user_ns = None,user_global_ns = None): |
|
615 | 614 | """Return a valid local and global user interactive namespaces. |
|
616 | 615 | |
|
617 | 616 | This builds a dict with the minimal information needed to operate as a |
|
618 | 617 | valid IPython user namespace, which you can pass to the various embedding |
|
619 | 618 | classes in ipython. The default implementation returns the same dict for |
|
620 | 619 | both the locals and the globals to allow functions to refer to variables in |
|
621 | 620 | the namespace. Customized implementations can return different dicts. The |
|
622 | 621 | locals dictionary can actually be anything following the basic mapping |
|
623 | 622 | protocol of a dict, but the globals dict must be a true dict, not even |
|
624 | 623 | a subclass. It is recommended that any custom object for the locals |
|
625 | 624 | namespace synchronize with the globals dict somehow. |
|
626 | 625 | |
|
627 | 626 | Raises TypeError if the provided globals namespace is not a true dict. |
|
628 | 627 | |
|
629 | 628 | :Parameters: |
|
630 | 629 | user_ns : dict-like, optional |
|
631 | 630 | The current user namespace. The items in this namespace should be |
|
632 | 631 | included in the output. If None, an appropriate blank namespace |
|
633 | 632 | should be created. |
|
634 | 633 | user_global_ns : dict, optional |
|
635 | 634 | The current user global namespace. The items in this namespace |
|
636 | 635 | should be included in the output. If None, an appropriate blank |
|
637 | 636 | namespace should be created. |
|
638 | 637 | |
|
639 | 638 | :Returns: |
|
640 | 639 | A tuple pair of dictionary-like object to be used as the local namespace |
|
641 | 640 | of the interpreter and a dict to be used as the global namespace. |
|
642 | 641 | """ |
|
643 | 642 | |
|
644 | 643 | if user_ns is None: |
|
645 | 644 | if make_user_ns is not _make_user_ns: |
|
646 | 645 | # Old API overridden. |
|
647 | 646 | # FIXME: Issue DeprecationWarning, or just let the old API live on? |
|
648 | 647 | user_ns = make_user_ns(user_ns) |
|
649 | 648 | else: |
|
650 | 649 | # Set __name__ to __main__ to better match the behavior of the |
|
651 | 650 | # normal interpreter. |
|
652 | 651 | user_ns = {'__name__' :'__main__', |
|
653 | 652 | '__builtins__' : __builtin__, |
|
654 | 653 | } |
|
655 | 654 | else: |
|
656 | 655 | user_ns.setdefault('__name__','__main__') |
|
657 | 656 | user_ns.setdefault('__builtins__',__builtin__) |
|
658 | 657 | |
|
659 | 658 | if user_global_ns is None: |
|
660 | 659 | if make_user_global_ns is not _make_user_global_ns: |
|
661 | 660 | # Old API overridden. |
|
662 | 661 | user_global_ns = make_user_global_ns(user_global_ns) |
|
663 | 662 | else: |
|
664 | 663 | user_global_ns = user_ns |
|
665 | 664 | if type(user_global_ns) is not dict: |
|
666 | 665 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
667 | 666 | % type(user_global_ns)) |
|
668 | 667 | |
|
669 | 668 | return user_ns, user_global_ns |
|
670 | 669 | |
|
671 | 670 | |
|
672 | 671 | def make_session(user_ns = None, shellclass = None): |
|
673 | 672 | """Makes, but does not launch an IPython session. |
|
674 | 673 | |
|
675 | 674 | Later on you can call obj.mainloop() on the returned object. |
|
676 | 675 | |
|
677 | 676 | Inputs: |
|
678 | 677 | |
|
679 | 678 | - user_ns(None): a dict to be used as the user's namespace with initial |
|
680 | 679 | data. |
|
681 | 680 | |
|
682 | 681 | WARNING: This should *not* be run when a session exists already.""" |
|
683 | 682 | |
|
684 | 683 | import IPython.Shell |
|
685 | 684 | if shellclass is None: |
|
686 | 685 | return IPython.Shell.start(user_ns) |
|
687 | 686 | return shellclass(user_ns = user_ns) |
@@ -1,197 +1,197 | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | |
|
3 | 3 | __docformat__ = "restructuredtext en" |
|
4 | 4 | |
|
5 | 5 | #------------------------------------------------------------------------------- |
|
6 | 6 | # Copyright (C) 2008 The IPython Development Team |
|
7 | 7 | # |
|
8 | 8 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | 9 | # the file COPYING, distributed as part of this software. |
|
10 | 10 | #------------------------------------------------------------------------------- |
|
11 | 11 | |
|
12 | 12 | #------------------------------------------------------------------------------- |
|
13 | 13 | # Imports |
|
14 | 14 | #------------------------------------------------------------------------------- |
|
15 | 15 | |
|
16 | 16 | import os |
|
17 | 17 | import sys |
|
18 | 18 | |
|
19 | 19 | |
|
20 | 20 | # This class is mostly taken from IPython. |
|
21 | 21 | class InputList(list): |
|
22 | 22 | """ Class to store user input. |
|
23 | 23 | |
|
24 | 24 | It's basically a list, but slices return a string instead of a list, thus |
|
25 | 25 | allowing things like (assuming 'In' is an instance): |
|
26 | 26 | |
|
27 | 27 | exec In[4:7] |
|
28 | 28 | |
|
29 | 29 | or |
|
30 | 30 | |
|
31 | 31 | exec In[5:9] + In[14] + In[21:25] |
|
32 | 32 | """ |
|
33 | 33 | |
|
34 | 34 | def __getslice__(self, i, j): |
|
35 | 35 | return ''.join(list.__getslice__(self, i, j)) |
|
36 | 36 | |
|
37 | 37 | def add(self, index, command): |
|
38 | 38 | """ Add a command to the list with the appropriate index. |
|
39 | 39 | |
|
40 | 40 | If the index is greater than the current length of the list, empty |
|
41 | 41 | strings are added in between. |
|
42 | 42 | """ |
|
43 | 43 | |
|
44 | 44 | length = len(self) |
|
45 | 45 | if length == index: |
|
46 | 46 | self.append(command) |
|
47 | 47 | elif length > index: |
|
48 | 48 | self[index] = command |
|
49 | 49 | else: |
|
50 | 50 | extras = index - length |
|
51 | 51 | self.extend([''] * extras) |
|
52 | 52 | self.append(command) |
|
53 | 53 | |
|
54 | 54 | |
|
55 | 55 | class Bunch(dict): |
|
56 | 56 | """ A dictionary that exposes its keys as attributes. |
|
57 | 57 | """ |
|
58 | 58 | |
|
59 | 59 | def __init__(self, *args, **kwds): |
|
60 | 60 | dict.__init__(self, *args, **kwds) |
|
61 | 61 | self.__dict__ = self |
|
62 | 62 | |
|
63 | 63 | |
|
64 | 64 | def esc_quotes(strng): |
|
65 | 65 | """ Return the input string with single and double quotes escaped out. |
|
66 | 66 | """ |
|
67 | 67 | |
|
68 | 68 | return strng.replace('"', '\\"').replace("'", "\\'") |
|
69 | 69 | |
|
70 | 70 | def make_quoted_expr(s): |
|
71 | 71 | """Return string s in appropriate quotes, using raw string if possible. |
|
72 | 72 | |
|
73 | Effectively this turns string: cd \ao\ao\ | |
|
74 | to: r"cd \ao\ao\_"[:-1] | |
|
73 | XXX - example removed because it caused encoding errors in documentation | |
|
74 | generation. We need a new example that doesn't contain invalid chars. | |
|
75 | 75 | |
|
76 | 76 | Note the use of raw string and padding at the end to allow trailing |
|
77 | 77 | backslash. |
|
78 | 78 | """ |
|
79 | 79 | |
|
80 | 80 | tail = '' |
|
81 | 81 | tailpadding = '' |
|
82 | 82 | raw = '' |
|
83 | 83 | if "\\" in s: |
|
84 | 84 | raw = 'r' |
|
85 | 85 | if s.endswith('\\'): |
|
86 | 86 | tail = '[:-1]' |
|
87 | 87 | tailpadding = '_' |
|
88 | 88 | if '"' not in s: |
|
89 | 89 | quote = '"' |
|
90 | 90 | elif "'" not in s: |
|
91 | 91 | quote = "'" |
|
92 | 92 | elif '"""' not in s and not s.endswith('"'): |
|
93 | 93 | quote = '"""' |
|
94 | 94 | elif "'''" not in s and not s.endswith("'"): |
|
95 | 95 | quote = "'''" |
|
96 | 96 | else: |
|
97 | 97 | # Give up, backslash-escaped string will do |
|
98 | 98 | return '"%s"' % esc_quotes(s) |
|
99 | 99 | res = ''.join([raw, quote, s, tailpadding, quote, tail]) |
|
100 | 100 | return res |
|
101 | 101 | |
|
102 | 102 | # This function is used by ipython in a lot of places to make system calls. |
|
103 | 103 | # We need it to be slightly different under win32, due to the vagaries of |
|
104 | 104 | # 'network shares'. A win32 override is below. |
|
105 | 105 | |
|
106 | 106 | def system_shell(cmd, verbose=False, debug=False, header=''): |
|
107 | 107 | """ Execute a command in the system shell; always return None. |
|
108 | 108 | |
|
109 | 109 | Parameters |
|
110 | 110 | ---------- |
|
111 | 111 | cmd : str |
|
112 | 112 | The command to execute. |
|
113 | 113 | verbose : bool |
|
114 | 114 | If True, print the command to be executed. |
|
115 | 115 | debug : bool |
|
116 | 116 | Only print, do not actually execute. |
|
117 | 117 | header : str |
|
118 | 118 | Header to print to screen prior to the executed command. No extra |
|
119 | 119 | newlines are added. |
|
120 | 120 | |
|
121 | 121 | Description |
|
122 | 122 | ----------- |
|
123 | 123 | This returns None so it can be conveniently used in interactive loops |
|
124 | 124 | without getting the return value (typically 0) printed many times. |
|
125 | 125 | """ |
|
126 | 126 | |
|
127 | 127 | if verbose or debug: |
|
128 | 128 | print header + cmd |
|
129 | 129 | |
|
130 | 130 | # Flush stdout so we don't mangle python's buffering. |
|
131 | 131 | sys.stdout.flush() |
|
132 | 132 | if not debug: |
|
133 | 133 | os.system(cmd) |
|
134 | 134 | |
|
135 | 135 | # Override shell() for win32 to deal with network shares. |
|
136 | 136 | if os.name in ('nt', 'dos'): |
|
137 | 137 | |
|
138 | 138 | system_shell_ori = system_shell |
|
139 | 139 | |
|
140 | 140 | def system_shell(cmd, verbose=False, debug=False, header=''): |
|
141 | 141 | if os.getcwd().startswith(r"\\"): |
|
142 | 142 | path = os.getcwd() |
|
143 | 143 | # Change to c drive (cannot be on UNC-share when issuing os.system, |
|
144 | 144 | # as cmd.exe cannot handle UNC addresses). |
|
145 | 145 | os.chdir("c:") |
|
146 | 146 | # Issue pushd to the UNC-share and then run the command. |
|
147 | 147 | try: |
|
148 | 148 | system_shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) |
|
149 | 149 | finally: |
|
150 | 150 | os.chdir(path) |
|
151 | 151 | else: |
|
152 | 152 | system_shell_ori(cmd,verbose,debug,header) |
|
153 | 153 | |
|
154 | 154 | system_shell.__doc__ = system_shell_ori.__doc__ |
|
155 | 155 | |
|
156 | 156 | def getoutputerror(cmd, verbose=False, debug=False, header='', split=False): |
|
157 | 157 | """ Executes a command and returns the output. |
|
158 | 158 | |
|
159 | 159 | Parameters |
|
160 | 160 | ---------- |
|
161 | 161 | cmd : str |
|
162 | 162 | The command to execute. |
|
163 | 163 | verbose : bool |
|
164 | 164 | If True, print the command to be executed. |
|
165 | 165 | debug : bool |
|
166 | 166 | Only print, do not actually execute. |
|
167 | 167 | header : str |
|
168 | 168 | Header to print to screen prior to the executed command. No extra |
|
169 | 169 | newlines are added. |
|
170 | 170 | split : bool |
|
171 | 171 | If True, return the output as a list split on newlines. |
|
172 | 172 | |
|
173 | 173 | """ |
|
174 | 174 | |
|
175 | 175 | if verbose or debug: |
|
176 | 176 | print header+cmd |
|
177 | 177 | |
|
178 | 178 | if not cmd: |
|
179 | 179 | # Return empty lists or strings. |
|
180 | 180 | if split: |
|
181 | 181 | return [], [] |
|
182 | 182 | else: |
|
183 | 183 | return '', '' |
|
184 | 184 | |
|
185 | 185 | if not debug: |
|
186 | 186 | # fixme: use subprocess. |
|
187 | 187 | pin,pout,perr = os.popen3(cmd) |
|
188 | 188 | tout = pout.read().rstrip() |
|
189 | 189 | terr = perr.read().rstrip() |
|
190 | 190 | pin.close() |
|
191 | 191 | pout.close() |
|
192 | 192 | perr.close() |
|
193 | 193 | if split: |
|
194 | 194 | return tout.split('\n'), terr.split('\n') |
|
195 | 195 | else: |
|
196 | 196 | return tout, terr |
|
197 | 197 |
@@ -1,244 +1,244 | |||
|
1 | 1 | """Decorators for labeling test objects. |
|
2 | 2 | |
|
3 | 3 | Decorators that merely return a modified version of the original function |
|
4 | 4 | object are straightforward. Decorators that return a new function object need |
|
5 | 5 | to use nose.tools.make_decorator(original_function)(decorator) in returning the |
|
6 | 6 | decorator, in order to preserve metadata such as function name, setup and |
|
7 | 7 | teardown functions and so on - see nose.tools for more information. |
|
8 | 8 | |
|
9 | 9 | This module provides a set of useful decorators meant to be ready to use in |
|
10 | 10 | your own tests. See the bottom of the file for the ready-made ones, and if you |
|
11 | 11 | find yourself writing a new one that may be of generic use, add it here. |
|
12 | 12 | |
|
13 | 13 | NOTE: This file contains IPython-specific decorators and imports the |
|
14 | 14 | numpy.testing.decorators file, which we've copied verbatim. Any of our own |
|
15 | 15 | code will be added at the bottom if we end up extending this. |
|
16 | 16 | """ |
|
17 | 17 | |
|
18 | 18 | # Stdlib imports |
|
19 | 19 | import inspect |
|
20 | 20 | import sys |
|
21 | 21 | |
|
22 | 22 | # Third-party imports |
|
23 | 23 | |
|
24 | 24 | # This is Michele Simionato's decorator module, also kept verbatim. |
|
25 | 25 | from decorator_msim import decorator, update_wrapper |
|
26 | 26 | |
|
27 | 27 | # Grab the numpy-specific decorators which we keep in a file that we |
|
28 | 28 | # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy |
|
29 | 29 | # of numpy.testing.decorators. |
|
30 | 30 | from decorators_numpy import * |
|
31 | 31 | |
|
32 | 32 | ############################################################################## |
|
33 | 33 | # Local code begins |
|
34 | 34 | |
|
35 | 35 | # Utility functions |
|
36 | 36 | |
|
37 | 37 | def apply_wrapper(wrapper,func): |
|
38 | 38 | """Apply a wrapper to a function for decoration. |
|
39 | 39 | |
|
40 | 40 | This mixes Michele Simionato's decorator tool with nose's make_decorator, |
|
41 | 41 | to apply a wrapper in a decorator so that all nose attributes, as well as |
|
42 | 42 | function signature and other properties, survive the decoration cleanly. |
|
43 | 43 | This will ensure that wrapped functions can still be well introspected via |
|
44 | 44 | IPython, for example. |
|
45 | 45 | """ |
|
46 | 46 | import nose.tools |
|
47 | 47 | |
|
48 | 48 | return decorator(wrapper,nose.tools.make_decorator(func)(wrapper)) |
|
49 | 49 | |
|
50 | 50 | |
|
51 | 51 | def make_label_dec(label,ds=None): |
|
52 | 52 | """Factory function to create a decorator that applies one or more labels. |
|
53 | 53 | |
|
54 | 54 | :Parameters: |
|
55 | 55 | label : string or sequence |
|
56 | 56 | One or more labels that will be applied by the decorator to the functions |
|
57 | 57 | it decorates. Labels are attributes of the decorated function with their |
|
58 | 58 | value set to True. |
|
59 | 59 | |
|
60 | 60 | :Keywords: |
|
61 | 61 | ds : string |
|
62 | 62 | An optional docstring for the resulting decorator. If not given, a |
|
63 | 63 | default docstring is auto-generated. |
|
64 | 64 | |
|
65 | 65 | :Returns: |
|
66 | 66 | A decorator. |
|
67 | 67 | |
|
68 | 68 | :Examples: |
|
69 | 69 | |
|
70 | 70 | A simple labeling decorator: |
|
71 | 71 | >>> slow = make_label_dec('slow') |
|
72 | 72 | >>> print slow.__doc__ |
|
73 | 73 | Labels a test as 'slow'. |
|
74 | 74 | |
|
75 | 75 | And one that uses multiple labels and a custom docstring: |
|
76 | 76 | >>> rare = make_label_dec(['slow','hard'], |
|
77 | 77 | ... "Mix labels 'slow' and 'hard' for rare tests.") |
|
78 | 78 | >>> print rare.__doc__ |
|
79 | 79 | Mix labels 'slow' and 'hard' for rare tests. |
|
80 | 80 | |
|
81 | 81 | Now, let's test using this one: |
|
82 | 82 | >>> @rare |
|
83 | 83 | ... def f(): pass |
|
84 | 84 | ... |
|
85 | 85 | >>> |
|
86 | 86 | >>> f.slow |
|
87 | 87 | True |
|
88 | 88 | >>> f.hard |
|
89 | 89 | True |
|
90 | 90 | """ |
|
91 | 91 | |
|
92 | 92 | if isinstance(label,basestring): |
|
93 | 93 | labels = [label] |
|
94 | 94 | else: |
|
95 | 95 | labels = label |
|
96 | 96 | |
|
97 | 97 | # Validate that the given label(s) are OK for use in setattr() by doing a |
|
98 | 98 | # dry run on a dummy function. |
|
99 | 99 | tmp = lambda : None |
|
100 | 100 | for label in labels: |
|
101 | 101 | setattr(tmp,label,True) |
|
102 | 102 | |
|
103 | 103 | # This is the actual decorator we'll return |
|
104 | 104 | def decor(f): |
|
105 | 105 | for label in labels: |
|
106 | 106 | setattr(f,label,True) |
|
107 | 107 | return f |
|
108 | 108 | |
|
109 | 109 | # Apply the user's docstring, or autogenerate a basic one |
|
110 | 110 | if ds is None: |
|
111 | 111 | ds = "Labels a test as %r." % label |
|
112 | 112 | decor.__doc__ = ds |
|
113 | 113 | |
|
114 | 114 | return decor |
|
115 | 115 | |
|
116 | 116 | |
|
117 | 117 | # Inspired by numpy's skipif, but uses the full apply_wrapper utility to |
|
118 | 118 | # preserve function metadata better and allows the skip condition to be a |
|
119 | 119 | # callable. |
|
120 | 120 | def skipif(skip_condition, msg=None): |
|
121 | 121 | ''' Make function raise SkipTest exception if skip_condition is true |
|
122 | 122 | |
|
123 | 123 | Parameters |
|
124 | --------- | |
|
124 | ---------- | |
|
125 | 125 | skip_condition : bool or callable. |
|
126 | 126 | Flag to determine whether to skip test. If the condition is a |
|
127 | 127 | callable, it is used at runtime to dynamically make the decision. This |
|
128 | 128 | is useful for tests that may require costly imports, to delay the cost |
|
129 | 129 | until the test suite is actually executed. |
|
130 | 130 | msg : string |
|
131 | 131 | Message to give on raising a SkipTest exception |
|
132 | 132 | |
|
133 | 133 | Returns |
|
134 | 134 | ------- |
|
135 | 135 | decorator : function |
|
136 | 136 | Decorator, which, when applied to a function, causes SkipTest |
|
137 | 137 | to be raised when the skip_condition was True, and the function |
|
138 | 138 | to be called normally otherwise. |
|
139 | 139 | |
|
140 | 140 | Notes |
|
141 | 141 | ----- |
|
142 | 142 | You will see from the code that we had to further decorate the |
|
143 | 143 | decorator with the nose.tools.make_decorator function in order to |
|
144 | 144 | transmit function name, and various other metadata. |
|
145 | 145 | ''' |
|
146 | 146 | |
|
147 | 147 | def skip_decorator(f): |
|
148 | 148 | # Local import to avoid a hard nose dependency and only incur the |
|
149 | 149 | # import time overhead at actual test-time. |
|
150 | 150 | import nose |
|
151 | 151 | |
|
152 | 152 | # Allow for both boolean or callable skip conditions. |
|
153 | 153 | if callable(skip_condition): |
|
154 | 154 | skip_val = lambda : skip_condition() |
|
155 | 155 | else: |
|
156 | 156 | skip_val = lambda : skip_condition |
|
157 | 157 | |
|
158 | 158 | def get_msg(func,msg=None): |
|
159 | 159 | """Skip message with information about function being skipped.""" |
|
160 | 160 | if msg is None: out = 'Test skipped due to test condition.' |
|
161 | 161 | else: out = msg |
|
162 | 162 | return "Skipping test: %s. %s" % (func.__name__,out) |
|
163 | 163 | |
|
164 | 164 | # We need to define *two* skippers because Python doesn't allow both |
|
165 | 165 | # return with value and yield inside the same function. |
|
166 | 166 | def skipper_func(*args, **kwargs): |
|
167 | 167 | """Skipper for normal test functions.""" |
|
168 | 168 | if skip_val(): |
|
169 | 169 | raise nose.SkipTest(get_msg(f,msg)) |
|
170 | 170 | else: |
|
171 | 171 | return f(*args, **kwargs) |
|
172 | 172 | |
|
173 | 173 | def skipper_gen(*args, **kwargs): |
|
174 | 174 | """Skipper for test generators.""" |
|
175 | 175 | if skip_val(): |
|
176 | 176 | raise nose.SkipTest(get_msg(f,msg)) |
|
177 | 177 | else: |
|
178 | 178 | for x in f(*args, **kwargs): |
|
179 | 179 | yield x |
|
180 | 180 | |
|
181 | 181 | # Choose the right skipper to use when building the actual generator. |
|
182 | 182 | if nose.util.isgenerator(f): |
|
183 | 183 | skipper = skipper_gen |
|
184 | 184 | else: |
|
185 | 185 | skipper = skipper_func |
|
186 | 186 | |
|
187 | 187 | return nose.tools.make_decorator(f)(skipper) |
|
188 | 188 | |
|
189 | 189 | return skip_decorator |
|
190 | 190 | |
|
191 | 191 | # A version with the condition set to true, common case just to attacha message |
|
192 | 192 | # to a skip decorator |
|
193 | 193 | def skip(msg=None): |
|
194 | 194 | """Decorator factory - mark a test function for skipping from test suite. |
|
195 | 195 | |
|
196 | 196 | :Parameters: |
|
197 | 197 | msg : string |
|
198 | 198 | Optional message to be added. |
|
199 | 199 | |
|
200 | 200 | :Returns: |
|
201 | 201 | decorator : function |
|
202 | 202 | Decorator, which, when applied to a function, causes SkipTest |
|
203 | 203 | to be raised, with the optional message added. |
|
204 | 204 | """ |
|
205 | 205 | |
|
206 | 206 | return skipif(True,msg) |
|
207 | 207 | |
|
208 | 208 | |
|
209 | 209 | #----------------------------------------------------------------------------- |
|
210 | 210 | # Utility functions for decorators |
|
211 | 211 | def numpy_not_available(): |
|
212 | 212 | """Can numpy be imported? Returns true if numpy does NOT import. |
|
213 | 213 | |
|
214 | 214 | This is used to make a decorator to skip tests that require numpy to be |
|
215 | 215 | available, but delay the 'import numpy' to test execution time. |
|
216 | 216 | """ |
|
217 | 217 | try: |
|
218 | 218 | import numpy |
|
219 | 219 | np_not_avail = False |
|
220 | 220 | except ImportError: |
|
221 | 221 | np_not_avail = True |
|
222 | 222 | |
|
223 | 223 | return np_not_avail |
|
224 | 224 | |
|
225 | 225 | #----------------------------------------------------------------------------- |
|
226 | 226 | # Decorators for public use |
|
227 | 227 | |
|
228 | 228 | skip_doctest = make_label_dec('skip_doctest', |
|
229 | 229 | """Decorator - mark a function or method for skipping its doctest. |
|
230 | 230 | |
|
231 | 231 | This decorator allows you to mark a function whose docstring you wish to |
|
232 | 232 | omit from testing, while preserving the docstring for introspection, help, |
|
233 | 233 | etc.""") |
|
234 | 234 | |
|
235 | 235 | # Decorators to skip certain tests on specific platforms. |
|
236 | 236 | skip_win32 = skipif(sys.platform=='win32', |
|
237 | 237 | "This test does not run under Windows") |
|
238 | 238 | skip_linux = skipif(sys.platform=='linux2',"This test does not run under Linux") |
|
239 | 239 | skip_osx = skipif(sys.platform=='darwin',"This test does not run under OS X") |
|
240 | 240 | |
|
241 | 241 | |
|
242 | 242 | skipif_not_numpy = skipif(numpy_not_available,"This test requires numpy") |
|
243 | 243 | |
|
244 | 244 | skipknownfailure = skip('This test is known to fail') |
@@ -1,97 +1,97 | |||
|
1 | 1 | """Decorators for labeling test objects |
|
2 | 2 | |
|
3 | 3 | Decorators that merely return a modified version of the original |
|
4 | 4 | function object are straightforward. Decorators that return a new |
|
5 | 5 | function object need to use |
|
6 | 6 | nose.tools.make_decorator(original_function)(decorator) in returning |
|
7 | 7 | the decorator, in order to preserve metadata such as function name, |
|
8 | 8 | setup and teardown functions and so on - see nose.tools for more |
|
9 | 9 | information. |
|
10 | 10 | |
|
11 | 11 | """ |
|
12 | 12 | |
|
13 | 13 | def slow(t): |
|
14 | 14 | """Labels a test as 'slow'. |
|
15 | 15 | |
|
16 | 16 | The exact definition of a slow test is obviously both subjective and |
|
17 | 17 | hardware-dependent, but in general any individual test that requires more |
|
18 | 18 | than a second or two should be labeled as slow (the whole suite consits of |
|
19 | 19 | thousands of tests, so even a second is significant).""" |
|
20 | 20 | |
|
21 | 21 | t.slow = True |
|
22 | 22 | return t |
|
23 | 23 | |
|
24 | 24 | def setastest(tf=True): |
|
25 | 25 | ''' Signals to nose that this function is or is not a test |
|
26 | 26 | |
|
27 | 27 | Parameters |
|
28 | 28 | ---------- |
|
29 | 29 | tf : bool |
|
30 | 30 | If True specifies this is a test, not a test otherwise |
|
31 | 31 | |
|
32 | 32 | e.g |
|
33 | 33 | >>> from numpy.testing.decorators import setastest |
|
34 | 34 | >>> @setastest(False) |
|
35 | 35 | ... def func_with_test_in_name(arg1, arg2): pass |
|
36 | 36 | ... |
|
37 | 37 | >>> |
|
38 | 38 | |
|
39 | 39 | This decorator cannot use the nose namespace, because it can be |
|
40 | 40 | called from a non-test module. See also istest and nottest in |
|
41 | 41 | nose.tools |
|
42 | 42 | |
|
43 | 43 | ''' |
|
44 | 44 | def set_test(t): |
|
45 | 45 | t.__test__ = tf |
|
46 | 46 | return t |
|
47 | 47 | return set_test |
|
48 | 48 | |
|
49 | 49 | def skipif(skip_condition=True, msg=None): |
|
50 | 50 | ''' Make function raise SkipTest exception if skip_condition is true |
|
51 | 51 | |
|
52 | 52 | Parameters |
|
53 | --------- | |
|
53 | ---------- | |
|
54 | 54 | skip_condition : bool or callable. |
|
55 | 55 | Flag to determine whether to skip test. If the condition is a |
|
56 | 56 | callable, it is used at runtime to dynamically make the decision. This |
|
57 | 57 | is useful for tests that may require costly imports, to delay the cost |
|
58 | 58 | until the test suite is actually executed. |
|
59 | 59 | msg : string |
|
60 | 60 | Message to give on raising a SkipTest exception |
|
61 | 61 | |
|
62 | 62 | Returns |
|
63 | 63 | ------- |
|
64 | 64 | decorator : function |
|
65 | 65 | Decorator, which, when applied to a function, causes SkipTest |
|
66 | 66 | to be raised when the skip_condition was True, and the function |
|
67 | 67 | to be called normally otherwise. |
|
68 | 68 | |
|
69 | 69 | Notes |
|
70 | 70 | ----- |
|
71 | 71 | You will see from the code that we had to further decorate the |
|
72 | 72 | decorator with the nose.tools.make_decorator function in order to |
|
73 | 73 | transmit function name, and various other metadata. |
|
74 | 74 | ''' |
|
75 | 75 | if msg is None: |
|
76 | 76 | msg = 'Test skipped due to test condition' |
|
77 | 77 | def skip_decorator(f): |
|
78 | 78 | # Local import to avoid a hard nose dependency and only incur the |
|
79 | 79 | # import time overhead at actual test-time. |
|
80 | 80 | import nose |
|
81 | 81 | def skipper(*args, **kwargs): |
|
82 | 82 | if skip_condition: |
|
83 | 83 | raise nose.SkipTest, msg |
|
84 | 84 | else: |
|
85 | 85 | return f(*args, **kwargs) |
|
86 | 86 | return nose.tools.make_decorator(f)(skipper) |
|
87 | 87 | return skip_decorator |
|
88 | 88 | |
|
89 | 89 | def skipknownfailure(f): |
|
90 | 90 | ''' Decorator to raise SkipTest for test known to fail |
|
91 | 91 | ''' |
|
92 | 92 | # Local import to avoid a hard nose dependency and only incur the |
|
93 | 93 | # import time overhead at actual test-time. |
|
94 | 94 | import nose |
|
95 | 95 | def skipper(*args, **kwargs): |
|
96 | 96 | raise nose.SkipTest, 'This test is known to fail' |
|
97 | 97 | return nose.tools.make_decorator(f)(skipper) |
@@ -1,86 +1,91 | |||
|
1 | 1 | # Makefile for Sphinx documentation |
|
2 | 2 | # |
|
3 | 3 | |
|
4 | 4 | # You can set these variables from the command line. |
|
5 | 5 | SPHINXOPTS = |
|
6 | 6 | SPHINXBUILD = sphinx-build |
|
7 | 7 | PAPER = |
|
8 | SRCDIR = source | |
|
8 | 9 | |
|
9 | 10 | # Internal variables. |
|
10 | 11 | PAPEROPT_a4 = -D latex_paper_size=a4 |
|
11 | 12 | PAPEROPT_letter = -D latex_paper_size=letter |
|
12 |
ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) |
|
|
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 | 17 | help: |
|
17 | 18 | @echo "Please use \`make <target>' where <target> is one of" |
|
18 | 19 | @echo " html to make standalone HTML files" |
|
19 | 20 | @echo " pickle to make pickle files (usable by e.g. sphinx-web)" |
|
20 | 21 | @echo " htmlhelp to make HTML files and a HTML help project" |
|
21 | 22 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" |
|
22 | 23 | @echo " changes to make an overview over all changed/added/deprecated items" |
|
23 | 24 | @echo " linkcheck to check all external links for integrity" |
|
24 | 25 | @echo |
|
25 | 26 | @echo "Compound utility targets:" |
|
26 | 27 | @echo "pdf latex and then runs the PDF generation" |
|
27 | 28 | @echo "all html and pdf" |
|
28 | 29 | @echo "dist all, and then puts the results in dist/" |
|
29 | 30 | |
|
30 | 31 | clean: |
|
31 | -rm -rf build/* dist/* | |
|
32 | -rm -rf build/* dist/* $(SRCDIR)/api/generated | |
|
32 | 33 | |
|
33 | 34 | pdf: latex |
|
34 | 35 | cd build/latex && make all-pdf |
|
35 | 36 | |
|
36 | 37 | all: html pdf |
|
37 | 38 | |
|
38 | 39 | dist: clean all |
|
39 | 40 | mkdir -p dist |
|
40 | 41 | ln build/latex/ipython.pdf dist/ |
|
41 | 42 | cp -al build/html dist/ |
|
42 | 43 | @echo "Build finished. Final docs are in dist/" |
|
43 | 44 | |
|
44 | html: | |
|
45 | html: api | |
|
45 | 46 | mkdir -p build/html build/doctrees |
|
46 | 47 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html |
|
47 | 48 | @echo |
|
48 | 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 | 55 | pickle: |
|
51 | 56 | mkdir -p build/pickle build/doctrees |
|
52 | 57 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle |
|
53 | 58 | @echo |
|
54 | 59 | @echo "Build finished; now you can process the pickle files or run" |
|
55 | 60 | @echo " sphinx-web build/pickle" |
|
56 | 61 | @echo "to start the sphinx-web server." |
|
57 | 62 | |
|
58 | 63 | web: pickle |
|
59 | 64 | |
|
60 | 65 | htmlhelp: |
|
61 | 66 | mkdir -p build/htmlhelp build/doctrees |
|
62 | 67 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp |
|
63 | 68 | @echo |
|
64 | 69 | @echo "Build finished; now you can run HTML Help Workshop with the" \ |
|
65 | 70 | ".hhp project file in build/htmlhelp." |
|
66 | 71 | |
|
67 | 72 | latex: |
|
68 | 73 | mkdir -p build/latex build/doctrees |
|
69 | 74 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex |
|
70 | 75 | @echo |
|
71 | 76 | @echo "Build finished; the LaTeX files are in build/latex." |
|
72 | 77 | @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ |
|
73 | 78 | "run these through (pdf)latex." |
|
74 | 79 | |
|
75 | 80 | changes: |
|
76 | 81 | mkdir -p build/changes build/doctrees |
|
77 | 82 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes |
|
78 | 83 | @echo |
|
79 | 84 | @echo "The overview file is in build/changes." |
|
80 | 85 | |
|
81 | 86 | linkcheck: |
|
82 | 87 | mkdir -p build/linkcheck build/doctrees |
|
83 | 88 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck |
|
84 | 89 | @echo |
|
85 | 90 | @echo "Link check complete; look for any errors in the above output " \ |
|
86 | 91 | "or in build/linkcheck/output.txt." |
@@ -1,187 +1,191 | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | # |
|
3 | 3 | # IPython documentation build configuration file. |
|
4 | 4 | |
|
5 | 5 | # NOTE: This file has been edited manually from the auto-generated one from |
|
6 | 6 | # sphinx. Do NOT delete and re-generate. If any changes from sphinx are |
|
7 | 7 | # needed, generate a scratch one and merge by hand any new fields needed. |
|
8 | 8 | |
|
9 | 9 | # |
|
10 | 10 | # This file is execfile()d with the current directory set to its containing dir. |
|
11 | 11 | # |
|
12 | 12 | # The contents of this file are pickled, so don't put values in the namespace |
|
13 | 13 | # that aren't pickleable (module imports are okay, they're removed automatically). |
|
14 | 14 | # |
|
15 | 15 | # All configuration values have a default value; values that are commented out |
|
16 | 16 | # serve to show the default value. |
|
17 | 17 | |
|
18 | 18 | import sys, os |
|
19 | 19 | |
|
20 | 20 | # If your extensions are in another directory, add it here. If the directory |
|
21 | 21 | # is relative to the documentation root, use os.path.abspath to make it |
|
22 | 22 | # absolute, like shown here. |
|
23 | 23 | sys.path.append(os.path.abspath('../sphinxext')) |
|
24 | 24 | |
|
25 | 25 | # Import support for ipython console session syntax highlighting (lives |
|
26 | 26 | # in the sphinxext directory defined above) |
|
27 | 27 | import ipython_console_highlighting |
|
28 | 28 | |
|
29 | 29 | # We load the ipython release info into a dict by explicit execution |
|
30 | 30 | iprelease = {} |
|
31 | 31 | execfile('../../IPython/Release.py',iprelease) |
|
32 | 32 | |
|
33 | 33 | # General configuration |
|
34 | 34 | # --------------------- |
|
35 | 35 | |
|
36 | 36 | # Add any Sphinx extension module names here, as strings. They can be extensions |
|
37 | 37 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. |
|
38 | 38 | extensions = ['sphinx.ext.autodoc', |
|
39 | 'inheritance_diagram', 'only_directives', | |
|
39 | 'sphinx.ext.doctest', | |
|
40 | ||
|
41 | 'only_directives', | |
|
42 | 'inheritance_diagram', | |
|
40 | 43 | 'ipython_console_highlighting', |
|
41 | 44 | # 'plot_directive', # disabled for now, needs matplotlib |
|
45 | 'numpydoc', # to preprocess docstrings | |
|
42 | 46 | ] |
|
43 | 47 | |
|
44 | 48 | # Add any paths that contain templates here, relative to this directory. |
|
45 | 49 | templates_path = ['_templates'] |
|
46 | 50 | |
|
47 | 51 | # The suffix of source filenames. |
|
48 | 52 | source_suffix = '.txt' |
|
49 | 53 | |
|
50 | 54 | # The master toctree document. |
|
51 | 55 | master_doc = 'index' |
|
52 | 56 | |
|
53 | 57 | # General substitutions. |
|
54 | 58 | project = 'IPython' |
|
55 | 59 | copyright = '2008, The IPython Development Team' |
|
56 | 60 | |
|
57 | 61 | # The default replacements for |version| and |release|, also used in various |
|
58 | 62 | # other places throughout the built documents. |
|
59 | 63 | # |
|
60 | 64 | # The full version, including alpha/beta/rc tags. |
|
61 | 65 | release = iprelease['version'] |
|
62 | 66 | # The short X.Y version. |
|
63 | 67 | version = '.'.join(release.split('.',2)[:2]) |
|
64 | 68 | |
|
65 | 69 | |
|
66 | 70 | # There are two options for replacing |today|: either, you set today to some |
|
67 | 71 | # non-false value, then it is used: |
|
68 | 72 | #today = '' |
|
69 | 73 | # Else, today_fmt is used as the format for a strftime call. |
|
70 | 74 | today_fmt = '%B %d, %Y' |
|
71 | 75 | |
|
72 | 76 | # List of documents that shouldn't be included in the build. |
|
73 | 77 | #unused_docs = [] |
|
74 | 78 | |
|
75 | 79 | # List of directories, relative to source directories, that shouldn't be searched |
|
76 | 80 | # for source files. |
|
77 | 81 | exclude_dirs = ['attic'] |
|
78 | 82 | |
|
79 | 83 | # If true, '()' will be appended to :func: etc. cross-reference text. |
|
80 | 84 | #add_function_parentheses = True |
|
81 | 85 | |
|
82 | 86 | # If true, the current module name will be prepended to all description |
|
83 | 87 | # unit titles (such as .. function::). |
|
84 | 88 | #add_module_names = True |
|
85 | 89 | |
|
86 | 90 | # If true, sectionauthor and moduleauthor directives will be shown in the |
|
87 | 91 | # output. They are ignored by default. |
|
88 | 92 | #show_authors = False |
|
89 | 93 | |
|
90 | 94 | # The name of the Pygments (syntax highlighting) style to use. |
|
91 | 95 | pygments_style = 'sphinx' |
|
92 | 96 | |
|
93 | 97 | |
|
94 | 98 | # Options for HTML output |
|
95 | 99 | # ----------------------- |
|
96 | 100 | |
|
97 | 101 | # The style sheet to use for HTML and HTML Help pages. A file of that name |
|
98 | 102 | # must exist either in Sphinx' static/ path, or in one of the custom paths |
|
99 | 103 | # given in html_static_path. |
|
100 | 104 | html_style = 'default.css' |
|
101 | 105 | |
|
102 | 106 | # The name for this set of Sphinx documents. If None, it defaults to |
|
103 | 107 | # "<project> v<release> documentation". |
|
104 | 108 | #html_title = None |
|
105 | 109 | |
|
106 | 110 | # The name of an image file (within the static path) to place at the top of |
|
107 | 111 | # the sidebar. |
|
108 | 112 | #html_logo = None |
|
109 | 113 | |
|
110 | 114 | # Add any paths that contain custom static files (such as style sheets) here, |
|
111 | 115 | # relative to this directory. They are copied after the builtin static files, |
|
112 | 116 | # so a file named "default.css" will overwrite the builtin "default.css". |
|
113 | 117 | html_static_path = ['_static'] |
|
114 | 118 | |
|
115 | 119 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, |
|
116 | 120 | # using the given strftime format. |
|
117 | 121 | html_last_updated_fmt = '%b %d, %Y' |
|
118 | 122 | |
|
119 | 123 | # If true, SmartyPants will be used to convert quotes and dashes to |
|
120 | 124 | # typographically correct entities. |
|
121 | 125 | #html_use_smartypants = True |
|
122 | 126 | |
|
123 | 127 | # Custom sidebar templates, maps document names to template names. |
|
124 | 128 | #html_sidebars = {} |
|
125 | 129 | |
|
126 | 130 | # Additional templates that should be rendered to pages, maps page names to |
|
127 | 131 | # template names. |
|
128 | 132 | #html_additional_pages = {} |
|
129 | 133 | |
|
130 | 134 | # If false, no module index is generated. |
|
131 | 135 | #html_use_modindex = True |
|
132 | 136 | |
|
133 | 137 | # If true, the reST sources are included in the HTML build as _sources/<name>. |
|
134 | 138 | #html_copy_source = True |
|
135 | 139 | |
|
136 | 140 | # If true, an OpenSearch description file will be output, and all pages will |
|
137 | 141 | # contain a <link> tag referring to it. The value of this option must be the |
|
138 | 142 | # base URL from which the finished HTML is served. |
|
139 | 143 | #html_use_opensearch = '' |
|
140 | 144 | |
|
141 | 145 | # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). |
|
142 | 146 | #html_file_suffix = '' |
|
143 | 147 | |
|
144 | 148 | # Output file base name for HTML help builder. |
|
145 | 149 | htmlhelp_basename = 'ipythondoc' |
|
146 | 150 | |
|
147 | 151 | |
|
148 | 152 | # Options for LaTeX output |
|
149 | 153 | # ------------------------ |
|
150 | 154 | |
|
151 | 155 | # The paper size ('letter' or 'a4'). |
|
152 | 156 | latex_paper_size = 'letter' |
|
153 | 157 | |
|
154 | 158 | # The font size ('10pt', '11pt' or '12pt'). |
|
155 | 159 | latex_font_size = '11pt' |
|
156 | 160 | |
|
157 | 161 | # Grouping the document tree into LaTeX files. List of tuples |
|
158 | 162 | # (source start file, target name, title, author, document class [howto/manual]). |
|
159 | 163 | |
|
160 | 164 | latex_documents = [ ('index', 'ipython.tex', 'IPython Documentation', |
|
161 | 165 | ur"""The IPython Development Team""", |
|
162 | 166 | 'manual'), |
|
163 | 167 | ] |
|
164 | 168 | |
|
165 | 169 | # The name of an image file (relative to this directory) to place at the top of |
|
166 | 170 | # the title page. |
|
167 | 171 | #latex_logo = None |
|
168 | 172 | |
|
169 | 173 | # For "manual" documents, if this is true, then toplevel headings are parts, |
|
170 | 174 | # not chapters. |
|
171 | 175 | #latex_use_parts = False |
|
172 | 176 | |
|
173 | 177 | # Additional stuff for the LaTeX preamble. |
|
174 | 178 | #latex_preamble = '' |
|
175 | 179 | |
|
176 | 180 | # Documents to append as an appendix to all manuals. |
|
177 | 181 | #latex_appendices = [] |
|
178 | 182 | |
|
179 | 183 | # If false, no module index is generated. |
|
180 | 184 | #latex_use_modindex = True |
|
181 | 185 | |
|
182 | 186 | |
|
183 | 187 | # Cleanup |
|
184 | 188 | # ------- |
|
185 | 189 | # delete release info to avoid pickling errors from sphinx |
|
186 | 190 | |
|
187 | 191 | del iprelease |
@@ -1,32 +1,33 | |||
|
1 | 1 | ===================== |
|
2 | 2 | IPython Documentation |
|
3 | 3 | ===================== |
|
4 | 4 | |
|
5 | 5 | .. htmlonly:: |
|
6 | 6 | |
|
7 | 7 | :Release: |release| |
|
8 | 8 | :Date: |today| |
|
9 | 9 | |
|
10 | 10 | Contents: |
|
11 | 11 | |
|
12 | 12 | .. toctree:: |
|
13 | 13 | :maxdepth: 2 |
|
14 | 14 | |
|
15 | 15 | overview.txt |
|
16 | 16 | install/index.txt |
|
17 | 17 | interactive/index.txt |
|
18 | 18 | parallel/index.txt |
|
19 | 19 | config/index.txt |
|
20 | changes.txt | |
|
21 | development/index.txt | |
|
22 | 20 | faq.txt |
|
23 | 21 | history.txt |
|
22 | changes.txt | |
|
23 | development/index.txt | |
|
24 | api/index.txt | |
|
24 | 25 | license_and_copyright.txt |
|
25 | 26 | credits.txt |
|
26 | 27 | |
|
27 | 28 | |
|
28 | 29 | .. htmlonly:: |
|
29 | 30 | |
|
30 | 31 | * :ref:`genindex` |
|
31 | 32 | * :ref:`modindex` |
|
32 | 33 | * :ref:`search` |
This diff has been collapsed as it changes many lines, (1571 lines changed) Show them Hide them | |||
@@ -1,3162 +1,1599 | |||
|
1 | 1 | .. IPython documentation master file, created by sphinx-quickstart.py on Mon Mar 24 17:01:34 2008. |
|
2 | 2 | You can adapt this file completely to your liking, but it should at least |
|
3 | 3 | contain the root 'toctree' directive. |
|
4 | 4 | |
|
5 | 5 | ================= |
|
6 | 6 | IPython reference |
|
7 | 7 | ================= |
|
8 | 8 | |
|
9 | 9 | .. contents:: |
|
10 | 10 | |
|
11 | 11 | .. _command_line_options: |
|
12 | 12 | |
|
13 | 13 | Command-line usage |
|
14 | 14 | ================== |
|
15 | 15 | |
|
16 | 16 | You start IPython with the command:: |
|
17 | 17 | |
|
18 | 18 | $ ipython [options] files |
|
19 | 19 | |
|
20 | 20 | If invoked with no options, it executes all the files listed in sequence |
|
21 | 21 | and drops you into the interpreter while still acknowledging any options |
|
22 | 22 | you may have set in your ipythonrc file. This behavior is different from |
|
23 | 23 | standard Python, which when called as python -i will only execute one |
|
24 | 24 | file and ignore your configuration setup. |
|
25 | 25 | |
|
26 | 26 | Please note that some of the configuration options are not available at |
|
27 | 27 | the command line, simply because they are not practical here. Look into |
|
28 | 28 | your ipythonrc configuration file for details on those. This file |
|
29 | 29 | typically installed in the $HOME/.ipython directory. For Windows users, |
|
30 | 30 | $HOME resolves to C:\\Documents and Settings\\YourUserName in most |
|
31 | 31 | instances. In the rest of this text, we will refer to this directory as |
|
32 | 32 | IPYTHONDIR. |
|
33 | 33 | |
|
34 | 34 | .. _Threading options: |
|
35 | 35 | |
|
36 | 36 | |
|
37 | 37 | Special Threading Options |
|
38 | 38 | ------------------------- |
|
39 | 39 | |
|
40 | 40 | The following special options are ONLY valid at the beginning of the |
|
41 | 41 | command line, and not later. This is because they control the initial- |
|
42 | 42 | ization of ipython itself, before the normal option-handling mechanism |
|
43 | 43 | is active. |
|
44 | 44 | |
|
45 | 45 | -gthread, -qthread, -q4thread, -wthread, -pylab: |
|
46 | 46 | Only one of these can be given, and it can only be given as |
|
47 | 47 | the first option passed to IPython (it will have no effect in |
|
48 | 48 | any other position). They provide threading support for the |
|
49 | 49 | GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the |
|
50 | 50 | matplotlib library. |
|
51 | 51 | |
|
52 | 52 | With any of the first four options, IPython starts running a |
|
53 | 53 | separate thread for the graphical toolkit's operation, so that |
|
54 | 54 | you can open and control graphical elements from within an |
|
55 | 55 | IPython command line, without blocking. All four provide |
|
56 | 56 | essentially the same functionality, respectively for GTK, Qt3, |
|
57 | 57 | Qt4 and WXWidgets (via their Python interfaces). |
|
58 | 58 | |
|
59 | 59 | Note that with -wthread, you can additionally use the |
|
60 | 60 | -wxversion option to request a specific version of wx to be |
|
61 | 61 | used. This requires that you have the wxversion Python module |
|
62 | 62 | installed, which is part of recent wxPython distributions. |
|
63 | 63 | |
|
64 | 64 | If -pylab is given, IPython loads special support for the mat |
|
65 | 65 | plotlib library (http://matplotlib.sourceforge.net), allowing |
|
66 | 66 | interactive usage of any of its backends as defined in the |
|
67 | 67 | user's ~/.matplotlib/matplotlibrc file. It automatically |
|
68 | 68 | activates GTK, Qt or WX threading for IPyhton if the choice of |
|
69 | 69 | matplotlib backend requires it. It also modifies the %run |
|
70 | 70 | command to correctly execute (without blocking) any |
|
71 | 71 | matplotlib-based script which calls show() at the end. |
|
72 | 72 | |
|
73 | 73 | -tk |
|
74 | 74 | The -g/q/q4/wthread options, and -pylab (if matplotlib is |
|
75 | 75 | configured to use GTK, Qt3, Qt4 or WX), will normally block Tk |
|
76 | 76 | graphical interfaces. This means that when either GTK, Qt or WX |
|
77 | 77 | threading is active, any attempt to open a Tk GUI will result in a |
|
78 | 78 | dead window, and possibly cause the Python interpreter to crash. |
|
79 | 79 | An extra option, -tk, is available to address this issue. It can |
|
80 | 80 | only be given as a second option after any of the above (-gthread, |
|
81 | 81 | -wthread or -pylab). |
|
82 | 82 | |
|
83 | 83 | If -tk is given, IPython will try to coordinate Tk threading |
|
84 | 84 | with GTK, Qt or WX. This is however potentially unreliable, and |
|
85 | 85 | you will have to test on your platform and Python configuration to |
|
86 | 86 | determine whether it works for you. Debian users have reported |
|
87 | 87 | success, apparently due to the fact that Debian builds all of Tcl, |
|
88 | 88 | Tk, Tkinter and Python with pthreads support. Under other Linux |
|
89 | 89 | environments (such as Fedora Core 2/3), this option has caused |
|
90 | 90 | random crashes and lockups of the Python interpreter. Under other |
|
91 | 91 | operating systems (Mac OSX and Windows), you'll need to try it to |
|
92 | 92 | find out, since currently no user reports are available. |
|
93 | 93 | |
|
94 | 94 | There is unfortunately no way for IPython to determine at run time |
|
95 | 95 | whether -tk will work reliably or not, so you will need to do some |
|
96 | 96 | experiments before relying on it for regular work. |
|
97 | 97 | |
|
98 | 98 | |
|
99 | 99 | |
|
100 | 100 | Regular Options |
|
101 | 101 | --------------- |
|
102 | 102 | |
|
103 | 103 | After the above threading options have been given, regular options can |
|
104 | 104 | follow in any order. All options can be abbreviated to their shortest |
|
105 | 105 | non-ambiguous form and are case-sensitive. One or two dashes can be |
|
106 | 106 | used. Some options have an alternate short form, indicated after a ``|``. |
|
107 | 107 | |
|
108 | 108 | Most options can also be set from your ipythonrc configuration file. See |
|
109 | 109 | the provided example for more details on what the options do. Options |
|
110 | 110 | given at the command line override the values set in the ipythonrc file. |
|
111 | 111 | |
|
112 | 112 | All options with a [no] prepended can be specified in negated form |
|
113 | 113 | (-nooption instead of -option) to turn the feature off. |
|
114 | 114 | |
|
115 | 115 | -help print a help message and exit. |
|
116 | 116 | |
|
117 | 117 | -pylab |
|
118 | 118 | this can only be given as the first option passed to IPython |
|
119 | 119 | (it will have no effect in any other position). It adds |
|
120 | 120 | special support for the matplotlib library |
|
121 | 121 | (http://matplotlib.sourceforge.ne), allowing interactive usage |
|
122 | 122 | of any of its backends as defined in the user's .matplotlibrc |
|
123 | 123 | file. It automatically activates GTK or WX threading for |
|
124 | 124 | IPyhton if the choice of matplotlib backend requires it. It |
|
125 | 125 | also modifies the %run command to correctly execute (without |
|
126 | 126 | blocking) any matplotlib-based script which calls show() at |
|
127 | 127 | the end. See `Matplotlib support`_ for more details. |
|
128 | 128 | |
|
129 | 129 | -autocall <val> |
|
130 | 130 | Make IPython automatically call any callable object even if you |
|
131 | 131 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
132 | 132 | 'str(43)' automatically. The value can be '0' to disable the feature, |
|
133 | 133 | '1' for smart autocall, where it is not applied if there are no more |
|
134 | 134 | arguments on the line, and '2' for full autocall, where all callable |
|
135 | 135 | objects are automatically called (even if no arguments are |
|
136 | 136 | present). The default is '1'. |
|
137 | 137 | |
|
138 | 138 | -[no]autoindent |
|
139 | 139 | Turn automatic indentation on/off. |
|
140 | 140 | |
|
141 | 141 | -[no]automagic |
|
142 | 142 | make magic commands automatic (without needing their first character |
|
143 | 143 | to be %). Type %magic at the IPython prompt for more information. |
|
144 | 144 | |
|
145 | 145 | -[no]autoedit_syntax |
|
146 | 146 | When a syntax error occurs after editing a file, automatically |
|
147 | 147 | open the file to the trouble causing line for convenient |
|
148 | 148 | fixing. |
|
149 | 149 | |
|
150 | 150 | -[no]banner Print the initial information banner (default on). |
|
151 | 151 | |
|
152 | 152 | -c <command> |
|
153 | 153 | execute the given command string. This is similar to the -c |
|
154 | 154 | option in the normal Python interpreter. |
|
155 | 155 | |
|
156 | 156 | -cache_size, cs <n> |
|
157 | 157 | size of the output cache (maximum number of entries to hold in |
|
158 | 158 | memory). The default is 1000, you can change it permanently in your |
|
159 | 159 | config file. Setting it to 0 completely disables the caching system, |
|
160 | 160 | and the minimum value accepted is 20 (if you provide a value less than |
|
161 | 161 | 20, it is reset to 0 and a warning is issued) This limit is defined |
|
162 | 162 | because otherwise you'll spend more time re-flushing a too small cache |
|
163 | 163 | than working. |
|
164 | 164 | |
|
165 | 165 | -classic, cl |
|
166 | 166 | Gives IPython a similar feel to the classic Python |
|
167 | 167 | prompt. |
|
168 | 168 | |
|
169 | 169 | -colors <scheme> |
|
170 | 170 | Color scheme for prompts and exception reporting. Currently |
|
171 | 171 | implemented: NoColor, Linux and LightBG. |
|
172 | 172 | |
|
173 | 173 | -[no]color_info |
|
174 | 174 | IPython can display information about objects via a set of functions, |
|
175 | 175 | and optionally can use colors for this, syntax highlighting source |
|
176 | 176 | code and various other elements. However, because this information is |
|
177 | 177 | passed through a pager (like 'less') and many pagers get confused with |
|
178 | 178 | color codes, this option is off by default. You can test it and turn |
|
179 | 179 | it on permanently in your ipythonrc file if it works for you. As a |
|
180 | 180 | reference, the 'less' pager supplied with Mandrake 8.2 works ok, but |
|
181 | 181 | that in RedHat 7.2 doesn't. |
|
182 | 182 | |
|
183 | 183 | Test it and turn it on permanently if it works with your |
|
184 | 184 | system. The magic function %color_info allows you to toggle this |
|
185 | 185 | interactively for testing. |
|
186 | 186 | |
|
187 | 187 | -[no]debug |
|
188 | 188 | Show information about the loading process. Very useful to pin down |
|
189 | 189 | problems with your configuration files or to get details about |
|
190 | 190 | session restores. |
|
191 | 191 | |
|
192 | 192 | -[no]deep_reload: |
|
193 | 193 | IPython can use the deep_reload module which reloads changes in |
|
194 | 194 | modules recursively (it replaces the reload() function, so you don't |
|
195 | 195 | need to change anything to use it). deep_reload() forces a full |
|
196 | 196 | reload of modules whose code may have changed, which the default |
|
197 | 197 | reload() function does not. |
|
198 | 198 | |
|
199 | 199 | When deep_reload is off, IPython will use the normal reload(), |
|
200 | 200 | but deep_reload will still be available as dreload(). This |
|
201 | 201 | feature is off by default [which means that you have both |
|
202 | 202 | normal reload() and dreload()]. |
|
203 | 203 | |
|
204 | 204 | -editor <name> |
|
205 | 205 | Which editor to use with the %edit command. By default, |
|
206 | 206 | IPython will honor your EDITOR environment variable (if not |
|
207 | 207 | set, vi is the Unix default and notepad the Windows one). |
|
208 | 208 | Since this editor is invoked on the fly by IPython and is |
|
209 | 209 | meant for editing small code snippets, you may want to use a |
|
210 | 210 | small, lightweight editor here (in case your default EDITOR is |
|
211 | 211 | something like Emacs). |
|
212 | 212 | |
|
213 | 213 | -ipythondir <name> |
|
214 | 214 | name of your IPython configuration directory IPYTHONDIR. This |
|
215 | 215 | can also be specified through the environment variable |
|
216 | 216 | IPYTHONDIR. |
|
217 | 217 | |
|
218 | 218 | -log, l |
|
219 | 219 | generate a log file of all input. The file is named |
|
220 | 220 | ipython_log.py in your current directory (which prevents logs |
|
221 | 221 | from multiple IPython sessions from trampling each other). You |
|
222 | 222 | can use this to later restore a session by loading your |
|
223 | 223 | logfile as a file to be executed with option -logplay (see |
|
224 | 224 | below). |
|
225 | 225 | |
|
226 | 226 | -logfile, lf <name> specify the name of your logfile. |
|
227 | 227 | |
|
228 | 228 | -logplay, lp <name> |
|
229 | 229 | |
|
230 | 230 | you can replay a previous log. For restoring a session as close as |
|
231 | 231 | possible to the state you left it in, use this option (don't just run |
|
232 | 232 | the logfile). With -logplay, IPython will try to reconstruct the |
|
233 | 233 | previous working environment in full, not just execute the commands in |
|
234 | 234 | the logfile. |
|
235 | 235 | |
|
236 | 236 | When a session is restored, logging is automatically turned on |
|
237 | 237 | again with the name of the logfile it was invoked with (it is |
|
238 | 238 | read from the log header). So once you've turned logging on for |
|
239 | 239 | a session, you can quit IPython and reload it as many times as |
|
240 | 240 | you want and it will continue to log its history and restore |
|
241 | 241 | from the beginning every time. |
|
242 | 242 | |
|
243 | 243 | Caveats: there are limitations in this option. The history |
|
244 | 244 | variables _i*,_* and _dh don't get restored properly. In the |
|
245 | 245 | future we will try to implement full session saving by writing |
|
246 | 246 | and retrieving a 'snapshot' of the memory state of IPython. But |
|
247 | 247 | our first attempts failed because of inherent limitations of |
|
248 | 248 | Python's Pickle module, so this may have to wait. |
|
249 | 249 | |
|
250 | 250 | -[no]messages |
|
251 | 251 | Print messages which IPython collects about its startup |
|
252 | 252 | process (default on). |
|
253 | 253 | |
|
254 | 254 | -[no]pdb |
|
255 | 255 | Automatically call the pdb debugger after every uncaught |
|
256 | 256 | exception. If you are used to debugging using pdb, this puts |
|
257 | 257 | you automatically inside of it after any call (either in |
|
258 | 258 | IPython or in code called by it) which triggers an exception |
|
259 | 259 | which goes uncaught. |
|
260 | 260 | |
|
261 | 261 | -pydb |
|
262 | 262 | Makes IPython use the third party "pydb" package as debugger, |
|
263 | 263 | instead of pdb. Requires that pydb is installed. |
|
264 | 264 | |
|
265 | 265 | -[no]pprint |
|
266 | 266 | ipython can optionally use the pprint (pretty printer) module |
|
267 | 267 | for displaying results. pprint tends to give a nicer display |
|
268 | 268 | of nested data structures. If you like it, you can turn it on |
|
269 | 269 | permanently in your config file (default off). |
|
270 | 270 | |
|
271 | 271 | -profile, p <name> |
|
272 | 272 | |
|
273 | 273 | assume that your config file is ipythonrc-<name> or |
|
274 | 274 | ipy_profile_<name>.py (looks in current dir first, then in |
|
275 | 275 | IPYTHONDIR). This is a quick way to keep and load multiple |
|
276 | 276 | config files for different tasks, especially if you use the |
|
277 | 277 | include option of config files. You can keep a basic |
|
278 | 278 | IPYTHONDIR/ipythonrc file and then have other 'profiles' which |
|
279 | 279 | include this one and load extra things for particular |
|
280 | 280 | tasks. For example: |
|
281 | 281 | |
|
282 | 282 | 1. $HOME/.ipython/ipythonrc : load basic things you always want. |
|
283 | 283 | 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules. |
|
284 | 284 | 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules. |
|
285 | 285 | |
|
286 | 286 | Since it is possible to create an endless loop by having |
|
287 | 287 | circular file inclusions, IPython will stop if it reaches 15 |
|
288 | 288 | recursive inclusions. |
|
289 | 289 | |
|
290 | 290 | -prompt_in1, pi1 <string> |
|
291 | 291 | |
|
292 | 292 | Specify the string used for input prompts. Note that if you are using |
|
293 | 293 | numbered prompts, the number is represented with a '\#' in the |
|
294 | 294 | string. Don't forget to quote strings with spaces embedded in |
|
295 | 295 | them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>` |
|
296 | 296 | discusses in detail all the available escapes to customize your |
|
297 | 297 | prompts. |
|
298 | 298 | |
|
299 | 299 | -prompt_in2, pi2 <string> |
|
300 | 300 | Similar to the previous option, but used for the continuation |
|
301 | 301 | prompts. The special sequence '\D' is similar to '\#', but |
|
302 | 302 | with all digits replaced dots (so you can have your |
|
303 | 303 | continuation prompt aligned with your input prompt). Default: |
|
304 | 304 | ' .\D.:' (note three spaces at the start for alignment with |
|
305 | 305 | 'In [\#]'). |
|
306 | 306 | |
|
307 | 307 | -prompt_out,po <string> |
|
308 | 308 | String used for output prompts, also uses numbers like |
|
309 | 309 | prompt_in1. Default: 'Out[\#]:' |
|
310 | 310 | |
|
311 | 311 | -quick start in bare bones mode (no config file loaded). |
|
312 | 312 | |
|
313 | 313 | -rcfile <name> |
|
314 | 314 | name of your IPython resource configuration file. Normally |
|
315 | 315 | IPython loads ipythonrc (from current directory) or |
|
316 | 316 | IPYTHONDIR/ipythonrc. |
|
317 | 317 | |
|
318 | 318 | If the loading of your config file fails, IPython starts with |
|
319 | 319 | a bare bones configuration (no modules loaded at all). |
|
320 | 320 | |
|
321 | 321 | -[no]readline |
|
322 | 322 | use the readline library, which is needed to support name |
|
323 | 323 | completion and command history, among other things. It is |
|
324 | 324 | enabled by default, but may cause problems for users of |
|
325 | 325 | X/Emacs in Python comint or shell buffers. |
|
326 | 326 | |
|
327 | 327 | Note that X/Emacs 'eterm' buffers (opened with M-x term) support |
|
328 | 328 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
329 | 329 | shell and C-c !) buffers do not. |
|
330 | 330 | |
|
331 | 331 | -screen_length, sl <n> |
|
332 | 332 | number of lines of your screen. This is used to control |
|
333 | 333 | printing of very long strings. Strings longer than this number |
|
334 | 334 | of lines will be sent through a pager instead of directly |
|
335 | 335 | printed. |
|
336 | 336 | |
|
337 | 337 | The default value for this is 0, which means IPython will |
|
338 | 338 | auto-detect your screen size every time it needs to print certain |
|
339 | 339 | potentially long strings (this doesn't change the behavior of the |
|
340 | 340 | 'print' keyword, it's only triggered internally). If for some |
|
341 | 341 | reason this isn't working well (it needs curses support), specify |
|
342 | 342 | it yourself. Otherwise don't change the default. |
|
343 | 343 | |
|
344 | 344 | -separate_in, si <string> |
|
345 | 345 | |
|
346 | 346 | separator before input prompts. |
|
347 | 347 | Default: '\n' |
|
348 | 348 | |
|
349 | 349 | -separate_out, so <string> |
|
350 | 350 | separator before output prompts. |
|
351 | 351 | Default: nothing. |
|
352 | 352 | |
|
353 | 353 | -separate_out2, so2 |
|
354 | 354 | separator after output prompts. |
|
355 | 355 | Default: nothing. |
|
356 | 356 | For these three options, use the value 0 to specify no separator. |
|
357 | 357 | |
|
358 | 358 | -nosep |
|
359 | 359 | shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 |
|
360 | 360 | 0'. Simply removes all input/output separators. |
|
361 | 361 | |
|
362 | 362 | -upgrade |
|
363 | 363 | allows you to upgrade your IPYTHONDIR configuration when you |
|
364 | 364 | install a new version of IPython. Since new versions may |
|
365 | 365 | include new command line options or example files, this copies |
|
366 | 366 | updated ipythonrc-type files. However, it backs up (with a |
|
367 | 367 | .old extension) all files which it overwrites so that you can |
|
368 | 368 | merge back any customizations you might have in your personal |
|
369 | 369 | files. Note that you should probably use %upgrade instead, |
|
370 | 370 | it's a safer alternative. |
|
371 | 371 | |
|
372 | 372 | |
|
373 | 373 | -Version print version information and exit. |
|
374 | 374 | |
|
375 | 375 | -wxversion <string> |
|
376 | 376 | Select a specific version of wxPython (used in conjunction |
|
377 | 377 | with -wthread). Requires the wxversion module, part of recent |
|
378 | 378 | wxPython distributions |
|
379 | 379 | |
|
380 | 380 | -xmode <modename> |
|
381 | 381 | |
|
382 | 382 | Mode for exception reporting. |
|
383 | 383 | |
|
384 | 384 | Valid modes: Plain, Context and Verbose. |
|
385 | 385 | |
|
386 | 386 | * Plain: similar to python's normal traceback printing. |
|
387 | 387 | * Context: prints 5 lines of context source code around each |
|
388 | 388 | line in the traceback. |
|
389 | 389 | * Verbose: similar to Context, but additionally prints the |
|
390 | 390 | variables currently visible where the exception happened |
|
391 | 391 | (shortening their strings if too long). This can potentially be |
|
392 | 392 | very slow, if you happen to have a huge data structure whose |
|
393 | 393 | string representation is complex to compute. Your computer may |
|
394 | 394 | appear to freeze for a while with cpu usage at 100%. If this |
|
395 | 395 | occurs, you can cancel the traceback with Ctrl-C (maybe hitting it |
|
396 | 396 | more than once). |
|
397 | 397 | |
|
398 | 398 | Interactive use |
|
399 | 399 | =============== |
|
400 | 400 | |
|
401 | 401 | Warning: IPython relies on the existence of a global variable called |
|
402 | 402 | _ip which controls the shell itself. If you redefine _ip to anything, |
|
403 | 403 | bizarre behavior will quickly occur. |
|
404 | 404 | |
|
405 | 405 | Other than the above warning, IPython is meant to work as a drop-in |
|
406 | 406 | replacement for the standard interactive interpreter. As such, any code |
|
407 | 407 | which is valid python should execute normally under IPython (cases where |
|
408 | 408 | this is not true should be reported as bugs). It does, however, offer |
|
409 | 409 | many features which are not available at a standard python prompt. What |
|
410 | 410 | follows is a list of these. |
|
411 | 411 | |
|
412 | 412 | |
|
413 | 413 | Caution for Windows users |
|
414 | 414 | ------------------------- |
|
415 | 415 | |
|
416 | 416 | Windows, unfortunately, uses the '\' character as a path |
|
417 | 417 | separator. This is a terrible choice, because '\' also represents the |
|
418 | 418 | escape character in most modern programming languages, including |
|
419 | 419 | Python. For this reason, using '/' character is recommended if you |
|
420 | 420 | have problems with ``\``. However, in Windows commands '/' flags |
|
421 | 421 | options, so you can not use it for the root directory. This means that |
|
422 | 422 | paths beginning at the root must be typed in a contrived manner like: |
|
423 | 423 | ``%copy \opt/foo/bar.txt \tmp`` |
|
424 | 424 | |
|
425 | 425 | .. _magic: |
|
426 | 426 | |
|
427 | 427 | Magic command system |
|
428 | 428 | -------------------- |
|
429 | 429 | |
|
430 | 430 | IPython will treat any line whose first character is a % as a special |
|
431 | 431 | call to a 'magic' function. These allow you to control the behavior of |
|
432 | 432 | IPython itself, plus a lot of system-type features. They are all |
|
433 | 433 | prefixed with a % character, but parameters are given without |
|
434 | 434 | parentheses or quotes. |
|
435 | 435 | |
|
436 | 436 | Example: typing '%cd mydir' (without the quotes) changes you working |
|
437 | 437 | directory to 'mydir', if it exists. |
|
438 | 438 | |
|
439 | 439 | If you have 'automagic' enabled (in your ipythonrc file, via the command |
|
440 | 440 | line option -automagic or with the %automagic function), you don't need |
|
441 | 441 | to type in the % explicitly. IPython will scan its internal list of |
|
442 | 442 | magic functions and call one if it exists. With automagic on you can |
|
443 | 443 | then just type 'cd mydir' to go to directory 'mydir'. The automagic |
|
444 | 444 | system has the lowest possible precedence in name searches, so defining |
|
445 | 445 | an identifier with the same name as an existing magic function will |
|
446 | 446 | shadow it for automagic use. You can still access the shadowed magic |
|
447 | 447 | function by explicitly using the % character at the beginning of the line. |
|
448 | 448 | |
|
449 | 449 | An example (with automagic on) should clarify all this:: |
|
450 | 450 | |
|
451 | 451 | In [1]: cd ipython # %cd is called by automagic |
|
452 | 452 | |
|
453 | 453 | /home/fperez/ipython |
|
454 | 454 | |
|
455 | 455 | In [2]: cd=1 # now cd is just a variable |
|
456 | 456 | |
|
457 | 457 | In [3]: cd .. # and doesn't work as a function anymore |
|
458 | 458 | |
|
459 | 459 | ------------------------------ |
|
460 | 460 | |
|
461 | 461 | File "<console>", line 1 |
|
462 | 462 | |
|
463 | 463 | cd .. |
|
464 | 464 | |
|
465 | 465 | ^ |
|
466 | 466 | |
|
467 | 467 | SyntaxError: invalid syntax |
|
468 | 468 | |
|
469 | 469 | In [4]: %cd .. # but %cd always works |
|
470 | 470 | |
|
471 | 471 | /home/fperez |
|
472 | 472 | |
|
473 | 473 | In [5]: del cd # if you remove the cd variable |
|
474 | 474 | |
|
475 | 475 | In [6]: cd ipython # automagic can work again |
|
476 | 476 | |
|
477 | 477 | /home/fperez/ipython |
|
478 | 478 | |
|
479 | 479 | You can define your own magic functions to extend the system. The |
|
480 | 480 | following example defines a new magic command, %impall:: |
|
481 | 481 | |
|
482 | 482 | import IPython.ipapi |
|
483 | 483 | |
|
484 | 484 | ip = IPython.ipapi.get() |
|
485 | 485 | |
|
486 | 486 | def doimp(self, arg): |
|
487 | 487 | |
|
488 | 488 | ip = self.api |
|
489 | 489 | |
|
490 | 490 | ip.ex("import %s; reload(%s); from %s import *" % ( |
|
491 | 491 | |
|
492 | 492 | arg,arg,arg) |
|
493 | 493 | |
|
494 | 494 | ) |
|
495 | 495 | |
|
496 | 496 | ip.expose_magic('impall', doimp) |
|
497 | 497 | |
|
498 | 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 | 503 | will define %cl as a new name for %clear. |
|
504 | 504 | |
|
505 | 505 | Type %magic for more information, including a list of all available |
|
506 | 506 | magic functions at any time and their docstrings. You can also type |
|
507 | 507 | %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for |
|
508 | 508 | information on the '?' system) to get information about any particular |
|
509 | 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 | 515 | Access to the standard Python help |
|
2079 | 516 | ---------------------------------- |
|
2080 | 517 | |
|
2081 | 518 | As of Python 2.1, a help system is available with access to object docstrings |
|
2082 | 519 | and the Python manuals. Simply type 'help' (no quotes) to access it. You can |
|
2083 | 520 | also type help(object) to obtain information about a given object, and |
|
2084 | 521 | help('keyword') for information on a keyword. As noted :ref:`here |
|
2085 | 522 | <accessing_help>`, you need to properly configure your environment variable |
|
2086 | 523 | PYTHONDOCS for this feature to work correctly. |
|
2087 | 524 | |
|
2088 | 525 | .. _dynamic_object_info: |
|
2089 | 526 | |
|
2090 | 527 | Dynamic object information |
|
2091 | 528 | -------------------------- |
|
2092 | 529 | |
|
2093 | 530 | Typing ?word or word? prints detailed information about an object. If |
|
2094 | 531 | certain strings in the object are too long (docstrings, code, etc.) they |
|
2095 | 532 | get snipped in the center for brevity. This system gives access variable |
|
2096 | 533 | types and values, full source code for any object (if available), |
|
2097 | 534 | function prototypes and other useful information. |
|
2098 | 535 | |
|
2099 | 536 | Typing ??word or word?? gives access to the full information without |
|
2100 | 537 | snipping long strings. Long strings are sent to the screen through the |
|
2101 | 538 | less pager if longer than the screen and printed otherwise. On systems |
|
2102 | 539 | lacking the less command, IPython uses a very basic internal pager. |
|
2103 | 540 | |
|
2104 | 541 | The following magic functions are particularly useful for gathering |
|
2105 | 542 | information about your working environment. You can get more details by |
|
2106 | 543 | typing %magic or querying them individually (use %function_name? with or |
|
2107 | 544 | without the %), this is just a summary: |
|
2108 | 545 | |
|
2109 | 546 | * **%pdoc <object>**: Print (or run through a pager if too long) the |
|
2110 | 547 | docstring for an object. If the given object is a class, it will |
|
2111 | 548 | print both the class and the constructor docstrings. |
|
2112 | 549 | * **%pdef <object>**: Print the definition header for any callable |
|
2113 | 550 | object. If the object is a class, print the constructor information. |
|
2114 | 551 | * **%psource <object>**: Print (or run through a pager if too long) |
|
2115 | 552 | the source code for an object. |
|
2116 | 553 | * **%pfile <object>**: Show the entire source file where an object was |
|
2117 | 554 | defined via a pager, opening it at the line where the object |
|
2118 | 555 | definition begins. |
|
2119 | 556 | * **%who/%whos**: These functions give information about identifiers |
|
2120 | 557 | you have defined interactively (not things you loaded or defined |
|
2121 | 558 | in your configuration files). %who just prints a list of |
|
2122 | 559 | identifiers and %whos prints a table with some basic details about |
|
2123 | 560 | each identifier. |
|
2124 | 561 | |
|
2125 | 562 | Note that the dynamic object information functions (?/??, %pdoc, %pfile, |
|
2126 | 563 | %pdef, %psource) give you access to documentation even on things which |
|
2127 | 564 | are not really defined as separate identifiers. Try for example typing |
|
2128 | 565 | {}.get? or after doing import os, type os.path.abspath??. |
|
2129 | 566 | |
|
2130 | 567 | |
|
2131 | 568 | .. _readline: |
|
2132 | 569 | |
|
2133 | 570 | Readline-based features |
|
2134 | 571 | ----------------------- |
|
2135 | 572 | |
|
2136 | 573 | These features require the GNU readline library, so they won't work if |
|
2137 | 574 | your Python installation lacks readline support. We will first describe |
|
2138 | 575 | the default behavior IPython uses, and then how to change it to suit |
|
2139 | 576 | your preferences. |
|
2140 | 577 | |
|
2141 | 578 | |
|
2142 | 579 | Command line completion |
|
2143 | 580 | +++++++++++++++++++++++ |
|
2144 | 581 | |
|
2145 | 582 | At any time, hitting TAB will complete any available python commands or |
|
2146 | 583 | variable names, and show you a list of the possible completions if |
|
2147 | 584 | there's no unambiguous one. It will also complete filenames in the |
|
2148 | 585 | current directory if no python names match what you've typed so far. |
|
2149 | 586 | |
|
2150 | 587 | |
|
2151 | 588 | Search command history |
|
2152 | 589 | ++++++++++++++++++++++ |
|
2153 | 590 | |
|
2154 | 591 | IPython provides two ways for searching through previous input and thus |
|
2155 | 592 | reduce the need for repetitive typing: |
|
2156 | 593 | |
|
2157 | 594 | 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n |
|
2158 | 595 | (next,down) to search through only the history items that match |
|
2159 | 596 | what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank |
|
2160 | 597 | prompt, they just behave like normal arrow keys. |
|
2161 | 598 | 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system |
|
2162 | 599 | searches your history for lines that contain what you've typed so |
|
2163 | 600 | far, completing as much as it can. |
|
2164 | 601 | |
|
2165 | 602 | |
|
2166 | 603 | Persistent command history across sessions |
|
2167 | 604 | ++++++++++++++++++++++++++++++++++++++++++ |
|
2168 | 605 | |
|
2169 | 606 | IPython will save your input history when it leaves and reload it next |
|
2170 | 607 | time you restart it. By default, the history file is named |
|
2171 | 608 | $IPYTHONDIR/history, but if you've loaded a named profile, |
|
2172 | 609 | '-PROFILE_NAME' is appended to the name. This allows you to keep |
|
2173 | 610 | separate histories related to various tasks: commands related to |
|
2174 | 611 | numerical work will not be clobbered by a system shell history, for |
|
2175 | 612 | example. |
|
2176 | 613 | |
|
2177 | 614 | |
|
2178 | 615 | Autoindent |
|
2179 | 616 | ++++++++++ |
|
2180 | 617 | |
|
2181 | 618 | IPython can recognize lines ending in ':' and indent the next line, |
|
2182 | 619 | while also un-indenting automatically after 'raise' or 'return'. |
|
2183 | 620 | |
|
2184 | 621 | This feature uses the readline library, so it will honor your ~/.inputrc |
|
2185 | 622 | configuration (or whatever file your INPUTRC variable points to). Adding |
|
2186 | 623 | the following lines to your .inputrc file can make indenting/unindenting |
|
2187 | 624 | more convenient (M-i indents, M-u unindents):: |
|
2188 | 625 | |
|
2189 | 626 | $if Python |
|
2190 | 627 | "\M-i": " " |
|
2191 | 628 | "\M-u": "\d\d\d\d" |
|
2192 | 629 | $endif |
|
2193 | 630 | |
|
2194 | 631 | Note that there are 4 spaces between the quote marks after "M-i" above. |
|
2195 | 632 | |
|
2196 | 633 | Warning: this feature is ON by default, but it can cause problems with |
|
2197 | 634 | the pasting of multi-line indented code (the pasted code gets |
|
2198 | 635 | re-indented on each line). A magic function %autoindent allows you to |
|
2199 | 636 | toggle it on/off at runtime. You can also disable it permanently on in |
|
2200 | 637 | your ipythonrc file (set autoindent 0). |
|
2201 | 638 | |
|
2202 | 639 | |
|
2203 | 640 | Customizing readline behavior |
|
2204 | 641 | +++++++++++++++++++++++++++++ |
|
2205 | 642 | |
|
2206 | 643 | All these features are based on the GNU readline library, which has an |
|
2207 | 644 | extremely customizable interface. Normally, readline is configured via a |
|
2208 | 645 | file which defines the behavior of the library; the details of the |
|
2209 | 646 | syntax for this can be found in the readline documentation available |
|
2210 | 647 | with your system or on the Internet. IPython doesn't read this file (if |
|
2211 | 648 | it exists) directly, but it does support passing to readline valid |
|
2212 | 649 | options via a simple interface. In brief, you can customize readline by |
|
2213 | 650 | setting the following options in your ipythonrc configuration file (note |
|
2214 | 651 | that these options can not be specified at the command line): |
|
2215 | 652 | |
|
2216 | 653 | * **readline_parse_and_bind**: this option can appear as many times as |
|
2217 | 654 | you want, each time defining a string to be executed via a |
|
2218 | 655 | readline.parse_and_bind() command. The syntax for valid commands |
|
2219 | 656 | of this kind can be found by reading the documentation for the GNU |
|
2220 | 657 | readline library, as these commands are of the kind which readline |
|
2221 | 658 | accepts in its configuration file. |
|
2222 | 659 | * **readline_remove_delims**: a string of characters to be removed |
|
2223 | 660 | from the default word-delimiters list used by readline, so that |
|
2224 | 661 | completions may be performed on strings which contain them. Do not |
|
2225 | 662 | change the default value unless you know what you're doing. |
|
2226 | 663 | * **readline_omit__names**: when tab-completion is enabled, hitting |
|
2227 | 664 | <tab> after a '.' in a name will complete all attributes of an |
|
2228 | 665 | object, including all the special methods whose names include |
|
2229 | 666 | double underscores (like __getitem__ or __class__). If you'd |
|
2230 | 667 | rather not see these names by default, you can set this option to |
|
2231 | 668 | 1. Note that even when this option is set, you can still see those |
|
2232 | 669 | names by explicitly typing a _ after the period and hitting <tab>: |
|
2233 | 670 | 'name._<tab>' will always complete attribute names starting with '_'. |
|
2234 | 671 | |
|
2235 | 672 | This option is off by default so that new users see all |
|
2236 | 673 | attributes of any objects they are dealing with. |
|
2237 | 674 | |
|
2238 | 675 | You will find the default values along with a corresponding detailed |
|
2239 | 676 | explanation in your ipythonrc file. |
|
2240 | 677 | |
|
2241 | 678 | |
|
2242 | 679 | Session logging and restoring |
|
2243 | 680 | ----------------------------- |
|
2244 | 681 | |
|
2245 | 682 | You can log all input from a session either by starting IPython with the |
|
2246 | 683 | command line switches -log or -logfile (see :ref:`here <command_line_options>`) |
|
2247 | 684 | or by activating the logging at any moment with the magic function %logstart. |
|
2248 | 685 | |
|
2249 | 686 | Log files can later be reloaded with the -logplay option and IPython |
|
2250 | 687 | will attempt to 'replay' the log by executing all the lines in it, thus |
|
2251 | 688 | restoring the state of a previous session. This feature is not quite |
|
2252 | 689 | perfect, but can still be useful in many cases. |
|
2253 | 690 | |
|
2254 | 691 | The log files can also be used as a way to have a permanent record of |
|
2255 | 692 | any code you wrote while experimenting. Log files are regular text files |
|
2256 | 693 | which you can later open in your favorite text editor to extract code or |
|
2257 | 694 | to 'clean them up' before using them to replay a session. |
|
2258 | 695 | |
|
2259 | 696 | The %logstart function for activating logging in mid-session is used as |
|
2260 | 697 | follows: |
|
2261 | 698 | |
|
2262 | 699 | %logstart [log_name [log_mode]] |
|
2263 | 700 | |
|
2264 | 701 | If no name is given, it defaults to a file named 'log' in your |
|
2265 | 702 | IPYTHONDIR directory, in 'rotate' mode (see below). |
|
2266 | 703 | |
|
2267 | 704 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
2268 | 705 | history up to that point and then continues logging. |
|
2269 | 706 | |
|
2270 | 707 | %logstart takes a second optional parameter: logging mode. This can be |
|
2271 | 708 | one of (note that the modes are given unquoted): |
|
2272 | 709 | |
|
2273 | 710 | * [over:] overwrite existing log_name. |
|
2274 | 711 | * [backup:] rename (if exists) to log_name~ and start log_name. |
|
2275 | 712 | * [append:] well, that says it. |
|
2276 | 713 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. |
|
2277 | 714 | |
|
2278 | 715 | The %logoff and %logon functions allow you to temporarily stop and |
|
2279 | 716 | resume logging to a file which had previously been started with |
|
2280 | 717 | %logstart. They will fail (with an explanation) if you try to use them |
|
2281 | 718 | before logging has been started. |
|
2282 | 719 | |
|
2283 | 720 | .. _system_shell_access: |
|
2284 | 721 | |
|
2285 | 722 | System shell access |
|
2286 | 723 | ------------------- |
|
2287 | 724 | |
|
2288 | 725 | Any input line beginning with a ! character is passed verbatim (minus |
|
2289 | 726 | the !, of course) to the underlying operating system. For example, |
|
2290 | 727 | typing !ls will run 'ls' in the current directory. |
|
2291 | 728 | |
|
2292 | 729 | Manual capture of command output |
|
2293 | 730 | -------------------------------- |
|
2294 | 731 | |
|
2295 | 732 | If the input line begins with two exclamation marks, !!, the command is |
|
2296 | 733 | executed but its output is captured and returned as a python list, split |
|
2297 | 734 | on newlines. Any output sent by the subprocess to standard error is |
|
2298 | 735 | printed separately, so that the resulting list only captures standard |
|
2299 | 736 | output. The !! syntax is a shorthand for the %sx magic command. |
|
2300 | 737 | |
|
2301 | 738 | Finally, the %sc magic (short for 'shell capture') is similar to %sx, |
|
2302 | 739 | but allowing more fine-grained control of the capture details, and |
|
2303 | 740 | storing the result directly into a named variable. The direct use of |
|
2304 | 741 | %sc is now deprecated, and you should ise the ``var = !cmd`` syntax |
|
2305 | 742 | instead. |
|
2306 | 743 | |
|
2307 | 744 | IPython also allows you to expand the value of python variables when |
|
2308 | 745 | making system calls. Any python variable or expression which you prepend |
|
2309 | 746 | with $ will get expanded before the system call is made:: |
|
2310 | 747 | |
|
2311 | 748 | In [1]: pyvar='Hello world' |
|
2312 | 749 | In [2]: !echo "A python variable: $pyvar" |
|
2313 | 750 | A python variable: Hello world |
|
2314 | 751 | |
|
2315 | 752 | If you want the shell to actually see a literal $, you need to type it |
|
2316 | 753 | twice:: |
|
2317 | 754 | |
|
2318 | 755 | In [3]: !echo "A system variable: $$HOME" |
|
2319 | 756 | A system variable: /home/fperez |
|
2320 | 757 | |
|
2321 | 758 | You can pass arbitrary expressions, though you'll need to delimit them |
|
2322 | 759 | with {} if there is ambiguity as to the extent of the expression:: |
|
2323 | 760 | |
|
2324 | 761 | In [5]: x=10 |
|
2325 | 762 | In [6]: y=20 |
|
2326 | 763 | In [13]: !echo $x+y |
|
2327 | 764 | 10+y |
|
2328 | 765 | In [7]: !echo ${x+y} |
|
2329 | 766 | 30 |
|
2330 | 767 | |
|
2331 | 768 | Even object attributes can be expanded:: |
|
2332 | 769 | |
|
2333 | 770 | In [12]: !echo $sys.argv |
|
2334 | 771 | [/home/fperez/usr/bin/ipython] |
|
2335 | 772 | |
|
2336 | 773 | |
|
2337 | 774 | System command aliases |
|
2338 | 775 | ---------------------- |
|
2339 | 776 | |
|
2340 | 777 | The %alias magic function and the alias option in the ipythonrc |
|
2341 | 778 | configuration file allow you to define magic functions which are in fact |
|
2342 | 779 | system shell commands. These aliases can have parameters. |
|
2343 | 780 | |
|
2344 | 781 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2345 | 782 | |
|
2346 | 783 | Then, typing '%alias_name params' will execute the system command 'cmd |
|
2347 | 784 | params' (from your underlying operating system). |
|
2348 | 785 | |
|
2349 | 786 | You can also define aliases with parameters using %s specifiers (one per |
|
2350 | 787 | parameter). The following example defines the %parts function as an |
|
2351 | 788 | alias to the command 'echo first %s second %s' where each %s will be |
|
2352 | 789 | replaced by a positional parameter to the call to %parts:: |
|
2353 | 790 | |
|
2354 | 791 | In [1]: alias parts echo first %s second %s |
|
2355 | 792 | In [2]: %parts A B |
|
2356 | 793 | first A second B |
|
2357 | 794 | In [3]: %parts A |
|
2358 | 795 | Incorrect number of arguments: 2 expected. |
|
2359 | 796 | parts is an alias to: 'echo first %s second %s' |
|
2360 | 797 | |
|
2361 | 798 | If called with no parameters, %alias prints the table of currently |
|
2362 | 799 | defined aliases. |
|
2363 | 800 | |
|
2364 | 801 | The %rehash/rehashx magics allow you to load your entire $PATH as |
|
2365 | 802 | ipython aliases. See their respective docstrings (or sec. 6.2 |
|
2366 | 803 | <#sec:magic> for further details). |
|
2367 | 804 | |
|
2368 | 805 | |
|
2369 | 806 | .. _dreload: |
|
2370 | 807 | |
|
2371 | 808 | Recursive reload |
|
2372 | 809 | ---------------- |
|
2373 | 810 | |
|
2374 | 811 | The dreload function does a recursive reload of a module: changes made |
|
2375 | 812 | to the module since you imported will actually be available without |
|
2376 | 813 | having to exit. |
|
2377 | 814 | |
|
2378 | 815 | |
|
2379 | 816 | Verbose and colored exception traceback printouts |
|
2380 | 817 | ------------------------------------------------- |
|
2381 | 818 | |
|
2382 | 819 | IPython provides the option to see very detailed exception tracebacks, |
|
2383 | 820 | which can be especially useful when debugging large programs. You can |
|
2384 | 821 | run any Python file with the %run function to benefit from these |
|
2385 | 822 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can |
|
2386 | 823 | be colored (if your terminal supports it) which makes them much easier |
|
2387 | 824 | to parse visually. |
|
2388 | 825 | |
|
2389 | 826 | See the magic xmode and colors functions for details (just type %magic). |
|
2390 | 827 | |
|
2391 | 828 | These features are basically a terminal version of Ka-Ping Yee's cgitb |
|
2392 | 829 | module, now part of the standard Python library. |
|
2393 | 830 | |
|
2394 | 831 | |
|
2395 | 832 | .. _input_caching: |
|
2396 | 833 | |
|
2397 | 834 | Input caching system |
|
2398 | 835 | -------------------- |
|
2399 | 836 | |
|
2400 | 837 | IPython offers numbered prompts (In/Out) with input and output caching. |
|
2401 | 838 | All input is saved and can be retrieved as variables (besides the usual |
|
2402 | 839 | arrow key recall). |
|
2403 | 840 | |
|
2404 | 841 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
2405 | 842 | _i: stores previous input. _ii: next previous. _iii: next-next previous. |
|
2406 | 843 | _ih : a list of all input _ih[n] is the input from line n and this list |
|
2407 | 844 | is aliased to the global variable In. If you overwrite In with a |
|
2408 | 845 | variable of your own, you can remake the assignment to the internal list |
|
2409 | 846 | with a simple 'In=_ih'. |
|
2410 | 847 | |
|
2411 | 848 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
2412 | 849 | being the prompt counter), such that |
|
2413 | 850 | _i<n> == _ih[<n>] == In[<n>]. |
|
2414 | 851 | |
|
2415 | 852 | For example, what you typed at prompt 14 is available as _i14, _ih[14] |
|
2416 | 853 | and In[14]. |
|
2417 | 854 | |
|
2418 | 855 | This allows you to easily cut and paste multi line interactive prompts |
|
2419 | 856 | by printing them out: they print like a clean string, without prompt |
|
2420 | 857 | characters. You can also manipulate them like regular variables (they |
|
2421 | 858 | are strings), modify or exec them (typing 'exec _i9' will re-execute the |
|
2422 | 859 | contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines |
|
2423 | 860 | 9 through 13 and line 18). |
|
2424 | 861 | |
|
2425 | 862 | You can also re-execute multiple lines of input easily by using the |
|
2426 | 863 | magic %macro function (which automates the process and allows |
|
2427 | 864 | re-execution without having to type 'exec' every time). The macro system |
|
2428 | 865 | also allows you to re-execute previous lines which include magic |
|
2429 | 866 | function calls (which require special processing). Type %macro? or see |
|
2430 | 867 | sec. 6.2 <#sec:magic> for more details on the macro system. |
|
2431 | 868 | |
|
2432 | 869 | A history function %hist allows you to see any part of your input |
|
2433 | 870 | history by printing a range of the _i variables. |
|
2434 | 871 | |
|
2435 | 872 | .. _output_caching: |
|
2436 | 873 | |
|
2437 | 874 | Output caching system |
|
2438 | 875 | --------------------- |
|
2439 | 876 | |
|
2440 | 877 | For output that is returned from actions, a system similar to the input |
|
2441 | 878 | cache exists but using _ instead of _i. Only actions that produce a |
|
2442 | 879 | result (NOT assignments, for example) are cached. If you are familiar |
|
2443 | 880 | with Mathematica, IPython's _ variables behave exactly like |
|
2444 | 881 | Mathematica's % variables. |
|
2445 | 882 | |
|
2446 | 883 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
2447 | 884 | |
|
2448 | 885 | * [_] (a single underscore) : stores previous output, like Python's |
|
2449 | 886 | default interpreter. |
|
2450 | 887 | * [__] (two underscores): next previous. |
|
2451 | 888 | * [___] (three underscores): next-next previous. |
|
2452 | 889 | |
|
2453 | 890 | Additionally, global variables named _<n> are dynamically created (<n> |
|
2454 | 891 | being the prompt counter), such that the result of output <n> is always |
|
2455 | 892 | available as _<n> (don't use the angle brackets, just the number, e.g. |
|
2456 | 893 | _21). |
|
2457 | 894 | |
|
2458 | 895 | These global variables are all stored in a global dictionary (not a |
|
2459 | 896 | list, since it only has entries for lines which returned a result) |
|
2460 | 897 | available under the names _oh and Out (similar to _ih and In). So the |
|
2461 | 898 | output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you |
|
2462 | 899 | accidentally overwrite the Out variable you can recover it by typing |
|
2463 | 900 | 'Out=_oh' at the prompt. |
|
2464 | 901 | |
|
2465 | 902 | This system obviously can potentially put heavy memory demands on your |
|
2466 | 903 | system, since it prevents Python's garbage collector from removing any |
|
2467 | 904 | previously computed results. You can control how many results are kept |
|
2468 | 905 | in memory with the option (at the command line or in your ipythonrc |
|
2469 | 906 | file) cache_size. If you set it to 0, the whole system is completely |
|
2470 | 907 | disabled and the prompts revert to the classic '>>>' of normal Python. |
|
2471 | 908 | |
|
2472 | 909 | |
|
2473 | 910 | Directory history |
|
2474 | 911 | ----------------- |
|
2475 | 912 | |
|
2476 | 913 | Your history of visited directories is kept in the global list _dh, and |
|
2477 | 914 | the magic %cd command can be used to go to any entry in that list. The |
|
2478 | 915 | %dhist command allows you to view this history. do ``cd -<TAB`` to |
|
2479 | 916 | conventiently view the directory history. |
|
2480 | 917 | |
|
2481 | 918 | |
|
2482 | 919 | Automatic parentheses and quotes |
|
2483 | 920 | -------------------------------- |
|
2484 | 921 | |
|
2485 | 922 | These features were adapted from Nathan Gray's LazyPython. They are |
|
2486 | 923 | meant to allow less typing for common situations. |
|
2487 | 924 | |
|
2488 | 925 | |
|
2489 | 926 | Automatic parentheses |
|
2490 | 927 | --------------------- |
|
2491 | 928 | |
|
2492 | 929 | Callable objects (i.e. functions, methods, etc) can be invoked like this |
|
2493 | 930 | (notice the commas between the arguments):: |
|
2494 | 931 | |
|
2495 | 932 | >>> callable_ob arg1, arg2, arg3 |
|
2496 | 933 | |
|
2497 | 934 | and the input will be translated to this:: |
|
2498 | 935 | |
|
2499 | 936 | -> callable_ob(arg1, arg2, arg3) |
|
2500 | 937 | |
|
2501 | 938 | You can force automatic parentheses by using '/' as the first character |
|
2502 | 939 | of a line. For example:: |
|
2503 | 940 | |
|
2504 | 941 | >>> /globals # becomes 'globals()' |
|
2505 | 942 | |
|
2506 | 943 | Note that the '/' MUST be the first character on the line! This won't work:: |
|
2507 | 944 | |
|
2508 | 945 | >>> print /globals # syntax error |
|
2509 | 946 | |
|
2510 | 947 | In most cases the automatic algorithm should work, so you should rarely |
|
2511 | 948 | need to explicitly invoke /. One notable exception is if you are trying |
|
2512 | 949 | to call a function with a list of tuples as arguments (the parenthesis |
|
2513 | 950 | will confuse IPython):: |
|
2514 | 951 | |
|
2515 | 952 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
2516 | 953 | |
|
2517 | 954 | but this will work:: |
|
2518 | 955 | |
|
2519 | 956 | In [2]: /zip (1,2,3),(4,5,6) |
|
2520 | 957 | ---> zip ((1,2,3),(4,5,6)) |
|
2521 | 958 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
2522 | 959 | |
|
2523 | 960 | IPython tells you that it has altered your command line by displaying |
|
2524 | 961 | the new command line preceded by ->. e.g.:: |
|
2525 | 962 | |
|
2526 | 963 | In [18]: callable list |
|
2527 | 964 | ----> callable (list) |
|
2528 | 965 | |
|
2529 | 966 | |
|
2530 | 967 | Automatic quoting |
|
2531 | 968 | ----------------- |
|
2532 | 969 | |
|
2533 | 970 | You can force automatic quoting of a function's arguments by using ',' |
|
2534 | 971 | or ';' as the first character of a line. For example:: |
|
2535 | 972 | |
|
2536 | 973 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
2537 | 974 | |
|
2538 | 975 | If you use ';' instead, the whole argument is quoted as a single string |
|
2539 | 976 | (while ',' splits on whitespace):: |
|
2540 | 977 | |
|
2541 | 978 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
2542 | 979 | |
|
2543 | 980 | >>> ;my_function a b c # becomes my_function("a b c") |
|
2544 | 981 | |
|
2545 | 982 | Note that the ',' or ';' MUST be the first character on the line! This |
|
2546 | 983 | won't work:: |
|
2547 | 984 | |
|
2548 | 985 | >>> x = ,my_function /home/me # syntax error |
|
2549 | 986 | |
|
2550 | 987 | IPython as your default Python environment |
|
2551 | 988 | ========================================== |
|
2552 | 989 | |
|
2553 | 990 | Python honors the environment variable PYTHONSTARTUP and will execute at |
|
2554 | 991 | startup the file referenced by this variable. If you put at the end of |
|
2555 | 992 | this file the following two lines of code:: |
|
2556 | 993 | |
|
2557 | 994 | import IPython |
|
2558 | 995 | IPython.Shell.IPShell().mainloop(sys_exit=1) |
|
2559 | 996 | |
|
2560 | 997 | then IPython will be your working environment anytime you start Python. |
|
2561 | 998 | The sys_exit=1 is needed to have IPython issue a call to sys.exit() when |
|
2562 | 999 | it finishes, otherwise you'll be back at the normal Python '>>>' |
|
2563 | 1000 | prompt. |
|
2564 | 1001 | |
|
2565 | 1002 | This is probably useful to developers who manage multiple Python |
|
2566 | 1003 | versions and don't want to have correspondingly multiple IPython |
|
2567 | 1004 | versions. Note that in this mode, there is no way to pass IPython any |
|
2568 | 1005 | command-line options, as those are trapped first by Python itself. |
|
2569 | 1006 | |
|
2570 | 1007 | .. _Embedding: |
|
2571 | 1008 | |
|
2572 | 1009 | Embedding IPython |
|
2573 | 1010 | ================= |
|
2574 | 1011 | |
|
2575 | 1012 | It is possible to start an IPython instance inside your own Python |
|
2576 | 1013 | programs. This allows you to evaluate dynamically the state of your |
|
2577 | 1014 | code, operate with your variables, analyze them, etc. Note however that |
|
2578 | 1015 | any changes you make to values while in the shell do not propagate back |
|
2579 | 1016 | to the running code, so it is safe to modify your values because you |
|
2580 | 1017 | won't break your code in bizarre ways by doing so. |
|
2581 | 1018 | |
|
2582 | 1019 | This feature allows you to easily have a fully functional python |
|
2583 | 1020 | environment for doing object introspection anywhere in your code with a |
|
2584 | 1021 | simple function call. In some cases a simple print statement is enough, |
|
2585 | 1022 | but if you need to do more detailed analysis of a code fragment this |
|
2586 | 1023 | feature can be very valuable. |
|
2587 | 1024 | |
|
2588 | 1025 | It can also be useful in scientific computing situations where it is |
|
2589 | 1026 | common to need to do some automatic, computationally intensive part and |
|
2590 | 1027 | then stop to look at data, plots, etc. |
|
2591 | 1028 | Opening an IPython instance will give you full access to your data and |
|
2592 | 1029 | functions, and you can resume program execution once you are done with |
|
2593 | 1030 | the interactive part (perhaps to stop again later, as many times as |
|
2594 | 1031 | needed). |
|
2595 | 1032 | |
|
2596 | 1033 | The following code snippet is the bare minimum you need to include in |
|
2597 | 1034 | your Python programs for this to work (detailed examples follow later):: |
|
2598 | 1035 | |
|
2599 | 1036 | from IPython.Shell import IPShellEmbed |
|
2600 | 1037 | |
|
2601 | 1038 | ipshell = IPShellEmbed() |
|
2602 | 1039 | |
|
2603 | 1040 | ipshell() # this call anywhere in your program will start IPython |
|
2604 | 1041 | |
|
2605 | 1042 | You can run embedded instances even in code which is itself being run at |
|
2606 | 1043 | the IPython interactive prompt with '%run <filename>'. Since it's easy |
|
2607 | 1044 | to get lost as to where you are (in your top-level IPython or in your |
|
2608 | 1045 | embedded one), it's a good idea in such cases to set the in/out prompts |
|
2609 | 1046 | to something different for the embedded instances. The code examples |
|
2610 | 1047 | below illustrate this. |
|
2611 | 1048 | |
|
2612 | 1049 | You can also have multiple IPython instances in your program and open |
|
2613 | 1050 | them separately, for example with different options for data |
|
2614 | 1051 | presentation. If you close and open the same instance multiple times, |
|
2615 | 1052 | its prompt counters simply continue from each execution to the next. |
|
2616 | 1053 | |
|
2617 | 1054 | Please look at the docstrings in the Shell.py module for more details on |
|
2618 | 1055 | the use of this system. |
|
2619 | 1056 | |
|
2620 | 1057 | The following sample file illustrating how to use the embedding |
|
2621 | 1058 | functionality is provided in the examples directory as example-embed.py. |
|
2622 | 1059 | It should be fairly self-explanatory:: |
|
2623 | 1060 | |
|
2624 | 1061 | |
|
2625 | 1062 | #!/usr/bin/env python |
|
2626 | 1063 | |
|
2627 | 1064 | """An example of how to embed an IPython shell into a running program. |
|
2628 | 1065 | |
|
2629 | 1066 | Please see the documentation in the IPython.Shell module for more details. |
|
2630 | 1067 | |
|
2631 | 1068 | The accompanying file example-embed-short.py has quick code fragments for |
|
2632 | 1069 | embedding which you can cut and paste in your code once you understand how |
|
2633 | 1070 | things work. |
|
2634 | 1071 | |
|
2635 | 1072 | The code in this file is deliberately extra-verbose, meant for learning.""" |
|
2636 | 1073 | |
|
2637 | 1074 | # The basics to get you going: |
|
2638 | 1075 | |
|
2639 | 1076 | # IPython sets the __IPYTHON__ variable so you can know if you have nested |
|
2640 | 1077 | # copies running. |
|
2641 | 1078 | |
|
2642 | 1079 | # Try running this code both at the command line and from inside IPython (with |
|
2643 | 1080 | # %run example-embed.py) |
|
2644 | 1081 | try: |
|
2645 | 1082 | __IPYTHON__ |
|
2646 | 1083 | except NameError: |
|
2647 | 1084 | nested = 0 |
|
2648 | 1085 | args = [''] |
|
2649 | 1086 | else: |
|
2650 | 1087 | print "Running nested copies of IPython." |
|
2651 | 1088 | print "The prompts for the nested copy have been modified" |
|
2652 | 1089 | nested = 1 |
|
2653 | 1090 | # what the embedded instance will see as sys.argv: |
|
2654 | 1091 | args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ', |
|
2655 | 1092 | '-po','Out<\\#>: ','-nosep'] |
|
2656 | 1093 | |
|
2657 | 1094 | # First import the embeddable shell class |
|
2658 | 1095 | from IPython.Shell import IPShellEmbed |
|
2659 | 1096 | |
|
2660 | 1097 | # Now create an instance of the embeddable shell. The first argument is a |
|
2661 | 1098 | # string with options exactly as you would type them if you were starting |
|
2662 | 1099 | # IPython at the system command line. Any parameters you want to define for |
|
2663 | 1100 | # configuration can thus be specified here. |
|
2664 | 1101 | ipshell = IPShellEmbed(args, |
|
2665 | 1102 | banner = 'Dropping into IPython', |
|
2666 | 1103 | exit_msg = 'Leaving Interpreter, back to program.') |
|
2667 | 1104 | |
|
2668 | 1105 | # Make a second instance, you can have as many as you want. |
|
2669 | 1106 | if nested: |
|
2670 | 1107 | args[1] = 'In2<\\#>' |
|
2671 | 1108 | else: |
|
2672 | 1109 | args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ', |
|
2673 | 1110 | '-po','Out<\\#>: ','-nosep'] |
|
2674 | 1111 | ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.') |
|
2675 | 1112 | |
|
2676 | 1113 | print '\nHello. This is printed from the main controller program.\n' |
|
2677 | 1114 | |
|
2678 | 1115 | # You can then call ipshell() anywhere you need it (with an optional |
|
2679 | 1116 | # message): |
|
2680 | 1117 | ipshell('***Called from top level. ' |
|
2681 | 1118 | 'Hit Ctrl-D to exit interpreter and continue program.\n' |
|
2682 | 1119 | 'Note that if you use %kill_embedded, you can fully deactivate\n' |
|
2683 | 1120 | 'This embedded instance so it will never turn on again') |
|
2684 | 1121 | |
|
2685 | 1122 | print '\nBack in caller program, moving along...\n' |
|
2686 | 1123 | |
|
2687 | 1124 | #--------------------------------------------------------------------------- |
|
2688 | 1125 | # More details: |
|
2689 | 1126 | |
|
2690 | 1127 | # IPShellEmbed instances don't print the standard system banner and |
|
2691 | 1128 | # messages. The IPython banner (which actually may contain initialization |
|
2692 | 1129 | # messages) is available as <instance>.IP.BANNER in case you want it. |
|
2693 | 1130 | |
|
2694 | 1131 | # IPShellEmbed instances print the following information everytime they |
|
2695 | 1132 | # start: |
|
2696 | 1133 | |
|
2697 | 1134 | # - A global startup banner. |
|
2698 | 1135 | |
|
2699 | 1136 | # - A call-specific header string, which you can use to indicate where in the |
|
2700 | 1137 | # execution flow the shell is starting. |
|
2701 | 1138 | |
|
2702 | 1139 | # They also print an exit message every time they exit. |
|
2703 | 1140 | |
|
2704 | 1141 | # Both the startup banner and the exit message default to None, and can be set |
|
2705 | 1142 | # either at the instance constructor or at any other time with the |
|
2706 | 1143 | # set_banner() and set_exit_msg() methods. |
|
2707 | 1144 | |
|
2708 | 1145 | # The shell instance can be also put in 'dummy' mode globally or on a per-call |
|
2709 | 1146 | # basis. This gives you fine control for debugging without having to change |
|
2710 | 1147 | # code all over the place. |
|
2711 | 1148 | |
|
2712 | 1149 | # The code below illustrates all this. |
|
2713 | 1150 | |
|
2714 | 1151 | |
|
2715 | 1152 | # This is how the global banner and exit_msg can be reset at any point |
|
2716 | 1153 | ipshell.set_banner('Entering interpreter - New Banner') |
|
2717 | 1154 | ipshell.set_exit_msg('Leaving interpreter - New exit_msg') |
|
2718 | 1155 | |
|
2719 | 1156 | def foo(m): |
|
2720 | 1157 | s = 'spam' |
|
2721 | 1158 | ipshell('***In foo(). Try @whos, or print s or m:') |
|
2722 | 1159 | print 'foo says m = ',m |
|
2723 | 1160 | |
|
2724 | 1161 | def bar(n): |
|
2725 | 1162 | s = 'eggs' |
|
2726 | 1163 | ipshell('***In bar(). Try @whos, or print s or n:') |
|
2727 | 1164 | print 'bar says n = ',n |
|
2728 | 1165 | |
|
2729 | 1166 | # Some calls to the above functions which will trigger IPython: |
|
2730 | 1167 | print 'Main program calling foo("eggs")\n' |
|
2731 | 1168 | foo('eggs') |
|
2732 | 1169 | |
|
2733 | 1170 | # The shell can be put in 'dummy' mode where calls to it silently return. This |
|
2734 | 1171 | # allows you, for example, to globally turn off debugging for a program with a |
|
2735 | 1172 | # single call. |
|
2736 | 1173 | ipshell.set_dummy_mode(1) |
|
2737 | 1174 | print '\nTrying to call IPython which is now "dummy":' |
|
2738 | 1175 | ipshell() |
|
2739 | 1176 | print 'Nothing happened...' |
|
2740 | 1177 | # The global 'dummy' mode can still be overridden for a single call |
|
2741 | 1178 | print '\nOverriding dummy mode manually:' |
|
2742 | 1179 | ipshell(dummy=0) |
|
2743 | 1180 | |
|
2744 | 1181 | # Reactivate the IPython shell |
|
2745 | 1182 | ipshell.set_dummy_mode(0) |
|
2746 | 1183 | |
|
2747 | 1184 | print 'You can even have multiple embedded instances:' |
|
2748 | 1185 | ipshell2() |
|
2749 | 1186 | |
|
2750 | 1187 | print '\nMain program calling bar("spam")\n' |
|
2751 | 1188 | bar('spam') |
|
2752 | 1189 | |
|
2753 | 1190 | print 'Main program finished. Bye!' |
|
2754 | 1191 | |
|
2755 | 1192 | #********************** End of file <example-embed.py> *********************** |
|
2756 | 1193 | |
|
2757 | 1194 | Once you understand how the system functions, you can use the following |
|
2758 | 1195 | code fragments in your programs which are ready for cut and paste:: |
|
2759 | 1196 | |
|
2760 | 1197 | |
|
2761 | 1198 | """Quick code snippets for embedding IPython into other programs. |
|
2762 | 1199 | |
|
2763 | 1200 | See example-embed.py for full details, this file has the bare minimum code for |
|
2764 | 1201 | cut and paste use once you understand how to use the system.""" |
|
2765 | 1202 | |
|
2766 | 1203 | #--------------------------------------------------------------------------- |
|
2767 | 1204 | # This code loads IPython but modifies a few things if it detects it's running |
|
2768 | 1205 | # embedded in another IPython session (helps avoid confusion) |
|
2769 | 1206 | |
|
2770 | 1207 | try: |
|
2771 | 1208 | __IPYTHON__ |
|
2772 | 1209 | except NameError: |
|
2773 | 1210 | argv = [''] |
|
2774 | 1211 | banner = exit_msg = '' |
|
2775 | 1212 | else: |
|
2776 | 1213 | # Command-line options for IPython (a list like sys.argv) |
|
2777 | 1214 | argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:'] |
|
2778 | 1215 | banner = '*** Nested interpreter ***' |
|
2779 | 1216 | exit_msg = '*** Back in main IPython ***' |
|
2780 | 1217 | |
|
2781 | 1218 | # First import the embeddable shell class |
|
2782 | 1219 | from IPython.Shell import IPShellEmbed |
|
2783 | 1220 | # Now create the IPython shell instance. Put ipshell() anywhere in your code |
|
2784 | 1221 | # where you want it to open. |
|
2785 | 1222 | ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg) |
|
2786 | 1223 | |
|
2787 | 1224 | #--------------------------------------------------------------------------- |
|
2788 | 1225 | # This code will load an embeddable IPython shell always with no changes for |
|
2789 | 1226 | # nested embededings. |
|
2790 | 1227 | |
|
2791 | 1228 | from IPython.Shell import IPShellEmbed |
|
2792 | 1229 | ipshell = IPShellEmbed() |
|
2793 | 1230 | # Now ipshell() will open IPython anywhere in the code. |
|
2794 | 1231 | |
|
2795 | 1232 | #--------------------------------------------------------------------------- |
|
2796 | 1233 | # This code loads an embeddable shell only if NOT running inside |
|
2797 | 1234 | # IPython. Inside IPython, the embeddable shell variable ipshell is just a |
|
2798 | 1235 | # dummy function. |
|
2799 | 1236 | |
|
2800 | 1237 | try: |
|
2801 | 1238 | __IPYTHON__ |
|
2802 | 1239 | except NameError: |
|
2803 | 1240 | from IPython.Shell import IPShellEmbed |
|
2804 | 1241 | ipshell = IPShellEmbed() |
|
2805 | 1242 | # Now ipshell() will open IPython anywhere in the code |
|
2806 | 1243 | else: |
|
2807 | 1244 | # Define a dummy ipshell() so the same code doesn't crash inside an |
|
2808 | 1245 | # interactive IPython |
|
2809 | 1246 | def ipshell(): pass |
|
2810 | 1247 | |
|
2811 | 1248 | #******************* End of file <example-embed-short.py> ******************** |
|
2812 | 1249 | |
|
2813 | 1250 | Using the Python debugger (pdb) |
|
2814 | 1251 | =============================== |
|
2815 | 1252 | |
|
2816 | 1253 | Running entire programs via pdb |
|
2817 | 1254 | ------------------------------- |
|
2818 | 1255 | |
|
2819 | 1256 | pdb, the Python debugger, is a powerful interactive debugger which |
|
2820 | 1257 | allows you to step through code, set breakpoints, watch variables, |
|
2821 | 1258 | etc. IPython makes it very easy to start any script under the control |
|
2822 | 1259 | of pdb, regardless of whether you have wrapped it into a 'main()' |
|
2823 | 1260 | function or not. For this, simply type '%run -d myscript' at an |
|
2824 | 1261 | IPython prompt. See the %run command's documentation (via '%run?' or |
|
2825 | 1262 | in Sec. magic_ for more details, including how to control where pdb |
|
2826 | 1263 | will stop execution first. |
|
2827 | 1264 | |
|
2828 | 1265 | For more information on the use of the pdb debugger, read the included |
|
2829 | 1266 | pdb.doc file (part of the standard Python distribution). On a stock |
|
2830 | 1267 | Linux system it is located at /usr/lib/python2.3/pdb.doc, but the |
|
2831 | 1268 | easiest way to read it is by using the help() function of the pdb module |
|
2832 | 1269 | as follows (in an IPython prompt): |
|
2833 | 1270 | |
|
2834 | 1271 | In [1]: import pdb |
|
2835 | 1272 | In [2]: pdb.help() |
|
2836 | 1273 | |
|
2837 | 1274 | This will load the pdb.doc document in a file viewer for you automatically. |
|
2838 | 1275 | |
|
2839 | 1276 | |
|
2840 | 1277 | Automatic invocation of pdb on exceptions |
|
2841 | 1278 | ----------------------------------------- |
|
2842 | 1279 | |
|
2843 | 1280 | IPython, if started with the -pdb option (or if the option is set in |
|
2844 | 1281 | your rc file) can call the Python pdb debugger every time your code |
|
2845 | 1282 | triggers an uncaught exception. This feature |
|
2846 | 1283 | can also be toggled at any time with the %pdb magic command. This can be |
|
2847 | 1284 | extremely useful in order to find the origin of subtle bugs, because pdb |
|
2848 | 1285 | opens up at the point in your code which triggered the exception, and |
|
2849 | 1286 | while your program is at this point 'dead', all the data is still |
|
2850 | 1287 | available and you can walk up and down the stack frame and understand |
|
2851 | 1288 | the origin of the problem. |
|
2852 | 1289 | |
|
2853 | 1290 | Furthermore, you can use these debugging facilities both with the |
|
2854 | 1291 | embedded IPython mode and without IPython at all. For an embedded shell |
|
2855 | 1292 | (see sec. Embedding_), simply call the constructor with |
|
2856 | 1293 | '-pdb' in the argument string and automatically pdb will be called if an |
|
2857 | 1294 | uncaught exception is triggered by your code. |
|
2858 | 1295 | |
|
2859 | 1296 | For stand-alone use of the feature in your programs which do not use |
|
2860 | 1297 | IPython at all, put the following lines toward the top of your 'main' |
|
2861 | 1298 | routine:: |
|
2862 | 1299 | |
|
2863 | 1300 | import sys,IPython.ultraTB |
|
2864 | 1301 | sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose', |
|
2865 | 1302 | color_scheme='Linux', call_pdb=1) |
|
2866 | 1303 | |
|
2867 | 1304 | The mode keyword can be either 'Verbose' or 'Plain', giving either very |
|
2868 | 1305 | detailed or normal tracebacks respectively. The color_scheme keyword can |
|
2869 | 1306 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same |
|
2870 | 1307 | options which can be set in IPython with -colors and -xmode. |
|
2871 | 1308 | |
|
2872 | 1309 | This will give any of your programs detailed, colored tracebacks with |
|
2873 | 1310 | automatic invocation of pdb. |
|
2874 | 1311 | |
|
2875 | 1312 | |
|
2876 | 1313 | Extensions for syntax processing |
|
2877 | 1314 | ================================ |
|
2878 | 1315 | |
|
2879 | 1316 | This isn't for the faint of heart, because the potential for breaking |
|
2880 | 1317 | things is quite high. But it can be a very powerful and useful feature. |
|
2881 | 1318 | In a nutshell, you can redefine the way IPython processes the user input |
|
2882 | 1319 | line to accept new, special extensions to the syntax without needing to |
|
2883 | 1320 | change any of IPython's own code. |
|
2884 | 1321 | |
|
2885 | 1322 | In the IPython/Extensions directory you will find some examples |
|
2886 | 1323 | supplied, which we will briefly describe now. These can be used 'as is' |
|
2887 | 1324 | (and both provide very useful functionality), or you can use them as a |
|
2888 | 1325 | starting point for writing your own extensions. |
|
2889 | 1326 | |
|
2890 | 1327 | |
|
2891 | 1328 | Pasting of code starting with '>>> ' or '... ' |
|
2892 | 1329 | ---------------------------------------------- |
|
2893 | 1330 | |
|
2894 | 1331 | In the python tutorial it is common to find code examples which have |
|
2895 | 1332 | been taken from real python sessions. The problem with those is that all |
|
2896 | 1333 | the lines begin with either '>>> ' or '... ', which makes it impossible |
|
2897 | 1334 | to paste them all at once. One must instead do a line by line manual |
|
2898 | 1335 | copying, carefully removing the leading extraneous characters. |
|
2899 | 1336 | |
|
2900 | 1337 | This extension identifies those starting characters and removes them |
|
2901 | 1338 | from the input automatically, so that one can paste multi-line examples |
|
2902 | 1339 | directly into IPython, saving a lot of time. Please look at the file |
|
2903 | 1340 | InterpreterPasteInput.py in the IPython/Extensions directory for details |
|
2904 | 1341 | on how this is done. |
|
2905 | 1342 | |
|
2906 | 1343 | IPython comes with a special profile enabling this feature, called |
|
2907 | 1344 | tutorial. Simply start IPython via 'ipython -p tutorial' and the feature |
|
2908 | 1345 | will be available. In a normal IPython session you can activate the |
|
2909 | 1346 | feature by importing the corresponding module with: |
|
2910 | 1347 | In [1]: import IPython.Extensions.InterpreterPasteInput |
|
2911 | 1348 | |
|
2912 | 1349 | The following is a 'screenshot' of how things work when this extension |
|
2913 | 1350 | is on, copying an example from the standard tutorial:: |
|
2914 | 1351 | |
|
2915 | 1352 | IPython profile: tutorial |
|
2916 | 1353 | |
|
2917 | 1354 | *** Pasting of code with ">>>" or "..." has been enabled. |
|
2918 | 1355 | |
|
2919 | 1356 | In [1]: >>> def fib2(n): # return Fibonacci series up to n |
|
2920 | 1357 | ...: ... """Return a list containing the Fibonacci series up to |
|
2921 | 1358 | n.""" |
|
2922 | 1359 | ...: ... result = [] |
|
2923 | 1360 | ...: ... a, b = 0, 1 |
|
2924 | 1361 | ...: ... while b < n: |
|
2925 | 1362 | ...: ... result.append(b) # see below |
|
2926 | 1363 | ...: ... a, b = b, a+b |
|
2927 | 1364 | ...: ... return result |
|
2928 | 1365 | ...: |
|
2929 | 1366 | |
|
2930 | 1367 | In [2]: fib2(10) |
|
2931 | 1368 | Out[2]: [1, 1, 2, 3, 5, 8] |
|
2932 | 1369 | |
|
2933 | 1370 | Note that as currently written, this extension does not recognize |
|
2934 | 1371 | IPython's prompts for pasting. Those are more complicated, since the |
|
2935 | 1372 | user can change them very easily, they involve numbers and can vary in |
|
2936 | 1373 | length. One could however extract all the relevant information from the |
|
2937 | 1374 | IPython instance and build an appropriate regular expression. This is |
|
2938 | 1375 | left as an exercise for the reader. |
|
2939 | 1376 | |
|
2940 | 1377 | |
|
2941 | 1378 | Input of physical quantities with units |
|
2942 | 1379 | --------------------------------------- |
|
2943 | 1380 | |
|
2944 | 1381 | The module PhysicalQInput allows a simplified form of input for physical |
|
2945 | 1382 | quantities with units. This file is meant to be used in conjunction with |
|
2946 | 1383 | the PhysicalQInteractive module (in the same directory) and |
|
2947 | 1384 | Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython |
|
2948 | 1385 | (http://dirac.cnrs-orleans.fr/ScientificPython/). |
|
2949 | 1386 | |
|
2950 | 1387 | The Physics.PhysicalQuantities module defines PhysicalQuantity objects, |
|
2951 | 1388 | but these must be declared as instances of a class. For example, to |
|
2952 | 1389 | define v as a velocity of 3 m/s, normally you would write:: |
|
2953 | 1390 | |
|
2954 | 1391 | In [1]: v = PhysicalQuantity(3,'m/s') |
|
2955 | 1392 | |
|
2956 | 1393 | Using the PhysicalQ_Input extension this can be input instead as: |
|
2957 | 1394 | In [1]: v = 3 m/s |
|
2958 | 1395 | which is much more convenient for interactive use (even though it is |
|
2959 | 1396 | blatantly invalid Python syntax). |
|
2960 | 1397 | |
|
2961 | 1398 | The physics profile supplied with IPython (enabled via 'ipython -p |
|
2962 | 1399 | physics') uses these extensions, which you can also activate with: |
|
2963 | 1400 | |
|
2964 | 1401 | from math import * # math MUST be imported BEFORE PhysicalQInteractive |
|
2965 | 1402 | from IPython.Extensions.PhysicalQInteractive import * |
|
2966 | 1403 | import IPython.Extensions.PhysicalQInput |
|
2967 | 1404 | |
|
2968 | 1405 | |
|
2969 | 1406 | Threading support |
|
2970 | 1407 | ================= |
|
2971 | 1408 | |
|
2972 | 1409 | WARNING: The threading support is still somewhat experimental, and it |
|
2973 | 1410 | has only seen reasonable testing under Linux. Threaded code is |
|
2974 | 1411 | particularly tricky to debug, and it tends to show extremely |
|
2975 | 1412 | platform-dependent behavior. Since I only have access to Linux machines, |
|
2976 | 1413 | I will have to rely on user's experiences and assistance for this area |
|
2977 | 1414 | of IPython to improve under other platforms. |
|
2978 | 1415 | |
|
2979 | 1416 | IPython, via the -gthread , -qthread, -q4thread and -wthread options |
|
2980 | 1417 | (described in Sec. `Threading options`_), can run in |
|
2981 | 1418 | multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications |
|
2982 | 1419 | respectively. These GUI toolkits need to control the python main loop of |
|
2983 | 1420 | execution, so under a normal Python interpreter, starting a pyGTK, Qt3, |
|
2984 | 1421 | Qt4 or WXPython application will immediately freeze the shell. |
|
2985 | 1422 | |
|
2986 | 1423 | IPython, with one of these options (you can only use one at a time), |
|
2987 | 1424 | separates the graphical loop and IPython's code execution run into |
|
2988 | 1425 | different threads. This allows you to test interactively (with %run, for |
|
2989 | 1426 | example) your GUI code without blocking. |
|
2990 | 1427 | |
|
2991 | 1428 | A nice mini-tutorial on using IPython along with the Qt Designer |
|
2992 | 1429 | application is available at the SciPy wiki: |
|
2993 | 1430 | http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer. |
|
2994 | 1431 | |
|
2995 | 1432 | |
|
2996 | 1433 | Tk issues |
|
2997 | 1434 | --------- |
|
2998 | 1435 | |
|
2999 | 1436 | As indicated in Sec. `Threading options`_, a special -tk option is |
|
3000 | 1437 | provided to try and allow Tk graphical applications to coexist |
|
3001 | 1438 | interactively with WX, Qt or GTK ones. Whether this works at all, |
|
3002 | 1439 | however, is very platform and configuration dependent. Please |
|
3003 | 1440 | experiment with simple test cases before committing to using this |
|
3004 | 1441 | combination of Tk and GTK/Qt/WX threading in a production environment. |
|
3005 | 1442 | |
|
3006 | 1443 | |
|
3007 | 1444 | I/O pitfalls |
|
3008 | 1445 | ------------ |
|
3009 | 1446 | |
|
3010 | 1447 | Be mindful that the Python interpreter switches between threads every |
|
3011 | 1448 | $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This |
|
3012 | 1449 | value can be read by using the sys.getcheckinterval() function, and it |
|
3013 | 1450 | can be reset via sys.setcheckinterval(N). This switching of threads can |
|
3014 | 1451 | cause subtly confusing effects if one of your threads is doing file I/O. |
|
3015 | 1452 | In text mode, most systems only flush file buffers when they encounter a |
|
3016 | 1453 | '\n'. An instruction as simple as:: |
|
3017 | 1454 | |
|
3018 | 1455 | print >> filehandle, ''hello world'' |
|
3019 | 1456 | |
|
3020 | 1457 | actually consists of several bytecodes, so it is possible that the |
|
3021 | 1458 | newline does not reach your file before the next thread switch. |
|
3022 | 1459 | Similarly, if you are writing to a file in binary mode, the file won't |
|
3023 | 1460 | be flushed until the buffer fills, and your other thread may see |
|
3024 | 1461 | apparently truncated files. |
|
3025 | 1462 | |
|
3026 | 1463 | For this reason, if you are using IPython's thread support and have (for |
|
3027 | 1464 | example) a GUI application which will read data generated by files |
|
3028 | 1465 | written to from the IPython thread, the safest approach is to open all |
|
3029 | 1466 | of your files in unbuffered mode (the third argument to the file/open |
|
3030 | 1467 | function is the buffering value):: |
|
3031 | 1468 | |
|
3032 | 1469 | filehandle = open(filename,mode,0) |
|
3033 | 1470 | |
|
3034 | 1471 | This is obviously a brute force way of avoiding race conditions with the |
|
3035 | 1472 | file buffering. If you want to do it cleanly, and you have a resource |
|
3036 | 1473 | which is being shared by the interactive IPython loop and your GUI |
|
3037 | 1474 | thread, you should really handle it with thread locking and |
|
3038 | 1475 | syncrhonization properties. The Python documentation discusses these. |
|
3039 | 1476 | |
|
3040 | 1477 | .. _interactive_demos: |
|
3041 | 1478 | |
|
3042 | 1479 | Interactive demos with IPython |
|
3043 | 1480 | ============================== |
|
3044 | 1481 | |
|
3045 | 1482 | IPython ships with a basic system for running scripts interactively in |
|
3046 | 1483 | sections, useful when presenting code to audiences. A few tags embedded |
|
3047 | 1484 | in comments (so that the script remains valid Python code) divide a file |
|
3048 | 1485 | into separate blocks, and the demo can be run one block at a time, with |
|
3049 | 1486 | IPython printing (with syntax highlighting) the block before executing |
|
3050 | 1487 | it, and returning to the interactive prompt after each block. The |
|
3051 | 1488 | interactive namespace is updated after each block is run with the |
|
3052 | 1489 | contents of the demo's namespace. |
|
3053 | 1490 | |
|
3054 | 1491 | This allows you to show a piece of code, run it and then execute |
|
3055 | 1492 | interactively commands based on the variables just created. Once you |
|
3056 | 1493 | want to continue, you simply execute the next block of the demo. The |
|
3057 | 1494 | following listing shows the markup necessary for dividing a script into |
|
3058 | 1495 | sections for execution as a demo:: |
|
3059 | 1496 | |
|
3060 | 1497 | |
|
3061 | 1498 | """A simple interactive demo to illustrate the use of IPython's Demo class. |
|
3062 | 1499 | |
|
3063 | 1500 | Any python script can be run as a demo, but that does little more than showing |
|
3064 | 1501 | it on-screen, syntax-highlighted in one shot. If you add a little simple |
|
3065 | 1502 | markup, you can stop at specified intervals and return to the ipython prompt, |
|
3066 | 1503 | resuming execution later. |
|
3067 | 1504 | """ |
|
3068 | 1505 | |
|
3069 | 1506 | print 'Hello, welcome to an interactive IPython demo.' |
|
3070 | 1507 | print 'Executing this block should require confirmation before proceeding,' |
|
3071 | 1508 | print 'unless auto_all has been set to true in the demo object' |
|
3072 | 1509 | |
|
3073 | 1510 | # The mark below defines a block boundary, which is a point where IPython will |
|
3074 | 1511 | # stop execution and return to the interactive prompt. |
|
3075 | 1512 | # Note that in actual interactive execution, |
|
3076 | 1513 | # <demo> --- stop --- |
|
3077 | 1514 | |
|
3078 | 1515 | x = 1 |
|
3079 | 1516 | y = 2 |
|
3080 | 1517 | |
|
3081 | 1518 | # <demo> --- stop --- |
|
3082 | 1519 | |
|
3083 | 1520 | # the mark below makes this block as silent |
|
3084 | 1521 | # <demo> silent |
|
3085 | 1522 | |
|
3086 | 1523 | print 'This is a silent block, which gets executed but not printed.' |
|
3087 | 1524 | |
|
3088 | 1525 | # <demo> --- stop --- |
|
3089 | 1526 | # <demo> auto |
|
3090 | 1527 | print 'This is an automatic block.' |
|
3091 | 1528 | print 'It is executed without asking for confirmation, but printed.' |
|
3092 | 1529 | z = x+y |
|
3093 | 1530 | |
|
3094 | 1531 | print 'z=',x |
|
3095 | 1532 | |
|
3096 | 1533 | # <demo> --- stop --- |
|
3097 | 1534 | # This is just another normal block. |
|
3098 | 1535 | print 'z is now:', z |
|
3099 | 1536 | |
|
3100 | 1537 | print 'bye!' |
|
3101 | 1538 | |
|
3102 | 1539 | In order to run a file as a demo, you must first make a Demo object out |
|
3103 | 1540 | of it. If the file is named myscript.py, the following code will make a |
|
3104 | 1541 | demo:: |
|
3105 | 1542 | |
|
3106 | 1543 | from IPython.demo import Demo |
|
3107 | 1544 | |
|
3108 | 1545 | mydemo = Demo('myscript.py') |
|
3109 | 1546 | |
|
3110 | 1547 | This creates the mydemo object, whose blocks you run one at a time by |
|
3111 | 1548 | simply calling the object with no arguments. If you have autocall active |
|
3112 | 1549 | in IPython (the default), all you need to do is type:: |
|
3113 | 1550 | |
|
3114 | 1551 | mydemo |
|
3115 | 1552 | |
|
3116 | 1553 | and IPython will call it, executing each block. Demo objects can be |
|
3117 | 1554 | restarted, you can move forward or back skipping blocks, re-execute the |
|
3118 | 1555 | last block, etc. Simply use the Tab key on a demo object to see its |
|
3119 | 1556 | methods, and call '?' on them to see their docstrings for more usage |
|
3120 | 1557 | details. In addition, the demo module itself contains a comprehensive |
|
3121 | 1558 | docstring, which you can access via:: |
|
3122 | 1559 | |
|
3123 | 1560 | from IPython import demo |
|
3124 | 1561 | |
|
3125 | 1562 | demo? |
|
3126 | 1563 | |
|
3127 | 1564 | Limitations: It is important to note that these demos are limited to |
|
3128 | 1565 | fairly simple uses. In particular, you can not put division marks in |
|
3129 | 1566 | indented code (loops, if statements, function definitions, etc.) |
|
3130 | 1567 | Supporting something like this would basically require tracking the |
|
3131 | 1568 | internal execution state of the Python interpreter, so only top-level |
|
3132 | 1569 | divisions are allowed. If you want to be able to open an IPython |
|
3133 | 1570 | instance at an arbitrary point in a program, you can use IPython's |
|
3134 | 1571 | embedding facilities, described in detail in Sec. 9 |
|
3135 | 1572 | |
|
3136 | 1573 | |
|
3137 | 1574 | .. _Matplotlib support: |
|
3138 | 1575 | |
|
3139 | 1576 | Plotting with matplotlib |
|
3140 | 1577 | ======================== |
|
3141 | 1578 | |
|
3142 | 1579 | The matplotlib library (http://matplotlib.sourceforge.net |
|
3143 | 1580 | http://matplotlib.sourceforge.net) provides high quality 2D plotting for |
|
3144 | 1581 | Python. Matplotlib can produce plots on screen using a variety of GUI |
|
3145 | 1582 | toolkits, including Tk, GTK and WXPython. It also provides a number of |
|
3146 | 1583 | commands useful for scientific computing, all with a syntax compatible |
|
3147 | 1584 | with that of the popular Matlab program. |
|
3148 | 1585 | |
|
3149 | 1586 | IPython accepts the special option -pylab (see :ref:`here |
|
3150 | 1587 | <command_line_options>`). This configures it to support matplotlib, honoring |
|
3151 | 1588 | the settings in the .matplotlibrc file. IPython will detect the user's choice |
|
3152 | 1589 | of matplotlib GUI backend, and automatically select the proper threading model |
|
3153 | 1590 | to prevent blocking. It also sets matplotlib in interactive mode and modifies |
|
3154 | 1591 | %run slightly, so that any matplotlib-based script can be executed using %run |
|
3155 | 1592 | and the final show() command does not block the interactive shell. |
|
3156 | 1593 | |
|
3157 | 1594 | The -pylab option must be given first in order for IPython to configure its |
|
3158 | 1595 | threading mode. However, you can still issue other options afterwards. This |
|
3159 | 1596 | allows you to have a matplotlib-based environment customized with additional |
|
3160 | 1597 | modules using the standard IPython profile mechanism (see :ref:`here |
|
3161 | 1598 | <profiles>`): ``ipython -pylab -p myprofile`` will load the profile defined in |
|
3162 | 1599 | ipythonrc-myprofile after configuring matplotlib. |
@@ -1,423 +1,407 | |||
|
1 | 1 | """ |
|
2 | 2 | Defines a docutils directive for inserting inheritance diagrams. |
|
3 | 3 | |
|
4 | 4 | Provide the directive with one or more classes or modules (separated |
|
5 | 5 | by whitespace). For modules, all of the classes in that module will |
|
6 | 6 | be used. |
|
7 | 7 | |
|
8 | 8 | Example:: |
|
9 | 9 | |
|
10 | 10 | Given the following classes: |
|
11 | 11 | |
|
12 | 12 | class A: pass |
|
13 | 13 | class B(A): pass |
|
14 | 14 | class C(A): pass |
|
15 | 15 | class D(B, C): pass |
|
16 | 16 | class E(B): pass |
|
17 | 17 | |
|
18 | 18 | .. inheritance-diagram: D E |
|
19 | 19 | |
|
20 | 20 | Produces a graph like the following: |
|
21 | 21 | |
|
22 | 22 | A |
|
23 | 23 | / \ |
|
24 | 24 | B C |
|
25 | 25 | / \ / |
|
26 | 26 | E D |
|
27 | 27 | |
|
28 | 28 | The graph is inserted as a PNG+image map into HTML and a PDF in |
|
29 | 29 | LaTeX. |
|
30 | 30 | """ |
|
31 | 31 | |
|
32 | 32 | import inspect |
|
33 | 33 | import os |
|
34 | 34 | import re |
|
35 | 35 | import subprocess |
|
36 | 36 | try: |
|
37 | 37 | from hashlib import md5 |
|
38 | 38 | except ImportError: |
|
39 | 39 | from md5 import md5 |
|
40 | 40 | |
|
41 | 41 | from docutils.nodes import Body, Element |
|
42 | from docutils.writers.html4css1 import HTMLTranslator | |
|
43 | from sphinx.latexwriter import LaTeXTranslator | |
|
44 | 42 | from docutils.parsers.rst import directives |
|
45 | 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 | 56 | class DotException(Exception): |
|
48 | 57 | pass |
|
49 | 58 | |
|
50 | 59 | class InheritanceGraph(object): |
|
51 | 60 | """ |
|
52 | 61 | Given a list of classes, determines the set of classes that |
|
53 | 62 | they inherit from all the way to the root "object", and then |
|
54 | 63 | is able to generate a graphviz dot graph from them. |
|
55 | 64 | """ |
|
56 | 65 | def __init__(self, class_names, show_builtins=False): |
|
57 | 66 | """ |
|
58 | 67 | *class_names* is a list of child classes to show bases from. |
|
59 | 68 | |
|
60 | 69 | If *show_builtins* is True, then Python builtins will be shown |
|
61 | 70 | in the graph. |
|
62 | 71 | """ |
|
63 | 72 | self.class_names = class_names |
|
64 | 73 | self.classes = self._import_classes(class_names) |
|
65 | 74 | self.all_classes = self._all_classes(self.classes) |
|
66 | 75 | if len(self.all_classes) == 0: |
|
67 | 76 | raise ValueError("No classes found for inheritance diagram") |
|
68 | 77 | self.show_builtins = show_builtins |
|
69 | 78 | |
|
70 | 79 | py_sig_re = re.compile(r'''^([\w.]*\.)? # class names |
|
71 | 80 | (\w+) \s* $ # optionally arguments |
|
72 | 81 | ''', re.VERBOSE) |
|
73 | 82 | |
|
74 | 83 | def _import_class_or_module(self, name): |
|
75 | 84 | """ |
|
76 | 85 | Import a class using its fully-qualified *name*. |
|
77 | 86 | """ |
|
78 | 87 | try: |
|
79 | 88 | path, base = self.py_sig_re.match(name).groups() |
|
80 | 89 | except: |
|
81 | 90 | raise ValueError( |
|
82 | 91 | "Invalid class or module '%s' specified for inheritance diagram" % name) |
|
83 | 92 | fullname = (path or '') + base |
|
84 | 93 | path = (path and path.rstrip('.')) |
|
85 | 94 | if not path: |
|
86 | 95 | path = base |
|
87 | if not path: | |
|
88 | raise ValueError( | |
|
89 | "Invalid class or module '%s' specified for inheritance diagram" % name) | |
|
90 | 96 | try: |
|
91 | 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 | 105 | except ImportError: |
|
93 | 106 | raise ValueError( |
|
94 | 107 | "Could not import class or module '%s' specified for inheritance diagram" % name) |
|
95 | 108 | |
|
96 | 109 | try: |
|
97 | 110 | todoc = module |
|
98 | 111 | for comp in fullname.split('.')[1:]: |
|
99 | 112 | todoc = getattr(todoc, comp) |
|
100 | 113 | except AttributeError: |
|
101 | 114 | raise ValueError( |
|
102 | 115 | "Could not find class or module '%s' specified for inheritance diagram" % name) |
|
103 | 116 | |
|
104 | 117 | # If a class, just return it |
|
105 | 118 | if inspect.isclass(todoc): |
|
106 | 119 | return [todoc] |
|
107 | 120 | elif inspect.ismodule(todoc): |
|
108 | 121 | classes = [] |
|
109 | 122 | for cls in todoc.__dict__.values(): |
|
110 | 123 | if inspect.isclass(cls) and cls.__module__ == todoc.__name__: |
|
111 | 124 | classes.append(cls) |
|
112 | 125 | return classes |
|
113 | 126 | raise ValueError( |
|
114 | 127 | "'%s' does not resolve to a class or module" % name) |
|
115 | 128 | |
|
116 | 129 | def _import_classes(self, class_names): |
|
117 | 130 | """ |
|
118 | 131 | Import a list of classes. |
|
119 | 132 | """ |
|
120 | 133 | classes = [] |
|
121 | 134 | for name in class_names: |
|
122 | 135 | classes.extend(self._import_class_or_module(name)) |
|
123 | 136 | return classes |
|
124 | 137 | |
|
125 | 138 | def _all_classes(self, classes): |
|
126 | 139 | """ |
|
127 | 140 | Return a list of all classes that are ancestors of *classes*. |
|
128 | 141 | """ |
|
129 | 142 | all_classes = {} |
|
130 | 143 | |
|
131 | 144 | def recurse(cls): |
|
132 | 145 | all_classes[cls] = None |
|
133 | 146 | for c in cls.__bases__: |
|
134 | 147 | if c not in all_classes: |
|
135 | 148 | recurse(c) |
|
136 | 149 | |
|
137 | 150 | for cls in classes: |
|
138 | 151 | recurse(cls) |
|
139 | 152 | |
|
140 | 153 | return all_classes.keys() |
|
141 | 154 | |
|
142 | 155 | def class_name(self, cls, parts=0): |
|
143 | 156 | """ |
|
144 | 157 | Given a class object, return a fully-qualified name. This |
|
145 | 158 | works for things I've tested in matplotlib so far, but may not |
|
146 | 159 | be completely general. |
|
147 | 160 | """ |
|
148 | 161 | module = cls.__module__ |
|
149 | 162 | if module == '__builtin__': |
|
150 | 163 | fullname = cls.__name__ |
|
151 | 164 | else: |
|
152 | 165 | fullname = "%s.%s" % (module, cls.__name__) |
|
153 | 166 | if parts == 0: |
|
154 | 167 | return fullname |
|
155 | 168 | name_parts = fullname.split('.') |
|
156 | 169 | return '.'.join(name_parts[-parts:]) |
|
157 | 170 | |
|
158 | 171 | def get_all_class_names(self): |
|
159 | 172 | """ |
|
160 | 173 | Get all of the class names involved in the graph. |
|
161 | 174 | """ |
|
162 | 175 | return [self.class_name(x) for x in self.all_classes] |
|
163 | 176 | |
|
164 | 177 | # These are the default options for graphviz |
|
165 | 178 | default_graph_options = { |
|
166 | 179 | "rankdir": "LR", |
|
167 | 180 | "size": '"8.0, 12.0"' |
|
168 | 181 | } |
|
169 | 182 | default_node_options = { |
|
170 | 183 | "shape": "box", |
|
171 | 184 | "fontsize": 10, |
|
172 | 185 | "height": 0.25, |
|
173 | 186 | "fontname": "Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans", |
|
174 | 187 | "style": '"setlinewidth(0.5)"' |
|
175 | 188 | } |
|
176 | 189 | default_edge_options = { |
|
177 | 190 | "arrowsize": 0.5, |
|
178 | 191 | "style": '"setlinewidth(0.5)"' |
|
179 | 192 | } |
|
180 | 193 | |
|
181 | 194 | def _format_node_options(self, options): |
|
182 | 195 | return ','.join(["%s=%s" % x for x in options.items()]) |
|
183 | 196 | def _format_graph_options(self, options): |
|
184 | 197 | return ''.join(["%s=%s;\n" % x for x in options.items()]) |
|
185 | 198 | |
|
186 | 199 | def generate_dot(self, fd, name, parts=0, urls={}, |
|
187 | 200 | graph_options={}, node_options={}, |
|
188 | 201 | edge_options={}): |
|
189 | 202 | """ |
|
190 | 203 | Generate a graphviz dot graph from the classes that |
|
191 | 204 | were passed in to __init__. |
|
192 | 205 | |
|
193 | 206 | *fd* is a Python file-like object to write to. |
|
194 | 207 | |
|
195 | 208 | *name* is the name of the graph |
|
196 | 209 | |
|
197 | 210 | *urls* is a dictionary mapping class names to http urls |
|
198 | 211 | |
|
199 | 212 | *graph_options*, *node_options*, *edge_options* are |
|
200 | 213 | dictionaries containing key/value pairs to pass on as graphviz |
|
201 | 214 | properties. |
|
202 | 215 | """ |
|
203 | 216 | g_options = self.default_graph_options.copy() |
|
204 | 217 | g_options.update(graph_options) |
|
205 | 218 | n_options = self.default_node_options.copy() |
|
206 | 219 | n_options.update(node_options) |
|
207 | 220 | e_options = self.default_edge_options.copy() |
|
208 | 221 | e_options.update(edge_options) |
|
209 | 222 | |
|
210 | 223 | fd.write('digraph %s {\n' % name) |
|
211 | 224 | fd.write(self._format_graph_options(g_options)) |
|
212 | 225 | |
|
213 | 226 | for cls in self.all_classes: |
|
214 | 227 | if not self.show_builtins and cls in __builtins__.values(): |
|
215 | 228 | continue |
|
216 | 229 | |
|
217 | 230 | name = self.class_name(cls, parts) |
|
218 | 231 | |
|
219 | 232 | # Write the node |
|
220 | 233 | this_node_options = n_options.copy() |
|
221 | 234 | url = urls.get(self.class_name(cls)) |
|
222 | 235 | if url is not None: |
|
223 | 236 | this_node_options['URL'] = '"%s"' % url |
|
224 | 237 | fd.write(' "%s" [%s];\n' % |
|
225 | 238 | (name, self._format_node_options(this_node_options))) |
|
226 | 239 | |
|
227 | 240 | # Write the edges |
|
228 | 241 | for base in cls.__bases__: |
|
229 | 242 | if not self.show_builtins and base in __builtins__.values(): |
|
230 | 243 | continue |
|
231 | 244 | |
|
232 | 245 | base_name = self.class_name(base, parts) |
|
233 | 246 | fd.write(' "%s" -> "%s" [%s];\n' % |
|
234 | 247 | (base_name, name, |
|
235 | 248 | self._format_node_options(e_options))) |
|
236 | 249 | fd.write('}\n') |
|
237 | 250 | |
|
238 | 251 | def run_dot(self, args, name, parts=0, urls={}, |
|
239 | 252 | graph_options={}, node_options={}, edge_options={}): |
|
240 | 253 | """ |
|
241 | 254 | Run graphviz 'dot' over this graph, returning whatever 'dot' |
|
242 | 255 | writes to stdout. |
|
243 | 256 | |
|
244 | 257 | *args* will be passed along as commandline arguments. |
|
245 | 258 | |
|
246 | 259 | *name* is the name of the graph |
|
247 | 260 | |
|
248 | 261 | *urls* is a dictionary mapping class names to http urls |
|
249 | 262 | |
|
250 | 263 | Raises DotException for any of the many os and |
|
251 | 264 | installation-related errors that may occur. |
|
252 | 265 | """ |
|
253 | 266 | try: |
|
254 | 267 | dot = subprocess.Popen(['dot'] + list(args), |
|
255 | 268 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
|
256 | 269 | close_fds=True) |
|
257 | 270 | except OSError: |
|
258 | 271 | raise DotException("Could not execute 'dot'. Are you sure you have 'graphviz' installed?") |
|
259 | 272 | except ValueError: |
|
260 | 273 | raise DotException("'dot' called with invalid arguments") |
|
261 | 274 | except: |
|
262 | 275 | raise DotException("Unexpected error calling 'dot'") |
|
263 | 276 | |
|
264 | 277 | self.generate_dot(dot.stdin, name, parts, urls, graph_options, |
|
265 | 278 | node_options, edge_options) |
|
266 | 279 | dot.stdin.close() |
|
267 | 280 | result = dot.stdout.read() |
|
268 | 281 | returncode = dot.wait() |
|
269 | 282 | if returncode != 0: |
|
270 | 283 | raise DotException("'dot' returned the errorcode %d" % returncode) |
|
271 | 284 | return result |
|
272 | 285 | |
|
273 | 286 | class inheritance_diagram(Body, Element): |
|
274 | 287 | """ |
|
275 | 288 | A docutils node to use as a placeholder for the inheritance |
|
276 | 289 | diagram. |
|
277 | 290 | """ |
|
278 | 291 | pass |
|
279 | 292 | |
|
280 |
def inheritance_diagram_directive |
|
|
293 | def inheritance_diagram_directive(name, arguments, options, content, lineno, | |
|
294 | content_offset, block_text, state, | |
|
295 | state_machine): | |
|
281 | 296 | """ |
|
282 | 297 | Run when the inheritance_diagram directive is first encountered. |
|
283 | 298 | """ |
|
284 | 299 | node = inheritance_diagram() |
|
285 | 300 | |
|
301 | class_names = arguments | |
|
302 | ||
|
286 | 303 | # Create a graph starting with the list of classes |
|
287 | 304 | graph = InheritanceGraph(class_names) |
|
288 | 305 | |
|
289 | 306 | # Create xref nodes for each target of the graph's image map and |
|
290 | 307 | # add them to the doc tree so that Sphinx can resolve the |
|
291 | 308 | # references to real URLs later. These nodes will eventually be |
|
292 | 309 | # removed from the doctree after we're done with them. |
|
293 | 310 | for name in graph.get_all_class_names(): |
|
294 | 311 | refnodes, x = xfileref_role( |
|
295 | 312 | 'class', ':class:`%s`' % name, name, 0, state) |
|
296 | 313 | node.extend(refnodes) |
|
297 | 314 | # Store the graph object so we can use it to generate the |
|
298 | 315 | # dot file later |
|
299 | 316 | node['graph'] = graph |
|
300 | 317 | # Store the original content for use as a hash |
|
301 | 318 | node['parts'] = options.get('parts', 0) |
|
302 | 319 | node['content'] = " ".join(class_names) |
|
303 | 320 | return [node] |
|
304 | 321 | |
|
305 | 322 | def get_graph_hash(node): |
|
306 | 323 | return md5(node['content'] + str(node['parts'])).hexdigest()[-10:] |
|
307 | 324 | |
|
308 | 325 | def html_output_graph(self, node): |
|
309 | 326 | """ |
|
310 | 327 | Output the graph for HTML. This will insert a PNG with clickable |
|
311 | 328 | image map. |
|
312 | 329 | """ |
|
313 | 330 | graph = node['graph'] |
|
314 | 331 | parts = node['parts'] |
|
315 | 332 | |
|
316 | 333 | graph_hash = get_graph_hash(node) |
|
317 | 334 | name = "inheritance%s" % graph_hash |
|
318 | png_path = os.path.join('_static', name + ".png") | |
|
319 | ||
|
320 | path = '_static' | |
|
321 | source = self.document.attributes['source'] | |
|
322 | count = source.split('/doc/')[-1].count('/') | |
|
323 | for i in range(count): | |
|
324 | if os.path.exists(path): break | |
|
325 | path = '../'+path | |
|
326 | path = '../'+path #specifically added for matplotlib | |
|
335 | path = '_images' | |
|
336 | dest_path = os.path.join(setup.app.builder.outdir, path) | |
|
337 | if not os.path.exists(dest_path): | |
|
338 | os.makedirs(dest_path) | |
|
339 | png_path = os.path.join(dest_path, name + ".png") | |
|
340 | path = setup.app.builder.imgpath | |
|
327 | 341 | |
|
328 | 342 | # Create a mapping from fully-qualified class names to URLs. |
|
329 | 343 | urls = {} |
|
330 | 344 | for child in node: |
|
331 | 345 | if child.get('refuri') is not None: |
|
332 | 346 | urls[child['reftitle']] = child.get('refuri') |
|
333 | 347 | elif child.get('refid') is not None: |
|
334 | 348 | urls[child['reftitle']] = '#' + child.get('refid') |
|
335 | 349 | |
|
336 | 350 | # These arguments to dot will save a PNG file to disk and write |
|
337 | 351 | # an HTML image map to stdout. |
|
338 | 352 | image_map = graph.run_dot(['-Tpng', '-o%s' % png_path, '-Tcmapx'], |
|
339 | 353 | name, parts, urls) |
|
340 | 354 | return ('<img src="%s/%s.png" usemap="#%s" class="inheritance"/>%s' % |
|
341 | 355 | (path, name, name, image_map)) |
|
342 | 356 | |
|
343 | 357 | def latex_output_graph(self, node): |
|
344 | 358 | """ |
|
345 | 359 | Output the graph for LaTeX. This will insert a PDF. |
|
346 | 360 | """ |
|
347 | 361 | graph = node['graph'] |
|
348 | 362 | parts = node['parts'] |
|
349 | 363 | |
|
350 | 364 | graph_hash = get_graph_hash(node) |
|
351 | 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 | 371 | graph.run_dot(['-Tpdf', '-o%s' % pdf_path], |
|
355 | 372 | name, parts, graph_options={'size': '"6.0,6.0"'}) |
|
356 |
return '\\includegraphics{ |
|
|
373 | return '\n\\includegraphics{%s}\n\n' % pdf_path | |
|
357 | 374 | |
|
358 | 375 | def visit_inheritance_diagram(inner_func): |
|
359 | 376 | """ |
|
360 | 377 | This is just a wrapper around html/latex_output_graph to make it |
|
361 | 378 | easier to handle errors and insert warnings. |
|
362 | 379 | """ |
|
363 | 380 | def visitor(self, node): |
|
364 | 381 | try: |
|
365 | 382 | content = inner_func(self, node) |
|
366 | 383 | except DotException, e: |
|
367 | 384 | # Insert the exception as a warning in the document |
|
368 | 385 | warning = self.document.reporter.warning(str(e), line=node.line) |
|
369 | 386 | warning.parent = node |
|
370 | 387 | node.children = [warning] |
|
371 | 388 | else: |
|
372 | 389 | source = self.document.attributes['source'] |
|
373 | 390 | self.body.append(content) |
|
374 | 391 | node.children = [] |
|
375 | 392 | return visitor |
|
376 | 393 | |
|
377 | 394 | def do_nothing(self, node): |
|
378 | 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 | 397 | def setup(app): |
|
415 | app.add_node(inheritance_diagram) | |
|
416 | ||
|
417 | HTMLTranslator.visit_inheritance_diagram = \ | |
|
418 | visit_inheritance_diagram(html_output_graph) | |
|
419 | HTMLTranslator.depart_inheritance_diagram = do_nothing | |
|
420 | ||
|
421 | LaTeXTranslator.visit_inheritance_diagram = \ | |
|
422 | visit_inheritance_diagram(latex_output_graph) | |
|
423 | LaTeXTranslator.depart_inheritance_diagram = do_nothing | |
|
398 | setup.app = app | |
|
399 | setup.confdir = app.confdir | |
|
400 | ||
|
401 | app.add_node( | |
|
402 | inheritance_diagram, | |
|
403 | latex=(visit_inheritance_diagram(latex_output_graph), do_nothing), | |
|
404 | html=(visit_inheritance_diagram(html_output_graph), do_nothing)) | |
|
405 | app.add_directive( | |
|
406 | 'inheritance-diagram', inheritance_diagram_directive, | |
|
407 | False, (1, 100, 0), parts = directives.nonnegative_int) |
@@ -1,75 +1,98 | |||
|
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 | 11 | from pygments.lexer import Lexer, do_insertions |
|
2 |
from pygments.lexers.agile import PythonConsoleLexer, PythonLexer, |
|
|
3 | PythonTracebackLexer | |
|
12 | from pygments.lexers.agile import (PythonConsoleLexer, PythonLexer, | |
|
13 | PythonTracebackLexer) | |
|
4 | 14 | from pygments.token import Comment, Generic |
|
15 | ||
|
5 | 16 | from sphinx import highlighting |
|
6 | import re | |
|
7 | 17 | |
|
18 | ||
|
19 | #----------------------------------------------------------------------------- | |
|
20 | # Global constants | |
|
8 | 21 | line_re = re.compile('.*?\n') |
|
9 | 22 | |
|
23 | #----------------------------------------------------------------------------- | |
|
24 | # Code begins - classes and functions | |
|
25 | ||
|
10 | 26 | class IPythonConsoleLexer(Lexer): |
|
11 | 27 | """ |
|
12 | 28 | For IPython console output or doctests, such as: |
|
13 | 29 | |
|
14 | Tracebacks are not currently supported. | |
|
15 | ||
|
16 | 30 | .. sourcecode:: ipython |
|
17 | 31 | |
|
18 | 32 | In [1]: a = 'foo' |
|
19 | 33 | |
|
20 | 34 | In [2]: a |
|
21 | 35 | Out[2]: 'foo' |
|
22 | 36 | |
|
23 | 37 | In [3]: print a |
|
24 | 38 | foo |
|
25 | 39 | |
|
26 | 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 | 49 | name = 'IPython console session' |
|
29 | 50 | aliases = ['ipython'] |
|
30 | 51 | mimetypes = ['text/x-ipython-console'] |
|
31 | 52 | input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)") |
|
32 | 53 | output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)") |
|
33 | 54 | continue_prompt = re.compile(" \.\.\.+:") |
|
34 | 55 | tb_start = re.compile("\-+") |
|
35 | 56 | |
|
36 | 57 | def get_tokens_unprocessed(self, text): |
|
37 | 58 | pylexer = PythonLexer(**self.options) |
|
38 | 59 | tblexer = PythonTracebackLexer(**self.options) |
|
39 | 60 | |
|
40 | 61 | curcode = '' |
|
41 | 62 | insertions = [] |
|
42 | 63 | for match in line_re.finditer(text): |
|
43 | 64 | line = match.group() |
|
44 | 65 | input_prompt = self.input_prompt.match(line) |
|
45 | 66 | continue_prompt = self.continue_prompt.match(line.rstrip()) |
|
46 | 67 | output_prompt = self.output_prompt.match(line) |
|
47 | 68 | if line.startswith("#"): |
|
48 | 69 | insertions.append((len(curcode), |
|
49 | 70 | [(0, Comment, line)])) |
|
50 | 71 | elif input_prompt is not None: |
|
51 | 72 | insertions.append((len(curcode), |
|
52 | 73 | [(0, Generic.Prompt, input_prompt.group())])) |
|
53 | 74 | curcode += line[input_prompt.end():] |
|
54 | 75 | elif continue_prompt is not None: |
|
55 | 76 | insertions.append((len(curcode), |
|
56 | 77 | [(0, Generic.Prompt, continue_prompt.group())])) |
|
57 | 78 | curcode += line[continue_prompt.end():] |
|
58 | 79 | elif output_prompt is not None: |
|
59 | 80 | insertions.append((len(curcode), |
|
60 | 81 | [(0, Generic.Output, output_prompt.group())])) |
|
61 | 82 | curcode += line[output_prompt.end():] |
|
62 | 83 | else: |
|
63 | 84 | if curcode: |
|
64 | 85 | for item in do_insertions(insertions, |
|
65 | 86 | pylexer.get_tokens_unprocessed(curcode)): |
|
66 | 87 | yield item |
|
67 | 88 | curcode = '' |
|
68 | 89 | insertions = [] |
|
69 | 90 | yield match.start(), Generic.Output, line |
|
70 | 91 | if curcode: |
|
71 | 92 | for item in do_insertions(insertions, |
|
72 | 93 | pylexer.get_tokens_unprocessed(curcode)): |
|
73 | 94 | yield item |
|
74 | 95 | |
|
96 | #----------------------------------------------------------------------------- | |
|
97 | # Register the extension as a valid pygments lexer | |
|
75 | 98 | highlighting.lexers['ipython'] = IPythonConsoleLexer() |
General Comments 0
You need to be logged in to leave comments.
Login now