Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,48 +1,51 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Class which mimics a module. |
|
3 | Class which mimics a module. | |
4 |
|
4 | |||
5 | Needed to allow pickle to correctly resolve namespaces during IPython |
|
5 | Needed to allow pickle to correctly resolve namespaces during IPython | |
6 | sessions. |
|
6 | sessions. | |
7 |
|
7 | |||
8 |
$Id: FakeModule.py |
|
8 | $Id: FakeModule.py 1322 2006-05-24 07:51:39Z fperez $""" | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu> |
|
11 | # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | class FakeModule: |
|
17 | class FakeModule: | |
18 | """Simple class with attribute access to fake a module. |
|
18 | """Simple class with attribute access to fake a module. | |
19 |
|
19 | |||
20 | This is not meant to replace a module, but to allow inserting a fake |
|
20 | This is not meant to replace a module, but to allow inserting a fake | |
21 | module in sys.modules so that systems which rely on run-time module |
|
21 | module in sys.modules so that systems which rely on run-time module | |
22 | importing (like shelve and pickle) work correctly in interactive IPython |
|
22 | importing (like shelve and pickle) work correctly in interactive IPython | |
23 | sessions. |
|
23 | sessions. | |
24 |
|
24 | |||
25 | Do NOT use this code for anything other than this IPython private hack.""" |
|
25 | Do NOT use this code for anything other than this IPython private hack.""" | |
26 |
|
26 | |||
27 | def __init__(self,adict): |
|
27 | def __init__(self,adict): | |
28 |
|
28 | |||
29 | # It seems pydoc (and perhaps others) needs any module instance to |
|
29 | # It seems pydoc (and perhaps others) needs any module instance to | |
30 | # implement a __nonzero__ method, so we add it if missing: |
|
30 | # implement a __nonzero__ method, so we add it if missing: | |
31 | if '__nonzero__' not in adict: |
|
31 | if '__nonzero__' not in adict: | |
32 | def __nonzero__(): |
|
32 | def __nonzero__(): | |
33 | return 1 |
|
33 | return 1 | |
34 | adict['__nonzero__'] = __nonzero__ |
|
34 | adict['__nonzero__'] = __nonzero__ | |
35 |
|
35 | |||
36 | self.__dict__ = adict |
|
36 | self.__dict__ = adict | |
37 |
|
37 | |||
|
38 | # modules should have a __file__ attribute | |||
|
39 | adict['__file__'] = __file__ | |||
|
40 | ||||
38 | def __getattr__(self,key): |
|
41 | def __getattr__(self,key): | |
39 | try: |
|
42 | try: | |
40 | return self.__dict__[key] |
|
43 | return self.__dict__[key] | |
41 | except KeyError, e: |
|
44 | except KeyError, e: | |
42 | raise AttributeError("FakeModule object has no attribute %s" % e) |
|
45 | raise AttributeError("FakeModule object has no attribute %s" % e) | |
43 |
|
46 | |||
44 | def __str__(self): |
|
47 | def __str__(self): | |
45 | return "<IPython.FakeModule instance>" |
|
48 | return "<IPython.FakeModule instance>" | |
46 |
|
49 | |||
47 | def __repr__(self): |
|
50 | def __repr__(self): | |
48 | return str(self) |
|
51 | return str(self) |
@@ -1,2953 +1,2958 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 |
|
3 | |||
4 |
$Id: Magic.py 13 |
|
4 | $Id: Magic.py 1322 2006-05-24 07:51:39Z fperez $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 |
|
13 | |||
14 | #**************************************************************************** |
|
14 | #**************************************************************************** | |
15 | # Modules and globals |
|
15 | # Modules and globals | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
18 | __author__ = '%s <%s>\n%s <%s>' % \ | |
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
20 | __license__ = Release.license |
|
20 | __license__ = Release.license | |
21 |
|
21 | |||
22 | # Python standard modules |
|
22 | # Python standard modules | |
23 | import __builtin__ |
|
23 | import __builtin__ | |
24 | import bdb |
|
24 | import bdb | |
25 | import inspect |
|
25 | import inspect | |
26 | import os |
|
26 | import os | |
27 | import pdb |
|
27 | import pdb | |
28 | import pydoc |
|
28 | import pydoc | |
29 | import shlex |
|
29 | import shlex | |
30 | import sys |
|
30 | import sys | |
31 | import re |
|
31 | import re | |
32 | import tempfile |
|
32 | import tempfile | |
33 | import time |
|
33 | import time | |
34 | import cPickle as pickle |
|
34 | import cPickle as pickle | |
35 | import textwrap |
|
35 | import textwrap | |
36 | from cStringIO import StringIO |
|
36 | from cStringIO import StringIO | |
37 | from getopt import getopt,GetoptError |
|
37 | from getopt import getopt,GetoptError | |
38 | from pprint import pprint, pformat |
|
38 | from pprint import pprint, pformat | |
39 |
|
39 | |||
40 | # profile isn't bundled by default in Debian for license reasons |
|
40 | # profile isn't bundled by default in Debian for license reasons | |
41 | try: |
|
41 | try: | |
42 | import profile,pstats |
|
42 | import profile,pstats | |
43 | except ImportError: |
|
43 | except ImportError: | |
44 | profile = pstats = None |
|
44 | profile = pstats = None | |
45 |
|
45 | |||
46 | # Homebrewed |
|
46 | # Homebrewed | |
47 | import IPython |
|
47 | import IPython | |
48 | from IPython import Debugger, OInspect, wildcard |
|
48 | from IPython import Debugger, OInspect, wildcard | |
49 | from IPython.FakeModule import FakeModule |
|
49 | from IPython.FakeModule import FakeModule | |
50 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
50 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
51 | from IPython.PyColorize import Parser |
|
51 | from IPython.PyColorize import Parser | |
52 | from IPython.ipstruct import Struct |
|
52 | from IPython.ipstruct import Struct | |
53 | from IPython.macro import Macro |
|
53 | from IPython.macro import Macro | |
54 | from IPython.genutils import * |
|
54 | from IPython.genutils import * | |
55 | from IPython import platutils |
|
55 | from IPython import platutils | |
56 |
|
56 | |||
57 | #*************************************************************************** |
|
57 | #*************************************************************************** | |
58 | # Utility functions |
|
58 | # Utility functions | |
59 | def on_off(tag): |
|
59 | def on_off(tag): | |
60 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
60 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
61 | return ['OFF','ON'][tag] |
|
61 | return ['OFF','ON'][tag] | |
62 |
|
62 | |||
63 | class Bunch: pass |
|
63 | class Bunch: pass | |
64 |
|
64 | |||
65 | #*************************************************************************** |
|
65 | #*************************************************************************** | |
66 | # Main class implementing Magic functionality |
|
66 | # Main class implementing Magic functionality | |
67 | class Magic: |
|
67 | class Magic: | |
68 | """Magic functions for InteractiveShell. |
|
68 | """Magic functions for InteractiveShell. | |
69 |
|
69 | |||
70 | Shell functions which can be reached as %function_name. All magic |
|
70 | Shell functions which can be reached as %function_name. All magic | |
71 | functions should accept a string, which they can parse for their own |
|
71 | functions should accept a string, which they can parse for their own | |
72 | needs. This can make some functions easier to type, eg `%cd ../` |
|
72 | needs. This can make some functions easier to type, eg `%cd ../` | |
73 | vs. `%cd("../")` |
|
73 | vs. `%cd("../")` | |
74 |
|
74 | |||
75 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
75 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
76 | at the command line, but it is is needed in the definition. """ |
|
76 | at the command line, but it is is needed in the definition. """ | |
77 |
|
77 | |||
78 | # class globals |
|
78 | # class globals | |
79 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
79 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
80 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
80 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
81 |
|
81 | |||
82 | #...................................................................... |
|
82 | #...................................................................... | |
83 | # some utility functions |
|
83 | # some utility functions | |
84 |
|
84 | |||
85 | def __init__(self,shell): |
|
85 | def __init__(self,shell): | |
86 |
|
86 | |||
87 | self.options_table = {} |
|
87 | self.options_table = {} | |
88 | if profile is None: |
|
88 | if profile is None: | |
89 | self.magic_prun = self.profile_missing_notice |
|
89 | self.magic_prun = self.profile_missing_notice | |
90 | self.shell = shell |
|
90 | self.shell = shell | |
91 |
|
91 | |||
92 | # namespace for holding state we may need |
|
92 | # namespace for holding state we may need | |
93 | self._magic_state = Bunch() |
|
93 | self._magic_state = Bunch() | |
94 |
|
94 | |||
95 | def profile_missing_notice(self, *args, **kwargs): |
|
95 | def profile_missing_notice(self, *args, **kwargs): | |
96 | error("""\ |
|
96 | error("""\ | |
97 | The profile module could not be found. If you are a Debian user, |
|
97 | The profile module could not be found. If you are a Debian user, | |
98 | it has been removed from the standard Debian package because of its non-free |
|
98 | it has been removed from the standard Debian package because of its non-free | |
99 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
99 | license. To use profiling, please install"python2.3-profiler" from non-free.""") | |
100 |
|
100 | |||
101 | def default_option(self,fn,optstr): |
|
101 | def default_option(self,fn,optstr): | |
102 | """Make an entry in the options_table for fn, with value optstr""" |
|
102 | """Make an entry in the options_table for fn, with value optstr""" | |
103 |
|
103 | |||
104 | if fn not in self.lsmagic(): |
|
104 | if fn not in self.lsmagic(): | |
105 | error("%s is not a magic function" % fn) |
|
105 | error("%s is not a magic function" % fn) | |
106 | self.options_table[fn] = optstr |
|
106 | self.options_table[fn] = optstr | |
107 |
|
107 | |||
108 | def lsmagic(self): |
|
108 | def lsmagic(self): | |
109 | """Return a list of currently available magic functions. |
|
109 | """Return a list of currently available magic functions. | |
110 |
|
110 | |||
111 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
111 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
112 | ['magic_ls','magic_cd',...]""" |
|
112 | ['magic_ls','magic_cd',...]""" | |
113 |
|
113 | |||
114 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
114 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
115 |
|
115 | |||
116 | # magics in class definition |
|
116 | # magics in class definition | |
117 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
117 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
118 | callable(Magic.__dict__[fn]) |
|
118 | callable(Magic.__dict__[fn]) | |
119 | # in instance namespace (run-time user additions) |
|
119 | # in instance namespace (run-time user additions) | |
120 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
120 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
121 | callable(self.__dict__[fn]) |
|
121 | callable(self.__dict__[fn]) | |
122 | # and bound magics by user (so they can access self): |
|
122 | # and bound magics by user (so they can access self): | |
123 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
123 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
124 | callable(self.__class__.__dict__[fn]) |
|
124 | callable(self.__class__.__dict__[fn]) | |
125 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
125 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
126 | filter(inst_magic,self.__dict__.keys()) + \ |
|
126 | filter(inst_magic,self.__dict__.keys()) + \ | |
127 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
127 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
128 | out = [] |
|
128 | out = [] | |
129 | for fn in magics: |
|
129 | for fn in magics: | |
130 | out.append(fn.replace('magic_','',1)) |
|
130 | out.append(fn.replace('magic_','',1)) | |
131 | out.sort() |
|
131 | out.sort() | |
132 | return out |
|
132 | return out | |
133 |
|
133 | |||
134 | def extract_input_slices(self,slices,raw=False): |
|
134 | def extract_input_slices(self,slices,raw=False): | |
135 | """Return as a string a set of input history slices. |
|
135 | """Return as a string a set of input history slices. | |
136 |
|
136 | |||
137 | Inputs: |
|
137 | Inputs: | |
138 |
|
138 | |||
139 | - slices: the set of slices is given as a list of strings (like |
|
139 | - slices: the set of slices is given as a list of strings (like | |
140 | ['1','4:8','9'], since this function is for use by magic functions |
|
140 | ['1','4:8','9'], since this function is for use by magic functions | |
141 | which get their arguments as strings. |
|
141 | which get their arguments as strings. | |
142 |
|
142 | |||
143 | Optional inputs: |
|
143 | Optional inputs: | |
144 |
|
144 | |||
145 | - raw(False): by default, the processed input is used. If this is |
|
145 | - raw(False): by default, the processed input is used. If this is | |
146 | true, the raw input history is used instead. |
|
146 | true, the raw input history is used instead. | |
147 |
|
147 | |||
148 | Note that slices can be called with two notations: |
|
148 | Note that slices can be called with two notations: | |
149 |
|
149 | |||
150 | N:M -> standard python form, means including items N...(M-1). |
|
150 | N:M -> standard python form, means including items N...(M-1). | |
151 |
|
151 | |||
152 | N-M -> include items N..M (closed endpoint).""" |
|
152 | N-M -> include items N..M (closed endpoint).""" | |
153 |
|
153 | |||
154 | if raw: |
|
154 | if raw: | |
155 | hist = self.shell.input_hist_raw |
|
155 | hist = self.shell.input_hist_raw | |
156 | else: |
|
156 | else: | |
157 | hist = self.shell.input_hist |
|
157 | hist = self.shell.input_hist | |
158 |
|
158 | |||
159 | cmds = [] |
|
159 | cmds = [] | |
160 | for chunk in slices: |
|
160 | for chunk in slices: | |
161 | if ':' in chunk: |
|
161 | if ':' in chunk: | |
162 | ini,fin = map(int,chunk.split(':')) |
|
162 | ini,fin = map(int,chunk.split(':')) | |
163 | elif '-' in chunk: |
|
163 | elif '-' in chunk: | |
164 | ini,fin = map(int,chunk.split('-')) |
|
164 | ini,fin = map(int,chunk.split('-')) | |
165 | fin += 1 |
|
165 | fin += 1 | |
166 | else: |
|
166 | else: | |
167 | ini = int(chunk) |
|
167 | ini = int(chunk) | |
168 | fin = ini+1 |
|
168 | fin = ini+1 | |
169 | cmds.append(hist[ini:fin]) |
|
169 | cmds.append(hist[ini:fin]) | |
170 | return cmds |
|
170 | return cmds | |
171 |
|
171 | |||
172 | def _ofind(self,oname): |
|
172 | def _ofind(self,oname): | |
173 | """Find an object in the available namespaces. |
|
173 | """Find an object in the available namespaces. | |
174 |
|
174 | |||
175 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
175 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
176 |
|
176 | |||
177 | Has special code to detect magic functions. |
|
177 | Has special code to detect magic functions. | |
178 | """ |
|
178 | """ | |
179 |
|
179 | |||
180 | oname = oname.strip() |
|
180 | oname = oname.strip() | |
181 |
|
181 | |||
182 | # Namespaces to search in: |
|
182 | # Namespaces to search in: | |
183 | user_ns = self.shell.user_ns |
|
183 | user_ns = self.shell.user_ns | |
184 | internal_ns = self.shell.internal_ns |
|
184 | internal_ns = self.shell.internal_ns | |
185 | builtin_ns = __builtin__.__dict__ |
|
185 | builtin_ns = __builtin__.__dict__ | |
186 | alias_ns = self.shell.alias_table |
|
186 | alias_ns = self.shell.alias_table | |
187 |
|
187 | |||
188 | # Put them in a list. The order is important so that we find things in |
|
188 | # Put them in a list. The order is important so that we find things in | |
189 | # the same order that Python finds them. |
|
189 | # the same order that Python finds them. | |
190 | namespaces = [ ('Interactive',user_ns), |
|
190 | namespaces = [ ('Interactive',user_ns), | |
191 | ('IPython internal',internal_ns), |
|
191 | ('IPython internal',internal_ns), | |
192 | ('Python builtin',builtin_ns), |
|
192 | ('Python builtin',builtin_ns), | |
193 | ('Alias',alias_ns), |
|
193 | ('Alias',alias_ns), | |
194 | ] |
|
194 | ] | |
195 |
|
195 | |||
196 | # initialize results to 'null' |
|
196 | # initialize results to 'null' | |
197 | found = 0; obj = None; ospace = None; ds = None; |
|
197 | found = 0; obj = None; ospace = None; ds = None; | |
198 | ismagic = 0; isalias = 0 |
|
198 | ismagic = 0; isalias = 0 | |
199 |
|
199 | |||
200 | # Look for the given name by splitting it in parts. If the head is |
|
200 | # Look for the given name by splitting it in parts. If the head is | |
201 | # found, then we look for all the remaining parts as members, and only |
|
201 | # found, then we look for all the remaining parts as members, and only | |
202 | # declare success if we can find them all. |
|
202 | # declare success if we can find them all. | |
203 | oname_parts = oname.split('.') |
|
203 | oname_parts = oname.split('.') | |
204 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
204 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
205 | for nsname,ns in namespaces: |
|
205 | for nsname,ns in namespaces: | |
206 | try: |
|
206 | try: | |
207 | obj = ns[oname_head] |
|
207 | obj = ns[oname_head] | |
208 | except KeyError: |
|
208 | except KeyError: | |
209 | continue |
|
209 | continue | |
210 | else: |
|
210 | else: | |
211 | for part in oname_rest: |
|
211 | for part in oname_rest: | |
212 | try: |
|
212 | try: | |
213 | obj = getattr(obj,part) |
|
213 | obj = getattr(obj,part) | |
214 | except: |
|
214 | except: | |
215 | # Blanket except b/c some badly implemented objects |
|
215 | # Blanket except b/c some badly implemented objects | |
216 | # allow __getattr__ to raise exceptions other than |
|
216 | # allow __getattr__ to raise exceptions other than | |
217 | # AttributeError, which then crashes IPython. |
|
217 | # AttributeError, which then crashes IPython. | |
218 | break |
|
218 | break | |
219 | else: |
|
219 | else: | |
220 | # If we finish the for loop (no break), we got all members |
|
220 | # If we finish the for loop (no break), we got all members | |
221 | found = 1 |
|
221 | found = 1 | |
222 | ospace = nsname |
|
222 | ospace = nsname | |
223 | if ns == alias_ns: |
|
223 | if ns == alias_ns: | |
224 | isalias = 1 |
|
224 | isalias = 1 | |
225 | break # namespace loop |
|
225 | break # namespace loop | |
226 |
|
226 | |||
227 | # Try to see if it's magic |
|
227 | # Try to see if it's magic | |
228 | if not found: |
|
228 | if not found: | |
229 | if oname.startswith(self.shell.ESC_MAGIC): |
|
229 | if oname.startswith(self.shell.ESC_MAGIC): | |
230 | oname = oname[1:] |
|
230 | oname = oname[1:] | |
231 | obj = getattr(self,'magic_'+oname,None) |
|
231 | obj = getattr(self,'magic_'+oname,None) | |
232 | if obj is not None: |
|
232 | if obj is not None: | |
233 | found = 1 |
|
233 | found = 1 | |
234 | ospace = 'IPython internal' |
|
234 | ospace = 'IPython internal' | |
235 | ismagic = 1 |
|
235 | ismagic = 1 | |
236 |
|
236 | |||
237 | # Last try: special-case some literals like '', [], {}, etc: |
|
237 | # Last try: special-case some literals like '', [], {}, etc: | |
238 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
238 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
239 | obj = eval(oname_head) |
|
239 | obj = eval(oname_head) | |
240 | found = 1 |
|
240 | found = 1 | |
241 | ospace = 'Interactive' |
|
241 | ospace = 'Interactive' | |
242 |
|
242 | |||
243 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
243 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
244 | 'ismagic':ismagic, 'isalias':isalias} |
|
244 | 'ismagic':ismagic, 'isalias':isalias} | |
245 |
|
245 | |||
246 | def arg_err(self,func): |
|
246 | def arg_err(self,func): | |
247 | """Print docstring if incorrect arguments were passed""" |
|
247 | """Print docstring if incorrect arguments were passed""" | |
248 | print 'Error in arguments:' |
|
248 | print 'Error in arguments:' | |
249 | print OInspect.getdoc(func) |
|
249 | print OInspect.getdoc(func) | |
250 |
|
250 | |||
251 | def format_latex(self,strng): |
|
251 | def format_latex(self,strng): | |
252 | """Format a string for latex inclusion.""" |
|
252 | """Format a string for latex inclusion.""" | |
253 |
|
253 | |||
254 | # Characters that need to be escaped for latex: |
|
254 | # Characters that need to be escaped for latex: | |
255 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
255 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
256 | # Magic command names as headers: |
|
256 | # Magic command names as headers: | |
257 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
257 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
258 | re.MULTILINE) |
|
258 | re.MULTILINE) | |
259 | # Magic commands |
|
259 | # Magic commands | |
260 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
260 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
261 | re.MULTILINE) |
|
261 | re.MULTILINE) | |
262 | # Paragraph continue |
|
262 | # Paragraph continue | |
263 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
263 | par_re = re.compile(r'\\$',re.MULTILINE) | |
264 |
|
264 | |||
265 | # The "\n" symbol |
|
265 | # The "\n" symbol | |
266 | newline_re = re.compile(r'\\n') |
|
266 | newline_re = re.compile(r'\\n') | |
267 |
|
267 | |||
268 | # Now build the string for output: |
|
268 | # Now build the string for output: | |
269 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
269 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
270 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
270 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
271 | strng) |
|
271 | strng) | |
272 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
272 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
273 | strng = par_re.sub(r'\\\\',strng) |
|
273 | strng = par_re.sub(r'\\\\',strng) | |
274 | strng = escape_re.sub(r'\\\1',strng) |
|
274 | strng = escape_re.sub(r'\\\1',strng) | |
275 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
275 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
276 | return strng |
|
276 | return strng | |
277 |
|
277 | |||
278 | def format_screen(self,strng): |
|
278 | def format_screen(self,strng): | |
279 | """Format a string for screen printing. |
|
279 | """Format a string for screen printing. | |
280 |
|
280 | |||
281 | This removes some latex-type format codes.""" |
|
281 | This removes some latex-type format codes.""" | |
282 | # Paragraph continue |
|
282 | # Paragraph continue | |
283 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
283 | par_re = re.compile(r'\\$',re.MULTILINE) | |
284 | strng = par_re.sub('',strng) |
|
284 | strng = par_re.sub('',strng) | |
285 | return strng |
|
285 | return strng | |
286 |
|
286 | |||
287 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
287 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
288 | """Parse options passed to an argument string. |
|
288 | """Parse options passed to an argument string. | |
289 |
|
289 | |||
290 | The interface is similar to that of getopt(), but it returns back a |
|
290 | The interface is similar to that of getopt(), but it returns back a | |
291 | Struct with the options as keys and the stripped argument string still |
|
291 | Struct with the options as keys and the stripped argument string still | |
292 | as a string. |
|
292 | as a string. | |
293 |
|
293 | |||
294 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
294 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
295 | This allows us to easily expand variables, glob files, quote |
|
295 | This allows us to easily expand variables, glob files, quote | |
296 | arguments, etc. |
|
296 | arguments, etc. | |
297 |
|
297 | |||
298 | Options: |
|
298 | Options: | |
299 | -mode: default 'string'. If given as 'list', the argument string is |
|
299 | -mode: default 'string'. If given as 'list', the argument string is | |
300 | returned as a list (split on whitespace) instead of a string. |
|
300 | returned as a list (split on whitespace) instead of a string. | |
301 |
|
301 | |||
302 | -list_all: put all option values in lists. Normally only options |
|
302 | -list_all: put all option values in lists. Normally only options | |
303 | appearing more than once are put in a list.""" |
|
303 | appearing more than once are put in a list.""" | |
304 |
|
304 | |||
305 | # inject default options at the beginning of the input line |
|
305 | # inject default options at the beginning of the input line | |
306 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
306 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
307 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
307 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
308 |
|
308 | |||
309 | mode = kw.get('mode','string') |
|
309 | mode = kw.get('mode','string') | |
310 | if mode not in ['string','list']: |
|
310 | if mode not in ['string','list']: | |
311 | raise ValueError,'incorrect mode given: %s' % mode |
|
311 | raise ValueError,'incorrect mode given: %s' % mode | |
312 | # Get options |
|
312 | # Get options | |
313 | list_all = kw.get('list_all',0) |
|
313 | list_all = kw.get('list_all',0) | |
314 |
|
314 | |||
315 | # Check if we have more than one argument to warrant extra processing: |
|
315 | # Check if we have more than one argument to warrant extra processing: | |
316 | odict = {} # Dictionary with options |
|
316 | odict = {} # Dictionary with options | |
317 | args = arg_str.split() |
|
317 | args = arg_str.split() | |
318 | if len(args) >= 1: |
|
318 | if len(args) >= 1: | |
319 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
319 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
320 | # need to look for options |
|
320 | # need to look for options | |
321 | argv = shlex.split(arg_str) |
|
321 | argv = shlex.split(arg_str) | |
322 | # Do regular option processing |
|
322 | # Do regular option processing | |
323 | try: |
|
323 | try: | |
324 | opts,args = getopt(argv,opt_str,*long_opts) |
|
324 | opts,args = getopt(argv,opt_str,*long_opts) | |
325 | except GetoptError,e: |
|
325 | except GetoptError,e: | |
326 | raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
326 | raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
327 | " ".join(long_opts))) |
|
327 | " ".join(long_opts))) | |
328 | for o,a in opts: |
|
328 | for o,a in opts: | |
329 | if o.startswith('--'): |
|
329 | if o.startswith('--'): | |
330 | o = o[2:] |
|
330 | o = o[2:] | |
331 | else: |
|
331 | else: | |
332 | o = o[1:] |
|
332 | o = o[1:] | |
333 | try: |
|
333 | try: | |
334 | odict[o].append(a) |
|
334 | odict[o].append(a) | |
335 | except AttributeError: |
|
335 | except AttributeError: | |
336 | odict[o] = [odict[o],a] |
|
336 | odict[o] = [odict[o],a] | |
337 | except KeyError: |
|
337 | except KeyError: | |
338 | if list_all: |
|
338 | if list_all: | |
339 | odict[o] = [a] |
|
339 | odict[o] = [a] | |
340 | else: |
|
340 | else: | |
341 | odict[o] = a |
|
341 | odict[o] = a | |
342 |
|
342 | |||
343 | # Prepare opts,args for return |
|
343 | # Prepare opts,args for return | |
344 | opts = Struct(odict) |
|
344 | opts = Struct(odict) | |
345 | if mode == 'string': |
|
345 | if mode == 'string': | |
346 | args = ' '.join(args) |
|
346 | args = ' '.join(args) | |
347 |
|
347 | |||
348 | return opts,args |
|
348 | return opts,args | |
349 |
|
349 | |||
350 | #...................................................................... |
|
350 | #...................................................................... | |
351 | # And now the actual magic functions |
|
351 | # And now the actual magic functions | |
352 |
|
352 | |||
353 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
353 | # Functions for IPython shell work (vars,funcs, config, etc) | |
354 | def magic_lsmagic(self, parameter_s = ''): |
|
354 | def magic_lsmagic(self, parameter_s = ''): | |
355 | """List currently available magic functions.""" |
|
355 | """List currently available magic functions.""" | |
356 | mesc = self.shell.ESC_MAGIC |
|
356 | mesc = self.shell.ESC_MAGIC | |
357 | print 'Available magic functions:\n'+mesc+\ |
|
357 | print 'Available magic functions:\n'+mesc+\ | |
358 | (' '+mesc).join(self.lsmagic()) |
|
358 | (' '+mesc).join(self.lsmagic()) | |
359 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
359 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
360 | return None |
|
360 | return None | |
361 |
|
361 | |||
362 | def magic_magic(self, parameter_s = ''): |
|
362 | def magic_magic(self, parameter_s = ''): | |
363 | """Print information about the magic function system.""" |
|
363 | """Print information about the magic function system.""" | |
364 |
|
364 | |||
365 | mode = '' |
|
365 | mode = '' | |
366 | try: |
|
366 | try: | |
367 | if parameter_s.split()[0] == '-latex': |
|
367 | if parameter_s.split()[0] == '-latex': | |
368 | mode = 'latex' |
|
368 | mode = 'latex' | |
369 | if parameter_s.split()[0] == '-brief': |
|
369 | if parameter_s.split()[0] == '-brief': | |
370 | mode = 'brief' |
|
370 | mode = 'brief' | |
371 | except: |
|
371 | except: | |
372 | pass |
|
372 | pass | |
373 |
|
373 | |||
374 | magic_docs = [] |
|
374 | magic_docs = [] | |
375 | for fname in self.lsmagic(): |
|
375 | for fname in self.lsmagic(): | |
376 | mname = 'magic_' + fname |
|
376 | mname = 'magic_' + fname | |
377 | for space in (Magic,self,self.__class__): |
|
377 | for space in (Magic,self,self.__class__): | |
378 | try: |
|
378 | try: | |
379 | fn = space.__dict__[mname] |
|
379 | fn = space.__dict__[mname] | |
380 | except KeyError: |
|
380 | except KeyError: | |
381 | pass |
|
381 | pass | |
382 | else: |
|
382 | else: | |
383 | break |
|
383 | break | |
384 | if mode == 'brief': |
|
384 | if mode == 'brief': | |
385 | # only first line |
|
385 | # only first line | |
386 | fndoc = fn.__doc__.split('\n',1)[0] |
|
386 | fndoc = fn.__doc__.split('\n',1)[0] | |
387 | else: |
|
387 | else: | |
388 | fndoc = fn.__doc__ |
|
388 | fndoc = fn.__doc__ | |
389 |
|
389 | |||
390 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
390 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
391 | fname,fndoc)) |
|
391 | fname,fndoc)) | |
392 | magic_docs = ''.join(magic_docs) |
|
392 | magic_docs = ''.join(magic_docs) | |
393 |
|
393 | |||
394 | if mode == 'latex': |
|
394 | if mode == 'latex': | |
395 | print self.format_latex(magic_docs) |
|
395 | print self.format_latex(magic_docs) | |
396 | return |
|
396 | return | |
397 | else: |
|
397 | else: | |
398 | magic_docs = self.format_screen(magic_docs) |
|
398 | magic_docs = self.format_screen(magic_docs) | |
399 | if mode == 'brief': |
|
399 | if mode == 'brief': | |
400 | return magic_docs |
|
400 | return magic_docs | |
401 |
|
401 | |||
402 | outmsg = """ |
|
402 | outmsg = """ | |
403 | IPython's 'magic' functions |
|
403 | IPython's 'magic' functions | |
404 | =========================== |
|
404 | =========================== | |
405 |
|
405 | |||
406 | The magic function system provides a series of functions which allow you to |
|
406 | The magic function system provides a series of functions which allow you to | |
407 | control the behavior of IPython itself, plus a lot of system-type |
|
407 | control the behavior of IPython itself, plus a lot of system-type | |
408 | features. All these functions are prefixed with a % character, but parameters |
|
408 | features. All these functions are prefixed with a % character, but parameters | |
409 | are given without parentheses or quotes. |
|
409 | are given without parentheses or quotes. | |
410 |
|
410 | |||
411 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
411 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
412 | %automagic function), you don't need to type in the % explicitly. By default, |
|
412 | %automagic function), you don't need to type in the % explicitly. By default, | |
413 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
413 | IPython ships with automagic on, so you should only rarely need the % escape. | |
414 |
|
414 | |||
415 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
415 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
416 | to 'mydir', if it exists. |
|
416 | to 'mydir', if it exists. | |
417 |
|
417 | |||
418 | You can define your own magic functions to extend the system. See the supplied |
|
418 | You can define your own magic functions to extend the system. See the supplied | |
419 | ipythonrc and example-magic.py files for details (in your ipython |
|
419 | ipythonrc and example-magic.py files for details (in your ipython | |
420 | configuration directory, typically $HOME/.ipython/). |
|
420 | configuration directory, typically $HOME/.ipython/). | |
421 |
|
421 | |||
422 | You can also define your own aliased names for magic functions. In your |
|
422 | You can also define your own aliased names for magic functions. In your | |
423 | ipythonrc file, placing a line like: |
|
423 | ipythonrc file, placing a line like: | |
424 |
|
424 | |||
425 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
425 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
426 |
|
426 | |||
427 | will define %pf as a new name for %profile. |
|
427 | will define %pf as a new name for %profile. | |
428 |
|
428 | |||
429 | You can also call magics in code using the ipmagic() function, which IPython |
|
429 | You can also call magics in code using the ipmagic() function, which IPython | |
430 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
430 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
431 |
|
431 | |||
432 | For a list of the available magic functions, use %lsmagic. For a description |
|
432 | For a list of the available magic functions, use %lsmagic. For a description | |
433 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
433 | of any of them, type %magic_name?, e.g. '%cd?'. | |
434 |
|
434 | |||
435 | Currently the magic system has the following functions:\n""" |
|
435 | Currently the magic system has the following functions:\n""" | |
436 |
|
436 | |||
437 | mesc = self.shell.ESC_MAGIC |
|
437 | mesc = self.shell.ESC_MAGIC | |
438 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
438 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
439 | "\n\n%s%s\n\n%s" % (outmsg, |
|
439 | "\n\n%s%s\n\n%s" % (outmsg, | |
440 | magic_docs,mesc,mesc, |
|
440 | magic_docs,mesc,mesc, | |
441 | (' '+mesc).join(self.lsmagic()), |
|
441 | (' '+mesc).join(self.lsmagic()), | |
442 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
442 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
443 |
|
443 | |||
444 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
444 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
445 |
|
445 | |||
446 | def magic_automagic(self, parameter_s = ''): |
|
446 | def magic_automagic(self, parameter_s = ''): | |
447 | """Make magic functions callable without having to type the initial %. |
|
447 | """Make magic functions callable without having to type the initial %. | |
448 |
|
448 | |||
449 | Toggles on/off (when off, you must call it as %automagic, of |
|
449 | Toggles on/off (when off, you must call it as %automagic, of | |
450 | course). Note that magic functions have lowest priority, so if there's |
|
450 | course). Note that magic functions have lowest priority, so if there's | |
451 | a variable whose name collides with that of a magic fn, automagic |
|
451 | a variable whose name collides with that of a magic fn, automagic | |
452 | won't work for that function (you get the variable instead). However, |
|
452 | won't work for that function (you get the variable instead). However, | |
453 | if you delete the variable (del var), the previously shadowed magic |
|
453 | if you delete the variable (del var), the previously shadowed magic | |
454 | function becomes visible to automagic again.""" |
|
454 | function becomes visible to automagic again.""" | |
455 |
|
455 | |||
456 | rc = self.shell.rc |
|
456 | rc = self.shell.rc | |
457 | rc.automagic = not rc.automagic |
|
457 | rc.automagic = not rc.automagic | |
458 | print '\n' + Magic.auto_status[rc.automagic] |
|
458 | print '\n' + Magic.auto_status[rc.automagic] | |
459 |
|
459 | |||
460 | def magic_autocall(self, parameter_s = ''): |
|
460 | def magic_autocall(self, parameter_s = ''): | |
461 | """Make functions callable without having to type parentheses. |
|
461 | """Make functions callable without having to type parentheses. | |
462 |
|
462 | |||
463 | Usage: |
|
463 | Usage: | |
464 |
|
464 | |||
465 | %autocall [mode] |
|
465 | %autocall [mode] | |
466 |
|
466 | |||
467 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
467 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
468 | value is toggled on and off (remembering the previous state).""" |
|
468 | value is toggled on and off (remembering the previous state).""" | |
469 |
|
469 | |||
470 | rc = self.shell.rc |
|
470 | rc = self.shell.rc | |
471 |
|
471 | |||
472 | if parameter_s: |
|
472 | if parameter_s: | |
473 | arg = int(parameter_s) |
|
473 | arg = int(parameter_s) | |
474 | else: |
|
474 | else: | |
475 | arg = 'toggle' |
|
475 | arg = 'toggle' | |
476 |
|
476 | |||
477 | if not arg in (0,1,2,'toggle'): |
|
477 | if not arg in (0,1,2,'toggle'): | |
478 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
478 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
479 | return |
|
479 | return | |
480 |
|
480 | |||
481 | if arg in (0,1,2): |
|
481 | if arg in (0,1,2): | |
482 | rc.autocall = arg |
|
482 | rc.autocall = arg | |
483 | else: # toggle |
|
483 | else: # toggle | |
484 | if rc.autocall: |
|
484 | if rc.autocall: | |
485 | self._magic_state.autocall_save = rc.autocall |
|
485 | self._magic_state.autocall_save = rc.autocall | |
486 | rc.autocall = 0 |
|
486 | rc.autocall = 0 | |
487 | else: |
|
487 | else: | |
488 | try: |
|
488 | try: | |
489 | rc.autocall = self._magic_state.autocall_save |
|
489 | rc.autocall = self._magic_state.autocall_save | |
490 | except AttributeError: |
|
490 | except AttributeError: | |
491 | rc.autocall = self._magic_state.autocall_save = 1 |
|
491 | rc.autocall = self._magic_state.autocall_save = 1 | |
492 |
|
492 | |||
493 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
493 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] | |
494 |
|
494 | |||
495 | def magic_autoindent(self, parameter_s = ''): |
|
495 | def magic_autoindent(self, parameter_s = ''): | |
496 | """Toggle autoindent on/off (if available).""" |
|
496 | """Toggle autoindent on/off (if available).""" | |
497 |
|
497 | |||
498 | self.shell.set_autoindent() |
|
498 | self.shell.set_autoindent() | |
499 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
499 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
500 |
|
500 | |||
501 | def magic_system_verbose(self, parameter_s = ''): |
|
501 | def magic_system_verbose(self, parameter_s = ''): | |
502 | """Toggle verbose printing of system calls on/off.""" |
|
502 | """Toggle verbose printing of system calls on/off.""" | |
503 |
|
503 | |||
504 | self.shell.rc_set_toggle('system_verbose') |
|
504 | self.shell.rc_set_toggle('system_verbose') | |
505 | print "System verbose printing is:",\ |
|
505 | print "System verbose printing is:",\ | |
506 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
506 | ['OFF','ON'][self.shell.rc.system_verbose] | |
507 |
|
507 | |||
508 | def magic_history(self, parameter_s = ''): |
|
508 | def magic_history(self, parameter_s = ''): | |
509 | """Print input history (_i<n> variables), with most recent last. |
|
509 | """Print input history (_i<n> variables), with most recent last. | |
510 |
|
510 | |||
511 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
511 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
512 | %history n -> print at most n inputs\\ |
|
512 | %history n -> print at most n inputs\\ | |
513 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
513 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
514 |
|
514 | |||
515 | Each input's number <n> is shown, and is accessible as the |
|
515 | Each input's number <n> is shown, and is accessible as the | |
516 | automatically generated variable _i<n>. Multi-line statements are |
|
516 | automatically generated variable _i<n>. Multi-line statements are | |
517 | printed starting at a new line for easy copy/paste. |
|
517 | printed starting at a new line for easy copy/paste. | |
518 |
|
518 | |||
519 |
|
519 | |||
520 | Options: |
|
520 | Options: | |
521 |
|
521 | |||
522 | -n: do NOT print line numbers. This is useful if you want to get a |
|
522 | -n: do NOT print line numbers. This is useful if you want to get a | |
523 | printout of many lines which can be directly pasted into a text |
|
523 | printout of many lines which can be directly pasted into a text | |
524 | editor. |
|
524 | editor. | |
525 |
|
525 | |||
526 | This feature is only available if numbered prompts are in use. |
|
526 | This feature is only available if numbered prompts are in use. | |
527 |
|
527 | |||
528 | -r: print the 'raw' history. IPython filters your input and |
|
528 | -r: print the 'raw' history. IPython filters your input and | |
529 | converts it all into valid Python source before executing it (things |
|
529 | converts it all into valid Python source before executing it (things | |
530 | like magics or aliases are turned into function calls, for |
|
530 | like magics or aliases are turned into function calls, for | |
531 | example). With this option, you'll see the unfiltered history |
|
531 | example). With this option, you'll see the unfiltered history | |
532 | instead of the filtered version: '%cd /' will be seen as '%cd /' |
|
532 | instead of the filtered version: '%cd /' will be seen as '%cd /' | |
533 | instead of '_ip.magic("%cd /")'. |
|
533 | instead of '_ip.magic("%cd /")'. | |
534 | """ |
|
534 | """ | |
535 |
|
535 | |||
536 | shell = self.shell |
|
536 | shell = self.shell | |
537 | if not shell.outputcache.do_full_cache: |
|
537 | if not shell.outputcache.do_full_cache: | |
538 | print 'This feature is only available if numbered prompts are in use.' |
|
538 | print 'This feature is only available if numbered prompts are in use.' | |
539 | return |
|
539 | return | |
540 | opts,args = self.parse_options(parameter_s,'nr',mode='list') |
|
540 | opts,args = self.parse_options(parameter_s,'nr',mode='list') | |
541 |
|
541 | |||
542 | if opts.has_key('r'): |
|
542 | if opts.has_key('r'): | |
543 | input_hist = shell.input_hist_raw |
|
543 | input_hist = shell.input_hist_raw | |
544 | else: |
|
544 | else: | |
545 | input_hist = shell.input_hist |
|
545 | input_hist = shell.input_hist | |
546 |
|
546 | |||
547 | default_length = 40 |
|
547 | default_length = 40 | |
548 | if len(args) == 0: |
|
548 | if len(args) == 0: | |
549 | final = len(input_hist) |
|
549 | final = len(input_hist) | |
550 | init = max(1,final-default_length) |
|
550 | init = max(1,final-default_length) | |
551 | elif len(args) == 1: |
|
551 | elif len(args) == 1: | |
552 | final = len(input_hist) |
|
552 | final = len(input_hist) | |
553 | init = max(1,final-int(args[0])) |
|
553 | init = max(1,final-int(args[0])) | |
554 | elif len(args) == 2: |
|
554 | elif len(args) == 2: | |
555 | init,final = map(int,args) |
|
555 | init,final = map(int,args) | |
556 | else: |
|
556 | else: | |
557 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
557 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
558 | print self.magic_hist.__doc__ |
|
558 | print self.magic_hist.__doc__ | |
559 | return |
|
559 | return | |
560 | width = len(str(final)) |
|
560 | width = len(str(final)) | |
561 | line_sep = ['','\n'] |
|
561 | line_sep = ['','\n'] | |
562 | print_nums = not opts.has_key('n') |
|
562 | print_nums = not opts.has_key('n') | |
563 | for in_num in range(init,final): |
|
563 | for in_num in range(init,final): | |
564 | inline = input_hist[in_num] |
|
564 | inline = input_hist[in_num] | |
565 | multiline = int(inline.count('\n') > 1) |
|
565 | multiline = int(inline.count('\n') > 1) | |
566 | if print_nums: |
|
566 | if print_nums: | |
567 | print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), |
|
567 | print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), | |
568 | print inline, |
|
568 | print inline, | |
569 |
|
569 | |||
570 | def magic_hist(self, parameter_s=''): |
|
570 | def magic_hist(self, parameter_s=''): | |
571 | """Alternate name for %history.""" |
|
571 | """Alternate name for %history.""" | |
572 | return self.magic_history(parameter_s) |
|
572 | return self.magic_history(parameter_s) | |
573 |
|
573 | |||
574 | def magic_p(self, parameter_s=''): |
|
574 | def magic_p(self, parameter_s=''): | |
575 | """Just a short alias for Python's 'print'.""" |
|
575 | """Just a short alias for Python's 'print'.""" | |
576 | exec 'print ' + parameter_s in self.shell.user_ns |
|
576 | exec 'print ' + parameter_s in self.shell.user_ns | |
577 |
|
577 | |||
578 | def magic_r(self, parameter_s=''): |
|
578 | def magic_r(self, parameter_s=''): | |
579 | """Repeat previous input. |
|
579 | """Repeat previous input. | |
580 |
|
580 | |||
581 | If given an argument, repeats the previous command which starts with |
|
581 | If given an argument, repeats the previous command which starts with | |
582 | the same string, otherwise it just repeats the previous input. |
|
582 | the same string, otherwise it just repeats the previous input. | |
583 |
|
583 | |||
584 | Shell escaped commands (with ! as first character) are not recognized |
|
584 | Shell escaped commands (with ! as first character) are not recognized | |
585 | by this system, only pure python code and magic commands. |
|
585 | by this system, only pure python code and magic commands. | |
586 | """ |
|
586 | """ | |
587 |
|
587 | |||
588 | start = parameter_s.strip() |
|
588 | start = parameter_s.strip() | |
589 | esc_magic = self.shell.ESC_MAGIC |
|
589 | esc_magic = self.shell.ESC_MAGIC | |
590 | # Identify magic commands even if automagic is on (which means |
|
590 | # Identify magic commands even if automagic is on (which means | |
591 | # the in-memory version is different from that typed by the user). |
|
591 | # the in-memory version is different from that typed by the user). | |
592 | if self.shell.rc.automagic: |
|
592 | if self.shell.rc.automagic: | |
593 | start_magic = esc_magic+start |
|
593 | start_magic = esc_magic+start | |
594 | else: |
|
594 | else: | |
595 | start_magic = start |
|
595 | start_magic = start | |
596 | # Look through the input history in reverse |
|
596 | # Look through the input history in reverse | |
597 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
597 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
598 | input = self.shell.input_hist[n] |
|
598 | input = self.shell.input_hist[n] | |
599 | # skip plain 'r' lines so we don't recurse to infinity |
|
599 | # skip plain 'r' lines so we don't recurse to infinity | |
600 | if input != '_ip.magic("r")\n' and \ |
|
600 | if input != '_ip.magic("r")\n' and \ | |
601 | (input.startswith(start) or input.startswith(start_magic)): |
|
601 | (input.startswith(start) or input.startswith(start_magic)): | |
602 | #print 'match',`input` # dbg |
|
602 | #print 'match',`input` # dbg | |
603 | print 'Executing:',input, |
|
603 | print 'Executing:',input, | |
604 | self.shell.runlines(input) |
|
604 | self.shell.runlines(input) | |
605 | return |
|
605 | return | |
606 | print 'No previous input matching `%s` found.' % start |
|
606 | print 'No previous input matching `%s` found.' % start | |
607 |
|
607 | |||
608 | def magic_page(self, parameter_s=''): |
|
608 | def magic_page(self, parameter_s=''): | |
609 | """Pretty print the object and display it through a pager. |
|
609 | """Pretty print the object and display it through a pager. | |
610 |
|
610 | |||
611 | If no parameter is given, use _ (last output).""" |
|
611 | If no parameter is given, use _ (last output).""" | |
612 | # After a function contributed by Olivier Aubert, slightly modified. |
|
612 | # After a function contributed by Olivier Aubert, slightly modified. | |
613 |
|
613 | |||
614 | oname = parameter_s and parameter_s or '_' |
|
614 | oname = parameter_s and parameter_s or '_' | |
615 | info = self._ofind(oname) |
|
615 | info = self._ofind(oname) | |
616 | if info['found']: |
|
616 | if info['found']: | |
617 | page(pformat(info['obj'])) |
|
617 | page(pformat(info['obj'])) | |
618 | else: |
|
618 | else: | |
619 | print 'Object `%s` not found' % oname |
|
619 | print 'Object `%s` not found' % oname | |
620 |
|
620 | |||
621 | def magic_profile(self, parameter_s=''): |
|
621 | def magic_profile(self, parameter_s=''): | |
622 | """Print your currently active IPyhton profile.""" |
|
622 | """Print your currently active IPyhton profile.""" | |
623 | if self.shell.rc.profile: |
|
623 | if self.shell.rc.profile: | |
624 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
624 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
625 | else: |
|
625 | else: | |
626 | print 'No profile active.' |
|
626 | print 'No profile active.' | |
627 |
|
627 | |||
628 | def _inspect(self,meth,oname,**kw): |
|
628 | def _inspect(self,meth,oname,**kw): | |
629 | """Generic interface to the inspector system. |
|
629 | """Generic interface to the inspector system. | |
630 |
|
630 | |||
631 | This function is meant to be called by pdef, pdoc & friends.""" |
|
631 | This function is meant to be called by pdef, pdoc & friends.""" | |
632 |
|
632 | |||
633 | oname = oname.strip() |
|
633 | oname = oname.strip() | |
634 | info = Struct(self._ofind(oname)) |
|
634 | info = Struct(self._ofind(oname)) | |
635 | if info.found: |
|
635 | if info.found: | |
636 | pmethod = getattr(self.shell.inspector,meth) |
|
636 | pmethod = getattr(self.shell.inspector,meth) | |
637 | formatter = info.ismagic and self.format_screen or None |
|
637 | formatter = info.ismagic and self.format_screen or None | |
638 | if meth == 'pdoc': |
|
638 | if meth == 'pdoc': | |
639 | pmethod(info.obj,oname,formatter) |
|
639 | pmethod(info.obj,oname,formatter) | |
640 | elif meth == 'pinfo': |
|
640 | elif meth == 'pinfo': | |
641 | pmethod(info.obj,oname,formatter,info,**kw) |
|
641 | pmethod(info.obj,oname,formatter,info,**kw) | |
642 | else: |
|
642 | else: | |
643 | pmethod(info.obj,oname) |
|
643 | pmethod(info.obj,oname) | |
644 | else: |
|
644 | else: | |
645 | print 'Object `%s` not found.' % oname |
|
645 | print 'Object `%s` not found.' % oname | |
646 | return 'not found' # so callers can take other action |
|
646 | return 'not found' # so callers can take other action | |
647 |
|
647 | |||
648 | def magic_pdef(self, parameter_s=''): |
|
648 | def magic_pdef(self, parameter_s=''): | |
649 | """Print the definition header for any callable object. |
|
649 | """Print the definition header for any callable object. | |
650 |
|
650 | |||
651 | If the object is a class, print the constructor information.""" |
|
651 | If the object is a class, print the constructor information.""" | |
652 | self._inspect('pdef',parameter_s) |
|
652 | self._inspect('pdef',parameter_s) | |
653 |
|
653 | |||
654 | def magic_pdoc(self, parameter_s=''): |
|
654 | def magic_pdoc(self, parameter_s=''): | |
655 | """Print the docstring for an object. |
|
655 | """Print the docstring for an object. | |
656 |
|
656 | |||
657 | If the given object is a class, it will print both the class and the |
|
657 | If the given object is a class, it will print both the class and the | |
658 | constructor docstrings.""" |
|
658 | constructor docstrings.""" | |
659 | self._inspect('pdoc',parameter_s) |
|
659 | self._inspect('pdoc',parameter_s) | |
660 |
|
660 | |||
661 | def magic_psource(self, parameter_s=''): |
|
661 | def magic_psource(self, parameter_s=''): | |
662 | """Print (or run through pager) the source code for an object.""" |
|
662 | """Print (or run through pager) the source code for an object.""" | |
663 | self._inspect('psource',parameter_s) |
|
663 | self._inspect('psource',parameter_s) | |
664 |
|
664 | |||
665 | def magic_pfile(self, parameter_s=''): |
|
665 | def magic_pfile(self, parameter_s=''): | |
666 | """Print (or run through pager) the file where an object is defined. |
|
666 | """Print (or run through pager) the file where an object is defined. | |
667 |
|
667 | |||
668 | The file opens at the line where the object definition begins. IPython |
|
668 | The file opens at the line where the object definition begins. IPython | |
669 | will honor the environment variable PAGER if set, and otherwise will |
|
669 | will honor the environment variable PAGER if set, and otherwise will | |
670 | do its best to print the file in a convenient form. |
|
670 | do its best to print the file in a convenient form. | |
671 |
|
671 | |||
672 | If the given argument is not an object currently defined, IPython will |
|
672 | If the given argument is not an object currently defined, IPython will | |
673 | try to interpret it as a filename (automatically adding a .py extension |
|
673 | try to interpret it as a filename (automatically adding a .py extension | |
674 | if needed). You can thus use %pfile as a syntax highlighting code |
|
674 | if needed). You can thus use %pfile as a syntax highlighting code | |
675 | viewer.""" |
|
675 | viewer.""" | |
676 |
|
676 | |||
677 | # first interpret argument as an object name |
|
677 | # first interpret argument as an object name | |
678 | out = self._inspect('pfile',parameter_s) |
|
678 | out = self._inspect('pfile',parameter_s) | |
679 | # if not, try the input as a filename |
|
679 | # if not, try the input as a filename | |
680 | if out == 'not found': |
|
680 | if out == 'not found': | |
681 | try: |
|
681 | try: | |
682 | filename = get_py_filename(parameter_s) |
|
682 | filename = get_py_filename(parameter_s) | |
683 | except IOError,msg: |
|
683 | except IOError,msg: | |
684 | print msg |
|
684 | print msg | |
685 | return |
|
685 | return | |
686 | page(self.shell.inspector.format(file(filename).read())) |
|
686 | page(self.shell.inspector.format(file(filename).read())) | |
687 |
|
687 | |||
688 | def magic_pinfo(self, parameter_s=''): |
|
688 | def magic_pinfo(self, parameter_s=''): | |
689 | """Provide detailed information about an object. |
|
689 | """Provide detailed information about an object. | |
690 |
|
690 | |||
691 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
691 | '%pinfo object' is just a synonym for object? or ?object.""" | |
692 |
|
692 | |||
693 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
693 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
694 |
|
694 | |||
695 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
695 | # detail_level: 0 -> obj? , 1 -> obj?? | |
696 | detail_level = 0 |
|
696 | detail_level = 0 | |
697 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
697 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
698 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
698 | # happen if the user types 'pinfo foo?' at the cmd line. | |
699 | pinfo,qmark1,oname,qmark2 = \ |
|
699 | pinfo,qmark1,oname,qmark2 = \ | |
700 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
700 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
701 | if pinfo or qmark1 or qmark2: |
|
701 | if pinfo or qmark1 or qmark2: | |
702 | detail_level = 1 |
|
702 | detail_level = 1 | |
703 | if "*" in oname: |
|
703 | if "*" in oname: | |
704 | self.magic_psearch(oname) |
|
704 | self.magic_psearch(oname) | |
705 | else: |
|
705 | else: | |
706 | self._inspect('pinfo',oname,detail_level=detail_level) |
|
706 | self._inspect('pinfo',oname,detail_level=detail_level) | |
707 |
|
707 | |||
708 | def magic_psearch(self, parameter_s=''): |
|
708 | def magic_psearch(self, parameter_s=''): | |
709 | """Search for object in namespaces by wildcard. |
|
709 | """Search for object in namespaces by wildcard. | |
710 |
|
710 | |||
711 | %psearch [options] PATTERN [OBJECT TYPE] |
|
711 | %psearch [options] PATTERN [OBJECT TYPE] | |
712 |
|
712 | |||
713 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
713 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
714 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
714 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
715 | rest of the command line must be unchanged (options come first), so |
|
715 | rest of the command line must be unchanged (options come first), so | |
716 | for example the following forms are equivalent |
|
716 | for example the following forms are equivalent | |
717 |
|
717 | |||
718 | %psearch -i a* function |
|
718 | %psearch -i a* function | |
719 | -i a* function? |
|
719 | -i a* function? | |
720 | ?-i a* function |
|
720 | ?-i a* function | |
721 |
|
721 | |||
722 | Arguments: |
|
722 | Arguments: | |
723 |
|
723 | |||
724 | PATTERN |
|
724 | PATTERN | |
725 |
|
725 | |||
726 | where PATTERN is a string containing * as a wildcard similar to its |
|
726 | where PATTERN is a string containing * as a wildcard similar to its | |
727 | use in a shell. The pattern is matched in all namespaces on the |
|
727 | use in a shell. The pattern is matched in all namespaces on the | |
728 | search path. By default objects starting with a single _ are not |
|
728 | search path. By default objects starting with a single _ are not | |
729 | matched, many IPython generated objects have a single |
|
729 | matched, many IPython generated objects have a single | |
730 | underscore. The default is case insensitive matching. Matching is |
|
730 | underscore. The default is case insensitive matching. Matching is | |
731 | also done on the attributes of objects and not only on the objects |
|
731 | also done on the attributes of objects and not only on the objects | |
732 | in a module. |
|
732 | in a module. | |
733 |
|
733 | |||
734 | [OBJECT TYPE] |
|
734 | [OBJECT TYPE] | |
735 |
|
735 | |||
736 | Is the name of a python type from the types module. The name is |
|
736 | Is the name of a python type from the types module. The name is | |
737 | given in lowercase without the ending type, ex. StringType is |
|
737 | given in lowercase without the ending type, ex. StringType is | |
738 | written string. By adding a type here only objects matching the |
|
738 | written string. By adding a type here only objects matching the | |
739 | given type are matched. Using all here makes the pattern match all |
|
739 | given type are matched. Using all here makes the pattern match all | |
740 | types (this is the default). |
|
740 | types (this is the default). | |
741 |
|
741 | |||
742 | Options: |
|
742 | Options: | |
743 |
|
743 | |||
744 | -a: makes the pattern match even objects whose names start with a |
|
744 | -a: makes the pattern match even objects whose names start with a | |
745 | single underscore. These names are normally ommitted from the |
|
745 | single underscore. These names are normally ommitted from the | |
746 | search. |
|
746 | search. | |
747 |
|
747 | |||
748 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
748 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
749 | these options is given, the default is read from your ipythonrc |
|
749 | these options is given, the default is read from your ipythonrc | |
750 | file. The option name which sets this value is |
|
750 | file. The option name which sets this value is | |
751 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
751 | 'wildcards_case_sensitive'. If this option is not specified in your | |
752 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
752 | ipythonrc file, IPython's internal default is to do a case sensitive | |
753 | search. |
|
753 | search. | |
754 |
|
754 | |||
755 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
755 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
756 | specifiy can be searched in any of the following namespaces: |
|
756 | specifiy can be searched in any of the following namespaces: | |
757 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
757 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
758 | 'builtin' and 'user' are the search defaults. Note that you should |
|
758 | 'builtin' and 'user' are the search defaults. Note that you should | |
759 | not use quotes when specifying namespaces. |
|
759 | not use quotes when specifying namespaces. | |
760 |
|
760 | |||
761 | 'Builtin' contains the python module builtin, 'user' contains all |
|
761 | 'Builtin' contains the python module builtin, 'user' contains all | |
762 | user data, 'alias' only contain the shell aliases and no python |
|
762 | user data, 'alias' only contain the shell aliases and no python | |
763 | objects, 'internal' contains objects used by IPython. The |
|
763 | objects, 'internal' contains objects used by IPython. The | |
764 | 'user_global' namespace is only used by embedded IPython instances, |
|
764 | 'user_global' namespace is only used by embedded IPython instances, | |
765 | and it contains module-level globals. You can add namespaces to the |
|
765 | and it contains module-level globals. You can add namespaces to the | |
766 | search with -s or exclude them with -e (these options can be given |
|
766 | search with -s or exclude them with -e (these options can be given | |
767 | more than once). |
|
767 | more than once). | |
768 |
|
768 | |||
769 | Examples: |
|
769 | Examples: | |
770 |
|
770 | |||
771 | %psearch a* -> objects beginning with an a |
|
771 | %psearch a* -> objects beginning with an a | |
772 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
772 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
773 | %psearch a* function -> all functions beginning with an a |
|
773 | %psearch a* function -> all functions beginning with an a | |
774 | %psearch re.e* -> objects beginning with an e in module re |
|
774 | %psearch re.e* -> objects beginning with an e in module re | |
775 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
775 | %psearch r*.e* -> objects that start with e in modules starting in r | |
776 | %psearch r*.* string -> all strings in modules beginning with r |
|
776 | %psearch r*.* string -> all strings in modules beginning with r | |
777 |
|
777 | |||
778 | Case sensitve search: |
|
778 | Case sensitve search: | |
779 |
|
779 | |||
780 | %psearch -c a* list all object beginning with lower case a |
|
780 | %psearch -c a* list all object beginning with lower case a | |
781 |
|
781 | |||
782 | Show objects beginning with a single _: |
|
782 | Show objects beginning with a single _: | |
783 |
|
783 | |||
784 | %psearch -a _* list objects beginning with a single underscore""" |
|
784 | %psearch -a _* list objects beginning with a single underscore""" | |
785 |
|
785 | |||
786 | # default namespaces to be searched |
|
786 | # default namespaces to be searched | |
787 | def_search = ['user','builtin'] |
|
787 | def_search = ['user','builtin'] | |
788 |
|
788 | |||
789 | # Process options/args |
|
789 | # Process options/args | |
790 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
790 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
791 | opt = opts.get |
|
791 | opt = opts.get | |
792 | shell = self.shell |
|
792 | shell = self.shell | |
793 | psearch = shell.inspector.psearch |
|
793 | psearch = shell.inspector.psearch | |
794 |
|
794 | |||
795 | # select case options |
|
795 | # select case options | |
796 | if opts.has_key('i'): |
|
796 | if opts.has_key('i'): | |
797 | ignore_case = True |
|
797 | ignore_case = True | |
798 | elif opts.has_key('c'): |
|
798 | elif opts.has_key('c'): | |
799 | ignore_case = False |
|
799 | ignore_case = False | |
800 | else: |
|
800 | else: | |
801 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
801 | ignore_case = not shell.rc.wildcards_case_sensitive | |
802 |
|
802 | |||
803 | # Build list of namespaces to search from user options |
|
803 | # Build list of namespaces to search from user options | |
804 | def_search.extend(opt('s',[])) |
|
804 | def_search.extend(opt('s',[])) | |
805 | ns_exclude = ns_exclude=opt('e',[]) |
|
805 | ns_exclude = ns_exclude=opt('e',[]) | |
806 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
806 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
807 |
|
807 | |||
808 | # Call the actual search |
|
808 | # Call the actual search | |
809 | try: |
|
809 | try: | |
810 | psearch(args,shell.ns_table,ns_search, |
|
810 | psearch(args,shell.ns_table,ns_search, | |
811 | show_all=opt('a'),ignore_case=ignore_case) |
|
811 | show_all=opt('a'),ignore_case=ignore_case) | |
812 | except: |
|
812 | except: | |
813 | shell.showtraceback() |
|
813 | shell.showtraceback() | |
814 |
|
814 | |||
815 | def magic_who_ls(self, parameter_s=''): |
|
815 | def magic_who_ls(self, parameter_s=''): | |
816 | """Return a sorted list of all interactive variables. |
|
816 | """Return a sorted list of all interactive variables. | |
817 |
|
817 | |||
818 | If arguments are given, only variables of types matching these |
|
818 | If arguments are given, only variables of types matching these | |
819 | arguments are returned.""" |
|
819 | arguments are returned.""" | |
820 |
|
820 | |||
821 | user_ns = self.shell.user_ns |
|
821 | user_ns = self.shell.user_ns | |
822 | internal_ns = self.shell.internal_ns |
|
822 | internal_ns = self.shell.internal_ns | |
823 | user_config_ns = self.shell.user_config_ns |
|
823 | user_config_ns = self.shell.user_config_ns | |
824 | out = [] |
|
824 | out = [] | |
825 | typelist = parameter_s.split() |
|
825 | typelist = parameter_s.split() | |
826 |
|
826 | |||
827 | for i in user_ns: |
|
827 | for i in user_ns: | |
828 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
828 | if not (i.startswith('_') or i.startswith('_i')) \ | |
829 | and not (i in internal_ns or i in user_config_ns): |
|
829 | and not (i in internal_ns or i in user_config_ns): | |
830 | if typelist: |
|
830 | if typelist: | |
831 | if type(user_ns[i]).__name__ in typelist: |
|
831 | if type(user_ns[i]).__name__ in typelist: | |
832 | out.append(i) |
|
832 | out.append(i) | |
833 | else: |
|
833 | else: | |
834 | out.append(i) |
|
834 | out.append(i) | |
835 | out.sort() |
|
835 | out.sort() | |
836 | return out |
|
836 | return out | |
837 |
|
837 | |||
838 | def magic_who(self, parameter_s=''): |
|
838 | def magic_who(self, parameter_s=''): | |
839 | """Print all interactive variables, with some minimal formatting. |
|
839 | """Print all interactive variables, with some minimal formatting. | |
840 |
|
840 | |||
841 | If any arguments are given, only variables whose type matches one of |
|
841 | If any arguments are given, only variables whose type matches one of | |
842 | these are printed. For example: |
|
842 | these are printed. For example: | |
843 |
|
843 | |||
844 | %who function str |
|
844 | %who function str | |
845 |
|
845 | |||
846 | will only list functions and strings, excluding all other types of |
|
846 | will only list functions and strings, excluding all other types of | |
847 | variables. To find the proper type names, simply use type(var) at a |
|
847 | variables. To find the proper type names, simply use type(var) at a | |
848 | command line to see how python prints type names. For example: |
|
848 | command line to see how python prints type names. For example: | |
849 |
|
849 | |||
850 | In [1]: type('hello')\\ |
|
850 | In [1]: type('hello')\\ | |
851 | Out[1]: <type 'str'> |
|
851 | Out[1]: <type 'str'> | |
852 |
|
852 | |||
853 | indicates that the type name for strings is 'str'. |
|
853 | indicates that the type name for strings is 'str'. | |
854 |
|
854 | |||
855 | %who always excludes executed names loaded through your configuration |
|
855 | %who always excludes executed names loaded through your configuration | |
856 | file and things which are internal to IPython. |
|
856 | file and things which are internal to IPython. | |
857 |
|
857 | |||
858 | This is deliberate, as typically you may load many modules and the |
|
858 | This is deliberate, as typically you may load many modules and the | |
859 | purpose of %who is to show you only what you've manually defined.""" |
|
859 | purpose of %who is to show you only what you've manually defined.""" | |
860 |
|
860 | |||
861 | varlist = self.magic_who_ls(parameter_s) |
|
861 | varlist = self.magic_who_ls(parameter_s) | |
862 | if not varlist: |
|
862 | if not varlist: | |
863 | print 'Interactive namespace is empty.' |
|
863 | print 'Interactive namespace is empty.' | |
864 | return |
|
864 | return | |
865 |
|
865 | |||
866 | # if we have variables, move on... |
|
866 | # if we have variables, move on... | |
867 |
|
867 | |||
868 | # stupid flushing problem: when prompts have no separators, stdout is |
|
868 | # stupid flushing problem: when prompts have no separators, stdout is | |
869 | # getting lost. I'm starting to think this is a python bug. I'm having |
|
869 | # getting lost. I'm starting to think this is a python bug. I'm having | |
870 | # to force a flush with a print because even a sys.stdout.flush |
|
870 | # to force a flush with a print because even a sys.stdout.flush | |
871 | # doesn't seem to do anything! |
|
871 | # doesn't seem to do anything! | |
872 |
|
872 | |||
873 | count = 0 |
|
873 | count = 0 | |
874 | for i in varlist: |
|
874 | for i in varlist: | |
875 | print i+'\t', |
|
875 | print i+'\t', | |
876 | count += 1 |
|
876 | count += 1 | |
877 | if count > 8: |
|
877 | if count > 8: | |
878 | count = 0 |
|
878 | count = 0 | |
879 |
|
879 | |||
880 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? |
|
880 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? | |
881 |
|
881 | |||
882 | print # well, this does force a flush at the expense of an extra \n |
|
882 | print # well, this does force a flush at the expense of an extra \n | |
883 |
|
883 | |||
884 | def magic_whos(self, parameter_s=''): |
|
884 | def magic_whos(self, parameter_s=''): | |
885 | """Like %who, but gives some extra information about each variable. |
|
885 | """Like %who, but gives some extra information about each variable. | |
886 |
|
886 | |||
887 | The same type filtering of %who can be applied here. |
|
887 | The same type filtering of %who can be applied here. | |
888 |
|
888 | |||
889 | For all variables, the type is printed. Additionally it prints: |
|
889 | For all variables, the type is printed. Additionally it prints: | |
890 |
|
890 | |||
891 | - For {},[],(): their length. |
|
891 | - For {},[],(): their length. | |
892 |
|
892 | |||
893 | - For Numeric arrays, a summary with shape, number of elements, |
|
893 | - For Numeric arrays, a summary with shape, number of elements, | |
894 | typecode and size in memory. |
|
894 | typecode and size in memory. | |
895 |
|
895 | |||
896 | - Everything else: a string representation, snipping their middle if |
|
896 | - Everything else: a string representation, snipping their middle if | |
897 | too long.""" |
|
897 | too long.""" | |
898 |
|
898 | |||
899 | varnames = self.magic_who_ls(parameter_s) |
|
899 | varnames = self.magic_who_ls(parameter_s) | |
900 | if not varnames: |
|
900 | if not varnames: | |
901 | print 'Interactive namespace is empty.' |
|
901 | print 'Interactive namespace is empty.' | |
902 | return |
|
902 | return | |
903 |
|
903 | |||
904 | # if we have variables, move on... |
|
904 | # if we have variables, move on... | |
905 |
|
905 | |||
906 | # for these types, show len() instead of data: |
|
906 | # for these types, show len() instead of data: | |
907 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
907 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
908 |
|
908 | |||
909 | # for Numeric arrays, display summary info |
|
909 | # for Numeric arrays, display summary info | |
910 | try: |
|
910 | try: | |
911 | import Numeric |
|
911 | import Numeric | |
912 | except ImportError: |
|
912 | except ImportError: | |
913 | array_type = None |
|
913 | array_type = None | |
914 | else: |
|
914 | else: | |
915 | array_type = Numeric.ArrayType.__name__ |
|
915 | array_type = Numeric.ArrayType.__name__ | |
916 |
|
916 | |||
917 | # Find all variable names and types so we can figure out column sizes |
|
917 | # Find all variable names and types so we can figure out column sizes | |
918 | get_vars = lambda i: self.shell.user_ns[i] |
|
918 | get_vars = lambda i: self.shell.user_ns[i] | |
919 | type_name = lambda v: type(v).__name__ |
|
919 | type_name = lambda v: type(v).__name__ | |
920 | varlist = map(get_vars,varnames) |
|
920 | varlist = map(get_vars,varnames) | |
921 |
|
921 | |||
922 | typelist = [] |
|
922 | typelist = [] | |
923 | for vv in varlist: |
|
923 | for vv in varlist: | |
924 | tt = type_name(vv) |
|
924 | tt = type_name(vv) | |
925 | if tt=='instance': |
|
925 | if tt=='instance': | |
926 | typelist.append(str(vv.__class__)) |
|
926 | typelist.append(str(vv.__class__)) | |
927 | else: |
|
927 | else: | |
928 | typelist.append(tt) |
|
928 | typelist.append(tt) | |
929 |
|
929 | |||
930 | # column labels and # of spaces as separator |
|
930 | # column labels and # of spaces as separator | |
931 | varlabel = 'Variable' |
|
931 | varlabel = 'Variable' | |
932 | typelabel = 'Type' |
|
932 | typelabel = 'Type' | |
933 | datalabel = 'Data/Info' |
|
933 | datalabel = 'Data/Info' | |
934 | colsep = 3 |
|
934 | colsep = 3 | |
935 | # variable format strings |
|
935 | # variable format strings | |
936 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
936 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
937 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
937 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
938 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
938 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
939 | # find the size of the columns to format the output nicely |
|
939 | # find the size of the columns to format the output nicely | |
940 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
940 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
941 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
941 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
942 | # table header |
|
942 | # table header | |
943 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
943 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
944 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
944 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
945 | # and the table itself |
|
945 | # and the table itself | |
946 | kb = 1024 |
|
946 | kb = 1024 | |
947 | Mb = 1048576 # kb**2 |
|
947 | Mb = 1048576 # kb**2 | |
948 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
948 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
949 | print itpl(vformat), |
|
949 | print itpl(vformat), | |
950 | if vtype in seq_types: |
|
950 | if vtype in seq_types: | |
951 | print len(var) |
|
951 | print len(var) | |
952 | elif vtype==array_type: |
|
952 | elif vtype==array_type: | |
953 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
953 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
954 | vsize = Numeric.size(var) |
|
954 | vsize = Numeric.size(var) | |
955 | vbytes = vsize*var.itemsize() |
|
955 | vbytes = vsize*var.itemsize() | |
956 | if vbytes < 100000: |
|
956 | if vbytes < 100000: | |
957 | print aformat % (vshape,vsize,var.typecode(),vbytes) |
|
957 | print aformat % (vshape,vsize,var.typecode(),vbytes) | |
958 | else: |
|
958 | else: | |
959 | print aformat % (vshape,vsize,var.typecode(),vbytes), |
|
959 | print aformat % (vshape,vsize,var.typecode(),vbytes), | |
960 | if vbytes < Mb: |
|
960 | if vbytes < Mb: | |
961 | print '(%s kb)' % (vbytes/kb,) |
|
961 | print '(%s kb)' % (vbytes/kb,) | |
962 | else: |
|
962 | else: | |
963 | print '(%s Mb)' % (vbytes/Mb,) |
|
963 | print '(%s Mb)' % (vbytes/Mb,) | |
964 | else: |
|
964 | else: | |
965 | vstr = str(var).replace('\n','\\n') |
|
965 | vstr = str(var).replace('\n','\\n') | |
966 | if len(vstr) < 50: |
|
966 | if len(vstr) < 50: | |
967 | print vstr |
|
967 | print vstr | |
968 | else: |
|
968 | else: | |
969 | printpl(vfmt_short) |
|
969 | printpl(vfmt_short) | |
970 |
|
970 | |||
971 | def magic_reset(self, parameter_s=''): |
|
971 | def magic_reset(self, parameter_s=''): | |
972 | """Resets the namespace by removing all names defined by the user. |
|
972 | """Resets the namespace by removing all names defined by the user. | |
973 |
|
973 | |||
974 | Input/Output history are left around in case you need them.""" |
|
974 | Input/Output history are left around in case you need them.""" | |
975 |
|
975 | |||
976 | ans = raw_input( |
|
976 | ans = raw_input( | |
977 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") |
|
977 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") | |
978 | if not ans.lower() == 'y': |
|
978 | if not ans.lower() == 'y': | |
979 | print 'Nothing done.' |
|
979 | print 'Nothing done.' | |
980 | return |
|
980 | return | |
981 | user_ns = self.shell.user_ns |
|
981 | user_ns = self.shell.user_ns | |
982 | for i in self.magic_who_ls(): |
|
982 | for i in self.magic_who_ls(): | |
983 | del(user_ns[i]) |
|
983 | del(user_ns[i]) | |
984 |
|
984 | |||
985 | def magic_config(self,parameter_s=''): |
|
985 | def magic_config(self,parameter_s=''): | |
986 | """Show IPython's internal configuration.""" |
|
986 | """Show IPython's internal configuration.""" | |
987 |
|
987 | |||
988 | page('Current configuration structure:\n'+ |
|
988 | page('Current configuration structure:\n'+ | |
989 | pformat(self.shell.rc.dict())) |
|
989 | pformat(self.shell.rc.dict())) | |
990 |
|
990 | |||
991 | def magic_logstart(self,parameter_s=''): |
|
991 | def magic_logstart(self,parameter_s=''): | |
992 | """Start logging anywhere in a session. |
|
992 | """Start logging anywhere in a session. | |
993 |
|
993 | |||
994 | %logstart [-o|-t] [log_name [log_mode]] |
|
994 | %logstart [-o|-t] [log_name [log_mode]] | |
995 |
|
995 | |||
996 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
996 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
997 | current directory, in 'rotate' mode (see below). |
|
997 | current directory, in 'rotate' mode (see below). | |
998 |
|
998 | |||
999 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
999 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1000 | history up to that point and then continues logging. |
|
1000 | history up to that point and then continues logging. | |
1001 |
|
1001 | |||
1002 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1002 | %logstart takes a second optional parameter: logging mode. This can be one | |
1003 | of (note that the modes are given unquoted):\\ |
|
1003 | of (note that the modes are given unquoted):\\ | |
1004 | append: well, that says it.\\ |
|
1004 | append: well, that says it.\\ | |
1005 | backup: rename (if exists) to name~ and start name.\\ |
|
1005 | backup: rename (if exists) to name~ and start name.\\ | |
1006 | global: single logfile in your home dir, appended to.\\ |
|
1006 | global: single logfile in your home dir, appended to.\\ | |
1007 | over : overwrite existing log.\\ |
|
1007 | over : overwrite existing log.\\ | |
1008 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1008 | rotate: create rotating logs name.1~, name.2~, etc. | |
1009 |
|
1009 | |||
1010 | Options: |
|
1010 | Options: | |
1011 |
|
1011 | |||
1012 | -o: log also IPython's output. In this mode, all commands which |
|
1012 | -o: log also IPython's output. In this mode, all commands which | |
1013 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1013 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1014 | their corresponding input line. The output lines are always |
|
1014 | their corresponding input line. The output lines are always | |
1015 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1015 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1016 | Python code. |
|
1016 | Python code. | |
1017 |
|
1017 | |||
1018 | Since this marker is always the same, filtering only the output from |
|
1018 | Since this marker is always the same, filtering only the output from | |
1019 | a log is very easy, using for example a simple awk call: |
|
1019 | a log is very easy, using for example a simple awk call: | |
1020 |
|
1020 | |||
1021 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1021 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1022 |
|
1022 | |||
1023 | -t: put timestamps before each input line logged (these are put in |
|
1023 | -t: put timestamps before each input line logged (these are put in | |
1024 | comments).""" |
|
1024 | comments).""" | |
1025 |
|
1025 | |||
1026 | opts,par = self.parse_options(parameter_s,'ot') |
|
1026 | opts,par = self.parse_options(parameter_s,'ot') | |
1027 | log_output = 'o' in opts |
|
1027 | log_output = 'o' in opts | |
1028 | timestamp = 't' in opts |
|
1028 | timestamp = 't' in opts | |
1029 |
|
1029 | |||
1030 | rc = self.shell.rc |
|
1030 | rc = self.shell.rc | |
1031 | logger = self.shell.logger |
|
1031 | logger = self.shell.logger | |
1032 |
|
1032 | |||
1033 | # if no args are given, the defaults set in the logger constructor by |
|
1033 | # if no args are given, the defaults set in the logger constructor by | |
1034 | # ipytohn remain valid |
|
1034 | # ipytohn remain valid | |
1035 | if par: |
|
1035 | if par: | |
1036 | try: |
|
1036 | try: | |
1037 | logfname,logmode = par.split() |
|
1037 | logfname,logmode = par.split() | |
1038 | except: |
|
1038 | except: | |
1039 | logfname = par |
|
1039 | logfname = par | |
1040 | logmode = 'backup' |
|
1040 | logmode = 'backup' | |
1041 | else: |
|
1041 | else: | |
1042 | logfname = logger.logfname |
|
1042 | logfname = logger.logfname | |
1043 | logmode = logger.logmode |
|
1043 | logmode = logger.logmode | |
1044 | # put logfname into rc struct as if it had been called on the command |
|
1044 | # put logfname into rc struct as if it had been called on the command | |
1045 | # line, so it ends up saved in the log header Save it in case we need |
|
1045 | # line, so it ends up saved in the log header Save it in case we need | |
1046 | # to restore it... |
|
1046 | # to restore it... | |
1047 | old_logfile = rc.opts.get('logfile','') |
|
1047 | old_logfile = rc.opts.get('logfile','') | |
1048 | if logfname: |
|
1048 | if logfname: | |
1049 | logfname = os.path.expanduser(logfname) |
|
1049 | logfname = os.path.expanduser(logfname) | |
1050 | rc.opts.logfile = logfname |
|
1050 | rc.opts.logfile = logfname | |
1051 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1051 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) | |
1052 | try: |
|
1052 | try: | |
1053 | started = logger.logstart(logfname,loghead,logmode, |
|
1053 | started = logger.logstart(logfname,loghead,logmode, | |
1054 | log_output,timestamp) |
|
1054 | log_output,timestamp) | |
1055 | except: |
|
1055 | except: | |
1056 | rc.opts.logfile = old_logfile |
|
1056 | rc.opts.logfile = old_logfile | |
1057 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1057 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1058 | else: |
|
1058 | else: | |
1059 | # log input history up to this point, optionally interleaving |
|
1059 | # log input history up to this point, optionally interleaving | |
1060 | # output if requested |
|
1060 | # output if requested | |
1061 |
|
1061 | |||
1062 | if timestamp: |
|
1062 | if timestamp: | |
1063 | # disable timestamping for the previous history, since we've |
|
1063 | # disable timestamping for the previous history, since we've | |
1064 | # lost those already (no time machine here). |
|
1064 | # lost those already (no time machine here). | |
1065 | logger.timestamp = False |
|
1065 | logger.timestamp = False | |
1066 | if log_output: |
|
1066 | if log_output: | |
1067 | log_write = logger.log_write |
|
1067 | log_write = logger.log_write | |
1068 | input_hist = self.shell.input_hist |
|
1068 | input_hist = self.shell.input_hist | |
1069 | output_hist = self.shell.output_hist |
|
1069 | output_hist = self.shell.output_hist | |
1070 | for n in range(1,len(input_hist)-1): |
|
1070 | for n in range(1,len(input_hist)-1): | |
1071 | log_write(input_hist[n].rstrip()) |
|
1071 | log_write(input_hist[n].rstrip()) | |
1072 | if n in output_hist: |
|
1072 | if n in output_hist: | |
1073 | log_write(repr(output_hist[n]),'output') |
|
1073 | log_write(repr(output_hist[n]),'output') | |
1074 | else: |
|
1074 | else: | |
1075 | logger.log_write(self.shell.input_hist[1:]) |
|
1075 | logger.log_write(self.shell.input_hist[1:]) | |
1076 | if timestamp: |
|
1076 | if timestamp: | |
1077 | # re-enable timestamping |
|
1077 | # re-enable timestamping | |
1078 | logger.timestamp = True |
|
1078 | logger.timestamp = True | |
1079 |
|
1079 | |||
1080 | print ('Activating auto-logging. ' |
|
1080 | print ('Activating auto-logging. ' | |
1081 | 'Current session state plus future input saved.') |
|
1081 | 'Current session state plus future input saved.') | |
1082 | logger.logstate() |
|
1082 | logger.logstate() | |
1083 |
|
1083 | |||
1084 | def magic_logoff(self,parameter_s=''): |
|
1084 | def magic_logoff(self,parameter_s=''): | |
1085 | """Temporarily stop logging. |
|
1085 | """Temporarily stop logging. | |
1086 |
|
1086 | |||
1087 | You must have previously started logging.""" |
|
1087 | You must have previously started logging.""" | |
1088 | self.shell.logger.switch_log(0) |
|
1088 | self.shell.logger.switch_log(0) | |
1089 |
|
1089 | |||
1090 | def magic_logon(self,parameter_s=''): |
|
1090 | def magic_logon(self,parameter_s=''): | |
1091 | """Restart logging. |
|
1091 | """Restart logging. | |
1092 |
|
1092 | |||
1093 | This function is for restarting logging which you've temporarily |
|
1093 | This function is for restarting logging which you've temporarily | |
1094 | stopped with %logoff. For starting logging for the first time, you |
|
1094 | stopped with %logoff. For starting logging for the first time, you | |
1095 | must use the %logstart function, which allows you to specify an |
|
1095 | must use the %logstart function, which allows you to specify an | |
1096 | optional log filename.""" |
|
1096 | optional log filename.""" | |
1097 |
|
1097 | |||
1098 | self.shell.logger.switch_log(1) |
|
1098 | self.shell.logger.switch_log(1) | |
1099 |
|
1099 | |||
1100 | def magic_logstate(self,parameter_s=''): |
|
1100 | def magic_logstate(self,parameter_s=''): | |
1101 | """Print the status of the logging system.""" |
|
1101 | """Print the status of the logging system.""" | |
1102 |
|
1102 | |||
1103 | self.shell.logger.logstate() |
|
1103 | self.shell.logger.logstate() | |
1104 |
|
1104 | |||
1105 | def magic_pdb(self, parameter_s=''): |
|
1105 | def magic_pdb(self, parameter_s=''): | |
1106 | """Control the calling of the pdb interactive debugger. |
|
1106 | """Control the calling of the pdb interactive debugger. | |
1107 |
|
1107 | |||
1108 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1108 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1109 | argument it works as a toggle. |
|
1109 | argument it works as a toggle. | |
1110 |
|
1110 | |||
1111 | When an exception is triggered, IPython can optionally call the |
|
1111 | When an exception is triggered, IPython can optionally call the | |
1112 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1112 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1113 | this feature on and off.""" |
|
1113 | this feature on and off.""" | |
1114 |
|
1114 | |||
1115 | par = parameter_s.strip().lower() |
|
1115 | par = parameter_s.strip().lower() | |
1116 |
|
1116 | |||
1117 | if par: |
|
1117 | if par: | |
1118 | try: |
|
1118 | try: | |
1119 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1119 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1120 | except KeyError: |
|
1120 | except KeyError: | |
1121 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1121 | print ('Incorrect argument. Use on/1, off/0, ' | |
1122 | 'or nothing for a toggle.') |
|
1122 | 'or nothing for a toggle.') | |
1123 | return |
|
1123 | return | |
1124 | else: |
|
1124 | else: | |
1125 | # toggle |
|
1125 | # toggle | |
1126 | new_pdb = not self.shell.InteractiveTB.call_pdb |
|
1126 | new_pdb = not self.shell.InteractiveTB.call_pdb | |
1127 |
|
1127 | |||
1128 | # set on the shell |
|
1128 | # set on the shell | |
1129 | self.shell.call_pdb = new_pdb |
|
1129 | self.shell.call_pdb = new_pdb | |
1130 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1130 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1131 |
|
1131 | |||
1132 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1132 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1133 | opts=None,arg_lst=None,prog_ns=None): |
|
1133 | opts=None,arg_lst=None,prog_ns=None): | |
1134 |
|
1134 | |||
1135 | """Run a statement through the python code profiler. |
|
1135 | """Run a statement through the python code profiler. | |
1136 |
|
1136 | |||
1137 | Usage:\\ |
|
1137 | Usage:\\ | |
1138 | %prun [options] statement |
|
1138 | %prun [options] statement | |
1139 |
|
1139 | |||
1140 | The given statement (which doesn't require quote marks) is run via the |
|
1140 | The given statement (which doesn't require quote marks) is run via the | |
1141 | python profiler in a manner similar to the profile.run() function. |
|
1141 | python profiler in a manner similar to the profile.run() function. | |
1142 | Namespaces are internally managed to work correctly; profile.run |
|
1142 | Namespaces are internally managed to work correctly; profile.run | |
1143 | cannot be used in IPython because it makes certain assumptions about |
|
1143 | cannot be used in IPython because it makes certain assumptions about | |
1144 | namespaces which do not hold under IPython. |
|
1144 | namespaces which do not hold under IPython. | |
1145 |
|
1145 | |||
1146 | Options: |
|
1146 | Options: | |
1147 |
|
1147 | |||
1148 | -l <limit>: you can place restrictions on what or how much of the |
|
1148 | -l <limit>: you can place restrictions on what or how much of the | |
1149 | profile gets printed. The limit value can be: |
|
1149 | profile gets printed. The limit value can be: | |
1150 |
|
1150 | |||
1151 | * A string: only information for function names containing this string |
|
1151 | * A string: only information for function names containing this string | |
1152 | is printed. |
|
1152 | is printed. | |
1153 |
|
1153 | |||
1154 | * An integer: only these many lines are printed. |
|
1154 | * An integer: only these many lines are printed. | |
1155 |
|
1155 | |||
1156 | * A float (between 0 and 1): this fraction of the report is printed |
|
1156 | * A float (between 0 and 1): this fraction of the report is printed | |
1157 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1157 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1158 |
|
1158 | |||
1159 | You can combine several limits with repeated use of the option. For |
|
1159 | You can combine several limits with repeated use of the option. For | |
1160 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1160 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1161 | information about class constructors. |
|
1161 | information about class constructors. | |
1162 |
|
1162 | |||
1163 | -r: return the pstats.Stats object generated by the profiling. This |
|
1163 | -r: return the pstats.Stats object generated by the profiling. This | |
1164 | object has all the information about the profile in it, and you can |
|
1164 | object has all the information about the profile in it, and you can | |
1165 | later use it for further analysis or in other functions. |
|
1165 | later use it for further analysis or in other functions. | |
1166 |
|
1166 | |||
1167 | Since magic functions have a particular form of calling which prevents |
|
1167 | Since magic functions have a particular form of calling which prevents | |
1168 | you from writing something like:\\ |
|
1168 | you from writing something like:\\ | |
1169 | In [1]: p = %prun -r print 4 # invalid!\\ |
|
1169 | In [1]: p = %prun -r print 4 # invalid!\\ | |
1170 | you must instead use IPython's automatic variables to assign this:\\ |
|
1170 | you must instead use IPython's automatic variables to assign this:\\ | |
1171 | In [1]: %prun -r print 4 \\ |
|
1171 | In [1]: %prun -r print 4 \\ | |
1172 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ |
|
1172 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ | |
1173 | In [2]: stats = _ |
|
1173 | In [2]: stats = _ | |
1174 |
|
1174 | |||
1175 | If you really need to assign this value via an explicit function call, |
|
1175 | If you really need to assign this value via an explicit function call, | |
1176 | you can always tap directly into the true name of the magic function |
|
1176 | you can always tap directly into the true name of the magic function | |
1177 | by using the _ip.magic function:\\ |
|
1177 | by using the _ip.magic function:\\ | |
1178 | In [3]: stats = _ip.magic('prun','-r print 4') |
|
1178 | In [3]: stats = _ip.magic('prun','-r print 4') | |
1179 |
|
1179 | |||
1180 | You can type _ip.magic? for more details. |
|
1180 | You can type _ip.magic? for more details. | |
1181 |
|
1181 | |||
1182 | -s <key>: sort profile by given key. You can provide more than one key |
|
1182 | -s <key>: sort profile by given key. You can provide more than one key | |
1183 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1183 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1184 | default sorting key is 'time'. |
|
1184 | default sorting key is 'time'. | |
1185 |
|
1185 | |||
1186 | The following is copied verbatim from the profile documentation |
|
1186 | The following is copied verbatim from the profile documentation | |
1187 | referenced below: |
|
1187 | referenced below: | |
1188 |
|
1188 | |||
1189 | When more than one key is provided, additional keys are used as |
|
1189 | When more than one key is provided, additional keys are used as | |
1190 | secondary criteria when the there is equality in all keys selected |
|
1190 | secondary criteria when the there is equality in all keys selected | |
1191 | before them. |
|
1191 | before them. | |
1192 |
|
1192 | |||
1193 | Abbreviations can be used for any key names, as long as the |
|
1193 | Abbreviations can be used for any key names, as long as the | |
1194 | abbreviation is unambiguous. The following are the keys currently |
|
1194 | abbreviation is unambiguous. The following are the keys currently | |
1195 | defined: |
|
1195 | defined: | |
1196 |
|
1196 | |||
1197 | Valid Arg Meaning\\ |
|
1197 | Valid Arg Meaning\\ | |
1198 | "calls" call count\\ |
|
1198 | "calls" call count\\ | |
1199 | "cumulative" cumulative time\\ |
|
1199 | "cumulative" cumulative time\\ | |
1200 | "file" file name\\ |
|
1200 | "file" file name\\ | |
1201 | "module" file name\\ |
|
1201 | "module" file name\\ | |
1202 | "pcalls" primitive call count\\ |
|
1202 | "pcalls" primitive call count\\ | |
1203 | "line" line number\\ |
|
1203 | "line" line number\\ | |
1204 | "name" function name\\ |
|
1204 | "name" function name\\ | |
1205 | "nfl" name/file/line\\ |
|
1205 | "nfl" name/file/line\\ | |
1206 | "stdname" standard name\\ |
|
1206 | "stdname" standard name\\ | |
1207 | "time" internal time |
|
1207 | "time" internal time | |
1208 |
|
1208 | |||
1209 | Note that all sorts on statistics are in descending order (placing |
|
1209 | Note that all sorts on statistics are in descending order (placing | |
1210 | most time consuming items first), where as name, file, and line number |
|
1210 | most time consuming items first), where as name, file, and line number | |
1211 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1211 | searches are in ascending order (i.e., alphabetical). The subtle | |
1212 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1212 | distinction between "nfl" and "stdname" is that the standard name is a | |
1213 | sort of the name as printed, which means that the embedded line |
|
1213 | sort of the name as printed, which means that the embedded line | |
1214 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1214 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1215 | would (if the file names were the same) appear in the string order |
|
1215 | would (if the file names were the same) appear in the string order | |
1216 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1216 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1217 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1217 | line numbers. In fact, sort_stats("nfl") is the same as | |
1218 | sort_stats("name", "file", "line"). |
|
1218 | sort_stats("name", "file", "line"). | |
1219 |
|
1219 | |||
1220 | -T <filename>: save profile results as shown on screen to a text |
|
1220 | -T <filename>: save profile results as shown on screen to a text | |
1221 | file. The profile is still shown on screen. |
|
1221 | file. The profile is still shown on screen. | |
1222 |
|
1222 | |||
1223 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1223 | -D <filename>: save (via dump_stats) profile statistics to given | |
1224 | filename. This data is in a format understod by the pstats module, and |
|
1224 | filename. This data is in a format understod by the pstats module, and | |
1225 | is generated by a call to the dump_stats() method of profile |
|
1225 | is generated by a call to the dump_stats() method of profile | |
1226 | objects. The profile is still shown on screen. |
|
1226 | objects. The profile is still shown on screen. | |
1227 |
|
1227 | |||
1228 | If you want to run complete programs under the profiler's control, use |
|
1228 | If you want to run complete programs under the profiler's control, use | |
1229 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1229 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1230 | contains profiler specific options as described here. |
|
1230 | contains profiler specific options as described here. | |
1231 |
|
1231 | |||
1232 | You can read the complete documentation for the profile module with:\\ |
|
1232 | You can read the complete documentation for the profile module with:\\ | |
1233 | In [1]: import profile; profile.help() """ |
|
1233 | In [1]: import profile; profile.help() """ | |
1234 |
|
1234 | |||
1235 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1235 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1236 | # protect user quote marks |
|
1236 | # protect user quote marks | |
1237 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1237 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1238 |
|
1238 | |||
1239 | if user_mode: # regular user call |
|
1239 | if user_mode: # regular user call | |
1240 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1240 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1241 | list_all=1) |
|
1241 | list_all=1) | |
1242 | namespace = self.shell.user_ns |
|
1242 | namespace = self.shell.user_ns | |
1243 | else: # called to run a program by %run -p |
|
1243 | else: # called to run a program by %run -p | |
1244 | try: |
|
1244 | try: | |
1245 | filename = get_py_filename(arg_lst[0]) |
|
1245 | filename = get_py_filename(arg_lst[0]) | |
1246 | except IOError,msg: |
|
1246 | except IOError,msg: | |
1247 | error(msg) |
|
1247 | error(msg) | |
1248 | return |
|
1248 | return | |
1249 |
|
1249 | |||
1250 | arg_str = 'execfile(filename,prog_ns)' |
|
1250 | arg_str = 'execfile(filename,prog_ns)' | |
1251 | namespace = locals() |
|
1251 | namespace = locals() | |
1252 |
|
1252 | |||
1253 | opts.merge(opts_def) |
|
1253 | opts.merge(opts_def) | |
1254 |
|
1254 | |||
1255 | prof = profile.Profile() |
|
1255 | prof = profile.Profile() | |
1256 | try: |
|
1256 | try: | |
1257 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1257 | prof = prof.runctx(arg_str,namespace,namespace) | |
1258 | sys_exit = '' |
|
1258 | sys_exit = '' | |
1259 | except SystemExit: |
|
1259 | except SystemExit: | |
1260 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1260 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1261 |
|
1261 | |||
1262 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1262 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1263 |
|
1263 | |||
1264 | lims = opts.l |
|
1264 | lims = opts.l | |
1265 | if lims: |
|
1265 | if lims: | |
1266 | lims = [] # rebuild lims with ints/floats/strings |
|
1266 | lims = [] # rebuild lims with ints/floats/strings | |
1267 | for lim in opts.l: |
|
1267 | for lim in opts.l: | |
1268 | try: |
|
1268 | try: | |
1269 | lims.append(int(lim)) |
|
1269 | lims.append(int(lim)) | |
1270 | except ValueError: |
|
1270 | except ValueError: | |
1271 | try: |
|
1271 | try: | |
1272 | lims.append(float(lim)) |
|
1272 | lims.append(float(lim)) | |
1273 | except ValueError: |
|
1273 | except ValueError: | |
1274 | lims.append(lim) |
|
1274 | lims.append(lim) | |
1275 |
|
1275 | |||
1276 | # trap output |
|
1276 | # trap output | |
1277 | sys_stdout = sys.stdout |
|
1277 | sys_stdout = sys.stdout | |
1278 | stdout_trap = StringIO() |
|
1278 | stdout_trap = StringIO() | |
1279 | try: |
|
1279 | try: | |
1280 | sys.stdout = stdout_trap |
|
1280 | sys.stdout = stdout_trap | |
1281 | stats.print_stats(*lims) |
|
1281 | stats.print_stats(*lims) | |
1282 | finally: |
|
1282 | finally: | |
1283 | sys.stdout = sys_stdout |
|
1283 | sys.stdout = sys_stdout | |
1284 | output = stdout_trap.getvalue() |
|
1284 | output = stdout_trap.getvalue() | |
1285 | output = output.rstrip() |
|
1285 | output = output.rstrip() | |
1286 |
|
1286 | |||
1287 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1287 | page(output,screen_lines=self.shell.rc.screen_length) | |
1288 | print sys_exit, |
|
1288 | print sys_exit, | |
1289 |
|
1289 | |||
1290 | dump_file = opts.D[0] |
|
1290 | dump_file = opts.D[0] | |
1291 | text_file = opts.T[0] |
|
1291 | text_file = opts.T[0] | |
1292 | if dump_file: |
|
1292 | if dump_file: | |
1293 | prof.dump_stats(dump_file) |
|
1293 | prof.dump_stats(dump_file) | |
1294 | print '\n*** Profile stats marshalled to file',\ |
|
1294 | print '\n*** Profile stats marshalled to file',\ | |
1295 | `dump_file`+'.',sys_exit |
|
1295 | `dump_file`+'.',sys_exit | |
1296 | if text_file: |
|
1296 | if text_file: | |
1297 | file(text_file,'w').write(output) |
|
1297 | file(text_file,'w').write(output) | |
1298 | print '\n*** Profile printout saved to text file',\ |
|
1298 | print '\n*** Profile printout saved to text file',\ | |
1299 | `text_file`+'.',sys_exit |
|
1299 | `text_file`+'.',sys_exit | |
1300 |
|
1300 | |||
1301 | if opts.has_key('r'): |
|
1301 | if opts.has_key('r'): | |
1302 | return stats |
|
1302 | return stats | |
1303 | else: |
|
1303 | else: | |
1304 | return None |
|
1304 | return None | |
1305 |
|
1305 | |||
1306 | def magic_run(self, parameter_s ='',runner=None): |
|
1306 | def magic_run(self, parameter_s ='',runner=None): | |
1307 | """Run the named file inside IPython as a program. |
|
1307 | """Run the named file inside IPython as a program. | |
1308 |
|
1308 | |||
1309 | Usage:\\ |
|
1309 | Usage:\\ | |
1310 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1310 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1311 |
|
1311 | |||
1312 | Parameters after the filename are passed as command-line arguments to |
|
1312 | Parameters after the filename are passed as command-line arguments to | |
1313 | the program (put in sys.argv). Then, control returns to IPython's |
|
1313 | the program (put in sys.argv). Then, control returns to IPython's | |
1314 | prompt. |
|
1314 | prompt. | |
1315 |
|
1315 | |||
1316 | This is similar to running at a system prompt:\\ |
|
1316 | This is similar to running at a system prompt:\\ | |
1317 | $ python file args\\ |
|
1317 | $ python file args\\ | |
1318 | but with the advantage of giving you IPython's tracebacks, and of |
|
1318 | but with the advantage of giving you IPython's tracebacks, and of | |
1319 | loading all variables into your interactive namespace for further use |
|
1319 | loading all variables into your interactive namespace for further use | |
1320 | (unless -p is used, see below). |
|
1320 | (unless -p is used, see below). | |
1321 |
|
1321 | |||
1322 | The file is executed in a namespace initially consisting only of |
|
1322 | The file is executed in a namespace initially consisting only of | |
1323 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1323 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1324 | sees its environment as if it were being run as a stand-alone |
|
1324 | sees its environment as if it were being run as a stand-alone | |
1325 | program. But after execution, the IPython interactive namespace gets |
|
1325 | program. But after execution, the IPython interactive namespace gets | |
1326 | updated with all variables defined in the program (except for __name__ |
|
1326 | updated with all variables defined in the program (except for __name__ | |
1327 | and sys.argv). This allows for very convenient loading of code for |
|
1327 | and sys.argv). This allows for very convenient loading of code for | |
1328 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1328 | interactive work, while giving each program a 'clean sheet' to run in. | |
1329 |
|
1329 | |||
1330 | Options: |
|
1330 | Options: | |
1331 |
|
1331 | |||
1332 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1332 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1333 | without extension (as python does under import). This allows running |
|
1333 | without extension (as python does under import). This allows running | |
1334 | scripts and reloading the definitions in them without calling code |
|
1334 | scripts and reloading the definitions in them without calling code | |
1335 | protected by an ' if __name__ == "__main__" ' clause. |
|
1335 | protected by an ' if __name__ == "__main__" ' clause. | |
1336 |
|
1336 | |||
1337 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1337 | -i: run the file in IPython's namespace instead of an empty one. This | |
1338 | is useful if you are experimenting with code written in a text editor |
|
1338 | is useful if you are experimenting with code written in a text editor | |
1339 | which depends on variables defined interactively. |
|
1339 | which depends on variables defined interactively. | |
1340 |
|
1340 | |||
1341 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1341 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1342 | being run. This is particularly useful if IPython is being used to |
|
1342 | being run. This is particularly useful if IPython is being used to | |
1343 | run unittests, which always exit with a sys.exit() call. In such |
|
1343 | run unittests, which always exit with a sys.exit() call. In such | |
1344 | cases you are interested in the output of the test results, not in |
|
1344 | cases you are interested in the output of the test results, not in | |
1345 | seeing a traceback of the unittest module. |
|
1345 | seeing a traceback of the unittest module. | |
1346 |
|
1346 | |||
1347 | -t: print timing information at the end of the run. IPython will give |
|
1347 | -t: print timing information at the end of the run. IPython will give | |
1348 | you an estimated CPU time consumption for your script, which under |
|
1348 | you an estimated CPU time consumption for your script, which under | |
1349 | Unix uses the resource module to avoid the wraparound problems of |
|
1349 | Unix uses the resource module to avoid the wraparound problems of | |
1350 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1350 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1351 | is also given (for Windows platforms this is reported as 0.0). |
|
1351 | is also given (for Windows platforms this is reported as 0.0). | |
1352 |
|
1352 | |||
1353 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1353 | If -t is given, an additional -N<N> option can be given, where <N> | |
1354 | must be an integer indicating how many times you want the script to |
|
1354 | must be an integer indicating how many times you want the script to | |
1355 | run. The final timing report will include total and per run results. |
|
1355 | run. The final timing report will include total and per run results. | |
1356 |
|
1356 | |||
1357 | For example (testing the script uniq_stable.py): |
|
1357 | For example (testing the script uniq_stable.py): | |
1358 |
|
1358 | |||
1359 | In [1]: run -t uniq_stable |
|
1359 | In [1]: run -t uniq_stable | |
1360 |
|
1360 | |||
1361 | IPython CPU timings (estimated):\\ |
|
1361 | IPython CPU timings (estimated):\\ | |
1362 | User : 0.19597 s.\\ |
|
1362 | User : 0.19597 s.\\ | |
1363 | System: 0.0 s.\\ |
|
1363 | System: 0.0 s.\\ | |
1364 |
|
1364 | |||
1365 | In [2]: run -t -N5 uniq_stable |
|
1365 | In [2]: run -t -N5 uniq_stable | |
1366 |
|
1366 | |||
1367 | IPython CPU timings (estimated):\\ |
|
1367 | IPython CPU timings (estimated):\\ | |
1368 | Total runs performed: 5\\ |
|
1368 | Total runs performed: 5\\ | |
1369 | Times : Total Per run\\ |
|
1369 | Times : Total Per run\\ | |
1370 | User : 0.910862 s, 0.1821724 s.\\ |
|
1370 | User : 0.910862 s, 0.1821724 s.\\ | |
1371 | System: 0.0 s, 0.0 s. |
|
1371 | System: 0.0 s, 0.0 s. | |
1372 |
|
1372 | |||
1373 | -d: run your program under the control of pdb, the Python debugger. |
|
1373 | -d: run your program under the control of pdb, the Python debugger. | |
1374 | This allows you to execute your program step by step, watch variables, |
|
1374 | This allows you to execute your program step by step, watch variables, | |
1375 | etc. Internally, what IPython does is similar to calling: |
|
1375 | etc. Internally, what IPython does is similar to calling: | |
1376 |
|
1376 | |||
1377 | pdb.run('execfile("YOURFILENAME")') |
|
1377 | pdb.run('execfile("YOURFILENAME")') | |
1378 |
|
1378 | |||
1379 | with a breakpoint set on line 1 of your file. You can change the line |
|
1379 | with a breakpoint set on line 1 of your file. You can change the line | |
1380 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1380 | number for this automatic breakpoint to be <N> by using the -bN option | |
1381 | (where N must be an integer). For example: |
|
1381 | (where N must be an integer). For example: | |
1382 |
|
1382 | |||
1383 | %run -d -b40 myscript |
|
1383 | %run -d -b40 myscript | |
1384 |
|
1384 | |||
1385 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1385 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1386 | the first breakpoint must be set on a line which actually does |
|
1386 | the first breakpoint must be set on a line which actually does | |
1387 | something (not a comment or docstring) for it to stop execution. |
|
1387 | something (not a comment or docstring) for it to stop execution. | |
1388 |
|
1388 | |||
1389 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1389 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1390 | first enter 'c' (without qoutes) to start execution up to the first |
|
1390 | first enter 'c' (without qoutes) to start execution up to the first | |
1391 | breakpoint. |
|
1391 | breakpoint. | |
1392 |
|
1392 | |||
1393 | Entering 'help' gives information about the use of the debugger. You |
|
1393 | Entering 'help' gives information about the use of the debugger. You | |
1394 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1394 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1395 | at a prompt. |
|
1395 | at a prompt. | |
1396 |
|
1396 | |||
1397 | -p: run program under the control of the Python profiler module (which |
|
1397 | -p: run program under the control of the Python profiler module (which | |
1398 | prints a detailed report of execution times, function calls, etc). |
|
1398 | prints a detailed report of execution times, function calls, etc). | |
1399 |
|
1399 | |||
1400 | You can pass other options after -p which affect the behavior of the |
|
1400 | You can pass other options after -p which affect the behavior of the | |
1401 | profiler itself. See the docs for %prun for details. |
|
1401 | profiler itself. See the docs for %prun for details. | |
1402 |
|
1402 | |||
1403 | In this mode, the program's variables do NOT propagate back to the |
|
1403 | In this mode, the program's variables do NOT propagate back to the | |
1404 | IPython interactive namespace (because they remain in the namespace |
|
1404 | IPython interactive namespace (because they remain in the namespace | |
1405 | where the profiler executes them). |
|
1405 | where the profiler executes them). | |
1406 |
|
1406 | |||
1407 | Internally this triggers a call to %prun, see its documentation for |
|
1407 | Internally this triggers a call to %prun, see its documentation for | |
1408 | details on the options available specifically for profiling.""" |
|
1408 | details on the options available specifically for profiling.""" | |
1409 |
|
1409 | |||
1410 | # get arguments and set sys.argv for program to be run. |
|
1410 | # get arguments and set sys.argv for program to be run. | |
1411 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1411 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1412 | mode='list',list_all=1) |
|
1412 | mode='list',list_all=1) | |
1413 |
|
1413 | |||
1414 | try: |
|
1414 | try: | |
1415 | filename = get_py_filename(arg_lst[0]) |
|
1415 | filename = get_py_filename(arg_lst[0]) | |
1416 | except IndexError: |
|
1416 | except IndexError: | |
1417 | warn('you must provide at least a filename.') |
|
1417 | warn('you must provide at least a filename.') | |
1418 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1418 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1419 | return |
|
1419 | return | |
1420 | except IOError,msg: |
|
1420 | except IOError,msg: | |
1421 | error(msg) |
|
1421 | error(msg) | |
1422 | return |
|
1422 | return | |
1423 |
|
1423 | |||
1424 | # Control the response to exit() calls made by the script being run |
|
1424 | # Control the response to exit() calls made by the script being run | |
1425 | exit_ignore = opts.has_key('e') |
|
1425 | exit_ignore = opts.has_key('e') | |
1426 |
|
1426 | |||
1427 | # Make sure that the running script gets a proper sys.argv as if it |
|
1427 | # Make sure that the running script gets a proper sys.argv as if it | |
1428 | # were run from a system shell. |
|
1428 | # were run from a system shell. | |
1429 | save_argv = sys.argv # save it for later restoring |
|
1429 | save_argv = sys.argv # save it for later restoring | |
1430 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1430 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1431 |
|
1431 | |||
1432 | if opts.has_key('i'): |
|
1432 | if opts.has_key('i'): | |
1433 | prog_ns = self.shell.user_ns |
|
1433 | prog_ns = self.shell.user_ns | |
1434 | __name__save = self.shell.user_ns['__name__'] |
|
1434 | __name__save = self.shell.user_ns['__name__'] | |
1435 | prog_ns['__name__'] = '__main__' |
|
1435 | prog_ns['__name__'] = '__main__' | |
1436 | else: |
|
1436 | else: | |
1437 | if opts.has_key('n'): |
|
1437 | if opts.has_key('n'): | |
1438 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1438 | name = os.path.splitext(os.path.basename(filename))[0] | |
1439 | else: |
|
1439 | else: | |
1440 | name = '__main__' |
|
1440 | name = '__main__' | |
1441 | prog_ns = {'__name__':name} |
|
1441 | prog_ns = {'__name__':name} | |
1442 |
|
1442 | |||
1443 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1443 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1444 | # set the __file__ global in the script's namespace |
|
1444 | # set the __file__ global in the script's namespace | |
1445 | prog_ns['__file__'] = filename |
|
1445 | prog_ns['__file__'] = filename | |
1446 |
|
1446 | |||
1447 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1447 | # pickle fix. See iplib for an explanation. But we need to make sure | |
1448 | # that, if we overwrite __main__, we replace it at the end |
|
1448 | # that, if we overwrite __main__, we replace it at the end | |
1449 | if prog_ns['__name__'] == '__main__': |
|
1449 | if prog_ns['__name__'] == '__main__': | |
1450 | restore_main = sys.modules['__main__'] |
|
1450 | restore_main = sys.modules['__main__'] | |
1451 | else: |
|
1451 | else: | |
1452 | restore_main = False |
|
1452 | restore_main = False | |
1453 |
|
1453 | |||
1454 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1454 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) | |
1455 |
|
1455 | |||
1456 | stats = None |
|
1456 | stats = None | |
1457 | try: |
|
1457 | try: | |
1458 | if opts.has_key('p'): |
|
1458 | if opts.has_key('p'): | |
1459 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1459 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1460 | else: |
|
1460 | else: | |
1461 | if opts.has_key('d'): |
|
1461 | if opts.has_key('d'): | |
1462 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1462 | deb = Debugger.Pdb(self.shell.rc.colors) | |
1463 | # reset Breakpoint state, which is moronically kept |
|
1463 | # reset Breakpoint state, which is moronically kept | |
1464 | # in a class |
|
1464 | # in a class | |
1465 | bdb.Breakpoint.next = 1 |
|
1465 | bdb.Breakpoint.next = 1 | |
1466 | bdb.Breakpoint.bplist = {} |
|
1466 | bdb.Breakpoint.bplist = {} | |
1467 | bdb.Breakpoint.bpbynumber = [None] |
|
1467 | bdb.Breakpoint.bpbynumber = [None] | |
1468 | # Set an initial breakpoint to stop execution |
|
1468 | # Set an initial breakpoint to stop execution | |
1469 | maxtries = 10 |
|
1469 | maxtries = 10 | |
1470 | bp = int(opts.get('b',[1])[0]) |
|
1470 | bp = int(opts.get('b',[1])[0]) | |
1471 | checkline = deb.checkline(filename,bp) |
|
1471 | checkline = deb.checkline(filename,bp) | |
1472 | if not checkline: |
|
1472 | if not checkline: | |
1473 | for bp in range(bp+1,bp+maxtries+1): |
|
1473 | for bp in range(bp+1,bp+maxtries+1): | |
1474 | if deb.checkline(filename,bp): |
|
1474 | if deb.checkline(filename,bp): | |
1475 | break |
|
1475 | break | |
1476 | else: |
|
1476 | else: | |
1477 | msg = ("\nI failed to find a valid line to set " |
|
1477 | msg = ("\nI failed to find a valid line to set " | |
1478 | "a breakpoint\n" |
|
1478 | "a breakpoint\n" | |
1479 | "after trying up to line: %s.\n" |
|
1479 | "after trying up to line: %s.\n" | |
1480 | "Please set a valid breakpoint manually " |
|
1480 | "Please set a valid breakpoint manually " | |
1481 | "with the -b option." % bp) |
|
1481 | "with the -b option." % bp) | |
1482 | error(msg) |
|
1482 | error(msg) | |
1483 | return |
|
1483 | return | |
1484 | # if we find a good linenumber, set the breakpoint |
|
1484 | # if we find a good linenumber, set the breakpoint | |
1485 | deb.do_break('%s:%s' % (filename,bp)) |
|
1485 | deb.do_break('%s:%s' % (filename,bp)) | |
1486 | # Start file run |
|
1486 | # Start file run | |
1487 | print "NOTE: Enter 'c' at the", |
|
1487 | print "NOTE: Enter 'c' at the", | |
1488 | print "ipdb> prompt to start your script." |
|
1488 | print "ipdb> prompt to start your script." | |
1489 | try: |
|
1489 | try: | |
1490 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1490 | deb.run('execfile("%s")' % filename,prog_ns) | |
1491 | except: |
|
1491 | except: | |
1492 | etype, value, tb = sys.exc_info() |
|
1492 | etype, value, tb = sys.exc_info() | |
1493 | # Skip three frames in the traceback: the %run one, |
|
1493 | # Skip three frames in the traceback: the %run one, | |
1494 | # one inside bdb.py, and the command-line typed by the |
|
1494 | # one inside bdb.py, and the command-line typed by the | |
1495 | # user (run by exec in pdb itself). |
|
1495 | # user (run by exec in pdb itself). | |
1496 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1496 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1497 | else: |
|
1497 | else: | |
1498 | if runner is None: |
|
1498 | if runner is None: | |
1499 | runner = self.shell.safe_execfile |
|
1499 | runner = self.shell.safe_execfile | |
1500 | if opts.has_key('t'): |
|
1500 | if opts.has_key('t'): | |
1501 | try: |
|
1501 | try: | |
1502 | nruns = int(opts['N'][0]) |
|
1502 | nruns = int(opts['N'][0]) | |
1503 | if nruns < 1: |
|
1503 | if nruns < 1: | |
1504 | error('Number of runs must be >=1') |
|
1504 | error('Number of runs must be >=1') | |
1505 | return |
|
1505 | return | |
1506 | except (KeyError): |
|
1506 | except (KeyError): | |
1507 | nruns = 1 |
|
1507 | nruns = 1 | |
1508 | if nruns == 1: |
|
1508 | if nruns == 1: | |
1509 | t0 = clock2() |
|
1509 | t0 = clock2() | |
1510 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1510 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1511 | t1 = clock2() |
|
1511 | t1 = clock2() | |
1512 | t_usr = t1[0]-t0[0] |
|
1512 | t_usr = t1[0]-t0[0] | |
1513 | t_sys = t1[1]-t1[1] |
|
1513 | t_sys = t1[1]-t1[1] | |
1514 | print "\nIPython CPU timings (estimated):" |
|
1514 | print "\nIPython CPU timings (estimated):" | |
1515 | print " User : %10s s." % t_usr |
|
1515 | print " User : %10s s." % t_usr | |
1516 | print " System: %10s s." % t_sys |
|
1516 | print " System: %10s s." % t_sys | |
1517 | else: |
|
1517 | else: | |
1518 | runs = range(nruns) |
|
1518 | runs = range(nruns) | |
1519 | t0 = clock2() |
|
1519 | t0 = clock2() | |
1520 | for nr in runs: |
|
1520 | for nr in runs: | |
1521 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1521 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1522 | t1 = clock2() |
|
1522 | t1 = clock2() | |
1523 | t_usr = t1[0]-t0[0] |
|
1523 | t_usr = t1[0]-t0[0] | |
1524 | t_sys = t1[1]-t1[1] |
|
1524 | t_sys = t1[1]-t1[1] | |
1525 | print "\nIPython CPU timings (estimated):" |
|
1525 | print "\nIPython CPU timings (estimated):" | |
1526 | print "Total runs performed:",nruns |
|
1526 | print "Total runs performed:",nruns | |
1527 | print " Times : %10s %10s" % ('Total','Per run') |
|
1527 | print " Times : %10s %10s" % ('Total','Per run') | |
1528 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1528 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1529 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1529 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1530 |
|
1530 | |||
1531 | else: |
|
1531 | else: | |
1532 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1532 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1533 | if opts.has_key('i'): |
|
1533 | if opts.has_key('i'): | |
1534 | self.shell.user_ns['__name__'] = __name__save |
|
1534 | self.shell.user_ns['__name__'] = __name__save | |
1535 | else: |
|
1535 | else: | |
1536 | # update IPython interactive namespace |
|
1536 | # update IPython interactive namespace | |
1537 | del prog_ns['__name__'] |
|
1537 | del prog_ns['__name__'] | |
1538 | self.shell.user_ns.update(prog_ns) |
|
1538 | self.shell.user_ns.update(prog_ns) | |
1539 | finally: |
|
1539 | finally: | |
1540 | sys.argv = save_argv |
|
1540 | sys.argv = save_argv | |
1541 | if restore_main: |
|
1541 | if restore_main: | |
1542 | sys.modules['__main__'] = restore_main |
|
1542 | sys.modules['__main__'] = restore_main | |
1543 | return stats |
|
1543 | return stats | |
1544 |
|
1544 | |||
1545 | def magic_runlog(self, parameter_s =''): |
|
1545 | def magic_runlog(self, parameter_s =''): | |
1546 | """Run files as logs. |
|
1546 | """Run files as logs. | |
1547 |
|
1547 | |||
1548 | Usage:\\ |
|
1548 | Usage:\\ | |
1549 | %runlog file1 file2 ... |
|
1549 | %runlog file1 file2 ... | |
1550 |
|
1550 | |||
1551 | Run the named files (treating them as log files) in sequence inside |
|
1551 | Run the named files (treating them as log files) in sequence inside | |
1552 | the interpreter, and return to the prompt. This is much slower than |
|
1552 | the interpreter, and return to the prompt. This is much slower than | |
1553 | %run because each line is executed in a try/except block, but it |
|
1553 | %run because each line is executed in a try/except block, but it | |
1554 | allows running files with syntax errors in them. |
|
1554 | allows running files with syntax errors in them. | |
1555 |
|
1555 | |||
1556 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1556 | Normally IPython will guess when a file is one of its own logfiles, so | |
1557 | you can typically use %run even for logs. This shorthand allows you to |
|
1557 | you can typically use %run even for logs. This shorthand allows you to | |
1558 | force any file to be treated as a log file.""" |
|
1558 | force any file to be treated as a log file.""" | |
1559 |
|
1559 | |||
1560 | for f in parameter_s.split(): |
|
1560 | for f in parameter_s.split(): | |
1561 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1561 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1562 | self.shell.user_ns,islog=1) |
|
1562 | self.shell.user_ns,islog=1) | |
1563 |
|
1563 | |||
1564 | def magic_timeit(self, parameter_s =''): |
|
1564 | def magic_timeit(self, parameter_s =''): | |
1565 | """Time execution of a Python statement or expression |
|
1565 | """Time execution of a Python statement or expression | |
1566 |
|
1566 | |||
1567 | Usage:\\ |
|
1567 | Usage:\\ | |
1568 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1568 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1569 |
|
1569 | |||
1570 | Time execution of a Python statement or expression using the timeit |
|
1570 | Time execution of a Python statement or expression using the timeit | |
1571 | module. |
|
1571 | module. | |
1572 |
|
1572 | |||
1573 | Options: |
|
1573 | Options: | |
1574 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1574 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1575 | is not given, a fitting value is chosen. |
|
1575 | is not given, a fitting value is chosen. | |
1576 |
|
1576 | |||
1577 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1577 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1578 | Default: 3 |
|
1578 | Default: 3 | |
1579 |
|
1579 | |||
1580 | -t: use time.time to measure the time, which is the default on Unix. |
|
1580 | -t: use time.time to measure the time, which is the default on Unix. | |
1581 | This function measures wall time. |
|
1581 | This function measures wall time. | |
1582 |
|
1582 | |||
1583 | -c: use time.clock to measure the time, which is the default on |
|
1583 | -c: use time.clock to measure the time, which is the default on | |
1584 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1584 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1585 | instead and returns the CPU user time. |
|
1585 | instead and returns the CPU user time. | |
1586 |
|
1586 | |||
1587 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1587 | -p<P>: use a precision of <P> digits to display the timing result. | |
1588 | Default: 3 |
|
1588 | Default: 3 | |
1589 |
|
1589 | |||
1590 |
|
1590 | |||
1591 | Examples:\\ |
|
1591 | Examples:\\ | |
1592 | In [1]: %timeit pass |
|
1592 | In [1]: %timeit pass | |
1593 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1593 | 10000000 loops, best of 3: 53.3 ns per loop | |
1594 |
|
1594 | |||
1595 | In [2]: u = None |
|
1595 | In [2]: u = None | |
1596 |
|
1596 | |||
1597 | In [3]: %timeit u is None |
|
1597 | In [3]: %timeit u is None | |
1598 | 10000000 loops, best of 3: 184 ns per loop |
|
1598 | 10000000 loops, best of 3: 184 ns per loop | |
1599 |
|
1599 | |||
1600 | In [4]: %timeit -r 4 u == None |
|
1600 | In [4]: %timeit -r 4 u == None | |
1601 | 1000000 loops, best of 4: 242 ns per loop |
|
1601 | 1000000 loops, best of 4: 242 ns per loop | |
1602 |
|
1602 | |||
1603 | In [5]: import time |
|
1603 | In [5]: import time | |
1604 |
|
1604 | |||
1605 | In [6]: %timeit -n1 time.sleep(2) |
|
1605 | In [6]: %timeit -n1 time.sleep(2) | |
1606 | 1 loops, best of 3: 2 s per loop |
|
1606 | 1 loops, best of 3: 2 s per loop | |
1607 |
|
1607 | |||
1608 |
|
1608 | |||
1609 | The times reported by %timeit will be slightly higher than those reported |
|
1609 | The times reported by %timeit will be slightly higher than those reported | |
1610 | by the timeit.py script when variables are accessed. This is due to the |
|
1610 | by the timeit.py script when variables are accessed. This is due to the | |
1611 | fact that %timeit executes the statement in the namespace of the shell, |
|
1611 | fact that %timeit executes the statement in the namespace of the shell, | |
1612 | compared with timeit.py, which uses a single setup statement to import |
|
1612 | compared with timeit.py, which uses a single setup statement to import | |
1613 | function or create variables. Generally, the bias does not matter as long |
|
1613 | function or create variables. Generally, the bias does not matter as long | |
1614 | as results from timeit.py are not mixed with those from %timeit.""" |
|
1614 | as results from timeit.py are not mixed with those from %timeit.""" | |
1615 | import timeit |
|
1615 | import timeit | |
1616 | import math |
|
1616 | import math | |
1617 |
|
1617 | |||
1618 | units = ["s", "ms", "\xc2\xb5s", "ns"] |
|
1618 | units = ["s", "ms", "\xc2\xb5s", "ns"] | |
1619 | scaling = [1, 1e3, 1e6, 1e9] |
|
1619 | scaling = [1, 1e3, 1e6, 1e9] | |
1620 |
|
1620 | |||
1621 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:') |
|
1621 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:') | |
1622 | if stmt == "": |
|
1622 | if stmt == "": | |
1623 | return |
|
1623 | return | |
1624 | timefunc = timeit.default_timer |
|
1624 | timefunc = timeit.default_timer | |
1625 | number = int(getattr(opts, "n", 0)) |
|
1625 | number = int(getattr(opts, "n", 0)) | |
1626 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1626 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1627 | precision = int(getattr(opts, "p", 3)) |
|
1627 | precision = int(getattr(opts, "p", 3)) | |
1628 | if hasattr(opts, "t"): |
|
1628 | if hasattr(opts, "t"): | |
1629 | timefunc = time.time |
|
1629 | timefunc = time.time | |
1630 | if hasattr(opts, "c"): |
|
1630 | if hasattr(opts, "c"): | |
1631 | timefunc = clock |
|
1631 | timefunc = clock | |
1632 |
|
1632 | |||
1633 | timer = timeit.Timer(timer=timefunc) |
|
1633 | timer = timeit.Timer(timer=timefunc) | |
1634 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1634 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1635 | # but is there a better way to achieve that the code stmt has access |
|
1635 | # but is there a better way to achieve that the code stmt has access | |
1636 | # to the shell namespace? |
|
1636 | # to the shell namespace? | |
1637 |
|
1637 | |||
1638 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), 'setup': "pass"} |
|
1638 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), 'setup': "pass"} | |
1639 | code = compile(src, "<magic-timeit>", "exec") |
|
1639 | code = compile(src, "<magic-timeit>", "exec") | |
1640 | ns = {} |
|
1640 | ns = {} | |
1641 | exec code in self.shell.user_ns, ns |
|
1641 | exec code in self.shell.user_ns, ns | |
1642 | timer.inner = ns["inner"] |
|
1642 | timer.inner = ns["inner"] | |
1643 |
|
1643 | |||
1644 | if number == 0: |
|
1644 | if number == 0: | |
1645 | # determine number so that 0.2 <= total time < 2.0 |
|
1645 | # determine number so that 0.2 <= total time < 2.0 | |
1646 | number = 1 |
|
1646 | number = 1 | |
1647 | for i in range(1, 10): |
|
1647 | for i in range(1, 10): | |
1648 | number *= 10 |
|
1648 | number *= 10 | |
1649 | if timer.timeit(number) >= 0.2: |
|
1649 | if timer.timeit(number) >= 0.2: | |
1650 | break |
|
1650 | break | |
1651 |
|
1651 | |||
1652 | best = min(timer.repeat(repeat, number)) / number |
|
1652 | best = min(timer.repeat(repeat, number)) / number | |
1653 |
|
1653 | |||
1654 | if best > 0.0: |
|
1654 | if best > 0.0: | |
1655 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1655 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1656 | else: |
|
1656 | else: | |
1657 | order = 3 |
|
1657 | order = 3 | |
1658 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1658 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1659 | precision, |
|
1659 | precision, | |
1660 | best * scaling[order], |
|
1660 | best * scaling[order], | |
1661 | units[order]) |
|
1661 | units[order]) | |
1662 |
|
1662 | |||
1663 | def magic_time(self,parameter_s = ''): |
|
1663 | def magic_time(self,parameter_s = ''): | |
1664 | """Time execution of a Python statement or expression. |
|
1664 | """Time execution of a Python statement or expression. | |
1665 |
|
1665 | |||
1666 | The CPU and wall clock times are printed, and the value of the |
|
1666 | The CPU and wall clock times are printed, and the value of the | |
1667 | expression (if any) is returned. Note that under Win32, system time |
|
1667 | expression (if any) is returned. Note that under Win32, system time | |
1668 | is always reported as 0, since it can not be measured. |
|
1668 | is always reported as 0, since it can not be measured. | |
1669 |
|
1669 | |||
1670 | This function provides very basic timing functionality. In Python |
|
1670 | This function provides very basic timing functionality. In Python | |
1671 | 2.3, the timeit module offers more control and sophistication, so this |
|
1671 | 2.3, the timeit module offers more control and sophistication, so this | |
1672 | could be rewritten to use it (patches welcome). |
|
1672 | could be rewritten to use it (patches welcome). | |
1673 |
|
1673 | |||
1674 | Some examples: |
|
1674 | Some examples: | |
1675 |
|
1675 | |||
1676 | In [1]: time 2**128 |
|
1676 | In [1]: time 2**128 | |
1677 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1677 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1678 | Wall time: 0.00 |
|
1678 | Wall time: 0.00 | |
1679 | Out[1]: 340282366920938463463374607431768211456L |
|
1679 | Out[1]: 340282366920938463463374607431768211456L | |
1680 |
|
1680 | |||
1681 | In [2]: n = 1000000 |
|
1681 | In [2]: n = 1000000 | |
1682 |
|
1682 | |||
1683 | In [3]: time sum(range(n)) |
|
1683 | In [3]: time sum(range(n)) | |
1684 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1684 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1685 | Wall time: 1.37 |
|
1685 | Wall time: 1.37 | |
1686 | Out[3]: 499999500000L |
|
1686 | Out[3]: 499999500000L | |
1687 |
|
1687 | |||
1688 | In [4]: time print 'hello world' |
|
1688 | In [4]: time print 'hello world' | |
1689 | hello world |
|
1689 | hello world | |
1690 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1690 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1691 | Wall time: 0.00 |
|
1691 | Wall time: 0.00 | |
1692 | """ |
|
1692 | """ | |
1693 |
|
1693 | |||
1694 | # fail immediately if the given expression can't be compiled |
|
1694 | # fail immediately if the given expression can't be compiled | |
1695 | try: |
|
1695 | try: | |
1696 | mode = 'eval' |
|
1696 | mode = 'eval' | |
1697 | code = compile(parameter_s,'<timed eval>',mode) |
|
1697 | code = compile(parameter_s,'<timed eval>',mode) | |
1698 | except SyntaxError: |
|
1698 | except SyntaxError: | |
1699 | mode = 'exec' |
|
1699 | mode = 'exec' | |
1700 | code = compile(parameter_s,'<timed exec>',mode) |
|
1700 | code = compile(parameter_s,'<timed exec>',mode) | |
1701 | # skew measurement as little as possible |
|
1701 | # skew measurement as little as possible | |
1702 | glob = self.shell.user_ns |
|
1702 | glob = self.shell.user_ns | |
1703 | clk = clock2 |
|
1703 | clk = clock2 | |
1704 | wtime = time.time |
|
1704 | wtime = time.time | |
1705 | # time execution |
|
1705 | # time execution | |
1706 | wall_st = wtime() |
|
1706 | wall_st = wtime() | |
1707 | if mode=='eval': |
|
1707 | if mode=='eval': | |
1708 | st = clk() |
|
1708 | st = clk() | |
1709 | out = eval(code,glob) |
|
1709 | out = eval(code,glob) | |
1710 | end = clk() |
|
1710 | end = clk() | |
1711 | else: |
|
1711 | else: | |
1712 | st = clk() |
|
1712 | st = clk() | |
1713 | exec code in glob |
|
1713 | exec code in glob | |
1714 | end = clk() |
|
1714 | end = clk() | |
1715 | out = None |
|
1715 | out = None | |
1716 | wall_end = wtime() |
|
1716 | wall_end = wtime() | |
1717 | # Compute actual times and report |
|
1717 | # Compute actual times and report | |
1718 | wall_time = wall_end-wall_st |
|
1718 | wall_time = wall_end-wall_st | |
1719 | cpu_user = end[0]-st[0] |
|
1719 | cpu_user = end[0]-st[0] | |
1720 | cpu_sys = end[1]-st[1] |
|
1720 | cpu_sys = end[1]-st[1] | |
1721 | cpu_tot = cpu_user+cpu_sys |
|
1721 | cpu_tot = cpu_user+cpu_sys | |
1722 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1722 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1723 | (cpu_user,cpu_sys,cpu_tot) |
|
1723 | (cpu_user,cpu_sys,cpu_tot) | |
1724 | print "Wall time: %.2f" % wall_time |
|
1724 | print "Wall time: %.2f" % wall_time | |
1725 | return out |
|
1725 | return out | |
1726 |
|
1726 | |||
1727 | def magic_macro(self,parameter_s = ''): |
|
1727 | def magic_macro(self,parameter_s = ''): | |
1728 | """Define a set of input lines as a macro for future re-execution. |
|
1728 | """Define a set of input lines as a macro for future re-execution. | |
1729 |
|
1729 | |||
1730 | Usage:\\ |
|
1730 | Usage:\\ | |
1731 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1731 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1732 |
|
1732 | |||
1733 | Options: |
|
1733 | Options: | |
1734 |
|
1734 | |||
1735 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1735 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1736 | so that magics are loaded in their transformed version to valid |
|
1736 | so that magics are loaded in their transformed version to valid | |
1737 | Python. If this option is given, the raw input as typed as the |
|
1737 | Python. If this option is given, the raw input as typed as the | |
1738 | command line is used instead. |
|
1738 | command line is used instead. | |
1739 |
|
1739 | |||
1740 | This will define a global variable called `name` which is a string |
|
1740 | This will define a global variable called `name` which is a string | |
1741 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1741 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1742 | above) from your input history into a single string. This variable |
|
1742 | above) from your input history into a single string. This variable | |
1743 | acts like an automatic function which re-executes those lines as if |
|
1743 | acts like an automatic function which re-executes those lines as if | |
1744 | you had typed them. You just type 'name' at the prompt and the code |
|
1744 | you had typed them. You just type 'name' at the prompt and the code | |
1745 | executes. |
|
1745 | executes. | |
1746 |
|
1746 | |||
1747 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1747 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1748 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1748 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1749 | using the lines numbered 5,6 and 7. |
|
1749 | using the lines numbered 5,6 and 7. | |
1750 |
|
1750 | |||
1751 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1751 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1752 | notation, where N:M means numbers N through M-1. |
|
1752 | notation, where N:M means numbers N through M-1. | |
1753 |
|
1753 | |||
1754 | For example, if your history contains (%hist prints it): |
|
1754 | For example, if your history contains (%hist prints it): | |
1755 |
|
1755 | |||
1756 | 44: x=1\\ |
|
1756 | 44: x=1\\ | |
1757 | 45: y=3\\ |
|
1757 | 45: y=3\\ | |
1758 | 46: z=x+y\\ |
|
1758 | 46: z=x+y\\ | |
1759 | 47: print x\\ |
|
1759 | 47: print x\\ | |
1760 | 48: a=5\\ |
|
1760 | 48: a=5\\ | |
1761 | 49: print 'x',x,'y',y\\ |
|
1761 | 49: print 'x',x,'y',y\\ | |
1762 |
|
1762 | |||
1763 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1763 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1764 | called my_macro with: |
|
1764 | called my_macro with: | |
1765 |
|
1765 | |||
1766 | In [51]: %macro my_macro 44-47 49 |
|
1766 | In [51]: %macro my_macro 44-47 49 | |
1767 |
|
1767 | |||
1768 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1768 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1769 | in one pass. |
|
1769 | in one pass. | |
1770 |
|
1770 | |||
1771 | You don't need to give the line-numbers in order, and any given line |
|
1771 | You don't need to give the line-numbers in order, and any given line | |
1772 | number can appear multiple times. You can assemble macros with any |
|
1772 | number can appear multiple times. You can assemble macros with any | |
1773 | lines from your input history in any order. |
|
1773 | lines from your input history in any order. | |
1774 |
|
1774 | |||
1775 | The macro is a simple object which holds its value in an attribute, |
|
1775 | The macro is a simple object which holds its value in an attribute, | |
1776 | but IPython's display system checks for macros and executes them as |
|
1776 | but IPython's display system checks for macros and executes them as | |
1777 | code instead of printing them when you type their name. |
|
1777 | code instead of printing them when you type their name. | |
1778 |
|
1778 | |||
1779 | You can view a macro's contents by explicitly printing it with: |
|
1779 | You can view a macro's contents by explicitly printing it with: | |
1780 |
|
1780 | |||
1781 | 'print macro_name'. |
|
1781 | 'print macro_name'. | |
1782 |
|
1782 | |||
1783 | For one-off cases which DON'T contain magic function calls in them you |
|
1783 | For one-off cases which DON'T contain magic function calls in them you | |
1784 | can obtain similar results by explicitly executing slices from your |
|
1784 | can obtain similar results by explicitly executing slices from your | |
1785 | input history with: |
|
1785 | input history with: | |
1786 |
|
1786 | |||
1787 | In [60]: exec In[44:48]+In[49]""" |
|
1787 | In [60]: exec In[44:48]+In[49]""" | |
1788 |
|
1788 | |||
1789 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1789 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1790 | name,ranges = args[0], args[1:] |
|
1790 | name,ranges = args[0], args[1:] | |
1791 | #print 'rng',ranges # dbg |
|
1791 | #print 'rng',ranges # dbg | |
1792 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1792 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1793 | macro = Macro(lines) |
|
1793 | macro = Macro(lines) | |
1794 | self.shell.user_ns.update({name:macro}) |
|
1794 | self.shell.user_ns.update({name:macro}) | |
1795 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1795 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1796 | print 'Macro contents:' |
|
1796 | print 'Macro contents:' | |
1797 | print macro, |
|
1797 | print macro, | |
1798 |
|
1798 | |||
1799 | def magic_save(self,parameter_s = ''): |
|
1799 | def magic_save(self,parameter_s = ''): | |
1800 | """Save a set of lines to a given filename. |
|
1800 | """Save a set of lines to a given filename. | |
1801 |
|
1801 | |||
1802 | Usage:\\ |
|
1802 | Usage:\\ | |
1803 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1803 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1804 |
|
1804 | |||
1805 | Options: |
|
1805 | Options: | |
1806 |
|
1806 | |||
1807 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1807 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1808 | so that magics are loaded in their transformed version to valid |
|
1808 | so that magics are loaded in their transformed version to valid | |
1809 | Python. If this option is given, the raw input as typed as the |
|
1809 | Python. If this option is given, the raw input as typed as the | |
1810 | command line is used instead. |
|
1810 | command line is used instead. | |
1811 |
|
1811 | |||
1812 | This function uses the same syntax as %macro for line extraction, but |
|
1812 | This function uses the same syntax as %macro for line extraction, but | |
1813 | instead of creating a macro it saves the resulting string to the |
|
1813 | instead of creating a macro it saves the resulting string to the | |
1814 | filename you specify. |
|
1814 | filename you specify. | |
1815 |
|
1815 | |||
1816 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1816 | It adds a '.py' extension to the file if you don't do so yourself, and | |
1817 | it asks for confirmation before overwriting existing files.""" |
|
1817 | it asks for confirmation before overwriting existing files.""" | |
1818 |
|
1818 | |||
1819 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1819 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1820 | fname,ranges = args[0], args[1:] |
|
1820 | fname,ranges = args[0], args[1:] | |
1821 | if not fname.endswith('.py'): |
|
1821 | if not fname.endswith('.py'): | |
1822 | fname += '.py' |
|
1822 | fname += '.py' | |
1823 | if os.path.isfile(fname): |
|
1823 | if os.path.isfile(fname): | |
1824 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1824 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
1825 | if ans.lower() not in ['y','yes']: |
|
1825 | if ans.lower() not in ['y','yes']: | |
1826 | print 'Operation cancelled.' |
|
1826 | print 'Operation cancelled.' | |
1827 | return |
|
1827 | return | |
1828 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
1828 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
1829 | f = file(fname,'w') |
|
1829 | f = file(fname,'w') | |
1830 | f.write(cmds) |
|
1830 | f.write(cmds) | |
1831 | f.close() |
|
1831 | f.close() | |
1832 | print 'The following commands were written to file `%s`:' % fname |
|
1832 | print 'The following commands were written to file `%s`:' % fname | |
1833 | print cmds |
|
1833 | print cmds | |
1834 |
|
1834 | |||
1835 | def _edit_macro(self,mname,macro): |
|
1835 | def _edit_macro(self,mname,macro): | |
1836 | """open an editor with the macro data in a file""" |
|
1836 | """open an editor with the macro data in a file""" | |
1837 | filename = self.shell.mktempfile(macro.value) |
|
1837 | filename = self.shell.mktempfile(macro.value) | |
1838 | self.shell.hooks.editor(filename) |
|
1838 | self.shell.hooks.editor(filename) | |
1839 |
|
1839 | |||
1840 | # and make a new macro object, to replace the old one |
|
1840 | # and make a new macro object, to replace the old one | |
1841 | mfile = open(filename) |
|
1841 | mfile = open(filename) | |
1842 | mvalue = mfile.read() |
|
1842 | mvalue = mfile.read() | |
1843 | mfile.close() |
|
1843 | mfile.close() | |
1844 | self.shell.user_ns[mname] = Macro(mvalue) |
|
1844 | self.shell.user_ns[mname] = Macro(mvalue) | |
1845 |
|
1845 | |||
1846 | def magic_ed(self,parameter_s=''): |
|
1846 | def magic_ed(self,parameter_s=''): | |
1847 | """Alias to %edit.""" |
|
1847 | """Alias to %edit.""" | |
1848 | return self.magic_edit(parameter_s) |
|
1848 | return self.magic_edit(parameter_s) | |
1849 |
|
1849 | |||
1850 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
1850 | def magic_edit(self,parameter_s='',last_call=['','']): | |
1851 | """Bring up an editor and execute the resulting code. |
|
1851 | """Bring up an editor and execute the resulting code. | |
1852 |
|
1852 | |||
1853 | Usage: |
|
1853 | Usage: | |
1854 | %edit [options] [args] |
|
1854 | %edit [options] [args] | |
1855 |
|
1855 | |||
1856 | %edit runs IPython's editor hook. The default version of this hook is |
|
1856 | %edit runs IPython's editor hook. The default version of this hook is | |
1857 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1857 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
1858 | environment variable $EDITOR. If this isn't found, it will default to |
|
1858 | environment variable $EDITOR. If this isn't found, it will default to | |
1859 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1859 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
1860 | docstring for how to change the editor hook. |
|
1860 | docstring for how to change the editor hook. | |
1861 |
|
1861 | |||
1862 | You can also set the value of this editor via the command line option |
|
1862 | You can also set the value of this editor via the command line option | |
1863 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
1863 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
1864 | specifically for IPython an editor different from your typical default |
|
1864 | specifically for IPython an editor different from your typical default | |
1865 | (and for Windows users who typically don't set environment variables). |
|
1865 | (and for Windows users who typically don't set environment variables). | |
1866 |
|
1866 | |||
1867 | This command allows you to conveniently edit multi-line code right in |
|
1867 | This command allows you to conveniently edit multi-line code right in | |
1868 | your IPython session. |
|
1868 | your IPython session. | |
1869 |
|
1869 | |||
1870 | If called without arguments, %edit opens up an empty editor with a |
|
1870 | If called without arguments, %edit opens up an empty editor with a | |
1871 | temporary file and will execute the contents of this file when you |
|
1871 | temporary file and will execute the contents of this file when you | |
1872 | close it (don't forget to save it!). |
|
1872 | close it (don't forget to save it!). | |
1873 |
|
1873 | |||
1874 |
|
1874 | |||
1875 | Options: |
|
1875 | Options: | |
1876 |
|
1876 | |||
|
1877 | -n <number>: open the editor at a specified line number. By default, | |||
|
1878 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |||
|
1879 | you can configure this by providing your own modified hook if your | |||
|
1880 | favorite editor supports line-number specifications with a different | |||
|
1881 | syntax. | |||
|
1882 | ||||
1877 | -p: this will call the editor with the same data as the previous time |
|
1883 | -p: this will call the editor with the same data as the previous time | |
1878 | it was used, regardless of how long ago (in your current session) it |
|
1884 | it was used, regardless of how long ago (in your current session) it | |
1879 | was. |
|
1885 | was. | |
1880 |
|
1886 | |||
1881 | -r: use 'raw' input. This option only applies to input taken from the |
|
1887 | -r: use 'raw' input. This option only applies to input taken from the | |
1882 | user's history. By default, the 'processed' history is used, so that |
|
1888 | user's history. By default, the 'processed' history is used, so that | |
1883 | magics are loaded in their transformed version to valid Python. If |
|
1889 | magics are loaded in their transformed version to valid Python. If | |
1884 | this option is given, the raw input as typed as the command line is |
|
1890 | this option is given, the raw input as typed as the command line is | |
1885 | used instead. When you exit the editor, it will be executed by |
|
1891 | used instead. When you exit the editor, it will be executed by | |
1886 | IPython's own processor. |
|
1892 | IPython's own processor. | |
1887 |
|
1893 | |||
1888 | -x: do not execute the edited code immediately upon exit. This is |
|
1894 | -x: do not execute the edited code immediately upon exit. This is | |
1889 | mainly useful if you are editing programs which need to be called with |
|
1895 | mainly useful if you are editing programs which need to be called with | |
1890 | command line arguments, which you can then do using %run. |
|
1896 | command line arguments, which you can then do using %run. | |
1891 |
|
1897 | |||
1892 |
|
1898 | |||
1893 | Arguments: |
|
1899 | Arguments: | |
1894 |
|
1900 | |||
1895 | If arguments are given, the following possibilites exist: |
|
1901 | If arguments are given, the following possibilites exist: | |
1896 |
|
1902 | |||
1897 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
1903 | - The arguments are numbers or pairs of colon-separated numbers (like | |
1898 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
1904 | 1 4:8 9). These are interpreted as lines of previous input to be | |
1899 | loaded into the editor. The syntax is the same of the %macro command. |
|
1905 | loaded into the editor. The syntax is the same of the %macro command. | |
1900 |
|
1906 | |||
1901 | - If the argument doesn't start with a number, it is evaluated as a |
|
1907 | - If the argument doesn't start with a number, it is evaluated as a | |
1902 | variable and its contents loaded into the editor. You can thus edit |
|
1908 | variable and its contents loaded into the editor. You can thus edit | |
1903 | any string which contains python code (including the result of |
|
1909 | any string which contains python code (including the result of | |
1904 | previous edits). |
|
1910 | previous edits). | |
1905 |
|
1911 | |||
1906 | - If the argument is the name of an object (other than a string), |
|
1912 | - If the argument is the name of an object (other than a string), | |
1907 | IPython will try to locate the file where it was defined and open the |
|
1913 | IPython will try to locate the file where it was defined and open the | |
1908 | editor at the point where it is defined. You can use `%edit function` |
|
1914 | editor at the point where it is defined. You can use `%edit function` | |
1909 | to load an editor exactly at the point where 'function' is defined, |
|
1915 | to load an editor exactly at the point where 'function' is defined, | |
1910 | edit it and have the file be executed automatically. |
|
1916 | edit it and have the file be executed automatically. | |
1911 |
|
1917 | |||
1912 | If the object is a macro (see %macro for details), this opens up your |
|
1918 | If the object is a macro (see %macro for details), this opens up your | |
1913 | specified editor with a temporary file containing the macro's data. |
|
1919 | specified editor with a temporary file containing the macro's data. | |
1914 | Upon exit, the macro is reloaded with the contents of the file. |
|
1920 | Upon exit, the macro is reloaded with the contents of the file. | |
1915 |
|
1921 | |||
1916 | Note: opening at an exact line is only supported under Unix, and some |
|
1922 | Note: opening at an exact line is only supported under Unix, and some | |
1917 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
1923 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
1918 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
1924 | '+NUMBER' parameter necessary for this feature. Good editors like | |
1919 | (X)Emacs, vi, jed, pico and joe all do. |
|
1925 | (X)Emacs, vi, jed, pico and joe all do. | |
1920 |
|
1926 | |||
1921 | - If the argument is not found as a variable, IPython will look for a |
|
1927 | - If the argument is not found as a variable, IPython will look for a | |
1922 | file with that name (adding .py if necessary) and load it into the |
|
1928 | file with that name (adding .py if necessary) and load it into the | |
1923 | editor. It will execute its contents with execfile() when you exit, |
|
1929 | editor. It will execute its contents with execfile() when you exit, | |
1924 | loading any code in the file into your interactive namespace. |
|
1930 | loading any code in the file into your interactive namespace. | |
1925 |
|
1931 | |||
1926 | After executing your code, %edit will return as output the code you |
|
1932 | After executing your code, %edit will return as output the code you | |
1927 | typed in the editor (except when it was an existing file). This way |
|
1933 | typed in the editor (except when it was an existing file). This way | |
1928 | you can reload the code in further invocations of %edit as a variable, |
|
1934 | you can reload the code in further invocations of %edit as a variable, | |
1929 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
1935 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
1930 | the output. |
|
1936 | the output. | |
1931 |
|
1937 | |||
1932 | Note that %edit is also available through the alias %ed. |
|
1938 | Note that %edit is also available through the alias %ed. | |
1933 |
|
1939 | |||
1934 | This is an example of creating a simple function inside the editor and |
|
1940 | This is an example of creating a simple function inside the editor and | |
1935 | then modifying it. First, start up the editor: |
|
1941 | then modifying it. First, start up the editor: | |
1936 |
|
1942 | |||
1937 | In [1]: ed\\ |
|
1943 | In [1]: ed\\ | |
1938 | Editing... done. Executing edited code...\\ |
|
1944 | Editing... done. Executing edited code...\\ | |
1939 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
1945 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' | |
1940 |
|
1946 | |||
1941 | We can then call the function foo(): |
|
1947 | We can then call the function foo(): | |
1942 |
|
1948 | |||
1943 | In [2]: foo()\\ |
|
1949 | In [2]: foo()\\ | |
1944 | foo() was defined in an editing session |
|
1950 | foo() was defined in an editing session | |
1945 |
|
1951 | |||
1946 | Now we edit foo. IPython automatically loads the editor with the |
|
1952 | Now we edit foo. IPython automatically loads the editor with the | |
1947 | (temporary) file where foo() was previously defined: |
|
1953 | (temporary) file where foo() was previously defined: | |
1948 |
|
1954 | |||
1949 | In [3]: ed foo\\ |
|
1955 | In [3]: ed foo\\ | |
1950 | Editing... done. Executing edited code... |
|
1956 | Editing... done. Executing edited code... | |
1951 |
|
1957 | |||
1952 | And if we call foo() again we get the modified version: |
|
1958 | And if we call foo() again we get the modified version: | |
1953 |
|
1959 | |||
1954 | In [4]: foo()\\ |
|
1960 | In [4]: foo()\\ | |
1955 | foo() has now been changed! |
|
1961 | foo() has now been changed! | |
1956 |
|
1962 | |||
1957 | Here is an example of how to edit a code snippet successive |
|
1963 | Here is an example of how to edit a code snippet successive | |
1958 | times. First we call the editor: |
|
1964 | times. First we call the editor: | |
1959 |
|
1965 | |||
1960 | In [8]: ed\\ |
|
1966 | In [8]: ed\\ | |
1961 | Editing... done. Executing edited code...\\ |
|
1967 | Editing... done. Executing edited code...\\ | |
1962 | hello\\ |
|
1968 | hello\\ | |
1963 | Out[8]: "print 'hello'\\n" |
|
1969 | Out[8]: "print 'hello'\\n" | |
1964 |
|
1970 | |||
1965 | Now we call it again with the previous output (stored in _): |
|
1971 | Now we call it again with the previous output (stored in _): | |
1966 |
|
1972 | |||
1967 | In [9]: ed _\\ |
|
1973 | In [9]: ed _\\ | |
1968 | Editing... done. Executing edited code...\\ |
|
1974 | Editing... done. Executing edited code...\\ | |
1969 | hello world\\ |
|
1975 | hello world\\ | |
1970 | Out[9]: "print 'hello world'\\n" |
|
1976 | Out[9]: "print 'hello world'\\n" | |
1971 |
|
1977 | |||
1972 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
1978 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
1973 |
|
1979 | |||
1974 | In [10]: ed _8\\ |
|
1980 | In [10]: ed _8\\ | |
1975 | Editing... done. Executing edited code...\\ |
|
1981 | Editing... done. Executing edited code...\\ | |
1976 | hello again\\ |
|
1982 | hello again\\ | |
1977 | Out[10]: "print 'hello again'\\n" |
|
1983 | Out[10]: "print 'hello again'\\n" | |
1978 |
|
1984 | |||
1979 |
|
1985 | |||
1980 | Changing the default editor hook: |
|
1986 | Changing the default editor hook: | |
1981 |
|
1987 | |||
1982 | If you wish to write your own editor hook, you can put it in a |
|
1988 | If you wish to write your own editor hook, you can put it in a | |
1983 | configuration file which you load at startup time. The default hook |
|
1989 | configuration file which you load at startup time. The default hook | |
1984 | is defined in the IPython.hooks module, and you can use that as a |
|
1990 | is defined in the IPython.hooks module, and you can use that as a | |
1985 | starting example for further modifications. That file also has |
|
1991 | starting example for further modifications. That file also has | |
1986 | general instructions on how to set a new hook for use once you've |
|
1992 | general instructions on how to set a new hook for use once you've | |
1987 | defined it.""" |
|
1993 | defined it.""" | |
1988 |
|
1994 | |||
1989 | # FIXME: This function has become a convoluted mess. It needs a |
|
1995 | # FIXME: This function has become a convoluted mess. It needs a | |
1990 | # ground-up rewrite with clean, simple logic. |
|
1996 | # ground-up rewrite with clean, simple logic. | |
1991 |
|
1997 | |||
1992 | def make_filename(arg): |
|
1998 | def make_filename(arg): | |
1993 | "Make a filename from the given args" |
|
1999 | "Make a filename from the given args" | |
1994 | try: |
|
2000 | try: | |
1995 | filename = get_py_filename(arg) |
|
2001 | filename = get_py_filename(arg) | |
1996 | except IOError: |
|
2002 | except IOError: | |
1997 | if args.endswith('.py'): |
|
2003 | if args.endswith('.py'): | |
1998 | filename = arg |
|
2004 | filename = arg | |
1999 | else: |
|
2005 | else: | |
2000 | filename = None |
|
2006 | filename = None | |
2001 | return filename |
|
2007 | return filename | |
2002 |
|
2008 | |||
2003 | # custom exceptions |
|
2009 | # custom exceptions | |
2004 | class DataIsObject(Exception): pass |
|
2010 | class DataIsObject(Exception): pass | |
2005 |
|
2011 | |||
2006 |
opts,args = self.parse_options(parameter_s,'prxn |
|
2012 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2007 |
|
||||
2008 | print 'opt.n: <%r>' % opts.n # dbg |
|
|||
2009 |
|
||||
2010 | # Set a few locals from the options for convenience: |
|
2013 | # Set a few locals from the options for convenience: | |
2011 | opts_p = opts.has_key('p') |
|
2014 | opts_p = opts.has_key('p') | |
2012 | opts_r = opts.has_key('r') |
|
2015 | opts_r = opts.has_key('r') | |
2013 |
|
2016 | |||
2014 | # Default line number value |
|
2017 | # Default line number value | |
2015 | lineno = None |
|
2018 | lineno = opts.get('n',None) | |
|
2019 | ||||
2016 | if opts_p: |
|
2020 | if opts_p: | |
2017 | args = '_%s' % last_call[0] |
|
2021 | args = '_%s' % last_call[0] | |
2018 | if not self.shell.user_ns.has_key(args): |
|
2022 | if not self.shell.user_ns.has_key(args): | |
2019 | args = last_call[1] |
|
2023 | args = last_call[1] | |
2020 |
|
2024 | |||
2021 | # use last_call to remember the state of the previous call, but don't |
|
2025 | # use last_call to remember the state of the previous call, but don't | |
2022 | # let it be clobbered by successive '-p' calls. |
|
2026 | # let it be clobbered by successive '-p' calls. | |
2023 | try: |
|
2027 | try: | |
2024 | last_call[0] = self.shell.outputcache.prompt_count |
|
2028 | last_call[0] = self.shell.outputcache.prompt_count | |
2025 | if not opts_p: |
|
2029 | if not opts_p: | |
2026 | last_call[1] = parameter_s |
|
2030 | last_call[1] = parameter_s | |
2027 | except: |
|
2031 | except: | |
2028 | pass |
|
2032 | pass | |
2029 |
|
2033 | |||
2030 | # by default this is done with temp files, except when the given |
|
2034 | # by default this is done with temp files, except when the given | |
2031 | # arg is a filename |
|
2035 | # arg is a filename | |
2032 | use_temp = 1 |
|
2036 | use_temp = 1 | |
2033 |
|
2037 | |||
2034 | if re.match(r'\d',args): |
|
2038 | if re.match(r'\d',args): | |
2035 | # Mode where user specifies ranges of lines, like in %macro. |
|
2039 | # Mode where user specifies ranges of lines, like in %macro. | |
2036 | # This means that you can't edit files whose names begin with |
|
2040 | # This means that you can't edit files whose names begin with | |
2037 | # numbers this way. Tough. |
|
2041 | # numbers this way. Tough. | |
2038 | ranges = args.split() |
|
2042 | ranges = args.split() | |
2039 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2043 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2040 | elif args.endswith('.py'): |
|
2044 | elif args.endswith('.py'): | |
2041 | filename = make_filename(args) |
|
2045 | filename = make_filename(args) | |
2042 | data = '' |
|
2046 | data = '' | |
2043 | use_temp = 0 |
|
2047 | use_temp = 0 | |
2044 | elif args: |
|
2048 | elif args: | |
2045 | try: |
|
2049 | try: | |
2046 | # Load the parameter given as a variable. If not a string, |
|
2050 | # Load the parameter given as a variable. If not a string, | |
2047 | # process it as an object instead (below) |
|
2051 | # process it as an object instead (below) | |
2048 |
|
2052 | |||
2049 | #print '*** args',args,'type',type(args) # dbg |
|
2053 | #print '*** args',args,'type',type(args) # dbg | |
2050 | data = eval(args,self.shell.user_ns) |
|
2054 | data = eval(args,self.shell.user_ns) | |
2051 | if not type(data) in StringTypes: |
|
2055 | if not type(data) in StringTypes: | |
2052 | raise DataIsObject |
|
2056 | raise DataIsObject | |
2053 |
|
2057 | |||
2054 | except (NameError,SyntaxError): |
|
2058 | except (NameError,SyntaxError): | |
2055 | # given argument is not a variable, try as a filename |
|
2059 | # given argument is not a variable, try as a filename | |
2056 | filename = make_filename(args) |
|
2060 | filename = make_filename(args) | |
2057 | if filename is None: |
|
2061 | if filename is None: | |
2058 | warn("Argument given (%s) can't be found as a variable " |
|
2062 | warn("Argument given (%s) can't be found as a variable " | |
2059 | "or as a filename." % args) |
|
2063 | "or as a filename." % args) | |
2060 | return |
|
2064 | return | |
2061 |
|
2065 | |||
2062 | data = '' |
|
2066 | data = '' | |
2063 | use_temp = 0 |
|
2067 | use_temp = 0 | |
2064 | except DataIsObject: |
|
2068 | except DataIsObject: | |
2065 |
|
2069 | |||
2066 | # macros have a special edit function |
|
2070 | # macros have a special edit function | |
2067 | if isinstance(data,Macro): |
|
2071 | if isinstance(data,Macro): | |
2068 | self._edit_macro(args,data) |
|
2072 | self._edit_macro(args,data) | |
2069 | return |
|
2073 | return | |
2070 |
|
2074 | |||
2071 | # For objects, try to edit the file where they are defined |
|
2075 | # For objects, try to edit the file where they are defined | |
2072 | try: |
|
2076 | try: | |
2073 | filename = inspect.getabsfile(data) |
|
2077 | filename = inspect.getabsfile(data) | |
2074 | datafile = 1 |
|
2078 | datafile = 1 | |
2075 | except TypeError: |
|
2079 | except TypeError: | |
2076 | filename = make_filename(args) |
|
2080 | filename = make_filename(args) | |
2077 | datafile = 1 |
|
2081 | datafile = 1 | |
2078 | warn('Could not find file where `%s` is defined.\n' |
|
2082 | warn('Could not find file where `%s` is defined.\n' | |
2079 | 'Opening a file named `%s`' % (args,filename)) |
|
2083 | 'Opening a file named `%s`' % (args,filename)) | |
2080 | # Now, make sure we can actually read the source (if it was in |
|
2084 | # Now, make sure we can actually read the source (if it was in | |
2081 | # a temp file it's gone by now). |
|
2085 | # a temp file it's gone by now). | |
2082 | if datafile: |
|
2086 | if datafile: | |
2083 | try: |
|
2087 | try: | |
|
2088 | if lineno is None: | |||
2084 | lineno = inspect.getsourcelines(data)[1] |
|
2089 | lineno = inspect.getsourcelines(data)[1] | |
2085 | except IOError: |
|
2090 | except IOError: | |
2086 | filename = make_filename(args) |
|
2091 | filename = make_filename(args) | |
2087 | if filename is None: |
|
2092 | if filename is None: | |
2088 | warn('The file `%s` where `%s` was defined cannot ' |
|
2093 | warn('The file `%s` where `%s` was defined cannot ' | |
2089 | 'be read.' % (filename,data)) |
|
2094 | 'be read.' % (filename,data)) | |
2090 | return |
|
2095 | return | |
2091 | use_temp = 0 |
|
2096 | use_temp = 0 | |
2092 | else: |
|
2097 | else: | |
2093 | data = '' |
|
2098 | data = '' | |
2094 |
|
2099 | |||
2095 | if use_temp: |
|
2100 | if use_temp: | |
2096 | filename = self.shell.mktempfile(data) |
|
2101 | filename = self.shell.mktempfile(data) | |
2097 | print 'IPython will make a temporary file named:',filename |
|
2102 | print 'IPython will make a temporary file named:',filename | |
2098 |
|
2103 | |||
2099 | # do actual editing here |
|
2104 | # do actual editing here | |
2100 | print 'Editing...', |
|
2105 | print 'Editing...', | |
2101 | sys.stdout.flush() |
|
2106 | sys.stdout.flush() | |
2102 | self.shell.hooks.editor(filename,lineno) |
|
2107 | self.shell.hooks.editor(filename,lineno) | |
2103 | if opts.has_key('x'): # -x prevents actual execution |
|
2108 | if opts.has_key('x'): # -x prevents actual execution | |
2104 |
|
2109 | |||
2105 | else: |
|
2110 | else: | |
2106 | print 'done. Executing edited code...' |
|
2111 | print 'done. Executing edited code...' | |
2107 | if opts_r: |
|
2112 | if opts_r: | |
2108 | self.shell.runlines(file_read(filename)) |
|
2113 | self.shell.runlines(file_read(filename)) | |
2109 | else: |
|
2114 | else: | |
2110 | self.shell.safe_execfile(filename,self.shell.user_ns) |
|
2115 | self.shell.safe_execfile(filename,self.shell.user_ns) | |
2111 | if use_temp: |
|
2116 | if use_temp: | |
2112 | try: |
|
2117 | try: | |
2113 | return open(filename).read() |
|
2118 | return open(filename).read() | |
2114 | except IOError,msg: |
|
2119 | except IOError,msg: | |
2115 | if msg.filename == filename: |
|
2120 | if msg.filename == filename: | |
2116 | warn('File not found. Did you forget to save?') |
|
2121 | warn('File not found. Did you forget to save?') | |
2117 | return |
|
2122 | return | |
2118 | else: |
|
2123 | else: | |
2119 | self.shell.showtraceback() |
|
2124 | self.shell.showtraceback() | |
2120 |
|
2125 | |||
2121 | def magic_xmode(self,parameter_s = ''): |
|
2126 | def magic_xmode(self,parameter_s = ''): | |
2122 | """Switch modes for the exception handlers. |
|
2127 | """Switch modes for the exception handlers. | |
2123 |
|
2128 | |||
2124 | Valid modes: Plain, Context and Verbose. |
|
2129 | Valid modes: Plain, Context and Verbose. | |
2125 |
|
2130 | |||
2126 | If called without arguments, acts as a toggle.""" |
|
2131 | If called without arguments, acts as a toggle.""" | |
2127 |
|
2132 | |||
2128 | def xmode_switch_err(name): |
|
2133 | def xmode_switch_err(name): | |
2129 | warn('Error changing %s exception modes.\n%s' % |
|
2134 | warn('Error changing %s exception modes.\n%s' % | |
2130 | (name,sys.exc_info()[1])) |
|
2135 | (name,sys.exc_info()[1])) | |
2131 |
|
2136 | |||
2132 | shell = self.shell |
|
2137 | shell = self.shell | |
2133 | new_mode = parameter_s.strip().capitalize() |
|
2138 | new_mode = parameter_s.strip().capitalize() | |
2134 | try: |
|
2139 | try: | |
2135 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2140 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2136 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2141 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2137 | except: |
|
2142 | except: | |
2138 | xmode_switch_err('user') |
|
2143 | xmode_switch_err('user') | |
2139 |
|
2144 | |||
2140 | # threaded shells use a special handler in sys.excepthook |
|
2145 | # threaded shells use a special handler in sys.excepthook | |
2141 | if shell.isthreaded: |
|
2146 | if shell.isthreaded: | |
2142 | try: |
|
2147 | try: | |
2143 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2148 | shell.sys_excepthook.set_mode(mode=new_mode) | |
2144 | except: |
|
2149 | except: | |
2145 | xmode_switch_err('threaded') |
|
2150 | xmode_switch_err('threaded') | |
2146 |
|
2151 | |||
2147 | def magic_colors(self,parameter_s = ''): |
|
2152 | def magic_colors(self,parameter_s = ''): | |
2148 | """Switch color scheme for prompts, info system and exception handlers. |
|
2153 | """Switch color scheme for prompts, info system and exception handlers. | |
2149 |
|
2154 | |||
2150 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2155 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2151 |
|
2156 | |||
2152 | Color scheme names are not case-sensitive.""" |
|
2157 | Color scheme names are not case-sensitive.""" | |
2153 |
|
2158 | |||
2154 | def color_switch_err(name): |
|
2159 | def color_switch_err(name): | |
2155 | warn('Error changing %s color schemes.\n%s' % |
|
2160 | warn('Error changing %s color schemes.\n%s' % | |
2156 | (name,sys.exc_info()[1])) |
|
2161 | (name,sys.exc_info()[1])) | |
2157 |
|
2162 | |||
2158 |
|
2163 | |||
2159 | new_scheme = parameter_s.strip() |
|
2164 | new_scheme = parameter_s.strip() | |
2160 | if not new_scheme: |
|
2165 | if not new_scheme: | |
2161 | print 'You must specify a color scheme.' |
|
2166 | print 'You must specify a color scheme.' | |
2162 | return |
|
2167 | return | |
2163 | import IPython.rlineimpl as readline |
|
2168 | import IPython.rlineimpl as readline | |
2164 | if not readline.have_readline: |
|
2169 | if not readline.have_readline: | |
2165 | msg = """\ |
|
2170 | msg = """\ | |
2166 | Proper color support under MS Windows requires Gary Bishop's readline library. |
|
2171 | Proper color support under MS Windows requires Gary Bishop's readline library. | |
2167 | You can find it at: |
|
2172 | You can find it at: | |
2168 | http://sourceforge.net/projects/uncpythontools |
|
2173 | http://sourceforge.net/projects/uncpythontools | |
2169 | Gary's readline needs the ctypes module, from: |
|
2174 | Gary's readline needs the ctypes module, from: | |
2170 | http://starship.python.net/crew/theller/ctypes |
|
2175 | http://starship.python.net/crew/theller/ctypes | |
2171 |
|
2176 | |||
2172 | Defaulting color scheme to 'NoColor'""" |
|
2177 | Defaulting color scheme to 'NoColor'""" | |
2173 | new_scheme = 'NoColor' |
|
2178 | new_scheme = 'NoColor' | |
2174 | warn(msg) |
|
2179 | warn(msg) | |
2175 | # local shortcut |
|
2180 | # local shortcut | |
2176 | shell = self.shell |
|
2181 | shell = self.shell | |
2177 |
|
2182 | |||
2178 | # Set prompt colors |
|
2183 | # Set prompt colors | |
2179 | try: |
|
2184 | try: | |
2180 | shell.outputcache.set_colors(new_scheme) |
|
2185 | shell.outputcache.set_colors(new_scheme) | |
2181 | except: |
|
2186 | except: | |
2182 | color_switch_err('prompt') |
|
2187 | color_switch_err('prompt') | |
2183 | else: |
|
2188 | else: | |
2184 | shell.rc.colors = \ |
|
2189 | shell.rc.colors = \ | |
2185 | shell.outputcache.color_table.active_scheme_name |
|
2190 | shell.outputcache.color_table.active_scheme_name | |
2186 | # Set exception colors |
|
2191 | # Set exception colors | |
2187 | try: |
|
2192 | try: | |
2188 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2193 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2189 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2194 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2190 | except: |
|
2195 | except: | |
2191 | color_switch_err('exception') |
|
2196 | color_switch_err('exception') | |
2192 |
|
2197 | |||
2193 | # threaded shells use a verbose traceback in sys.excepthook |
|
2198 | # threaded shells use a verbose traceback in sys.excepthook | |
2194 | if shell.isthreaded: |
|
2199 | if shell.isthreaded: | |
2195 | try: |
|
2200 | try: | |
2196 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2201 | shell.sys_excepthook.set_colors(scheme=new_scheme) | |
2197 | except: |
|
2202 | except: | |
2198 | color_switch_err('system exception handler') |
|
2203 | color_switch_err('system exception handler') | |
2199 |
|
2204 | |||
2200 | # Set info (for 'object?') colors |
|
2205 | # Set info (for 'object?') colors | |
2201 | if shell.rc.color_info: |
|
2206 | if shell.rc.color_info: | |
2202 | try: |
|
2207 | try: | |
2203 | shell.inspector.set_active_scheme(new_scheme) |
|
2208 | shell.inspector.set_active_scheme(new_scheme) | |
2204 | except: |
|
2209 | except: | |
2205 | color_switch_err('object inspector') |
|
2210 | color_switch_err('object inspector') | |
2206 | else: |
|
2211 | else: | |
2207 | shell.inspector.set_active_scheme('NoColor') |
|
2212 | shell.inspector.set_active_scheme('NoColor') | |
2208 |
|
2213 | |||
2209 | def magic_color_info(self,parameter_s = ''): |
|
2214 | def magic_color_info(self,parameter_s = ''): | |
2210 | """Toggle color_info. |
|
2215 | """Toggle color_info. | |
2211 |
|
2216 | |||
2212 | The color_info configuration parameter controls whether colors are |
|
2217 | The color_info configuration parameter controls whether colors are | |
2213 | used for displaying object details (by things like %psource, %pfile or |
|
2218 | used for displaying object details (by things like %psource, %pfile or | |
2214 | the '?' system). This function toggles this value with each call. |
|
2219 | the '?' system). This function toggles this value with each call. | |
2215 |
|
2220 | |||
2216 | Note that unless you have a fairly recent pager (less works better |
|
2221 | Note that unless you have a fairly recent pager (less works better | |
2217 | than more) in your system, using colored object information displays |
|
2222 | than more) in your system, using colored object information displays | |
2218 | will not work properly. Test it and see.""" |
|
2223 | will not work properly. Test it and see.""" | |
2219 |
|
2224 | |||
2220 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2225 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
2221 | self.magic_colors(self.shell.rc.colors) |
|
2226 | self.magic_colors(self.shell.rc.colors) | |
2222 | print 'Object introspection functions have now coloring:', |
|
2227 | print 'Object introspection functions have now coloring:', | |
2223 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2228 | print ['OFF','ON'][self.shell.rc.color_info] | |
2224 |
|
2229 | |||
2225 | def magic_Pprint(self, parameter_s=''): |
|
2230 | def magic_Pprint(self, parameter_s=''): | |
2226 | """Toggle pretty printing on/off.""" |
|
2231 | """Toggle pretty printing on/off.""" | |
2227 |
|
2232 | |||
2228 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2233 | self.shell.rc.pprint = 1 - self.shell.rc.pprint | |
2229 | print 'Pretty printing has been turned', \ |
|
2234 | print 'Pretty printing has been turned', \ | |
2230 | ['OFF','ON'][self.shell.rc.pprint] |
|
2235 | ['OFF','ON'][self.shell.rc.pprint] | |
2231 |
|
2236 | |||
2232 | def magic_exit(self, parameter_s=''): |
|
2237 | def magic_exit(self, parameter_s=''): | |
2233 | """Exit IPython, confirming if configured to do so. |
|
2238 | """Exit IPython, confirming if configured to do so. | |
2234 |
|
2239 | |||
2235 | You can configure whether IPython asks for confirmation upon exit by |
|
2240 | You can configure whether IPython asks for confirmation upon exit by | |
2236 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2241 | setting the confirm_exit flag in the ipythonrc file.""" | |
2237 |
|
2242 | |||
2238 | self.shell.exit() |
|
2243 | self.shell.exit() | |
2239 |
|
2244 | |||
2240 | def magic_quit(self, parameter_s=''): |
|
2245 | def magic_quit(self, parameter_s=''): | |
2241 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2246 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
2242 |
|
2247 | |||
2243 | self.shell.exit() |
|
2248 | self.shell.exit() | |
2244 |
|
2249 | |||
2245 | def magic_Exit(self, parameter_s=''): |
|
2250 | def magic_Exit(self, parameter_s=''): | |
2246 | """Exit IPython without confirmation.""" |
|
2251 | """Exit IPython without confirmation.""" | |
2247 |
|
2252 | |||
2248 | self.shell.exit_now = True |
|
2253 | self.shell.exit_now = True | |
2249 |
|
2254 | |||
2250 | def magic_Quit(self, parameter_s=''): |
|
2255 | def magic_Quit(self, parameter_s=''): | |
2251 | """Exit IPython without confirmation (like %Exit).""" |
|
2256 | """Exit IPython without confirmation (like %Exit).""" | |
2252 |
|
2257 | |||
2253 | self.shell.exit_now = True |
|
2258 | self.shell.exit_now = True | |
2254 |
|
2259 | |||
2255 | #...................................................................... |
|
2260 | #...................................................................... | |
2256 | # Functions to implement unix shell-type things |
|
2261 | # Functions to implement unix shell-type things | |
2257 |
|
2262 | |||
2258 | def magic_alias(self, parameter_s = ''): |
|
2263 | def magic_alias(self, parameter_s = ''): | |
2259 | """Define an alias for a system command. |
|
2264 | """Define an alias for a system command. | |
2260 |
|
2265 | |||
2261 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2266 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2262 |
|
2267 | |||
2263 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2268 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2264 | params' (from your underlying operating system). |
|
2269 | params' (from your underlying operating system). | |
2265 |
|
2270 | |||
2266 | Aliases have lower precedence than magic functions and Python normal |
|
2271 | Aliases have lower precedence than magic functions and Python normal | |
2267 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2272 | variables, so if 'foo' is both a Python variable and an alias, the | |
2268 | alias can not be executed until 'del foo' removes the Python variable. |
|
2273 | alias can not be executed until 'del foo' removes the Python variable. | |
2269 |
|
2274 | |||
2270 | You can use the %l specifier in an alias definition to represent the |
|
2275 | You can use the %l specifier in an alias definition to represent the | |
2271 | whole line when the alias is called. For example: |
|
2276 | whole line when the alias is called. For example: | |
2272 |
|
2277 | |||
2273 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
2278 | In [2]: alias all echo "Input in brackets: <%l>"\\ | |
2274 | In [3]: all hello world\\ |
|
2279 | In [3]: all hello world\\ | |
2275 | Input in brackets: <hello world> |
|
2280 | Input in brackets: <hello world> | |
2276 |
|
2281 | |||
2277 | You can also define aliases with parameters using %s specifiers (one |
|
2282 | You can also define aliases with parameters using %s specifiers (one | |
2278 | per parameter): |
|
2283 | per parameter): | |
2279 |
|
2284 | |||
2280 | In [1]: alias parts echo first %s second %s\\ |
|
2285 | In [1]: alias parts echo first %s second %s\\ | |
2281 | In [2]: %parts A B\\ |
|
2286 | In [2]: %parts A B\\ | |
2282 | first A second B\\ |
|
2287 | first A second B\\ | |
2283 | In [3]: %parts A\\ |
|
2288 | In [3]: %parts A\\ | |
2284 | Incorrect number of arguments: 2 expected.\\ |
|
2289 | Incorrect number of arguments: 2 expected.\\ | |
2285 | parts is an alias to: 'echo first %s second %s' |
|
2290 | parts is an alias to: 'echo first %s second %s' | |
2286 |
|
2291 | |||
2287 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2292 | Note that %l and %s are mutually exclusive. You can only use one or | |
2288 | the other in your aliases. |
|
2293 | the other in your aliases. | |
2289 |
|
2294 | |||
2290 | Aliases expand Python variables just like system calls using ! or !! |
|
2295 | Aliases expand Python variables just like system calls using ! or !! | |
2291 | do: all expressions prefixed with '$' get expanded. For details of |
|
2296 | do: all expressions prefixed with '$' get expanded. For details of | |
2292 | the semantic rules, see PEP-215: |
|
2297 | the semantic rules, see PEP-215: | |
2293 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2298 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2294 | IPython for variable expansion. If you want to access a true shell |
|
2299 | IPython for variable expansion. If you want to access a true shell | |
2295 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2300 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2296 |
|
2301 | |||
2297 | In [6]: alias show echo\\ |
|
2302 | In [6]: alias show echo\\ | |
2298 | In [7]: PATH='A Python string'\\ |
|
2303 | In [7]: PATH='A Python string'\\ | |
2299 | In [8]: show $PATH\\ |
|
2304 | In [8]: show $PATH\\ | |
2300 | A Python string\\ |
|
2305 | A Python string\\ | |
2301 | In [9]: show $$PATH\\ |
|
2306 | In [9]: show $$PATH\\ | |
2302 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2307 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2303 |
|
2308 | |||
2304 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2309 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2305 | and %rehashx functions, which automatically create aliases for the |
|
2310 | and %rehashx functions, which automatically create aliases for the | |
2306 | contents of your $PATH. |
|
2311 | contents of your $PATH. | |
2307 |
|
2312 | |||
2308 | If called with no parameters, %alias prints the current alias table.""" |
|
2313 | If called with no parameters, %alias prints the current alias table.""" | |
2309 |
|
2314 | |||
2310 | par = parameter_s.strip() |
|
2315 | par = parameter_s.strip() | |
2311 | if not par: |
|
2316 | if not par: | |
2312 | if self.shell.rc.automagic: |
|
2317 | if self.shell.rc.automagic: | |
2313 | prechar = '' |
|
2318 | prechar = '' | |
2314 | else: |
|
2319 | else: | |
2315 | prechar = self.shell.ESC_MAGIC |
|
2320 | prechar = self.shell.ESC_MAGIC | |
2316 | #print 'Alias\t\tSystem Command\n'+'-'*30 |
|
2321 | #print 'Alias\t\tSystem Command\n'+'-'*30 | |
2317 | atab = self.shell.alias_table |
|
2322 | atab = self.shell.alias_table | |
2318 | aliases = atab.keys() |
|
2323 | aliases = atab.keys() | |
2319 | aliases.sort() |
|
2324 | aliases.sort() | |
2320 | res = [] |
|
2325 | res = [] | |
2321 | for alias in aliases: |
|
2326 | for alias in aliases: | |
2322 | res.append((alias, atab[alias][1])) |
|
2327 | res.append((alias, atab[alias][1])) | |
2323 | print "Total number of aliases:",len(aliases) |
|
2328 | print "Total number of aliases:",len(aliases) | |
2324 | return res |
|
2329 | return res | |
2325 | try: |
|
2330 | try: | |
2326 | alias,cmd = par.split(None,1) |
|
2331 | alias,cmd = par.split(None,1) | |
2327 | except: |
|
2332 | except: | |
2328 | print OInspect.getdoc(self.magic_alias) |
|
2333 | print OInspect.getdoc(self.magic_alias) | |
2329 | else: |
|
2334 | else: | |
2330 | nargs = cmd.count('%s') |
|
2335 | nargs = cmd.count('%s') | |
2331 | if nargs>0 and cmd.find('%l')>=0: |
|
2336 | if nargs>0 and cmd.find('%l')>=0: | |
2332 | error('The %s and %l specifiers are mutually exclusive ' |
|
2337 | error('The %s and %l specifiers are mutually exclusive ' | |
2333 | 'in alias definitions.') |
|
2338 | 'in alias definitions.') | |
2334 | else: # all looks OK |
|
2339 | else: # all looks OK | |
2335 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2340 | self.shell.alias_table[alias] = (nargs,cmd) | |
2336 | self.shell.alias_table_validate(verbose=0) |
|
2341 | self.shell.alias_table_validate(verbose=0) | |
2337 | # end magic_alias |
|
2342 | # end magic_alias | |
2338 |
|
2343 | |||
2339 | def magic_unalias(self, parameter_s = ''): |
|
2344 | def magic_unalias(self, parameter_s = ''): | |
2340 | """Remove an alias""" |
|
2345 | """Remove an alias""" | |
2341 |
|
2346 | |||
2342 | aname = parameter_s.strip() |
|
2347 | aname = parameter_s.strip() | |
2343 | if aname in self.shell.alias_table: |
|
2348 | if aname in self.shell.alias_table: | |
2344 | del self.shell.alias_table[aname] |
|
2349 | del self.shell.alias_table[aname] | |
2345 |
|
2350 | |||
2346 | def magic_rehash(self, parameter_s = ''): |
|
2351 | def magic_rehash(self, parameter_s = ''): | |
2347 | """Update the alias table with all entries in $PATH. |
|
2352 | """Update the alias table with all entries in $PATH. | |
2348 |
|
2353 | |||
2349 | This version does no checks on execute permissions or whether the |
|
2354 | This version does no checks on execute permissions or whether the | |
2350 | contents of $PATH are truly files (instead of directories or something |
|
2355 | contents of $PATH are truly files (instead of directories or something | |
2351 | else). For such a safer (but slower) version, use %rehashx.""" |
|
2356 | else). For such a safer (but slower) version, use %rehashx.""" | |
2352 |
|
2357 | |||
2353 | # This function (and rehashx) manipulate the alias_table directly |
|
2358 | # This function (and rehashx) manipulate the alias_table directly | |
2354 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
2359 | # rather than calling magic_alias, for speed reasons. A rehash on a | |
2355 | # typical Linux box involves several thousand entries, so efficiency |
|
2360 | # typical Linux box involves several thousand entries, so efficiency | |
2356 | # here is a top concern. |
|
2361 | # here is a top concern. | |
2357 |
|
2362 | |||
2358 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
2363 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) | |
2359 | alias_table = self.shell.alias_table |
|
2364 | alias_table = self.shell.alias_table | |
2360 | for pdir in path: |
|
2365 | for pdir in path: | |
2361 | for ff in os.listdir(pdir): |
|
2366 | for ff in os.listdir(pdir): | |
2362 | # each entry in the alias table must be (N,name), where |
|
2367 | # each entry in the alias table must be (N,name), where | |
2363 | # N is the number of positional arguments of the alias. |
|
2368 | # N is the number of positional arguments of the alias. | |
2364 | alias_table[ff] = (0,ff) |
|
2369 | alias_table[ff] = (0,ff) | |
2365 | # Make sure the alias table doesn't contain keywords or builtins |
|
2370 | # Make sure the alias table doesn't contain keywords or builtins | |
2366 | self.shell.alias_table_validate() |
|
2371 | self.shell.alias_table_validate() | |
2367 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
2372 | # Call again init_auto_alias() so we get 'rm -i' and other modified | |
2368 | # aliases since %rehash will probably clobber them |
|
2373 | # aliases since %rehash will probably clobber them | |
2369 | self.shell.init_auto_alias() |
|
2374 | self.shell.init_auto_alias() | |
2370 |
|
2375 | |||
2371 | def magic_rehashx(self, parameter_s = ''): |
|
2376 | def magic_rehashx(self, parameter_s = ''): | |
2372 | """Update the alias table with all executable files in $PATH. |
|
2377 | """Update the alias table with all executable files in $PATH. | |
2373 |
|
2378 | |||
2374 | This version explicitly checks that every entry in $PATH is a file |
|
2379 | This version explicitly checks that every entry in $PATH is a file | |
2375 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2380 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2376 |
|
2381 | |||
2377 | Under Windows, it checks executability as a match agains a |
|
2382 | Under Windows, it checks executability as a match agains a | |
2378 | '|'-separated string of extensions, stored in the IPython config |
|
2383 | '|'-separated string of extensions, stored in the IPython config | |
2379 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ |
|
2384 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ | |
2380 |
|
2385 | |||
2381 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2386 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2382 | os.environ['PATH'].split(os.pathsep)] |
|
2387 | os.environ['PATH'].split(os.pathsep)] | |
2383 | path = filter(os.path.isdir,path) |
|
2388 | path = filter(os.path.isdir,path) | |
2384 |
|
2389 | |||
2385 | alias_table = self.shell.alias_table |
|
2390 | alias_table = self.shell.alias_table | |
2386 | syscmdlist = [] |
|
2391 | syscmdlist = [] | |
2387 | if os.name == 'posix': |
|
2392 | if os.name == 'posix': | |
2388 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2393 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2389 | os.access(fname,os.X_OK) |
|
2394 | os.access(fname,os.X_OK) | |
2390 | else: |
|
2395 | else: | |
2391 |
|
2396 | |||
2392 | try: |
|
2397 | try: | |
2393 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2398 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2394 | except KeyError: |
|
2399 | except KeyError: | |
2395 | winext = 'exe|com|bat' |
|
2400 | winext = 'exe|com|bat' | |
2396 |
|
2401 | |||
2397 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2402 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2398 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2403 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2399 | savedir = os.getcwd() |
|
2404 | savedir = os.getcwd() | |
2400 | try: |
|
2405 | try: | |
2401 | # write the whole loop for posix/Windows so we don't have an if in |
|
2406 | # write the whole loop for posix/Windows so we don't have an if in | |
2402 | # the innermost part |
|
2407 | # the innermost part | |
2403 | if os.name == 'posix': |
|
2408 | if os.name == 'posix': | |
2404 | for pdir in path: |
|
2409 | for pdir in path: | |
2405 | os.chdir(pdir) |
|
2410 | os.chdir(pdir) | |
2406 | for ff in os.listdir(pdir): |
|
2411 | for ff in os.listdir(pdir): | |
2407 | if isexec(ff): |
|
2412 | if isexec(ff): | |
2408 | # each entry in the alias table must be (N,name), |
|
2413 | # each entry in the alias table must be (N,name), | |
2409 | # where N is the number of positional arguments of the |
|
2414 | # where N is the number of positional arguments of the | |
2410 | # alias. |
|
2415 | # alias. | |
2411 | alias_table[ff] = (0,ff) |
|
2416 | alias_table[ff] = (0,ff) | |
2412 | syscmdlist.append(ff) |
|
2417 | syscmdlist.append(ff) | |
2413 | else: |
|
2418 | else: | |
2414 | for pdir in path: |
|
2419 | for pdir in path: | |
2415 | os.chdir(pdir) |
|
2420 | os.chdir(pdir) | |
2416 | for ff in os.listdir(pdir): |
|
2421 | for ff in os.listdir(pdir): | |
2417 | if isexec(ff): |
|
2422 | if isexec(ff): | |
2418 | alias_table[execre.sub(r'\1',ff)] = (0,ff) |
|
2423 | alias_table[execre.sub(r'\1',ff)] = (0,ff) | |
2419 | syscmdlist.append(ff) |
|
2424 | syscmdlist.append(ff) | |
2420 | # Make sure the alias table doesn't contain keywords or builtins |
|
2425 | # Make sure the alias table doesn't contain keywords or builtins | |
2421 | self.shell.alias_table_validate() |
|
2426 | self.shell.alias_table_validate() | |
2422 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2427 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2423 | # modified aliases since %rehashx will probably clobber them |
|
2428 | # modified aliases since %rehashx will probably clobber them | |
2424 | self.shell.init_auto_alias() |
|
2429 | self.shell.init_auto_alias() | |
2425 | db = self.getapi().db |
|
2430 | db = self.getapi().db | |
2426 | db['syscmdlist'] = syscmdlist |
|
2431 | db['syscmdlist'] = syscmdlist | |
2427 | finally: |
|
2432 | finally: | |
2428 | os.chdir(savedir) |
|
2433 | os.chdir(savedir) | |
2429 |
|
2434 | |||
2430 | def magic_pwd(self, parameter_s = ''): |
|
2435 | def magic_pwd(self, parameter_s = ''): | |
2431 | """Return the current working directory path.""" |
|
2436 | """Return the current working directory path.""" | |
2432 | return os.getcwd() |
|
2437 | return os.getcwd() | |
2433 |
|
2438 | |||
2434 | def magic_cd(self, parameter_s=''): |
|
2439 | def magic_cd(self, parameter_s=''): | |
2435 | """Change the current working directory. |
|
2440 | """Change the current working directory. | |
2436 |
|
2441 | |||
2437 | This command automatically maintains an internal list of directories |
|
2442 | This command automatically maintains an internal list of directories | |
2438 | you visit during your IPython session, in the variable _dh. The |
|
2443 | you visit during your IPython session, in the variable _dh. The | |
2439 | command %dhist shows this history nicely formatted. |
|
2444 | command %dhist shows this history nicely formatted. | |
2440 |
|
2445 | |||
2441 | Usage: |
|
2446 | Usage: | |
2442 |
|
2447 | |||
2443 | cd 'dir': changes to directory 'dir'. |
|
2448 | cd 'dir': changes to directory 'dir'. | |
2444 |
|
2449 | |||
2445 | cd -: changes to the last visited directory. |
|
2450 | cd -: changes to the last visited directory. | |
2446 |
|
2451 | |||
2447 | cd -<n>: changes to the n-th directory in the directory history. |
|
2452 | cd -<n>: changes to the n-th directory in the directory history. | |
2448 |
|
2453 | |||
2449 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2454 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2450 | (note: cd <bookmark_name> is enough if there is no |
|
2455 | (note: cd <bookmark_name> is enough if there is no | |
2451 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2456 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2452 |
|
2457 | |||
2453 | Options: |
|
2458 | Options: | |
2454 |
|
2459 | |||
2455 | -q: quiet. Do not print the working directory after the cd command is |
|
2460 | -q: quiet. Do not print the working directory after the cd command is | |
2456 | executed. By default IPython's cd command does print this directory, |
|
2461 | executed. By default IPython's cd command does print this directory, | |
2457 | since the default prompts do not display path information. |
|
2462 | since the default prompts do not display path information. | |
2458 |
|
2463 | |||
2459 | Note that !cd doesn't work for this purpose because the shell where |
|
2464 | Note that !cd doesn't work for this purpose because the shell where | |
2460 | !command runs is immediately discarded after executing 'command'.""" |
|
2465 | !command runs is immediately discarded after executing 'command'.""" | |
2461 |
|
2466 | |||
2462 | parameter_s = parameter_s.strip() |
|
2467 | parameter_s = parameter_s.strip() | |
2463 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2468 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2464 |
|
2469 | |||
2465 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2470 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2466 | # jump in directory history by number |
|
2471 | # jump in directory history by number | |
2467 | if numcd: |
|
2472 | if numcd: | |
2468 | nn = int(numcd.group(2)) |
|
2473 | nn = int(numcd.group(2)) | |
2469 | try: |
|
2474 | try: | |
2470 | ps = self.shell.user_ns['_dh'][nn] |
|
2475 | ps = self.shell.user_ns['_dh'][nn] | |
2471 | except IndexError: |
|
2476 | except IndexError: | |
2472 | print 'The requested directory does not exist in history.' |
|
2477 | print 'The requested directory does not exist in history.' | |
2473 | return |
|
2478 | return | |
2474 | else: |
|
2479 | else: | |
2475 | opts = {} |
|
2480 | opts = {} | |
2476 | else: |
|
2481 | else: | |
2477 | #turn all non-space-escaping backslashes to slashes, |
|
2482 | #turn all non-space-escaping backslashes to slashes, | |
2478 | # for c:\windows\directory\names\ |
|
2483 | # for c:\windows\directory\names\ | |
2479 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2484 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2480 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2485 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2481 | # jump to previous |
|
2486 | # jump to previous | |
2482 | if ps == '-': |
|
2487 | if ps == '-': | |
2483 | try: |
|
2488 | try: | |
2484 | ps = self.shell.user_ns['_dh'][-2] |
|
2489 | ps = self.shell.user_ns['_dh'][-2] | |
2485 | except IndexError: |
|
2490 | except IndexError: | |
2486 | print 'No previous directory to change to.' |
|
2491 | print 'No previous directory to change to.' | |
2487 | return |
|
2492 | return | |
2488 | # jump to bookmark if needed |
|
2493 | # jump to bookmark if needed | |
2489 | else: |
|
2494 | else: | |
2490 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2495 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2491 | bkms = self.db.get('bookmarks', {}) |
|
2496 | bkms = self.db.get('bookmarks', {}) | |
2492 |
|
2497 | |||
2493 | if bkms.has_key(ps): |
|
2498 | if bkms.has_key(ps): | |
2494 | target = bkms[ps] |
|
2499 | target = bkms[ps] | |
2495 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2500 | print '(bookmark:%s) -> %s' % (ps,target) | |
2496 | ps = target |
|
2501 | ps = target | |
2497 | else: |
|
2502 | else: | |
2498 | if opts.has_key('b'): |
|
2503 | if opts.has_key('b'): | |
2499 | error("Bookmark '%s' not found. " |
|
2504 | error("Bookmark '%s' not found. " | |
2500 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2505 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2501 | return |
|
2506 | return | |
2502 |
|
2507 | |||
2503 | # at this point ps should point to the target dir |
|
2508 | # at this point ps should point to the target dir | |
2504 | if ps: |
|
2509 | if ps: | |
2505 | try: |
|
2510 | try: | |
2506 | os.chdir(os.path.expanduser(ps)) |
|
2511 | os.chdir(os.path.expanduser(ps)) | |
2507 | ttitle = ("IPy:" + ( |
|
2512 | ttitle = ("IPy:" + ( | |
2508 | os.getcwd() == '/' and '/' or os.path.basename(os.getcwd()))) |
|
2513 | os.getcwd() == '/' and '/' or os.path.basename(os.getcwd()))) | |
2509 | platutils.set_term_title(ttitle) |
|
2514 | platutils.set_term_title(ttitle) | |
2510 | except OSError: |
|
2515 | except OSError: | |
2511 | print sys.exc_info()[1] |
|
2516 | print sys.exc_info()[1] | |
2512 | else: |
|
2517 | else: | |
2513 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2518 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2514 | else: |
|
2519 | else: | |
2515 | os.chdir(self.shell.home_dir) |
|
2520 | os.chdir(self.shell.home_dir) | |
2516 | platutils.set_term_title("IPy:~") |
|
2521 | platutils.set_term_title("IPy:~") | |
2517 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2522 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2518 | if not 'q' in opts: |
|
2523 | if not 'q' in opts: | |
2519 | print self.shell.user_ns['_dh'][-1] |
|
2524 | print self.shell.user_ns['_dh'][-1] | |
2520 |
|
2525 | |||
2521 | def magic_dhist(self, parameter_s=''): |
|
2526 | def magic_dhist(self, parameter_s=''): | |
2522 | """Print your history of visited directories. |
|
2527 | """Print your history of visited directories. | |
2523 |
|
2528 | |||
2524 | %dhist -> print full history\\ |
|
2529 | %dhist -> print full history\\ | |
2525 | %dhist n -> print last n entries only\\ |
|
2530 | %dhist n -> print last n entries only\\ | |
2526 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2531 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2527 |
|
2532 | |||
2528 | This history is automatically maintained by the %cd command, and |
|
2533 | This history is automatically maintained by the %cd command, and | |
2529 | always available as the global list variable _dh. You can use %cd -<n> |
|
2534 | always available as the global list variable _dh. You can use %cd -<n> | |
2530 | to go to directory number <n>.""" |
|
2535 | to go to directory number <n>.""" | |
2531 |
|
2536 | |||
2532 | dh = self.shell.user_ns['_dh'] |
|
2537 | dh = self.shell.user_ns['_dh'] | |
2533 | if parameter_s: |
|
2538 | if parameter_s: | |
2534 | try: |
|
2539 | try: | |
2535 | args = map(int,parameter_s.split()) |
|
2540 | args = map(int,parameter_s.split()) | |
2536 | except: |
|
2541 | except: | |
2537 | self.arg_err(Magic.magic_dhist) |
|
2542 | self.arg_err(Magic.magic_dhist) | |
2538 | return |
|
2543 | return | |
2539 | if len(args) == 1: |
|
2544 | if len(args) == 1: | |
2540 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2545 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2541 | elif len(args) == 2: |
|
2546 | elif len(args) == 2: | |
2542 | ini,fin = args |
|
2547 | ini,fin = args | |
2543 | else: |
|
2548 | else: | |
2544 | self.arg_err(Magic.magic_dhist) |
|
2549 | self.arg_err(Magic.magic_dhist) | |
2545 | return |
|
2550 | return | |
2546 | else: |
|
2551 | else: | |
2547 | ini,fin = 0,len(dh) |
|
2552 | ini,fin = 0,len(dh) | |
2548 | nlprint(dh, |
|
2553 | nlprint(dh, | |
2549 | header = 'Directory history (kept in _dh)', |
|
2554 | header = 'Directory history (kept in _dh)', | |
2550 | start=ini,stop=fin) |
|
2555 | start=ini,stop=fin) | |
2551 |
|
2556 | |||
2552 | def magic_env(self, parameter_s=''): |
|
2557 | def magic_env(self, parameter_s=''): | |
2553 | """List environment variables.""" |
|
2558 | """List environment variables.""" | |
2554 |
|
2559 | |||
2555 | return os.environ.data |
|
2560 | return os.environ.data | |
2556 |
|
2561 | |||
2557 | def magic_pushd(self, parameter_s=''): |
|
2562 | def magic_pushd(self, parameter_s=''): | |
2558 | """Place the current dir on stack and change directory. |
|
2563 | """Place the current dir on stack and change directory. | |
2559 |
|
2564 | |||
2560 | Usage:\\ |
|
2565 | Usage:\\ | |
2561 | %pushd ['dirname'] |
|
2566 | %pushd ['dirname'] | |
2562 |
|
2567 | |||
2563 | %pushd with no arguments does a %pushd to your home directory. |
|
2568 | %pushd with no arguments does a %pushd to your home directory. | |
2564 | """ |
|
2569 | """ | |
2565 | if parameter_s == '': parameter_s = '~' |
|
2570 | if parameter_s == '': parameter_s = '~' | |
2566 | dir_s = self.shell.dir_stack |
|
2571 | dir_s = self.shell.dir_stack | |
2567 | if len(dir_s)>0 and os.path.expanduser(parameter_s) != \ |
|
2572 | if len(dir_s)>0 and os.path.expanduser(parameter_s) != \ | |
2568 | os.path.expanduser(self.shell.dir_stack[0]): |
|
2573 | os.path.expanduser(self.shell.dir_stack[0]): | |
2569 | try: |
|
2574 | try: | |
2570 | self.magic_cd(parameter_s) |
|
2575 | self.magic_cd(parameter_s) | |
2571 | dir_s.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2576 | dir_s.insert(0,os.getcwd().replace(self.home_dir,'~')) | |
2572 | self.magic_dirs() |
|
2577 | self.magic_dirs() | |
2573 | except: |
|
2578 | except: | |
2574 | print 'Invalid directory' |
|
2579 | print 'Invalid directory' | |
2575 | else: |
|
2580 | else: | |
2576 | print 'You are already there!' |
|
2581 | print 'You are already there!' | |
2577 |
|
2582 | |||
2578 | def magic_popd(self, parameter_s=''): |
|
2583 | def magic_popd(self, parameter_s=''): | |
2579 | """Change to directory popped off the top of the stack. |
|
2584 | """Change to directory popped off the top of the stack. | |
2580 | """ |
|
2585 | """ | |
2581 | if len (self.shell.dir_stack) > 1: |
|
2586 | if len (self.shell.dir_stack) > 1: | |
2582 | self.shell.dir_stack.pop(0) |
|
2587 | self.shell.dir_stack.pop(0) | |
2583 | self.magic_cd(self.shell.dir_stack[0]) |
|
2588 | self.magic_cd(self.shell.dir_stack[0]) | |
2584 | print self.shell.dir_stack[0] |
|
2589 | print self.shell.dir_stack[0] | |
2585 | else: |
|
2590 | else: | |
2586 | print "You can't remove the starting directory from the stack:",\ |
|
2591 | print "You can't remove the starting directory from the stack:",\ | |
2587 | self.shell.dir_stack |
|
2592 | self.shell.dir_stack | |
2588 |
|
2593 | |||
2589 | def magic_dirs(self, parameter_s=''): |
|
2594 | def magic_dirs(self, parameter_s=''): | |
2590 | """Return the current directory stack.""" |
|
2595 | """Return the current directory stack.""" | |
2591 |
|
2596 | |||
2592 | return self.shell.dir_stack[:] |
|
2597 | return self.shell.dir_stack[:] | |
2593 |
|
2598 | |||
2594 | def magic_sc(self, parameter_s=''): |
|
2599 | def magic_sc(self, parameter_s=''): | |
2595 | """Shell capture - execute a shell command and capture its output. |
|
2600 | """Shell capture - execute a shell command and capture its output. | |
2596 |
|
2601 | |||
2597 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2602 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2598 |
|
2603 | |||
2599 | You should use the form 'var = !command' instead. Example: |
|
2604 | You should use the form 'var = !command' instead. Example: | |
2600 |
|
2605 | |||
2601 | "%sc -l myfiles = ls ~" should now be written as |
|
2606 | "%sc -l myfiles = ls ~" should now be written as | |
2602 |
|
2607 | |||
2603 | "myfiles = !ls ~" |
|
2608 | "myfiles = !ls ~" | |
2604 |
|
2609 | |||
2605 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2610 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2606 | below. |
|
2611 | below. | |
2607 |
|
2612 | |||
2608 | -- |
|
2613 | -- | |
2609 | %sc [options] varname=command |
|
2614 | %sc [options] varname=command | |
2610 |
|
2615 | |||
2611 | IPython will run the given command using commands.getoutput(), and |
|
2616 | IPython will run the given command using commands.getoutput(), and | |
2612 | will then update the user's interactive namespace with a variable |
|
2617 | will then update the user's interactive namespace with a variable | |
2613 | called varname, containing the value of the call. Your command can |
|
2618 | called varname, containing the value of the call. Your command can | |
2614 | contain shell wildcards, pipes, etc. |
|
2619 | contain shell wildcards, pipes, etc. | |
2615 |
|
2620 | |||
2616 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2621 | The '=' sign in the syntax is mandatory, and the variable name you | |
2617 | supply must follow Python's standard conventions for valid names. |
|
2622 | supply must follow Python's standard conventions for valid names. | |
2618 |
|
2623 | |||
2619 | (A special format without variable name exists for internal use) |
|
2624 | (A special format without variable name exists for internal use) | |
2620 |
|
2625 | |||
2621 | Options: |
|
2626 | Options: | |
2622 |
|
2627 | |||
2623 | -l: list output. Split the output on newlines into a list before |
|
2628 | -l: list output. Split the output on newlines into a list before | |
2624 | assigning it to the given variable. By default the output is stored |
|
2629 | assigning it to the given variable. By default the output is stored | |
2625 | as a single string. |
|
2630 | as a single string. | |
2626 |
|
2631 | |||
2627 | -v: verbose. Print the contents of the variable. |
|
2632 | -v: verbose. Print the contents of the variable. | |
2628 |
|
2633 | |||
2629 | In most cases you should not need to split as a list, because the |
|
2634 | In most cases you should not need to split as a list, because the | |
2630 | returned value is a special type of string which can automatically |
|
2635 | returned value is a special type of string which can automatically | |
2631 | provide its contents either as a list (split on newlines) or as a |
|
2636 | provide its contents either as a list (split on newlines) or as a | |
2632 | space-separated string. These are convenient, respectively, either |
|
2637 | space-separated string. These are convenient, respectively, either | |
2633 | for sequential processing or to be passed to a shell command. |
|
2638 | for sequential processing or to be passed to a shell command. | |
2634 |
|
2639 | |||
2635 | For example: |
|
2640 | For example: | |
2636 |
|
2641 | |||
2637 | # Capture into variable a |
|
2642 | # Capture into variable a | |
2638 | In [9]: sc a=ls *py |
|
2643 | In [9]: sc a=ls *py | |
2639 |
|
2644 | |||
2640 | # a is a string with embedded newlines |
|
2645 | # a is a string with embedded newlines | |
2641 | In [10]: a |
|
2646 | In [10]: a | |
2642 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2647 | Out[10]: 'setup.py\nwin32_manual_post_install.py' | |
2643 |
|
2648 | |||
2644 | # which can be seen as a list: |
|
2649 | # which can be seen as a list: | |
2645 | In [11]: a.l |
|
2650 | In [11]: a.l | |
2646 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2651 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] | |
2647 |
|
2652 | |||
2648 | # or as a whitespace-separated string: |
|
2653 | # or as a whitespace-separated string: | |
2649 | In [12]: a.s |
|
2654 | In [12]: a.s | |
2650 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2655 | Out[12]: 'setup.py win32_manual_post_install.py' | |
2651 |
|
2656 | |||
2652 | # a.s is useful to pass as a single command line: |
|
2657 | # a.s is useful to pass as a single command line: | |
2653 | In [13]: !wc -l $a.s |
|
2658 | In [13]: !wc -l $a.s | |
2654 | 146 setup.py |
|
2659 | 146 setup.py | |
2655 | 130 win32_manual_post_install.py |
|
2660 | 130 win32_manual_post_install.py | |
2656 | 276 total |
|
2661 | 276 total | |
2657 |
|
2662 | |||
2658 | # while the list form is useful to loop over: |
|
2663 | # while the list form is useful to loop over: | |
2659 | In [14]: for f in a.l: |
|
2664 | In [14]: for f in a.l: | |
2660 | ....: !wc -l $f |
|
2665 | ....: !wc -l $f | |
2661 | ....: |
|
2666 | ....: | |
2662 | 146 setup.py |
|
2667 | 146 setup.py | |
2663 | 130 win32_manual_post_install.py |
|
2668 | 130 win32_manual_post_install.py | |
2664 |
|
2669 | |||
2665 | Similiarly, the lists returned by the -l option are also special, in |
|
2670 | Similiarly, the lists returned by the -l option are also special, in | |
2666 | the sense that you can equally invoke the .s attribute on them to |
|
2671 | the sense that you can equally invoke the .s attribute on them to | |
2667 | automatically get a whitespace-separated string from their contents: |
|
2672 | automatically get a whitespace-separated string from their contents: | |
2668 |
|
2673 | |||
2669 | In [1]: sc -l b=ls *py |
|
2674 | In [1]: sc -l b=ls *py | |
2670 |
|
2675 | |||
2671 | In [2]: b |
|
2676 | In [2]: b | |
2672 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2677 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] | |
2673 |
|
2678 | |||
2674 | In [3]: b.s |
|
2679 | In [3]: b.s | |
2675 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2680 | Out[3]: 'setup.py win32_manual_post_install.py' | |
2676 |
|
2681 | |||
2677 | In summary, both the lists and strings used for ouptut capture have |
|
2682 | In summary, both the lists and strings used for ouptut capture have | |
2678 | the following special attributes: |
|
2683 | the following special attributes: | |
2679 |
|
2684 | |||
2680 | .l (or .list) : value as list. |
|
2685 | .l (or .list) : value as list. | |
2681 | .n (or .nlstr): value as newline-separated string. |
|
2686 | .n (or .nlstr): value as newline-separated string. | |
2682 | .s (or .spstr): value as space-separated string. |
|
2687 | .s (or .spstr): value as space-separated string. | |
2683 | """ |
|
2688 | """ | |
2684 |
|
2689 | |||
2685 | opts,args = self.parse_options(parameter_s,'lv') |
|
2690 | opts,args = self.parse_options(parameter_s,'lv') | |
2686 | # Try to get a variable name and command to run |
|
2691 | # Try to get a variable name and command to run | |
2687 | try: |
|
2692 | try: | |
2688 | # the variable name must be obtained from the parse_options |
|
2693 | # the variable name must be obtained from the parse_options | |
2689 | # output, which uses shlex.split to strip options out. |
|
2694 | # output, which uses shlex.split to strip options out. | |
2690 | var,_ = args.split('=',1) |
|
2695 | var,_ = args.split('=',1) | |
2691 | var = var.strip() |
|
2696 | var = var.strip() | |
2692 | # But the the command has to be extracted from the original input |
|
2697 | # But the the command has to be extracted from the original input | |
2693 | # parameter_s, not on what parse_options returns, to avoid the |
|
2698 | # parameter_s, not on what parse_options returns, to avoid the | |
2694 | # quote stripping which shlex.split performs on it. |
|
2699 | # quote stripping which shlex.split performs on it. | |
2695 | _,cmd = parameter_s.split('=',1) |
|
2700 | _,cmd = parameter_s.split('=',1) | |
2696 | except ValueError: |
|
2701 | except ValueError: | |
2697 | var,cmd = '','' |
|
2702 | var,cmd = '','' | |
2698 | # If all looks ok, proceed |
|
2703 | # If all looks ok, proceed | |
2699 | out,err = self.shell.getoutputerror(cmd) |
|
2704 | out,err = self.shell.getoutputerror(cmd) | |
2700 | if err: |
|
2705 | if err: | |
2701 | print >> Term.cerr,err |
|
2706 | print >> Term.cerr,err | |
2702 | if opts.has_key('l'): |
|
2707 | if opts.has_key('l'): | |
2703 | out = SList(out.split('\n')) |
|
2708 | out = SList(out.split('\n')) | |
2704 | else: |
|
2709 | else: | |
2705 | out = LSString(out) |
|
2710 | out = LSString(out) | |
2706 | if opts.has_key('v'): |
|
2711 | if opts.has_key('v'): | |
2707 | print '%s ==\n%s' % (var,pformat(out)) |
|
2712 | print '%s ==\n%s' % (var,pformat(out)) | |
2708 | if var: |
|
2713 | if var: | |
2709 | self.shell.user_ns.update({var:out}) |
|
2714 | self.shell.user_ns.update({var:out}) | |
2710 | else: |
|
2715 | else: | |
2711 | return out |
|
2716 | return out | |
2712 |
|
2717 | |||
2713 | def magic_sx(self, parameter_s=''): |
|
2718 | def magic_sx(self, parameter_s=''): | |
2714 | """Shell execute - run a shell command and capture its output. |
|
2719 | """Shell execute - run a shell command and capture its output. | |
2715 |
|
2720 | |||
2716 | %sx command |
|
2721 | %sx command | |
2717 |
|
2722 | |||
2718 | IPython will run the given command using commands.getoutput(), and |
|
2723 | IPython will run the given command using commands.getoutput(), and | |
2719 | return the result formatted as a list (split on '\\n'). Since the |
|
2724 | return the result formatted as a list (split on '\\n'). Since the | |
2720 | output is _returned_, it will be stored in ipython's regular output |
|
2725 | output is _returned_, it will be stored in ipython's regular output | |
2721 | cache Out[N] and in the '_N' automatic variables. |
|
2726 | cache Out[N] and in the '_N' automatic variables. | |
2722 |
|
2727 | |||
2723 | Notes: |
|
2728 | Notes: | |
2724 |
|
2729 | |||
2725 | 1) If an input line begins with '!!', then %sx is automatically |
|
2730 | 1) If an input line begins with '!!', then %sx is automatically | |
2726 | invoked. That is, while: |
|
2731 | invoked. That is, while: | |
2727 | !ls |
|
2732 | !ls | |
2728 | causes ipython to simply issue system('ls'), typing |
|
2733 | causes ipython to simply issue system('ls'), typing | |
2729 | !!ls |
|
2734 | !!ls | |
2730 | is a shorthand equivalent to: |
|
2735 | is a shorthand equivalent to: | |
2731 | %sx ls |
|
2736 | %sx ls | |
2732 |
|
2737 | |||
2733 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2738 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2734 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2739 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2735 | to process line-oriented shell output via further python commands. |
|
2740 | to process line-oriented shell output via further python commands. | |
2736 | %sc is meant to provide much finer control, but requires more |
|
2741 | %sc is meant to provide much finer control, but requires more | |
2737 | typing. |
|
2742 | typing. | |
2738 |
|
2743 | |||
2739 | 3) Just like %sc -l, this is a list with special attributes: |
|
2744 | 3) Just like %sc -l, this is a list with special attributes: | |
2740 |
|
2745 | |||
2741 | .l (or .list) : value as list. |
|
2746 | .l (or .list) : value as list. | |
2742 | .n (or .nlstr): value as newline-separated string. |
|
2747 | .n (or .nlstr): value as newline-separated string. | |
2743 | .s (or .spstr): value as whitespace-separated string. |
|
2748 | .s (or .spstr): value as whitespace-separated string. | |
2744 |
|
2749 | |||
2745 | This is very useful when trying to use such lists as arguments to |
|
2750 | This is very useful when trying to use such lists as arguments to | |
2746 | system commands.""" |
|
2751 | system commands.""" | |
2747 |
|
2752 | |||
2748 | if parameter_s: |
|
2753 | if parameter_s: | |
2749 | out,err = self.shell.getoutputerror(parameter_s) |
|
2754 | out,err = self.shell.getoutputerror(parameter_s) | |
2750 | if err: |
|
2755 | if err: | |
2751 | print >> Term.cerr,err |
|
2756 | print >> Term.cerr,err | |
2752 | return SList(out.split('\n')) |
|
2757 | return SList(out.split('\n')) | |
2753 |
|
2758 | |||
2754 | def magic_bg(self, parameter_s=''): |
|
2759 | def magic_bg(self, parameter_s=''): | |
2755 | """Run a job in the background, in a separate thread. |
|
2760 | """Run a job in the background, in a separate thread. | |
2756 |
|
2761 | |||
2757 | For example, |
|
2762 | For example, | |
2758 |
|
2763 | |||
2759 | %bg myfunc(x,y,z=1) |
|
2764 | %bg myfunc(x,y,z=1) | |
2760 |
|
2765 | |||
2761 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2766 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
2762 | execution starts, a message will be printed indicating the job |
|
2767 | execution starts, a message will be printed indicating the job | |
2763 | number. If your job number is 5, you can use |
|
2768 | number. If your job number is 5, you can use | |
2764 |
|
2769 | |||
2765 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2770 | myvar = jobs.result(5) or myvar = jobs[5].result | |
2766 |
|
2771 | |||
2767 | to assign this result to variable 'myvar'. |
|
2772 | to assign this result to variable 'myvar'. | |
2768 |
|
2773 | |||
2769 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2774 | IPython has a job manager, accessible via the 'jobs' object. You can | |
2770 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2775 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
2771 | its attributes. All attributes not starting with an underscore are |
|
2776 | its attributes. All attributes not starting with an underscore are | |
2772 | meant for public use. |
|
2777 | meant for public use. | |
2773 |
|
2778 | |||
2774 | In particular, look at the jobs.new() method, which is used to create |
|
2779 | In particular, look at the jobs.new() method, which is used to create | |
2775 | new jobs. This magic %bg function is just a convenience wrapper |
|
2780 | new jobs. This magic %bg function is just a convenience wrapper | |
2776 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2781 | around jobs.new(), for expression-based jobs. If you want to create a | |
2777 | new job with an explicit function object and arguments, you must call |
|
2782 | new job with an explicit function object and arguments, you must call | |
2778 | jobs.new() directly. |
|
2783 | jobs.new() directly. | |
2779 |
|
2784 | |||
2780 | The jobs.new docstring also describes in detail several important |
|
2785 | The jobs.new docstring also describes in detail several important | |
2781 | caveats associated with a thread-based model for background job |
|
2786 | caveats associated with a thread-based model for background job | |
2782 | execution. Type jobs.new? for details. |
|
2787 | execution. Type jobs.new? for details. | |
2783 |
|
2788 | |||
2784 | You can check the status of all jobs with jobs.status(). |
|
2789 | You can check the status of all jobs with jobs.status(). | |
2785 |
|
2790 | |||
2786 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2791 | The jobs variable is set by IPython into the Python builtin namespace. | |
2787 | If you ever declare a variable named 'jobs', you will shadow this |
|
2792 | If you ever declare a variable named 'jobs', you will shadow this | |
2788 | name. You can either delete your global jobs variable to regain |
|
2793 | name. You can either delete your global jobs variable to regain | |
2789 | access to the job manager, or make a new name and assign it manually |
|
2794 | access to the job manager, or make a new name and assign it manually | |
2790 | to the manager (stored in IPython's namespace). For example, to |
|
2795 | to the manager (stored in IPython's namespace). For example, to | |
2791 | assign the job manager to the Jobs name, use: |
|
2796 | assign the job manager to the Jobs name, use: | |
2792 |
|
2797 | |||
2793 | Jobs = __builtins__.jobs""" |
|
2798 | Jobs = __builtins__.jobs""" | |
2794 |
|
2799 | |||
2795 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2800 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
2796 |
|
2801 | |||
2797 |
|
2802 | |||
2798 | def magic_bookmark(self, parameter_s=''): |
|
2803 | def magic_bookmark(self, parameter_s=''): | |
2799 | """Manage IPython's bookmark system. |
|
2804 | """Manage IPython's bookmark system. | |
2800 |
|
2805 | |||
2801 | %bookmark <name> - set bookmark to current dir |
|
2806 | %bookmark <name> - set bookmark to current dir | |
2802 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2807 | %bookmark <name> <dir> - set bookmark to <dir> | |
2803 | %bookmark -l - list all bookmarks |
|
2808 | %bookmark -l - list all bookmarks | |
2804 | %bookmark -d <name> - remove bookmark |
|
2809 | %bookmark -d <name> - remove bookmark | |
2805 | %bookmark -r - remove all bookmarks |
|
2810 | %bookmark -r - remove all bookmarks | |
2806 |
|
2811 | |||
2807 | You can later on access a bookmarked folder with: |
|
2812 | You can later on access a bookmarked folder with: | |
2808 | %cd -b <name> |
|
2813 | %cd -b <name> | |
2809 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2814 | or simply '%cd <name>' if there is no directory called <name> AND | |
2810 | there is such a bookmark defined. |
|
2815 | there is such a bookmark defined. | |
2811 |
|
2816 | |||
2812 | Your bookmarks persist through IPython sessions, but they are |
|
2817 | Your bookmarks persist through IPython sessions, but they are | |
2813 | associated with each profile.""" |
|
2818 | associated with each profile.""" | |
2814 |
|
2819 | |||
2815 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2820 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
2816 | if len(args) > 2: |
|
2821 | if len(args) > 2: | |
2817 | error('You can only give at most two arguments') |
|
2822 | error('You can only give at most two arguments') | |
2818 | return |
|
2823 | return | |
2819 |
|
2824 | |||
2820 | bkms = self.db.get('bookmarks',{}) |
|
2825 | bkms = self.db.get('bookmarks',{}) | |
2821 |
|
2826 | |||
2822 | if opts.has_key('d'): |
|
2827 | if opts.has_key('d'): | |
2823 | try: |
|
2828 | try: | |
2824 | todel = args[0] |
|
2829 | todel = args[0] | |
2825 | except IndexError: |
|
2830 | except IndexError: | |
2826 | error('You must provide a bookmark to delete') |
|
2831 | error('You must provide a bookmark to delete') | |
2827 | else: |
|
2832 | else: | |
2828 | try: |
|
2833 | try: | |
2829 | del bkms[todel] |
|
2834 | del bkms[todel] | |
2830 | except: |
|
2835 | except: | |
2831 | error("Can't delete bookmark '%s'" % todel) |
|
2836 | error("Can't delete bookmark '%s'" % todel) | |
2832 | elif opts.has_key('r'): |
|
2837 | elif opts.has_key('r'): | |
2833 | bkms = {} |
|
2838 | bkms = {} | |
2834 | elif opts.has_key('l'): |
|
2839 | elif opts.has_key('l'): | |
2835 | bks = bkms.keys() |
|
2840 | bks = bkms.keys() | |
2836 | bks.sort() |
|
2841 | bks.sort() | |
2837 | if bks: |
|
2842 | if bks: | |
2838 | size = max(map(len,bks)) |
|
2843 | size = max(map(len,bks)) | |
2839 | else: |
|
2844 | else: | |
2840 | size = 0 |
|
2845 | size = 0 | |
2841 | fmt = '%-'+str(size)+'s -> %s' |
|
2846 | fmt = '%-'+str(size)+'s -> %s' | |
2842 | print 'Current bookmarks:' |
|
2847 | print 'Current bookmarks:' | |
2843 | for bk in bks: |
|
2848 | for bk in bks: | |
2844 | print fmt % (bk,bkms[bk]) |
|
2849 | print fmt % (bk,bkms[bk]) | |
2845 | else: |
|
2850 | else: | |
2846 | if not args: |
|
2851 | if not args: | |
2847 | error("You must specify the bookmark name") |
|
2852 | error("You must specify the bookmark name") | |
2848 | elif len(args)==1: |
|
2853 | elif len(args)==1: | |
2849 | bkms[args[0]] = os.getcwd() |
|
2854 | bkms[args[0]] = os.getcwd() | |
2850 | elif len(args)==2: |
|
2855 | elif len(args)==2: | |
2851 | bkms[args[0]] = args[1] |
|
2856 | bkms[args[0]] = args[1] | |
2852 | self.db['bookmarks'] = bkms |
|
2857 | self.db['bookmarks'] = bkms | |
2853 |
|
2858 | |||
2854 | def magic_pycat(self, parameter_s=''): |
|
2859 | def magic_pycat(self, parameter_s=''): | |
2855 | """Show a syntax-highlighted file through a pager. |
|
2860 | """Show a syntax-highlighted file through a pager. | |
2856 |
|
2861 | |||
2857 | This magic is similar to the cat utility, but it will assume the file |
|
2862 | This magic is similar to the cat utility, but it will assume the file | |
2858 | to be Python source and will show it with syntax highlighting. """ |
|
2863 | to be Python source and will show it with syntax highlighting. """ | |
2859 |
|
2864 | |||
2860 | try: |
|
2865 | try: | |
2861 | filename = get_py_filename(parameter_s) |
|
2866 | filename = get_py_filename(parameter_s) | |
2862 | cont = file_read(filename) |
|
2867 | cont = file_read(filename) | |
2863 | except IOError: |
|
2868 | except IOError: | |
2864 | try: |
|
2869 | try: | |
2865 | cont = eval(parameter_s,self.user_ns) |
|
2870 | cont = eval(parameter_s,self.user_ns) | |
2866 | except NameError: |
|
2871 | except NameError: | |
2867 | cont = None |
|
2872 | cont = None | |
2868 | if cont is None: |
|
2873 | if cont is None: | |
2869 | print "Error: no such file or variable" |
|
2874 | print "Error: no such file or variable" | |
2870 | return |
|
2875 | return | |
2871 |
|
2876 | |||
2872 | page(self.shell.pycolorize(cont), |
|
2877 | page(self.shell.pycolorize(cont), | |
2873 | screen_lines=self.shell.rc.screen_length) |
|
2878 | screen_lines=self.shell.rc.screen_length) | |
2874 |
|
2879 | |||
2875 | def magic_cpaste(self, parameter_s=''): |
|
2880 | def magic_cpaste(self, parameter_s=''): | |
2876 | """Allows you to paste & execute a pre-formatted code block from clipboard |
|
2881 | """Allows you to paste & execute a pre-formatted code block from clipboard | |
2877 |
|
2882 | |||
2878 | You must terminate the block with '--' (two minus-signs) alone on the |
|
2883 | You must terminate the block with '--' (two minus-signs) alone on the | |
2879 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
2884 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
2880 | is the new sentinel for this operation) |
|
2885 | is the new sentinel for this operation) | |
2881 |
|
2886 | |||
2882 | The block is dedented prior to execution to enable execution of |
|
2887 | The block is dedented prior to execution to enable execution of | |
2883 | method definitions. The executed block is also assigned to variable |
|
2888 | method definitions. The executed block is also assigned to variable | |
2884 | named 'pasted_block' for later editing with '%edit pasted_block'. |
|
2889 | named 'pasted_block' for later editing with '%edit pasted_block'. | |
2885 |
|
2890 | |||
2886 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
2891 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
2887 | This assigns the pasted block to variable 'foo' as string, without |
|
2892 | This assigns the pasted block to variable 'foo' as string, without | |
2888 | dedenting or executing it. |
|
2893 | dedenting or executing it. | |
2889 |
|
2894 | |||
2890 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
2895 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
2891 | Just press enter and type -- (and press enter again) and the block |
|
2896 | Just press enter and type -- (and press enter again) and the block | |
2892 | will be what was just pasted. |
|
2897 | will be what was just pasted. | |
2893 |
|
2898 | |||
2894 | IPython statements (magics, shell escapes) are not supported (yet). |
|
2899 | IPython statements (magics, shell escapes) are not supported (yet). | |
2895 | """ |
|
2900 | """ | |
2896 | opts,args = self.parse_options(parameter_s,'s:',mode='string') |
|
2901 | opts,args = self.parse_options(parameter_s,'s:',mode='string') | |
2897 | par = args.strip() |
|
2902 | par = args.strip() | |
2898 | sentinel = opts.get('s','--') |
|
2903 | sentinel = opts.get('s','--') | |
2899 |
|
2904 | |||
2900 | from IPython import iplib |
|
2905 | from IPython import iplib | |
2901 | lines = [] |
|
2906 | lines = [] | |
2902 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
2907 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
2903 | while 1: |
|
2908 | while 1: | |
2904 | l = iplib.raw_input_original(':') |
|
2909 | l = iplib.raw_input_original(':') | |
2905 | if l ==sentinel: |
|
2910 | if l ==sentinel: | |
2906 | break |
|
2911 | break | |
2907 | lines.append(l) |
|
2912 | lines.append(l) | |
2908 | block = "\n".join(lines) + '\n' |
|
2913 | block = "\n".join(lines) + '\n' | |
2909 | #print "block:\n",block |
|
2914 | #print "block:\n",block | |
2910 | if not par: |
|
2915 | if not par: | |
2911 | b = textwrap.dedent(block) |
|
2916 | b = textwrap.dedent(block) | |
2912 | exec b in self.user_ns |
|
2917 | exec b in self.user_ns | |
2913 | self.user_ns['pasted_block'] = b |
|
2918 | self.user_ns['pasted_block'] = b | |
2914 | else: |
|
2919 | else: | |
2915 | self.user_ns[par] = block |
|
2920 | self.user_ns[par] = block | |
2916 | print "Block assigned to '%s'" % par |
|
2921 | print "Block assigned to '%s'" % par | |
2917 |
|
2922 | |||
2918 | def magic_quickref(self,arg): |
|
2923 | def magic_quickref(self,arg): | |
2919 | """ Show a quick reference sheet """ |
|
2924 | """ Show a quick reference sheet """ | |
2920 | import IPython.usage |
|
2925 | import IPython.usage | |
2921 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
2926 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') | |
2922 |
|
2927 | |||
2923 | page(qr) |
|
2928 | page(qr) | |
2924 |
|
2929 | |||
2925 | def magic_upgrade(self,arg): |
|
2930 | def magic_upgrade(self,arg): | |
2926 | """ Upgrade your IPython installation |
|
2931 | """ Upgrade your IPython installation | |
2927 |
|
2932 | |||
2928 | This will copy the config files that don't yet exist in your |
|
2933 | This will copy the config files that don't yet exist in your | |
2929 | ipython dir from the system config dir. Use this after upgrading |
|
2934 | ipython dir from the system config dir. Use this after upgrading | |
2930 | IPython if you don't wish to delete your .ipython dir. |
|
2935 | IPython if you don't wish to delete your .ipython dir. | |
2931 |
|
2936 | |||
2932 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
2937 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
2933 | new users) |
|
2938 | new users) | |
2934 |
|
2939 | |||
2935 | """ |
|
2940 | """ | |
2936 | ip = self.getapi() |
|
2941 | ip = self.getapi() | |
2937 | ipinstallation = path(IPython.__file__).dirname() |
|
2942 | ipinstallation = path(IPython.__file__).dirname() | |
2938 | upgrade_script = sys.executable + " " + ipinstallation / 'upgrade_dir.py' |
|
2943 | upgrade_script = sys.executable + " " + ipinstallation / 'upgrade_dir.py' | |
2939 | src_config = ipinstallation / 'UserConfig' |
|
2944 | src_config = ipinstallation / 'UserConfig' | |
2940 | userdir = path(ip.options.ipythondir) |
|
2945 | userdir = path(ip.options.ipythondir) | |
2941 | cmd = upgrade_script + " " + src_config + " " + userdir |
|
2946 | cmd = upgrade_script + " " + src_config + " " + userdir | |
2942 | print ">",cmd |
|
2947 | print ">",cmd | |
2943 | shell(cmd) |
|
2948 | shell(cmd) | |
2944 | if arg == '-nolegacy': |
|
2949 | if arg == '-nolegacy': | |
2945 | legacy = userdir.files('ipythonrc*') |
|
2950 | legacy = userdir.files('ipythonrc*') | |
2946 | print "Nuking legacy files:",legacy |
|
2951 | print "Nuking legacy files:",legacy | |
2947 |
|
2952 | |||
2948 | [p.remove() for p in legacy] |
|
2953 | [p.remove() for p in legacy] | |
2949 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
2954 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
2950 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
2955 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
2951 |
|
2956 | |||
2952 |
|
2957 | |||
2953 | # end Magic |
|
2958 | # end Magic |
@@ -1,570 +1,581 b'' | |||||
1 | """Word completion for IPython. |
|
1 | """Word completion for IPython. | |
2 |
|
2 | |||
3 | This module is a fork of the rlcompleter module in the Python standard |
|
3 | This module is a fork of the rlcompleter module in the Python standard | |
4 | library. The original enhancements made to rlcompleter have been sent |
|
4 | library. The original enhancements made to rlcompleter have been sent | |
5 | upstream and were accepted as of Python 2.3, but we need a lot more |
|
5 | upstream and were accepted as of Python 2.3, but we need a lot more | |
6 | functionality specific to IPython, so this module will continue to live as an |
|
6 | functionality specific to IPython, so this module will continue to live as an | |
7 | IPython-specific utility. |
|
7 | IPython-specific utility. | |
8 |
|
8 | |||
9 | --------------------------------------------------------------------------- |
|
9 | --------------------------------------------------------------------------- | |
10 | Original rlcompleter documentation: |
|
10 | Original rlcompleter documentation: | |
11 |
|
11 | |||
12 | This requires the latest extension to the readline module (the |
|
12 | This requires the latest extension to the readline module (the | |
13 | completes keywords, built-ins and globals in __main__; when completing |
|
13 | completes keywords, built-ins and globals in __main__; when completing | |
14 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
14 | NAME.NAME..., it evaluates (!) the expression up to the last dot and | |
15 | completes its attributes. |
|
15 | completes its attributes. | |
16 |
|
16 | |||
17 | It's very cool to do "import string" type "string.", hit the |
|
17 | It's very cool to do "import string" type "string.", hit the | |
18 | completion key (twice), and see the list of names defined by the |
|
18 | completion key (twice), and see the list of names defined by the | |
19 | string module! |
|
19 | string module! | |
20 |
|
20 | |||
21 | Tip: to use the tab key as the completion key, call |
|
21 | Tip: to use the tab key as the completion key, call | |
22 |
|
22 | |||
23 | readline.parse_and_bind("tab: complete") |
|
23 | readline.parse_and_bind("tab: complete") | |
24 |
|
24 | |||
25 | Notes: |
|
25 | Notes: | |
26 |
|
26 | |||
27 | - Exceptions raised by the completer function are *ignored* (and |
|
27 | - Exceptions raised by the completer function are *ignored* (and | |
28 | generally cause the completion to fail). This is a feature -- since |
|
28 | generally cause the completion to fail). This is a feature -- since | |
29 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
29 | readline sets the tty device in raw (or cbreak) mode, printing a | |
30 | traceback wouldn't work well without some complicated hoopla to save, |
|
30 | traceback wouldn't work well without some complicated hoopla to save, | |
31 | reset and restore the tty state. |
|
31 | reset and restore the tty state. | |
32 |
|
32 | |||
33 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
33 | - The evaluation of the NAME.NAME... form may cause arbitrary | |
34 | application defined code to be executed if an object with a |
|
34 | application defined code to be executed if an object with a | |
35 | __getattr__ hook is found. Since it is the responsibility of the |
|
35 | __getattr__ hook is found. Since it is the responsibility of the | |
36 | application (or the user) to enable this feature, I consider this an |
|
36 | application (or the user) to enable this feature, I consider this an | |
37 | acceptable risk. More complicated expressions (e.g. function calls or |
|
37 | acceptable risk. More complicated expressions (e.g. function calls or | |
38 | indexing operations) are *not* evaluated. |
|
38 | indexing operations) are *not* evaluated. | |
39 |
|
39 | |||
40 | - GNU readline is also used by the built-in functions input() and |
|
40 | - GNU readline is also used by the built-in functions input() and | |
41 | raw_input(), and thus these also benefit/suffer from the completer |
|
41 | raw_input(), and thus these also benefit/suffer from the completer | |
42 | features. Clearly an interactive application can benefit by |
|
42 | features. Clearly an interactive application can benefit by | |
43 | specifying its own completer function and using raw_input() for all |
|
43 | specifying its own completer function and using raw_input() for all | |
44 | its input. |
|
44 | its input. | |
45 |
|
45 | |||
46 | - When the original stdin is not a tty device, GNU readline is never |
|
46 | - When the original stdin is not a tty device, GNU readline is never | |
47 | used, and this module (and the readline module) are silently inactive. |
|
47 | used, and this module (and the readline module) are silently inactive. | |
48 |
|
48 | |||
49 | """ |
|
49 | """ | |
50 |
|
50 | |||
51 | #***************************************************************************** |
|
51 | #***************************************************************************** | |
52 | # |
|
52 | # | |
53 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
53 | # Since this file is essentially a minimally modified copy of the rlcompleter | |
54 | # module which is part of the standard Python distribution, I assume that the |
|
54 | # module which is part of the standard Python distribution, I assume that the | |
55 | # proper procedure is to maintain its copyright as belonging to the Python |
|
55 | # proper procedure is to maintain its copyright as belonging to the Python | |
56 | # Software Foundation (in addition to my own, for all new code). |
|
56 | # Software Foundation (in addition to my own, for all new code). | |
57 | # |
|
57 | # | |
58 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
58 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
59 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
59 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
60 | # |
|
60 | # | |
61 | # Distributed under the terms of the BSD License. The full license is in |
|
61 | # Distributed under the terms of the BSD License. The full license is in | |
62 | # the file COPYING, distributed as part of this software. |
|
62 | # the file COPYING, distributed as part of this software. | |
63 | # |
|
63 | # | |
64 | #***************************************************************************** |
|
64 | #***************************************************************************** | |
65 |
|
65 | |||
66 | import __builtin__ |
|
66 | import __builtin__ | |
67 | import __main__ |
|
67 | import __main__ | |
68 | import glob |
|
68 | import glob | |
69 | import keyword |
|
69 | import keyword | |
70 | import os |
|
70 | import os | |
71 | import re |
|
71 | import re | |
72 | import shlex |
|
72 | import shlex | |
73 | import sys |
|
73 | import sys | |
74 | import IPython.rlineimpl as readline |
|
74 | import IPython.rlineimpl as readline | |
75 |
|
75 | |||
76 | import types |
|
76 | import types | |
77 |
|
77 | |||
78 | # Python 2.4 offers sets as a builtin |
|
78 | # Python 2.4 offers sets as a builtin | |
79 | try: |
|
79 | try: | |
80 | set([1,2]) |
|
80 | set([1,2]) | |
81 | except NameError: |
|
81 | except NameError: | |
82 | from sets import Set as set |
|
82 | from sets import Set as set | |
83 |
|
83 | |||
84 | from IPython.genutils import debugx |
|
84 | from IPython.genutils import debugx | |
85 |
|
85 | |||
86 | __all__ = ['Completer','IPCompleter'] |
|
86 | __all__ = ['Completer','IPCompleter'] | |
87 |
|
87 | |||
88 | def get_class_members(cls): |
|
88 | def get_class_members(cls): | |
89 | ret = dir(cls) |
|
89 | ret = dir(cls) | |
90 | if hasattr(cls,'__bases__'): |
|
90 | if hasattr(cls,'__bases__'): | |
91 | for base in cls.__bases__: |
|
91 | for base in cls.__bases__: | |
92 | ret.extend(get_class_members(base)) |
|
92 | ret.extend(get_class_members(base)) | |
93 | return ret |
|
93 | return ret | |
94 |
|
94 | |||
95 | class Completer: |
|
95 | class Completer: | |
96 | def __init__(self,namespace=None,global_namespace=None): |
|
96 | def __init__(self,namespace=None,global_namespace=None): | |
97 | """Create a new completer for the command line. |
|
97 | """Create a new completer for the command line. | |
98 |
|
98 | |||
99 | Completer([namespace,global_namespace]) -> completer instance. |
|
99 | Completer([namespace,global_namespace]) -> completer instance. | |
100 |
|
100 | |||
101 | If unspecified, the default namespace where completions are performed |
|
101 | If unspecified, the default namespace where completions are performed | |
102 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
102 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
103 | given as dictionaries. |
|
103 | given as dictionaries. | |
104 |
|
104 | |||
105 | An optional second namespace can be given. This allows the completer |
|
105 | An optional second namespace can be given. This allows the completer | |
106 | to handle cases where both the local and global scopes need to be |
|
106 | to handle cases where both the local and global scopes need to be | |
107 | distinguished. |
|
107 | distinguished. | |
108 |
|
108 | |||
109 | Completer instances should be used as the completion mechanism of |
|
109 | Completer instances should be used as the completion mechanism of | |
110 | readline via the set_completer() call: |
|
110 | readline via the set_completer() call: | |
111 |
|
111 | |||
112 | readline.set_completer(Completer(my_namespace).complete) |
|
112 | readline.set_completer(Completer(my_namespace).complete) | |
113 | """ |
|
113 | """ | |
114 |
|
114 | |||
115 | # some minimal strict typechecks. For some core data structures, I |
|
115 | # some minimal strict typechecks. For some core data structures, I | |
116 | # want actual basic python types, not just anything that looks like |
|
116 | # want actual basic python types, not just anything that looks like | |
117 | # one. This is especially true for namespaces. |
|
117 | # one. This is especially true for namespaces. | |
118 | for ns in (namespace,global_namespace): |
|
118 | for ns in (namespace,global_namespace): | |
119 | if ns is not None and type(ns) != types.DictType: |
|
119 | if ns is not None and type(ns) != types.DictType: | |
120 | raise TypeError,'namespace must be a dictionary' |
|
120 | raise TypeError,'namespace must be a dictionary' | |
121 |
|
121 | |||
122 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
122 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
123 | # specific namespace or to use __main__.__dict__. This will allow us |
|
123 | # specific namespace or to use __main__.__dict__. This will allow us | |
124 | # to bind to __main__.__dict__ at completion time, not now. |
|
124 | # to bind to __main__.__dict__ at completion time, not now. | |
125 | if namespace is None: |
|
125 | if namespace is None: | |
126 | self.use_main_ns = 1 |
|
126 | self.use_main_ns = 1 | |
127 | else: |
|
127 | else: | |
128 | self.use_main_ns = 0 |
|
128 | self.use_main_ns = 0 | |
129 | self.namespace = namespace |
|
129 | self.namespace = namespace | |
130 |
|
130 | |||
131 | # The global namespace, if given, can be bound directly |
|
131 | # The global namespace, if given, can be bound directly | |
132 | if global_namespace is None: |
|
132 | if global_namespace is None: | |
133 | self.global_namespace = {} |
|
133 | self.global_namespace = {} | |
134 | else: |
|
134 | else: | |
135 | self.global_namespace = global_namespace |
|
135 | self.global_namespace = global_namespace | |
136 |
|
136 | |||
137 | def complete(self, text, state): |
|
137 | def complete(self, text, state): | |
138 | """Return the next possible completion for 'text'. |
|
138 | """Return the next possible completion for 'text'. | |
139 |
|
139 | |||
140 | This is called successively with state == 0, 1, 2, ... until it |
|
140 | This is called successively with state == 0, 1, 2, ... until it | |
141 | returns None. The completion should begin with 'text'. |
|
141 | returns None. The completion should begin with 'text'. | |
142 |
|
142 | |||
143 | """ |
|
143 | """ | |
144 | if self.use_main_ns: |
|
144 | if self.use_main_ns: | |
145 | self.namespace = __main__.__dict__ |
|
145 | self.namespace = __main__.__dict__ | |
146 |
|
146 | |||
147 | if state == 0: |
|
147 | if state == 0: | |
148 | if "." in text: |
|
148 | if "." in text: | |
149 | self.matches = self.attr_matches(text) |
|
149 | self.matches = self.attr_matches(text) | |
150 | else: |
|
150 | else: | |
151 | self.matches = self.global_matches(text) |
|
151 | self.matches = self.global_matches(text) | |
152 | try: |
|
152 | try: | |
153 | return self.matches[state] |
|
153 | return self.matches[state] | |
154 | except IndexError: |
|
154 | except IndexError: | |
155 | return None |
|
155 | return None | |
156 |
|
156 | |||
157 | def global_matches(self, text): |
|
157 | def global_matches(self, text): | |
158 | """Compute matches when text is a simple name. |
|
158 | """Compute matches when text is a simple name. | |
159 |
|
159 | |||
160 | Return a list of all keywords, built-in functions and names currently |
|
160 | Return a list of all keywords, built-in functions and names currently | |
161 | defined in self.namespace or self.global_namespace that match. |
|
161 | defined in self.namespace or self.global_namespace that match. | |
162 |
|
162 | |||
163 | """ |
|
163 | """ | |
164 | matches = [] |
|
164 | matches = [] | |
165 | match_append = matches.append |
|
165 | match_append = matches.append | |
166 | n = len(text) |
|
166 | n = len(text) | |
167 | for lst in [keyword.kwlist, |
|
167 | for lst in [keyword.kwlist, | |
168 | __builtin__.__dict__.keys(), |
|
168 | __builtin__.__dict__.keys(), | |
169 | self.namespace.keys(), |
|
169 | self.namespace.keys(), | |
170 | self.global_namespace.keys()]: |
|
170 | self.global_namespace.keys()]: | |
171 | for word in lst: |
|
171 | for word in lst: | |
172 | if word[:n] == text and word != "__builtins__": |
|
172 | if word[:n] == text and word != "__builtins__": | |
173 | match_append(word) |
|
173 | match_append(word) | |
174 | return matches |
|
174 | return matches | |
175 |
|
175 | |||
176 | def attr_matches(self, text): |
|
176 | def attr_matches(self, text): | |
177 | """Compute matches when text contains a dot. |
|
177 | """Compute matches when text contains a dot. | |
178 |
|
178 | |||
179 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
179 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
180 | evaluatable in self.namespace or self.global_namespace, it will be |
|
180 | evaluatable in self.namespace or self.global_namespace, it will be | |
181 | evaluated and its attributes (as revealed by dir()) are used as |
|
181 | evaluated and its attributes (as revealed by dir()) are used as | |
182 | possible completions. (For class instances, class members are are |
|
182 | possible completions. (For class instances, class members are are | |
183 | also considered.) |
|
183 | also considered.) | |
184 |
|
184 | |||
185 | WARNING: this can still invoke arbitrary C code, if an object |
|
185 | WARNING: this can still invoke arbitrary C code, if an object | |
186 | with a __getattr__ hook is evaluated. |
|
186 | with a __getattr__ hook is evaluated. | |
187 |
|
187 | |||
188 | """ |
|
188 | """ | |
189 | import re |
|
189 | import re | |
190 |
|
190 | |||
191 | # Another option, seems to work great. Catches things like ''.<tab> |
|
191 | # Another option, seems to work great. Catches things like ''.<tab> | |
192 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
192 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
193 |
|
193 | |||
194 | if not m: |
|
194 | if not m: | |
195 | return [] |
|
195 | return [] | |
196 |
|
196 | |||
197 | expr, attr = m.group(1, 3) |
|
197 | expr, attr = m.group(1, 3) | |
198 | try: |
|
198 | try: | |
199 | object = eval(expr, self.namespace) |
|
199 | object = eval(expr, self.namespace) | |
200 | except: |
|
200 | except: | |
201 | object = eval(expr, self.global_namespace) |
|
201 | object = eval(expr, self.global_namespace) | |
202 |
|
202 | |||
203 | # Start building the attribute list via dir(), and then complete it |
|
203 | # Start building the attribute list via dir(), and then complete it | |
204 | # with a few extra special-purpose calls. |
|
204 | # with a few extra special-purpose calls. | |
205 | words = dir(object) |
|
205 | words = dir(object) | |
206 |
|
206 | |||
207 | if hasattr(object,'__class__'): |
|
207 | if hasattr(object,'__class__'): | |
208 | words.append('__class__') |
|
208 | words.append('__class__') | |
209 | words.extend(get_class_members(object.__class__)) |
|
209 | words.extend(get_class_members(object.__class__)) | |
210 |
|
210 | |||
211 | # this is the 'dir' function for objects with Enthought's traits |
|
211 | # this is the 'dir' function for objects with Enthought's traits | |
212 | if hasattr(object, 'trait_names'): |
|
212 | if hasattr(object, 'trait_names'): | |
213 | try: |
|
213 | try: | |
214 | words.extend(object.trait_names()) |
|
214 | words.extend(object.trait_names()) | |
215 | # eliminate possible duplicates, as some traits may also |
|
215 | # eliminate possible duplicates, as some traits may also | |
216 | # appear as normal attributes in the dir() call. |
|
216 | # appear as normal attributes in the dir() call. | |
217 | words = set(words) |
|
217 | words = set(words) | |
218 | except TypeError: |
|
218 | except TypeError: | |
219 | # This will happen if `object` is a class and not an instance. |
|
219 | # This will happen if `object` is a class and not an instance. | |
220 | pass |
|
220 | pass | |
221 |
|
221 | |||
|
222 | # Support for PyCrust-style _getAttributeNames magic method. | |||
|
223 | if hasattr(object, '_getAttributeNames'): | |||
|
224 | try: | |||
|
225 | words.extend(object._getAttributeNames()) | |||
|
226 | # Eliminate duplicates. | |||
|
227 | words = set(words) | |||
|
228 | except TypeError: | |||
|
229 | # `object` is a class and not an instance. Ignore | |||
|
230 | # this error. | |||
|
231 | pass | |||
|
232 | ||||
222 | # filter out non-string attributes which may be stuffed by dir() calls |
|
233 | # filter out non-string attributes which may be stuffed by dir() calls | |
223 | # and poor coding in third-party modules |
|
234 | # and poor coding in third-party modules | |
224 | words = [w for w in words |
|
235 | words = [w for w in words | |
225 | if isinstance(w, basestring) and w != "__builtins__"] |
|
236 | if isinstance(w, basestring) and w != "__builtins__"] | |
226 | # Build match list to return |
|
237 | # Build match list to return | |
227 | n = len(attr) |
|
238 | n = len(attr) | |
228 | return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
239 | return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
229 |
|
240 | |||
230 | class IPCompleter(Completer): |
|
241 | class IPCompleter(Completer): | |
231 | """Extension of the completer class with IPython-specific features""" |
|
242 | """Extension of the completer class with IPython-specific features""" | |
232 |
|
243 | |||
233 | def __init__(self,shell,namespace=None,global_namespace=None, |
|
244 | def __init__(self,shell,namespace=None,global_namespace=None, | |
234 | omit__names=0,alias_table=None): |
|
245 | omit__names=0,alias_table=None): | |
235 | """IPCompleter() -> completer |
|
246 | """IPCompleter() -> completer | |
236 |
|
247 | |||
237 | Return a completer object suitable for use by the readline library |
|
248 | Return a completer object suitable for use by the readline library | |
238 | via readline.set_completer(). |
|
249 | via readline.set_completer(). | |
239 |
|
250 | |||
240 | Inputs: |
|
251 | Inputs: | |
241 |
|
252 | |||
242 | - shell: a pointer to the ipython shell itself. This is needed |
|
253 | - shell: a pointer to the ipython shell itself. This is needed | |
243 | because this completer knows about magic functions, and those can |
|
254 | because this completer knows about magic functions, and those can | |
244 | only be accessed via the ipython instance. |
|
255 | only be accessed via the ipython instance. | |
245 |
|
256 | |||
246 | - namespace: an optional dict where completions are performed. |
|
257 | - namespace: an optional dict where completions are performed. | |
247 |
|
258 | |||
248 | - global_namespace: secondary optional dict for completions, to |
|
259 | - global_namespace: secondary optional dict for completions, to | |
249 | handle cases (such as IPython embedded inside functions) where |
|
260 | handle cases (such as IPython embedded inside functions) where | |
250 | both Python scopes are visible. |
|
261 | both Python scopes are visible. | |
251 |
|
262 | |||
252 | - The optional omit__names parameter sets the completer to omit the |
|
263 | - The optional omit__names parameter sets the completer to omit the | |
253 | 'magic' names (__magicname__) for python objects unless the text |
|
264 | 'magic' names (__magicname__) for python objects unless the text | |
254 | to be completed explicitly starts with one or more underscores. |
|
265 | to be completed explicitly starts with one or more underscores. | |
255 |
|
266 | |||
256 | - If alias_table is supplied, it should be a dictionary of aliases |
|
267 | - If alias_table is supplied, it should be a dictionary of aliases | |
257 | to complete. """ |
|
268 | to complete. """ | |
258 |
|
269 | |||
259 | Completer.__init__(self,namespace,global_namespace) |
|
270 | Completer.__init__(self,namespace,global_namespace) | |
260 | self.magic_prefix = shell.name+'.magic_' |
|
271 | self.magic_prefix = shell.name+'.magic_' | |
261 | self.magic_escape = shell.ESC_MAGIC |
|
272 | self.magic_escape = shell.ESC_MAGIC | |
262 | self.readline = readline |
|
273 | self.readline = readline | |
263 | delims = self.readline.get_completer_delims() |
|
274 | delims = self.readline.get_completer_delims() | |
264 | delims = delims.replace(self.magic_escape,'') |
|
275 | delims = delims.replace(self.magic_escape,'') | |
265 | self.readline.set_completer_delims(delims) |
|
276 | self.readline.set_completer_delims(delims) | |
266 | self.get_line_buffer = self.readline.get_line_buffer |
|
277 | self.get_line_buffer = self.readline.get_line_buffer | |
267 | self.omit__names = omit__names |
|
278 | self.omit__names = omit__names | |
268 | self.merge_completions = shell.rc.readline_merge_completions |
|
279 | self.merge_completions = shell.rc.readline_merge_completions | |
269 |
|
280 | |||
270 | if alias_table is None: |
|
281 | if alias_table is None: | |
271 | alias_table = {} |
|
282 | alias_table = {} | |
272 | self.alias_table = alias_table |
|
283 | self.alias_table = alias_table | |
273 | # Regexp to split filenames with spaces in them |
|
284 | # Regexp to split filenames with spaces in them | |
274 | self.space_name_re = re.compile(r'([^\\] )') |
|
285 | self.space_name_re = re.compile(r'([^\\] )') | |
275 | # Hold a local ref. to glob.glob for speed |
|
286 | # Hold a local ref. to glob.glob for speed | |
276 | self.glob = glob.glob |
|
287 | self.glob = glob.glob | |
277 |
|
288 | |||
278 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
289 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
279 | # buffers, to avoid completion problems. |
|
290 | # buffers, to avoid completion problems. | |
280 | term = os.environ.get('TERM','xterm') |
|
291 | term = os.environ.get('TERM','xterm') | |
281 | self.dumb_terminal = term in ['dumb','emacs'] |
|
292 | self.dumb_terminal = term in ['dumb','emacs'] | |
282 |
|
293 | |||
283 | # Special handling of backslashes needed in win32 platforms |
|
294 | # Special handling of backslashes needed in win32 platforms | |
284 | if sys.platform == "win32": |
|
295 | if sys.platform == "win32": | |
285 | self.clean_glob = self._clean_glob_win32 |
|
296 | self.clean_glob = self._clean_glob_win32 | |
286 | else: |
|
297 | else: | |
287 | self.clean_glob = self._clean_glob |
|
298 | self.clean_glob = self._clean_glob | |
288 | self.matchers = [self.python_matches, |
|
299 | self.matchers = [self.python_matches, | |
289 | self.file_matches, |
|
300 | self.file_matches, | |
290 | self.alias_matches, |
|
301 | self.alias_matches, | |
291 | self.python_func_kw_matches] |
|
302 | self.python_func_kw_matches] | |
292 |
|
303 | |||
293 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
304 | # Code contributed by Alex Schmolck, for ipython/emacs integration | |
294 | def all_completions(self, text): |
|
305 | def all_completions(self, text): | |
295 | """Return all possible completions for the benefit of emacs.""" |
|
306 | """Return all possible completions for the benefit of emacs.""" | |
296 |
|
307 | |||
297 | completions = [] |
|
308 | completions = [] | |
298 | comp_append = completions.append |
|
309 | comp_append = completions.append | |
299 | try: |
|
310 | try: | |
300 | for i in xrange(sys.maxint): |
|
311 | for i in xrange(sys.maxint): | |
301 | res = self.complete(text, i) |
|
312 | res = self.complete(text, i) | |
302 |
|
313 | |||
303 | if not res: break |
|
314 | if not res: break | |
304 |
|
315 | |||
305 | comp_append(res) |
|
316 | comp_append(res) | |
306 | #XXX workaround for ``notDefined.<tab>`` |
|
317 | #XXX workaround for ``notDefined.<tab>`` | |
307 | except NameError: |
|
318 | except NameError: | |
308 | pass |
|
319 | pass | |
309 | return completions |
|
320 | return completions | |
310 | # /end Alex Schmolck code. |
|
321 | # /end Alex Schmolck code. | |
311 |
|
322 | |||
312 | def _clean_glob(self,text): |
|
323 | def _clean_glob(self,text): | |
313 | return self.glob("%s*" % text) |
|
324 | return self.glob("%s*" % text) | |
314 |
|
325 | |||
315 | def _clean_glob_win32(self,text): |
|
326 | def _clean_glob_win32(self,text): | |
316 | return [f.replace("\\","/") |
|
327 | return [f.replace("\\","/") | |
317 | for f in self.glob("%s*" % text)] |
|
328 | for f in self.glob("%s*" % text)] | |
318 |
|
329 | |||
319 | def file_matches(self, text): |
|
330 | def file_matches(self, text): | |
320 | """Match filneames, expanding ~USER type strings. |
|
331 | """Match filneames, expanding ~USER type strings. | |
321 |
|
332 | |||
322 | Most of the seemingly convoluted logic in this completer is an |
|
333 | Most of the seemingly convoluted logic in this completer is an | |
323 | attempt to handle filenames with spaces in them. And yet it's not |
|
334 | attempt to handle filenames with spaces in them. And yet it's not | |
324 | quite perfect, because Python's readline doesn't expose all of the |
|
335 | quite perfect, because Python's readline doesn't expose all of the | |
325 | GNU readline details needed for this to be done correctly. |
|
336 | GNU readline details needed for this to be done correctly. | |
326 |
|
337 | |||
327 | For a filename with a space in it, the printed completions will be |
|
338 | For a filename with a space in it, the printed completions will be | |
328 | only the parts after what's already been typed (instead of the |
|
339 | only the parts after what's already been typed (instead of the | |
329 | full completions, as is normally done). I don't think with the |
|
340 | full completions, as is normally done). I don't think with the | |
330 | current (as of Python 2.3) Python readline it's possible to do |
|
341 | current (as of Python 2.3) Python readline it's possible to do | |
331 | better.""" |
|
342 | better.""" | |
332 |
|
343 | |||
333 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
344 | #print 'Completer->file_matches: <%s>' % text # dbg | |
334 |
|
345 | |||
335 | # chars that require escaping with backslash - i.e. chars |
|
346 | # chars that require escaping with backslash - i.e. chars | |
336 | # that readline treats incorrectly as delimiters, but we |
|
347 | # that readline treats incorrectly as delimiters, but we | |
337 | # don't want to treat as delimiters in filename matching |
|
348 | # don't want to treat as delimiters in filename matching | |
338 | # when escaped with backslash |
|
349 | # when escaped with backslash | |
339 |
|
350 | |||
340 | protectables = ' ()[]{}' |
|
351 | protectables = ' ()[]{}' | |
341 |
|
352 | |||
342 | def protect_filename(s): |
|
353 | def protect_filename(s): | |
343 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
354 | return "".join([(ch in protectables and '\\' + ch or ch) | |
344 | for ch in s]) |
|
355 | for ch in s]) | |
345 |
|
356 | |||
346 | lbuf = self.lbuf |
|
357 | lbuf = self.lbuf | |
347 | open_quotes = 0 # track strings with open quotes |
|
358 | open_quotes = 0 # track strings with open quotes | |
348 | try: |
|
359 | try: | |
349 | lsplit = shlex.split(lbuf)[-1] |
|
360 | lsplit = shlex.split(lbuf)[-1] | |
350 | except ValueError: |
|
361 | except ValueError: | |
351 | # typically an unmatched ", or backslash without escaped char. |
|
362 | # typically an unmatched ", or backslash without escaped char. | |
352 | if lbuf.count('"')==1: |
|
363 | if lbuf.count('"')==1: | |
353 | open_quotes = 1 |
|
364 | open_quotes = 1 | |
354 | lsplit = lbuf.split('"')[-1] |
|
365 | lsplit = lbuf.split('"')[-1] | |
355 | elif lbuf.count("'")==1: |
|
366 | elif lbuf.count("'")==1: | |
356 | open_quotes = 1 |
|
367 | open_quotes = 1 | |
357 | lsplit = lbuf.split("'")[-1] |
|
368 | lsplit = lbuf.split("'")[-1] | |
358 | else: |
|
369 | else: | |
359 | return None |
|
370 | return None | |
360 | except IndexError: |
|
371 | except IndexError: | |
361 | # tab pressed on empty line |
|
372 | # tab pressed on empty line | |
362 | lsplit = "" |
|
373 | lsplit = "" | |
363 |
|
374 | |||
364 | if lsplit != protect_filename(lsplit): |
|
375 | if lsplit != protect_filename(lsplit): | |
365 | # if protectables are found, do matching on the whole escaped |
|
376 | # if protectables are found, do matching on the whole escaped | |
366 | # name |
|
377 | # name | |
367 | has_protectables = 1 |
|
378 | has_protectables = 1 | |
368 | text0,text = text,lsplit |
|
379 | text0,text = text,lsplit | |
369 | else: |
|
380 | else: | |
370 | has_protectables = 0 |
|
381 | has_protectables = 0 | |
371 | text = os.path.expanduser(text) |
|
382 | text = os.path.expanduser(text) | |
372 |
|
383 | |||
373 | if text == "": |
|
384 | if text == "": | |
374 | return [protect_filename(f) for f in self.glob("*")] |
|
385 | return [protect_filename(f) for f in self.glob("*")] | |
375 |
|
386 | |||
376 | m0 = self.clean_glob(text.replace('\\','')) |
|
387 | m0 = self.clean_glob(text.replace('\\','')) | |
377 | if has_protectables: |
|
388 | if has_protectables: | |
378 | # If we had protectables, we need to revert our changes to the |
|
389 | # If we had protectables, we need to revert our changes to the | |
379 | # beginning of filename so that we don't double-write the part |
|
390 | # beginning of filename so that we don't double-write the part | |
380 | # of the filename we have so far |
|
391 | # of the filename we have so far | |
381 | len_lsplit = len(lsplit) |
|
392 | len_lsplit = len(lsplit) | |
382 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] |
|
393 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] | |
383 | else: |
|
394 | else: | |
384 | if open_quotes: |
|
395 | if open_quotes: | |
385 | # if we have a string with an open quote, we don't need to |
|
396 | # if we have a string with an open quote, we don't need to | |
386 | # protect the names at all (and we _shouldn't_, as it |
|
397 | # protect the names at all (and we _shouldn't_, as it | |
387 | # would cause bugs when the filesystem call is made). |
|
398 | # would cause bugs when the filesystem call is made). | |
388 | matches = m0 |
|
399 | matches = m0 | |
389 | else: |
|
400 | else: | |
390 | matches = [protect_filename(f) for f in m0] |
|
401 | matches = [protect_filename(f) for f in m0] | |
391 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
402 | if len(matches) == 1 and os.path.isdir(matches[0]): | |
392 | # Takes care of links to directories also. Use '/' |
|
403 | # Takes care of links to directories also. Use '/' | |
393 | # explicitly, even under Windows, so that name completions |
|
404 | # explicitly, even under Windows, so that name completions | |
394 | # don't end up escaped. |
|
405 | # don't end up escaped. | |
395 | matches[0] += '/' |
|
406 | matches[0] += '/' | |
396 | return matches |
|
407 | return matches | |
397 |
|
408 | |||
398 | def alias_matches(self, text): |
|
409 | def alias_matches(self, text): | |
399 | """Match internal system aliases""" |
|
410 | """Match internal system aliases""" | |
400 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg |
|
411 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg | |
401 |
|
412 | |||
402 | # if we are not in the first 'item', alias matching |
|
413 | # if we are not in the first 'item', alias matching | |
403 | # doesn't make sense |
|
414 | # doesn't make sense | |
404 | if ' ' in self.lbuf: |
|
415 | if ' ' in self.lbuf: | |
405 | return [] |
|
416 | return [] | |
406 | text = os.path.expanduser(text) |
|
417 | text = os.path.expanduser(text) | |
407 | aliases = self.alias_table.keys() |
|
418 | aliases = self.alias_table.keys() | |
408 | if text == "": |
|
419 | if text == "": | |
409 | return aliases |
|
420 | return aliases | |
410 | else: |
|
421 | else: | |
411 | return [alias for alias in aliases if alias.startswith(text)] |
|
422 | return [alias for alias in aliases if alias.startswith(text)] | |
412 |
|
423 | |||
413 | def python_matches(self,text): |
|
424 | def python_matches(self,text): | |
414 | """Match attributes or global python names""" |
|
425 | """Match attributes or global python names""" | |
415 |
|
426 | |||
416 | #print 'Completer->python_matches, txt=<%s>' % text # dbg |
|
427 | #print 'Completer->python_matches, txt=<%s>' % text # dbg | |
417 | if "." in text: |
|
428 | if "." in text: | |
418 | try: |
|
429 | try: | |
419 | matches = self.attr_matches(text) |
|
430 | matches = self.attr_matches(text) | |
420 | if text.endswith('.') and self.omit__names: |
|
431 | if text.endswith('.') and self.omit__names: | |
421 | if self.omit__names == 1: |
|
432 | if self.omit__names == 1: | |
422 | # true if txt is _not_ a __ name, false otherwise: |
|
433 | # true if txt is _not_ a __ name, false otherwise: | |
423 | no__name = (lambda txt: |
|
434 | no__name = (lambda txt: | |
424 | re.match(r'.*\.__.*?__',txt) is None) |
|
435 | re.match(r'.*\.__.*?__',txt) is None) | |
425 | else: |
|
436 | else: | |
426 | # true if txt is _not_ a _ name, false otherwise: |
|
437 | # true if txt is _not_ a _ name, false otherwise: | |
427 | no__name = (lambda txt: |
|
438 | no__name = (lambda txt: | |
428 | re.match(r'.*\._.*?',txt) is None) |
|
439 | re.match(r'.*\._.*?',txt) is None) | |
429 | matches = filter(no__name, matches) |
|
440 | matches = filter(no__name, matches) | |
430 | except NameError: |
|
441 | except NameError: | |
431 | # catches <undefined attributes>.<tab> |
|
442 | # catches <undefined attributes>.<tab> | |
432 | matches = [] |
|
443 | matches = [] | |
433 | else: |
|
444 | else: | |
434 | matches = self.global_matches(text) |
|
445 | matches = self.global_matches(text) | |
435 | # this is so completion finds magics when automagic is on: |
|
446 | # this is so completion finds magics when automagic is on: | |
436 | if (matches == [] and |
|
447 | if (matches == [] and | |
437 | not text.startswith(os.sep) and |
|
448 | not text.startswith(os.sep) and | |
438 | not ' ' in self.lbuf): |
|
449 | not ' ' in self.lbuf): | |
439 | matches = self.attr_matches(self.magic_prefix+text) |
|
450 | matches = self.attr_matches(self.magic_prefix+text) | |
440 | return matches |
|
451 | return matches | |
441 |
|
452 | |||
442 | def _default_arguments(self, obj): |
|
453 | def _default_arguments(self, obj): | |
443 | """Return the list of default arguments of obj if it is callable, |
|
454 | """Return the list of default arguments of obj if it is callable, | |
444 | or empty list otherwise.""" |
|
455 | or empty list otherwise.""" | |
445 |
|
456 | |||
446 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
457 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
447 | # for classes, check for __init__,__new__ |
|
458 | # for classes, check for __init__,__new__ | |
448 | if inspect.isclass(obj): |
|
459 | if inspect.isclass(obj): | |
449 | obj = (getattr(obj,'__init__',None) or |
|
460 | obj = (getattr(obj,'__init__',None) or | |
450 | getattr(obj,'__new__',None)) |
|
461 | getattr(obj,'__new__',None)) | |
451 | # for all others, check if they are __call__able |
|
462 | # for all others, check if they are __call__able | |
452 | elif hasattr(obj, '__call__'): |
|
463 | elif hasattr(obj, '__call__'): | |
453 | obj = obj.__call__ |
|
464 | obj = obj.__call__ | |
454 | # XXX: is there a way to handle the builtins ? |
|
465 | # XXX: is there a way to handle the builtins ? | |
455 | try: |
|
466 | try: | |
456 | args,_,_1,defaults = inspect.getargspec(obj) |
|
467 | args,_,_1,defaults = inspect.getargspec(obj) | |
457 | if defaults: |
|
468 | if defaults: | |
458 | return args[-len(defaults):] |
|
469 | return args[-len(defaults):] | |
459 | except TypeError: pass |
|
470 | except TypeError: pass | |
460 | return [] |
|
471 | return [] | |
461 |
|
472 | |||
462 | def python_func_kw_matches(self,text): |
|
473 | def python_func_kw_matches(self,text): | |
463 | """Match named parameters (kwargs) of the last open function""" |
|
474 | """Match named parameters (kwargs) of the last open function""" | |
464 |
|
475 | |||
465 | if "." in text: # a parameter cannot be dotted |
|
476 | if "." in text: # a parameter cannot be dotted | |
466 | return [] |
|
477 | return [] | |
467 | try: regexp = self.__funcParamsRegex |
|
478 | try: regexp = self.__funcParamsRegex | |
468 | except AttributeError: |
|
479 | except AttributeError: | |
469 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
480 | regexp = self.__funcParamsRegex = re.compile(r''' | |
470 | '.*?' | # single quoted strings or |
|
481 | '.*?' | # single quoted strings or | |
471 | ".*?" | # double quoted strings or |
|
482 | ".*?" | # double quoted strings or | |
472 | \w+ | # identifier |
|
483 | \w+ | # identifier | |
473 | \S # other characters |
|
484 | \S # other characters | |
474 | ''', re.VERBOSE | re.DOTALL) |
|
485 | ''', re.VERBOSE | re.DOTALL) | |
475 | # 1. find the nearest identifier that comes before an unclosed |
|
486 | # 1. find the nearest identifier that comes before an unclosed | |
476 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
487 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" | |
477 | tokens = regexp.findall(self.get_line_buffer()) |
|
488 | tokens = regexp.findall(self.get_line_buffer()) | |
478 | tokens.reverse() |
|
489 | tokens.reverse() | |
479 | iterTokens = iter(tokens); openPar = 0 |
|
490 | iterTokens = iter(tokens); openPar = 0 | |
480 | for token in iterTokens: |
|
491 | for token in iterTokens: | |
481 | if token == ')': |
|
492 | if token == ')': | |
482 | openPar -= 1 |
|
493 | openPar -= 1 | |
483 | elif token == '(': |
|
494 | elif token == '(': | |
484 | openPar += 1 |
|
495 | openPar += 1 | |
485 | if openPar > 0: |
|
496 | if openPar > 0: | |
486 | # found the last unclosed parenthesis |
|
497 | # found the last unclosed parenthesis | |
487 | break |
|
498 | break | |
488 | else: |
|
499 | else: | |
489 | return [] |
|
500 | return [] | |
490 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
501 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
491 | ids = [] |
|
502 | ids = [] | |
492 | isId = re.compile(r'\w+$').match |
|
503 | isId = re.compile(r'\w+$').match | |
493 | while True: |
|
504 | while True: | |
494 | try: |
|
505 | try: | |
495 | ids.append(iterTokens.next()) |
|
506 | ids.append(iterTokens.next()) | |
496 | if not isId(ids[-1]): |
|
507 | if not isId(ids[-1]): | |
497 | ids.pop(); break |
|
508 | ids.pop(); break | |
498 | if not iterTokens.next() == '.': |
|
509 | if not iterTokens.next() == '.': | |
499 | break |
|
510 | break | |
500 | except StopIteration: |
|
511 | except StopIteration: | |
501 | break |
|
512 | break | |
502 | # lookup the candidate callable matches either using global_matches |
|
513 | # lookup the candidate callable matches either using global_matches | |
503 | # or attr_matches for dotted names |
|
514 | # or attr_matches for dotted names | |
504 | if len(ids) == 1: |
|
515 | if len(ids) == 1: | |
505 | callableMatches = self.global_matches(ids[0]) |
|
516 | callableMatches = self.global_matches(ids[0]) | |
506 | else: |
|
517 | else: | |
507 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
518 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
508 | argMatches = [] |
|
519 | argMatches = [] | |
509 | for callableMatch in callableMatches: |
|
520 | for callableMatch in callableMatches: | |
510 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
521 | try: namedArgs = self._default_arguments(eval(callableMatch, | |
511 | self.namespace)) |
|
522 | self.namespace)) | |
512 | except: continue |
|
523 | except: continue | |
513 | for namedArg in namedArgs: |
|
524 | for namedArg in namedArgs: | |
514 | if namedArg.startswith(text): |
|
525 | if namedArg.startswith(text): | |
515 | argMatches.append("%s=" %namedArg) |
|
526 | argMatches.append("%s=" %namedArg) | |
516 | return argMatches |
|
527 | return argMatches | |
517 |
|
528 | |||
518 | def complete(self, text, state): |
|
529 | def complete(self, text, state): | |
519 | """Return the next possible completion for 'text'. |
|
530 | """Return the next possible completion for 'text'. | |
520 |
|
531 | |||
521 | This is called successively with state == 0, 1, 2, ... until it |
|
532 | This is called successively with state == 0, 1, 2, ... until it | |
522 | returns None. The completion should begin with 'text'. """ |
|
533 | returns None. The completion should begin with 'text'. """ | |
523 |
|
534 | |||
524 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
535 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg | |
525 |
|
536 | |||
526 | # if there is only a tab on a line with only whitespace, instead |
|
537 | # if there is only a tab on a line with only whitespace, instead | |
527 | # of the mostly useless 'do you want to see all million |
|
538 | # of the mostly useless 'do you want to see all million | |
528 | # completions' message, just do the right thing and give the user |
|
539 | # completions' message, just do the right thing and give the user | |
529 | # his tab! Incidentally, this enables pasting of tabbed text from |
|
540 | # his tab! Incidentally, this enables pasting of tabbed text from | |
530 | # an editor (as long as autoindent is off). |
|
541 | # an editor (as long as autoindent is off). | |
531 |
|
542 | |||
532 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we |
|
543 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we | |
533 | # don't interfere with their own tab-completion mechanism. |
|
544 | # don't interfere with their own tab-completion mechanism. | |
534 | self.lbuf = self.get_line_buffer()[:self.readline.get_endidx()] |
|
545 | self.lbuf = self.get_line_buffer()[:self.readline.get_endidx()] | |
535 | if not (self.dumb_terminal or self.get_line_buffer().strip()): |
|
546 | if not (self.dumb_terminal or self.get_line_buffer().strip()): | |
536 | self.readline.insert_text('\t') |
|
547 | self.readline.insert_text('\t') | |
537 | return None |
|
548 | return None | |
538 |
|
549 | |||
539 | magic_escape = self.magic_escape |
|
550 | magic_escape = self.magic_escape | |
540 | magic_prefix = self.magic_prefix |
|
551 | magic_prefix = self.magic_prefix | |
541 |
|
552 | |||
542 | try: |
|
553 | try: | |
543 | if text.startswith(magic_escape): |
|
554 | if text.startswith(magic_escape): | |
544 | text = text.replace(magic_escape,magic_prefix) |
|
555 | text = text.replace(magic_escape,magic_prefix) | |
545 | elif text.startswith('~'): |
|
556 | elif text.startswith('~'): | |
546 | text = os.path.expanduser(text) |
|
557 | text = os.path.expanduser(text) | |
547 | if state == 0: |
|
558 | if state == 0: | |
548 | # Extend the list of completions with the results of each |
|
559 | # Extend the list of completions with the results of each | |
549 | # matcher, so we return results to the user from all |
|
560 | # matcher, so we return results to the user from all | |
550 | # namespaces. |
|
561 | # namespaces. | |
551 | if self.merge_completions: |
|
562 | if self.merge_completions: | |
552 | self.matches = [] |
|
563 | self.matches = [] | |
553 | for matcher in self.matchers: |
|
564 | for matcher in self.matchers: | |
554 | self.matches.extend(matcher(text)) |
|
565 | self.matches.extend(matcher(text)) | |
555 | else: |
|
566 | else: | |
556 | for matcher in self.matchers: |
|
567 | for matcher in self.matchers: | |
557 | self.matches = matcher(text) |
|
568 | self.matches = matcher(text) | |
558 | if self.matches: |
|
569 | if self.matches: | |
559 | break |
|
570 | break | |
560 |
|
571 | |||
561 | try: |
|
572 | try: | |
562 | return self.matches[state].replace(magic_prefix,magic_escape) |
|
573 | return self.matches[state].replace(magic_prefix,magic_escape) | |
563 | except IndexError: |
|
574 | except IndexError: | |
564 | return None |
|
575 | return None | |
565 | except: |
|
576 | except: | |
566 | #from IPython.ultraTB import AutoFormattedTB; # dbg |
|
577 | #from IPython.ultraTB import AutoFormattedTB; # dbg | |
567 | #tb=AutoFormattedTB('Verbose');tb() #dbg |
|
578 | #tb=AutoFormattedTB('Verbose');tb() #dbg | |
568 |
|
579 | |||
569 | # If completion fails, don't annoy the user. |
|
580 | # If completion fails, don't annoy the user. | |
570 | return None |
|
581 | return None |
@@ -1,1703 +1,1708 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | General purpose utilities. |
|
3 | General purpose utilities. | |
4 |
|
4 | |||
5 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
5 | This is a grab-bag of stuff I find useful in most programs I write. Some of | |
6 | these things are also convenient when working at the command line. |
|
6 | these things are also convenient when working at the command line. | |
7 |
|
7 | |||
8 |
$Id: genutils.py 13 |
|
8 | $Id: genutils.py 1322 2006-05-24 07:51:39Z fperez $""" | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
19 | __license__ = Release.license |
|
19 | __license__ = Release.license | |
20 |
|
20 | |||
21 | #**************************************************************************** |
|
21 | #**************************************************************************** | |
22 | # required modules from the Python standard library |
|
22 | # required modules from the Python standard library | |
23 | import __main__ |
|
23 | import __main__ | |
24 | import commands |
|
24 | import commands | |
25 | import os |
|
25 | import os | |
26 | import re |
|
26 | import re | |
27 | import shutil |
|
27 | import shutil | |
28 | import sys |
|
28 | import sys | |
29 | import tempfile |
|
29 | import tempfile | |
30 | import time |
|
30 | import time | |
31 | import types |
|
31 | import types | |
32 |
|
32 | |||
33 | # Other IPython utilities |
|
33 | # Other IPython utilities | |
34 | from IPython.Itpl import Itpl,itpl,printpl |
|
34 | from IPython.Itpl import Itpl,itpl,printpl | |
35 | from IPython import DPyGetOpt |
|
35 | from IPython import DPyGetOpt | |
36 | from path import path |
|
36 | from path import path | |
37 | if os.name == "nt": |
|
37 | if os.name == "nt": | |
38 | from IPython.winconsole import get_console_size |
|
38 | from IPython.winconsole import get_console_size | |
39 |
|
39 | |||
40 | #**************************************************************************** |
|
40 | #**************************************************************************** | |
41 | # Exceptions |
|
41 | # Exceptions | |
42 | class Error(Exception): |
|
42 | class Error(Exception): | |
43 | """Base class for exceptions in this module.""" |
|
43 | """Base class for exceptions in this module.""" | |
44 | pass |
|
44 | pass | |
45 |
|
45 | |||
46 | #---------------------------------------------------------------------------- |
|
46 | #---------------------------------------------------------------------------- | |
47 | class IOStream: |
|
47 | class IOStream: | |
48 | def __init__(self,stream,fallback): |
|
48 | def __init__(self,stream,fallback): | |
49 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
49 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): | |
50 | stream = fallback |
|
50 | stream = fallback | |
51 | self.stream = stream |
|
51 | self.stream = stream | |
52 | self._swrite = stream.write |
|
52 | self._swrite = stream.write | |
53 | self.flush = stream.flush |
|
53 | self.flush = stream.flush | |
54 |
|
54 | |||
55 | def write(self,data): |
|
55 | def write(self,data): | |
56 | try: |
|
56 | try: | |
57 | self._swrite(data) |
|
57 | self._swrite(data) | |
58 | except: |
|
58 | except: | |
59 | try: |
|
59 | try: | |
60 | # print handles some unicode issues which may trip a plain |
|
60 | # print handles some unicode issues which may trip a plain | |
61 | # write() call. Attempt to emulate write() by using a |
|
61 | # write() call. Attempt to emulate write() by using a | |
62 | # trailing comma |
|
62 | # trailing comma | |
63 | print >> self.stream, data, |
|
63 | print >> self.stream, data, | |
64 | except: |
|
64 | except: | |
65 | # if we get here, something is seriously broken. |
|
65 | # if we get here, something is seriously broken. | |
66 | print >> sys.stderr, \ |
|
66 | print >> sys.stderr, \ | |
67 | 'ERROR - failed to write data to stream:', self.stream |
|
67 | 'ERROR - failed to write data to stream:', self.stream | |
68 |
|
68 | |||
69 | class IOTerm: |
|
69 | class IOTerm: | |
70 | """ Term holds the file or file-like objects for handling I/O operations. |
|
70 | """ Term holds the file or file-like objects for handling I/O operations. | |
71 |
|
71 | |||
72 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
72 | These are normally just sys.stdin, sys.stdout and sys.stderr but for | |
73 | Windows they can can replaced to allow editing the strings before they are |
|
73 | Windows they can can replaced to allow editing the strings before they are | |
74 | displayed.""" |
|
74 | displayed.""" | |
75 |
|
75 | |||
76 | # In the future, having IPython channel all its I/O operations through |
|
76 | # In the future, having IPython channel all its I/O operations through | |
77 | # this class will make it easier to embed it into other environments which |
|
77 | # this class will make it easier to embed it into other environments which | |
78 | # are not a normal terminal (such as a GUI-based shell) |
|
78 | # are not a normal terminal (such as a GUI-based shell) | |
79 | def __init__(self,cin=None,cout=None,cerr=None): |
|
79 | def __init__(self,cin=None,cout=None,cerr=None): | |
80 | self.cin = IOStream(cin,sys.stdin) |
|
80 | self.cin = IOStream(cin,sys.stdin) | |
81 | self.cout = IOStream(cout,sys.stdout) |
|
81 | self.cout = IOStream(cout,sys.stdout) | |
82 | self.cerr = IOStream(cerr,sys.stderr) |
|
82 | self.cerr = IOStream(cerr,sys.stderr) | |
83 |
|
83 | |||
84 | # Global variable to be used for all I/O |
|
84 | # Global variable to be used for all I/O | |
85 | Term = IOTerm() |
|
85 | Term = IOTerm() | |
86 |
|
86 | |||
87 | import IPython.rlineimpl as readline |
|
87 | import IPython.rlineimpl as readline | |
88 | # Remake Term to use the readline i/o facilities |
|
88 | # Remake Term to use the readline i/o facilities | |
89 | if sys.platform == 'win32' and readline.have_readline: |
|
89 | if sys.platform == 'win32' and readline.have_readline: | |
90 |
|
90 | |||
91 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) |
|
91 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) | |
92 |
|
92 | |||
93 |
|
93 | |||
94 | #**************************************************************************** |
|
94 | #**************************************************************************** | |
95 | # Generic warning/error printer, used by everything else |
|
95 | # Generic warning/error printer, used by everything else | |
96 | def warn(msg,level=2,exit_val=1): |
|
96 | def warn(msg,level=2,exit_val=1): | |
97 | """Standard warning printer. Gives formatting consistency. |
|
97 | """Standard warning printer. Gives formatting consistency. | |
98 |
|
98 | |||
99 | Output is sent to Term.cerr (sys.stderr by default). |
|
99 | Output is sent to Term.cerr (sys.stderr by default). | |
100 |
|
100 | |||
101 | Options: |
|
101 | Options: | |
102 |
|
102 | |||
103 | -level(2): allows finer control: |
|
103 | -level(2): allows finer control: | |
104 | 0 -> Do nothing, dummy function. |
|
104 | 0 -> Do nothing, dummy function. | |
105 | 1 -> Print message. |
|
105 | 1 -> Print message. | |
106 | 2 -> Print 'WARNING:' + message. (Default level). |
|
106 | 2 -> Print 'WARNING:' + message. (Default level). | |
107 | 3 -> Print 'ERROR:' + message. |
|
107 | 3 -> Print 'ERROR:' + message. | |
108 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
108 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). | |
109 |
|
109 | |||
110 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
110 | -exit_val (1): exit value returned by sys.exit() for a level 4 | |
111 | warning. Ignored for all other levels.""" |
|
111 | warning. Ignored for all other levels.""" | |
112 |
|
112 | |||
113 | if level>0: |
|
113 | if level>0: | |
114 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
114 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] | |
115 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
115 | print >> Term.cerr, '%s%s' % (header[level],msg) | |
116 | if level == 4: |
|
116 | if level == 4: | |
117 | print >> Term.cerr,'Exiting.\n' |
|
117 | print >> Term.cerr,'Exiting.\n' | |
118 | sys.exit(exit_val) |
|
118 | sys.exit(exit_val) | |
119 |
|
119 | |||
120 | def info(msg): |
|
120 | def info(msg): | |
121 | """Equivalent to warn(msg,level=1).""" |
|
121 | """Equivalent to warn(msg,level=1).""" | |
122 |
|
122 | |||
123 | warn(msg,level=1) |
|
123 | warn(msg,level=1) | |
124 |
|
124 | |||
125 | def error(msg): |
|
125 | def error(msg): | |
126 | """Equivalent to warn(msg,level=3).""" |
|
126 | """Equivalent to warn(msg,level=3).""" | |
127 |
|
127 | |||
128 | warn(msg,level=3) |
|
128 | warn(msg,level=3) | |
129 |
|
129 | |||
130 | def fatal(msg,exit_val=1): |
|
130 | def fatal(msg,exit_val=1): | |
131 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
131 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" | |
132 |
|
132 | |||
133 | warn(msg,exit_val=exit_val,level=4) |
|
133 | warn(msg,exit_val=exit_val,level=4) | |
134 |
|
134 | |||
135 | #--------------------------------------------------------------------------- |
|
135 | #--------------------------------------------------------------------------- | |
136 | # Debugging routines |
|
136 | # Debugging routines | |
137 | # |
|
137 | # | |
138 | def debugx(expr,pre_msg=''): |
|
138 | def debugx(expr,pre_msg=''): | |
139 | """Print the value of an expression from the caller's frame. |
|
139 | """Print the value of an expression from the caller's frame. | |
140 |
|
140 | |||
141 | Takes an expression, evaluates it in the caller's frame and prints both |
|
141 | Takes an expression, evaluates it in the caller's frame and prints both | |
142 | the given expression and the resulting value (as well as a debug mark |
|
142 | the given expression and the resulting value (as well as a debug mark | |
143 | indicating the name of the calling function. The input must be of a form |
|
143 | indicating the name of the calling function. The input must be of a form | |
144 | suitable for eval(). |
|
144 | suitable for eval(). | |
145 |
|
145 | |||
146 | An optional message can be passed, which will be prepended to the printed |
|
146 | An optional message can be passed, which will be prepended to the printed | |
147 | expr->value pair.""" |
|
147 | expr->value pair.""" | |
148 |
|
148 | |||
149 | cf = sys._getframe(1) |
|
149 | cf = sys._getframe(1) | |
150 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, |
|
150 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, | |
151 | eval(expr,cf.f_globals,cf.f_locals)) |
|
151 | eval(expr,cf.f_globals,cf.f_locals)) | |
152 |
|
152 | |||
153 | # deactivate it by uncommenting the following line, which makes it a no-op |
|
153 | # deactivate it by uncommenting the following line, which makes it a no-op | |
154 | #def debugx(expr,pre_msg=''): pass |
|
154 | #def debugx(expr,pre_msg=''): pass | |
155 |
|
155 | |||
156 | #---------------------------------------------------------------------------- |
|
156 | #---------------------------------------------------------------------------- | |
157 | StringTypes = types.StringTypes |
|
157 | StringTypes = types.StringTypes | |
158 |
|
158 | |||
159 | # Basic timing functionality |
|
159 | # Basic timing functionality | |
160 |
|
160 | |||
161 | # If possible (Unix), use the resource module instead of time.clock() |
|
161 | # If possible (Unix), use the resource module instead of time.clock() | |
162 | try: |
|
162 | try: | |
163 | import resource |
|
163 | import resource | |
164 | def clock(): |
|
164 | def clock(): | |
165 | """clock() -> floating point number |
|
165 | """clock() -> floating point number | |
166 |
|
166 | |||
167 | Return the CPU time in seconds (user time only, system time is |
|
167 | Return the CPU time in seconds (user time only, system time is | |
168 | ignored) since the start of the process. This is done via a call to |
|
168 | ignored) since the start of the process. This is done via a call to | |
169 | resource.getrusage, so it avoids the wraparound problems in |
|
169 | resource.getrusage, so it avoids the wraparound problems in | |
170 | time.clock().""" |
|
170 | time.clock().""" | |
171 |
|
171 | |||
172 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
172 | return resource.getrusage(resource.RUSAGE_SELF)[0] | |
173 |
|
173 | |||
174 | def clock2(): |
|
174 | def clock2(): | |
175 | """clock2() -> (t_user,t_system) |
|
175 | """clock2() -> (t_user,t_system) | |
176 |
|
176 | |||
177 | Similar to clock(), but return a tuple of user/system times.""" |
|
177 | Similar to clock(), but return a tuple of user/system times.""" | |
178 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
178 | return resource.getrusage(resource.RUSAGE_SELF)[:2] | |
179 |
|
179 | |||
180 | except ImportError: |
|
180 | except ImportError: | |
181 | clock = time.clock |
|
181 | clock = time.clock | |
182 | def clock2(): |
|
182 | def clock2(): | |
183 | """Under windows, system CPU time can't be measured. |
|
183 | """Under windows, system CPU time can't be measured. | |
184 |
|
184 | |||
185 | This just returns clock() and zero.""" |
|
185 | This just returns clock() and zero.""" | |
186 | return time.clock(),0.0 |
|
186 | return time.clock(),0.0 | |
187 |
|
187 | |||
188 | def timings_out(reps,func,*args,**kw): |
|
188 | def timings_out(reps,func,*args,**kw): | |
189 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
189 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) | |
190 |
|
190 | |||
191 | Execute a function reps times, return a tuple with the elapsed total |
|
191 | Execute a function reps times, return a tuple with the elapsed total | |
192 | CPU time in seconds, the time per call and the function's output. |
|
192 | CPU time in seconds, the time per call and the function's output. | |
193 |
|
193 | |||
194 | Under Unix, the return value is the sum of user+system time consumed by |
|
194 | Under Unix, the return value is the sum of user+system time consumed by | |
195 | the process, computed via the resource module. This prevents problems |
|
195 | the process, computed via the resource module. This prevents problems | |
196 | related to the wraparound effect which the time.clock() function has. |
|
196 | related to the wraparound effect which the time.clock() function has. | |
197 |
|
197 | |||
198 | Under Windows the return value is in wall clock seconds. See the |
|
198 | Under Windows the return value is in wall clock seconds. See the | |
199 | documentation for the time module for more details.""" |
|
199 | documentation for the time module for more details.""" | |
200 |
|
200 | |||
201 | reps = int(reps) |
|
201 | reps = int(reps) | |
202 | assert reps >=1, 'reps must be >= 1' |
|
202 | assert reps >=1, 'reps must be >= 1' | |
203 | if reps==1: |
|
203 | if reps==1: | |
204 | start = clock() |
|
204 | start = clock() | |
205 | out = func(*args,**kw) |
|
205 | out = func(*args,**kw) | |
206 | tot_time = clock()-start |
|
206 | tot_time = clock()-start | |
207 | else: |
|
207 | else: | |
208 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
208 | rng = xrange(reps-1) # the last time is executed separately to store output | |
209 | start = clock() |
|
209 | start = clock() | |
210 | for dummy in rng: func(*args,**kw) |
|
210 | for dummy in rng: func(*args,**kw) | |
211 | out = func(*args,**kw) # one last time |
|
211 | out = func(*args,**kw) # one last time | |
212 | tot_time = clock()-start |
|
212 | tot_time = clock()-start | |
213 | av_time = tot_time / reps |
|
213 | av_time = tot_time / reps | |
214 | return tot_time,av_time,out |
|
214 | return tot_time,av_time,out | |
215 |
|
215 | |||
216 | def timings(reps,func,*args,**kw): |
|
216 | def timings(reps,func,*args,**kw): | |
217 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
217 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) | |
218 |
|
218 | |||
219 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
219 | Execute a function reps times, return a tuple with the elapsed total CPU | |
220 | time in seconds and the time per call. These are just the first two values |
|
220 | time in seconds and the time per call. These are just the first two values | |
221 | in timings_out().""" |
|
221 | in timings_out().""" | |
222 |
|
222 | |||
223 | return timings_out(reps,func,*args,**kw)[0:2] |
|
223 | return timings_out(reps,func,*args,**kw)[0:2] | |
224 |
|
224 | |||
225 | def timing(func,*args,**kw): |
|
225 | def timing(func,*args,**kw): | |
226 | """timing(func,*args,**kw) -> t_total |
|
226 | """timing(func,*args,**kw) -> t_total | |
227 |
|
227 | |||
228 | Execute a function once, return the elapsed total CPU time in |
|
228 | Execute a function once, return the elapsed total CPU time in | |
229 | seconds. This is just the first value in timings_out().""" |
|
229 | seconds. This is just the first value in timings_out().""" | |
230 |
|
230 | |||
231 | return timings_out(1,func,*args,**kw)[0] |
|
231 | return timings_out(1,func,*args,**kw)[0] | |
232 |
|
232 | |||
233 | #**************************************************************************** |
|
233 | #**************************************************************************** | |
234 | # file and system |
|
234 | # file and system | |
235 |
|
235 | |||
236 | def system(cmd,verbose=0,debug=0,header=''): |
|
236 | def system(cmd,verbose=0,debug=0,header=''): | |
237 | """Execute a system command, return its exit status. |
|
237 | """Execute a system command, return its exit status. | |
238 |
|
238 | |||
239 | Options: |
|
239 | Options: | |
240 |
|
240 | |||
241 | - verbose (0): print the command to be executed. |
|
241 | - verbose (0): print the command to be executed. | |
242 |
|
242 | |||
243 | - debug (0): only print, do not actually execute. |
|
243 | - debug (0): only print, do not actually execute. | |
244 |
|
244 | |||
245 | - header (''): Header to print on screen prior to the executed command (it |
|
245 | - header (''): Header to print on screen prior to the executed command (it | |
246 | is only prepended to the command, no newlines are added). |
|
246 | is only prepended to the command, no newlines are added). | |
247 |
|
247 | |||
248 | Note: a stateful version of this function is available through the |
|
248 | Note: a stateful version of this function is available through the | |
249 | SystemExec class.""" |
|
249 | SystemExec class.""" | |
250 |
|
250 | |||
251 | stat = 0 |
|
251 | stat = 0 | |
252 | if verbose or debug: print header+cmd |
|
252 | if verbose or debug: print header+cmd | |
253 | sys.stdout.flush() |
|
253 | sys.stdout.flush() | |
254 | if not debug: stat = os.system(cmd) |
|
254 | if not debug: stat = os.system(cmd) | |
255 | return stat |
|
255 | return stat | |
256 |
|
256 | |||
257 | # This function is used by ipython in a lot of places to make system calls. |
|
257 | # This function is used by ipython in a lot of places to make system calls. | |
258 | # We need it to be slightly different under win32, due to the vagaries of |
|
258 | # We need it to be slightly different under win32, due to the vagaries of | |
259 | # 'network shares'. A win32 override is below. |
|
259 | # 'network shares'. A win32 override is below. | |
260 |
|
260 | |||
261 | def shell(cmd,verbose=0,debug=0,header=''): |
|
261 | def shell(cmd,verbose=0,debug=0,header=''): | |
262 | """Execute a command in the system shell, always return None. |
|
262 | """Execute a command in the system shell, always return None. | |
263 |
|
263 | |||
264 | Options: |
|
264 | Options: | |
265 |
|
265 | |||
266 | - verbose (0): print the command to be executed. |
|
266 | - verbose (0): print the command to be executed. | |
267 |
|
267 | |||
268 | - debug (0): only print, do not actually execute. |
|
268 | - debug (0): only print, do not actually execute. | |
269 |
|
269 | |||
270 | - header (''): Header to print on screen prior to the executed command (it |
|
270 | - header (''): Header to print on screen prior to the executed command (it | |
271 | is only prepended to the command, no newlines are added). |
|
271 | is only prepended to the command, no newlines are added). | |
272 |
|
272 | |||
273 | Note: this is similar to genutils.system(), but it returns None so it can |
|
273 | Note: this is similar to genutils.system(), but it returns None so it can | |
274 | be conveniently used in interactive loops without getting the return value |
|
274 | be conveniently used in interactive loops without getting the return value | |
275 | (typically 0) printed many times.""" |
|
275 | (typically 0) printed many times.""" | |
276 |
|
276 | |||
277 | stat = 0 |
|
277 | stat = 0 | |
278 | if verbose or debug: print header+cmd |
|
278 | if verbose or debug: print header+cmd | |
279 | # flush stdout so we don't mangle python's buffering |
|
279 | # flush stdout so we don't mangle python's buffering | |
280 | sys.stdout.flush() |
|
280 | sys.stdout.flush() | |
281 | if not debug: |
|
281 | if not debug: | |
282 | os.system(cmd) |
|
282 | os.system(cmd) | |
283 |
|
283 | |||
284 | # override shell() for win32 to deal with network shares |
|
284 | # override shell() for win32 to deal with network shares | |
285 | if os.name in ('nt','dos'): |
|
285 | if os.name in ('nt','dos'): | |
286 |
|
286 | |||
287 | shell_ori = shell |
|
287 | shell_ori = shell | |
288 |
|
288 | |||
289 | def shell(cmd,verbose=0,debug=0,header=''): |
|
289 | def shell(cmd,verbose=0,debug=0,header=''): | |
290 | if os.getcwd().startswith(r"\\"): |
|
290 | if os.getcwd().startswith(r"\\"): | |
291 | path = os.getcwd() |
|
291 | path = os.getcwd() | |
292 | # change to c drive (cannot be on UNC-share when issuing os.system, |
|
292 | # change to c drive (cannot be on UNC-share when issuing os.system, | |
293 | # as cmd.exe cannot handle UNC addresses) |
|
293 | # as cmd.exe cannot handle UNC addresses) | |
294 | os.chdir("c:") |
|
294 | os.chdir("c:") | |
295 | # issue pushd to the UNC-share and then run the command |
|
295 | # issue pushd to the UNC-share and then run the command | |
296 | try: |
|
296 | try: | |
297 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) |
|
297 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) | |
298 | finally: |
|
298 | finally: | |
299 | os.chdir(path) |
|
299 | os.chdir(path) | |
300 | else: |
|
300 | else: | |
301 | shell_ori(cmd,verbose,debug,header) |
|
301 | shell_ori(cmd,verbose,debug,header) | |
302 |
|
302 | |||
303 | shell.__doc__ = shell_ori.__doc__ |
|
303 | shell.__doc__ = shell_ori.__doc__ | |
304 |
|
304 | |||
305 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
305 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): | |
306 | """Dummy substitute for perl's backquotes. |
|
306 | """Dummy substitute for perl's backquotes. | |
307 |
|
307 | |||
308 | Executes a command and returns the output. |
|
308 | Executes a command and returns the output. | |
309 |
|
309 | |||
310 | Accepts the same arguments as system(), plus: |
|
310 | Accepts the same arguments as system(), plus: | |
311 |
|
311 | |||
312 | - split(0): if true, the output is returned as a list split on newlines. |
|
312 | - split(0): if true, the output is returned as a list split on newlines. | |
313 |
|
313 | |||
314 | Note: a stateful version of this function is available through the |
|
314 | Note: a stateful version of this function is available through the | |
315 | SystemExec class. |
|
315 | SystemExec class. | |
316 |
|
316 | |||
317 | This is pretty much deprecated and rarely used, |
|
317 | This is pretty much deprecated and rarely used, | |
318 | genutils.getoutputerror may be what you need. |
|
318 | genutils.getoutputerror may be what you need. | |
319 |
|
319 | |||
320 | """ |
|
320 | """ | |
321 |
|
321 | |||
322 | if verbose or debug: print header+cmd |
|
322 | if verbose or debug: print header+cmd | |
323 | if not debug: |
|
323 | if not debug: | |
324 | output = os.popen(cmd).read() |
|
324 | output = os.popen(cmd).read() | |
325 | # stipping last \n is here for backwards compat. |
|
325 | # stipping last \n is here for backwards compat. | |
326 | if output.endswith('\n'): |
|
326 | if output.endswith('\n'): | |
327 | output = output[:-1] |
|
327 | output = output[:-1] | |
328 | if split: |
|
328 | if split: | |
329 | return output.split('\n') |
|
329 | return output.split('\n') | |
330 | else: |
|
330 | else: | |
331 | return output |
|
331 | return output | |
332 |
|
332 | |||
333 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
333 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): | |
334 | """Return (standard output,standard error) of executing cmd in a shell. |
|
334 | """Return (standard output,standard error) of executing cmd in a shell. | |
335 |
|
335 | |||
336 | Accepts the same arguments as system(), plus: |
|
336 | Accepts the same arguments as system(), plus: | |
337 |
|
337 | |||
338 | - split(0): if true, each of stdout/err is returned as a list split on |
|
338 | - split(0): if true, each of stdout/err is returned as a list split on | |
339 | newlines. |
|
339 | newlines. | |
340 |
|
340 | |||
341 | Note: a stateful version of this function is available through the |
|
341 | Note: a stateful version of this function is available through the | |
342 | SystemExec class.""" |
|
342 | SystemExec class.""" | |
343 |
|
343 | |||
344 | if verbose or debug: print header+cmd |
|
344 | if verbose or debug: print header+cmd | |
345 | if not cmd: |
|
345 | if not cmd: | |
346 | if split: |
|
346 | if split: | |
347 | return [],[] |
|
347 | return [],[] | |
348 | else: |
|
348 | else: | |
349 | return '','' |
|
349 | return '','' | |
350 | if not debug: |
|
350 | if not debug: | |
351 | pin,pout,perr = os.popen3(cmd) |
|
351 | pin,pout,perr = os.popen3(cmd) | |
352 | tout = pout.read().rstrip() |
|
352 | tout = pout.read().rstrip() | |
353 | terr = perr.read().rstrip() |
|
353 | terr = perr.read().rstrip() | |
354 | pin.close() |
|
354 | pin.close() | |
355 | pout.close() |
|
355 | pout.close() | |
356 | perr.close() |
|
356 | perr.close() | |
357 | if split: |
|
357 | if split: | |
358 | return tout.split('\n'),terr.split('\n') |
|
358 | return tout.split('\n'),terr.split('\n') | |
359 | else: |
|
359 | else: | |
360 | return tout,terr |
|
360 | return tout,terr | |
361 |
|
361 | |||
362 | # for compatibility with older naming conventions |
|
362 | # for compatibility with older naming conventions | |
363 | xsys = system |
|
363 | xsys = system | |
364 | bq = getoutput |
|
364 | bq = getoutput | |
365 |
|
365 | |||
366 | class SystemExec: |
|
366 | class SystemExec: | |
367 | """Access the system and getoutput functions through a stateful interface. |
|
367 | """Access the system and getoutput functions through a stateful interface. | |
368 |
|
368 | |||
369 | Note: here we refer to the system and getoutput functions from this |
|
369 | Note: here we refer to the system and getoutput functions from this | |
370 | library, not the ones from the standard python library. |
|
370 | library, not the ones from the standard python library. | |
371 |
|
371 | |||
372 | This class offers the system and getoutput functions as methods, but the |
|
372 | This class offers the system and getoutput functions as methods, but the | |
373 | verbose, debug and header parameters can be set for the instance (at |
|
373 | verbose, debug and header parameters can be set for the instance (at | |
374 | creation time or later) so that they don't need to be specified on each |
|
374 | creation time or later) so that they don't need to be specified on each | |
375 | call. |
|
375 | call. | |
376 |
|
376 | |||
377 | For efficiency reasons, there's no way to override the parameters on a |
|
377 | For efficiency reasons, there's no way to override the parameters on a | |
378 | per-call basis other than by setting instance attributes. If you need |
|
378 | per-call basis other than by setting instance attributes. If you need | |
379 | local overrides, it's best to directly call system() or getoutput(). |
|
379 | local overrides, it's best to directly call system() or getoutput(). | |
380 |
|
380 | |||
381 | The following names are provided as alternate options: |
|
381 | The following names are provided as alternate options: | |
382 | - xsys: alias to system |
|
382 | - xsys: alias to system | |
383 | - bq: alias to getoutput |
|
383 | - bq: alias to getoutput | |
384 |
|
384 | |||
385 | An instance can then be created as: |
|
385 | An instance can then be created as: | |
386 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
386 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') | |
387 |
|
387 | |||
388 | And used as: |
|
388 | And used as: | |
389 | >>> sysexec.xsys('pwd') |
|
389 | >>> sysexec.xsys('pwd') | |
390 | >>> dirlist = sysexec.bq('ls -l') |
|
390 | >>> dirlist = sysexec.bq('ls -l') | |
391 | """ |
|
391 | """ | |
392 |
|
392 | |||
393 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
393 | def __init__(self,verbose=0,debug=0,header='',split=0): | |
394 | """Specify the instance's values for verbose, debug and header.""" |
|
394 | """Specify the instance's values for verbose, debug and header.""" | |
395 | setattr_list(self,'verbose debug header split') |
|
395 | setattr_list(self,'verbose debug header split') | |
396 |
|
396 | |||
397 | def system(self,cmd): |
|
397 | def system(self,cmd): | |
398 | """Stateful interface to system(), with the same keyword parameters.""" |
|
398 | """Stateful interface to system(), with the same keyword parameters.""" | |
399 |
|
399 | |||
400 | system(cmd,self.verbose,self.debug,self.header) |
|
400 | system(cmd,self.verbose,self.debug,self.header) | |
401 |
|
401 | |||
402 | def shell(self,cmd): |
|
402 | def shell(self,cmd): | |
403 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
403 | """Stateful interface to shell(), with the same keyword parameters.""" | |
404 |
|
404 | |||
405 | shell(cmd,self.verbose,self.debug,self.header) |
|
405 | shell(cmd,self.verbose,self.debug,self.header) | |
406 |
|
406 | |||
407 | xsys = system # alias |
|
407 | xsys = system # alias | |
408 |
|
408 | |||
409 | def getoutput(self,cmd): |
|
409 | def getoutput(self,cmd): | |
410 | """Stateful interface to getoutput().""" |
|
410 | """Stateful interface to getoutput().""" | |
411 |
|
411 | |||
412 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
412 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) | |
413 |
|
413 | |||
414 | def getoutputerror(self,cmd): |
|
414 | def getoutputerror(self,cmd): | |
415 | """Stateful interface to getoutputerror().""" |
|
415 | """Stateful interface to getoutputerror().""" | |
416 |
|
416 | |||
417 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
417 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) | |
418 |
|
418 | |||
419 | bq = getoutput # alias |
|
419 | bq = getoutput # alias | |
420 |
|
420 | |||
421 | #----------------------------------------------------------------------------- |
|
421 | #----------------------------------------------------------------------------- | |
422 | def mutex_opts(dict,ex_op): |
|
422 | def mutex_opts(dict,ex_op): | |
423 | """Check for presence of mutually exclusive keys in a dict. |
|
423 | """Check for presence of mutually exclusive keys in a dict. | |
424 |
|
424 | |||
425 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
425 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" | |
426 | for op1,op2 in ex_op: |
|
426 | for op1,op2 in ex_op: | |
427 | if op1 in dict and op2 in dict: |
|
427 | if op1 in dict and op2 in dict: | |
428 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
428 | raise ValueError,'\n*** ERROR in Arguments *** '\ | |
429 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
429 | 'Options '+op1+' and '+op2+' are mutually exclusive.' | |
430 |
|
430 | |||
431 | #----------------------------------------------------------------------------- |
|
431 | #----------------------------------------------------------------------------- | |
432 | def get_py_filename(name): |
|
432 | def get_py_filename(name): | |
433 | """Return a valid python filename in the current directory. |
|
433 | """Return a valid python filename in the current directory. | |
434 |
|
434 | |||
435 | If the given name is not a file, it adds '.py' and searches again. |
|
435 | If the given name is not a file, it adds '.py' and searches again. | |
436 | Raises IOError with an informative message if the file isn't found.""" |
|
436 | Raises IOError with an informative message if the file isn't found.""" | |
437 |
|
437 | |||
438 | name = os.path.expanduser(name) |
|
438 | name = os.path.expanduser(name) | |
439 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
439 | if not os.path.isfile(name) and not name.endswith('.py'): | |
440 | name += '.py' |
|
440 | name += '.py' | |
441 | if os.path.isfile(name): |
|
441 | if os.path.isfile(name): | |
442 | return name |
|
442 | return name | |
443 | else: |
|
443 | else: | |
444 | raise IOError,'File `%s` not found.' % name |
|
444 | raise IOError,'File `%s` not found.' % name | |
445 |
|
445 | |||
446 | #----------------------------------------------------------------------------- |
|
446 | #----------------------------------------------------------------------------- | |
447 | def filefind(fname,alt_dirs = None): |
|
447 | def filefind(fname,alt_dirs = None): | |
448 | """Return the given filename either in the current directory, if it |
|
448 | """Return the given filename either in the current directory, if it | |
449 | exists, or in a specified list of directories. |
|
449 | exists, or in a specified list of directories. | |
450 |
|
450 | |||
451 | ~ expansion is done on all file and directory names. |
|
451 | ~ expansion is done on all file and directory names. | |
452 |
|
452 | |||
453 | Upon an unsuccessful search, raise an IOError exception.""" |
|
453 | Upon an unsuccessful search, raise an IOError exception.""" | |
454 |
|
454 | |||
455 | if alt_dirs is None: |
|
455 | if alt_dirs is None: | |
456 | try: |
|
456 | try: | |
457 | alt_dirs = get_home_dir() |
|
457 | alt_dirs = get_home_dir() | |
458 | except HomeDirError: |
|
458 | except HomeDirError: | |
459 | alt_dirs = os.getcwd() |
|
459 | alt_dirs = os.getcwd() | |
460 | search = [fname] + list_strings(alt_dirs) |
|
460 | search = [fname] + list_strings(alt_dirs) | |
461 | search = map(os.path.expanduser,search) |
|
461 | search = map(os.path.expanduser,search) | |
462 | #print 'search list for',fname,'list:',search # dbg |
|
462 | #print 'search list for',fname,'list:',search # dbg | |
463 | fname = search[0] |
|
463 | fname = search[0] | |
464 | if os.path.isfile(fname): |
|
464 | if os.path.isfile(fname): | |
465 | return fname |
|
465 | return fname | |
466 | for direc in search[1:]: |
|
466 | for direc in search[1:]: | |
467 | testname = os.path.join(direc,fname) |
|
467 | testname = os.path.join(direc,fname) | |
468 | #print 'testname',testname # dbg |
|
468 | #print 'testname',testname # dbg | |
469 | if os.path.isfile(testname): |
|
469 | if os.path.isfile(testname): | |
470 | return testname |
|
470 | return testname | |
471 | raise IOError,'File' + `fname` + \ |
|
471 | raise IOError,'File' + `fname` + \ | |
472 | ' not found in current or supplied directories:' + `alt_dirs` |
|
472 | ' not found in current or supplied directories:' + `alt_dirs` | |
473 |
|
473 | |||
474 | #---------------------------------------------------------------------------- |
|
474 | #---------------------------------------------------------------------------- | |
475 | def file_read(filename): |
|
475 | def file_read(filename): | |
476 | """Read a file and close it. Returns the file source.""" |
|
476 | """Read a file and close it. Returns the file source.""" | |
477 | fobj = open(filename,'r'); |
|
477 | fobj = open(filename,'r'); | |
478 | source = fobj.read(); |
|
478 | source = fobj.read(); | |
479 | fobj.close() |
|
479 | fobj.close() | |
480 | return source |
|
480 | return source | |
481 |
|
481 | |||
482 | def file_readlines(filename): |
|
482 | def file_readlines(filename): | |
483 | """Read a file and close it. Returns the file source using readlines().""" |
|
483 | """Read a file and close it. Returns the file source using readlines().""" | |
484 | fobj = open(filename,'r'); |
|
484 | fobj = open(filename,'r'); | |
485 | lines = fobj.readlines(); |
|
485 | lines = fobj.readlines(); | |
486 | fobj.close() |
|
486 | fobj.close() | |
487 | return lines |
|
487 | return lines | |
488 |
|
488 | |||
489 | #---------------------------------------------------------------------------- |
|
489 | #---------------------------------------------------------------------------- | |
490 | def target_outdated(target,deps): |
|
490 | def target_outdated(target,deps): | |
491 | """Determine whether a target is out of date. |
|
491 | """Determine whether a target is out of date. | |
492 |
|
492 | |||
493 | target_outdated(target,deps) -> 1/0 |
|
493 | target_outdated(target,deps) -> 1/0 | |
494 |
|
494 | |||
495 | deps: list of filenames which MUST exist. |
|
495 | deps: list of filenames which MUST exist. | |
496 | target: single filename which may or may not exist. |
|
496 | target: single filename which may or may not exist. | |
497 |
|
497 | |||
498 | If target doesn't exist or is older than any file listed in deps, return |
|
498 | If target doesn't exist or is older than any file listed in deps, return | |
499 | true, otherwise return false. |
|
499 | true, otherwise return false. | |
500 | """ |
|
500 | """ | |
501 | try: |
|
501 | try: | |
502 | target_time = os.path.getmtime(target) |
|
502 | target_time = os.path.getmtime(target) | |
503 | except os.error: |
|
503 | except os.error: | |
504 | return 1 |
|
504 | return 1 | |
505 | for dep in deps: |
|
505 | for dep in deps: | |
506 | dep_time = os.path.getmtime(dep) |
|
506 | dep_time = os.path.getmtime(dep) | |
507 | if dep_time > target_time: |
|
507 | if dep_time > target_time: | |
508 | #print "For target",target,"Dep failed:",dep # dbg |
|
508 | #print "For target",target,"Dep failed:",dep # dbg | |
509 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
509 | #print "times (dep,tar):",dep_time,target_time # dbg | |
510 | return 1 |
|
510 | return 1 | |
511 | return 0 |
|
511 | return 0 | |
512 |
|
512 | |||
513 | #----------------------------------------------------------------------------- |
|
513 | #----------------------------------------------------------------------------- | |
514 | def target_update(target,deps,cmd): |
|
514 | def target_update(target,deps,cmd): | |
515 | """Update a target with a given command given a list of dependencies. |
|
515 | """Update a target with a given command given a list of dependencies. | |
516 |
|
516 | |||
517 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
517 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
518 |
|
518 | |||
519 | This is just a wrapper around target_outdated() which calls the given |
|
519 | This is just a wrapper around target_outdated() which calls the given | |
520 | command if target is outdated.""" |
|
520 | command if target is outdated.""" | |
521 |
|
521 | |||
522 | if target_outdated(target,deps): |
|
522 | if target_outdated(target,deps): | |
523 | xsys(cmd) |
|
523 | xsys(cmd) | |
524 |
|
524 | |||
525 | #---------------------------------------------------------------------------- |
|
525 | #---------------------------------------------------------------------------- | |
526 | def unquote_ends(istr): |
|
526 | def unquote_ends(istr): | |
527 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
527 | """Remove a single pair of quotes from the endpoints of a string.""" | |
528 |
|
528 | |||
529 | if not istr: |
|
529 | if not istr: | |
530 | return istr |
|
530 | return istr | |
531 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
531 | if (istr[0]=="'" and istr[-1]=="'") or \ | |
532 | (istr[0]=='"' and istr[-1]=='"'): |
|
532 | (istr[0]=='"' and istr[-1]=='"'): | |
533 | return istr[1:-1] |
|
533 | return istr[1:-1] | |
534 | else: |
|
534 | else: | |
535 | return istr |
|
535 | return istr | |
536 |
|
536 | |||
537 | #---------------------------------------------------------------------------- |
|
537 | #---------------------------------------------------------------------------- | |
538 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
538 | def process_cmdline(argv,names=[],defaults={},usage=''): | |
539 | """ Process command-line options and arguments. |
|
539 | """ Process command-line options and arguments. | |
540 |
|
540 | |||
541 | Arguments: |
|
541 | Arguments: | |
542 |
|
542 | |||
543 | - argv: list of arguments, typically sys.argv. |
|
543 | - argv: list of arguments, typically sys.argv. | |
544 |
|
544 | |||
545 | - names: list of option names. See DPyGetOpt docs for details on options |
|
545 | - names: list of option names. See DPyGetOpt docs for details on options | |
546 | syntax. |
|
546 | syntax. | |
547 |
|
547 | |||
548 | - defaults: dict of default values. |
|
548 | - defaults: dict of default values. | |
549 |
|
549 | |||
550 | - usage: optional usage notice to print if a wrong argument is passed. |
|
550 | - usage: optional usage notice to print if a wrong argument is passed. | |
551 |
|
551 | |||
552 | Return a dict of options and a list of free arguments.""" |
|
552 | Return a dict of options and a list of free arguments.""" | |
553 |
|
553 | |||
554 | getopt = DPyGetOpt.DPyGetOpt() |
|
554 | getopt = DPyGetOpt.DPyGetOpt() | |
555 | getopt.setIgnoreCase(0) |
|
555 | getopt.setIgnoreCase(0) | |
556 | getopt.parseConfiguration(names) |
|
556 | getopt.parseConfiguration(names) | |
557 |
|
557 | |||
558 | try: |
|
558 | try: | |
559 | getopt.processArguments(argv) |
|
559 | getopt.processArguments(argv) | |
560 | except: |
|
560 | except: | |
561 | print usage |
|
561 | print usage | |
562 | warn(`sys.exc_value`,level=4) |
|
562 | warn(`sys.exc_value`,level=4) | |
563 |
|
563 | |||
564 | defaults.update(getopt.optionValues) |
|
564 | defaults.update(getopt.optionValues) | |
565 | args = getopt.freeValues |
|
565 | args = getopt.freeValues | |
566 |
|
566 | |||
567 | return defaults,args |
|
567 | return defaults,args | |
568 |
|
568 | |||
569 | #---------------------------------------------------------------------------- |
|
569 | #---------------------------------------------------------------------------- | |
570 | def optstr2types(ostr): |
|
570 | def optstr2types(ostr): | |
571 | """Convert a string of option names to a dict of type mappings. |
|
571 | """Convert a string of option names to a dict of type mappings. | |
572 |
|
572 | |||
573 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
573 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} | |
574 |
|
574 | |||
575 | This is used to get the types of all the options in a string formatted |
|
575 | This is used to get the types of all the options in a string formatted | |
576 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
576 | with the conventions of DPyGetOpt. The 'type' None is used for options | |
577 | which are strings (they need no further conversion). This function's main |
|
577 | which are strings (they need no further conversion). This function's main | |
578 | use is to get a typemap for use with read_dict(). |
|
578 | use is to get a typemap for use with read_dict(). | |
579 | """ |
|
579 | """ | |
580 |
|
580 | |||
581 | typeconv = {None:'',int:'',float:''} |
|
581 | typeconv = {None:'',int:'',float:''} | |
582 | typemap = {'s':None,'i':int,'f':float} |
|
582 | typemap = {'s':None,'i':int,'f':float} | |
583 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
583 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') | |
584 |
|
584 | |||
585 | for w in ostr.split(): |
|
585 | for w in ostr.split(): | |
586 | oname,alias,otype = opt_re.match(w).groups() |
|
586 | oname,alias,otype = opt_re.match(w).groups() | |
587 | if otype == '' or alias == '!': # simple switches are integers too |
|
587 | if otype == '' or alias == '!': # simple switches are integers too | |
588 | otype = 'i' |
|
588 | otype = 'i' | |
589 | typeconv[typemap[otype]] += oname + ' ' |
|
589 | typeconv[typemap[otype]] += oname + ' ' | |
590 | return typeconv |
|
590 | return typeconv | |
591 |
|
591 | |||
592 | #---------------------------------------------------------------------------- |
|
592 | #---------------------------------------------------------------------------- | |
593 | def read_dict(filename,type_conv=None,**opt): |
|
593 | def read_dict(filename,type_conv=None,**opt): | |
594 |
|
594 | |||
595 | """Read a dictionary of key=value pairs from an input file, optionally |
|
595 | """Read a dictionary of key=value pairs from an input file, optionally | |
596 | performing conversions on the resulting values. |
|
596 | performing conversions on the resulting values. | |
597 |
|
597 | |||
598 | read_dict(filename,type_conv,**opt) -> dict |
|
598 | read_dict(filename,type_conv,**opt) -> dict | |
599 |
|
599 | |||
600 | Only one value per line is accepted, the format should be |
|
600 | Only one value per line is accepted, the format should be | |
601 | # optional comments are ignored |
|
601 | # optional comments are ignored | |
602 | key value\n |
|
602 | key value\n | |
603 |
|
603 | |||
604 | Args: |
|
604 | Args: | |
605 |
|
605 | |||
606 | - type_conv: A dictionary specifying which keys need to be converted to |
|
606 | - type_conv: A dictionary specifying which keys need to be converted to | |
607 | which types. By default all keys are read as strings. This dictionary |
|
607 | which types. By default all keys are read as strings. This dictionary | |
608 | should have as its keys valid conversion functions for strings |
|
608 | should have as its keys valid conversion functions for strings | |
609 | (int,long,float,complex, or your own). The value for each key |
|
609 | (int,long,float,complex, or your own). The value for each key | |
610 | (converter) should be a whitespace separated string containing the names |
|
610 | (converter) should be a whitespace separated string containing the names | |
611 | of all the entries in the file to be converted using that function. For |
|
611 | of all the entries in the file to be converted using that function. For | |
612 | keys to be left alone, use None as the conversion function (only needed |
|
612 | keys to be left alone, use None as the conversion function (only needed | |
613 | with purge=1, see below). |
|
613 | with purge=1, see below). | |
614 |
|
614 | |||
615 | - opt: dictionary with extra options as below (default in parens) |
|
615 | - opt: dictionary with extra options as below (default in parens) | |
616 |
|
616 | |||
617 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
617 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out | |
618 | of the dictionary to be returned. If purge is going to be used, the |
|
618 | of the dictionary to be returned. If purge is going to be used, the | |
619 | set of keys to be left as strings also has to be explicitly specified |
|
619 | set of keys to be left as strings also has to be explicitly specified | |
620 | using the (non-existent) conversion function None. |
|
620 | using the (non-existent) conversion function None. | |
621 |
|
621 | |||
622 | fs(None): field separator. This is the key/value separator to be used |
|
622 | fs(None): field separator. This is the key/value separator to be used | |
623 | when parsing the file. The None default means any whitespace [behavior |
|
623 | when parsing the file. The None default means any whitespace [behavior | |
624 | of string.split()]. |
|
624 | of string.split()]. | |
625 |
|
625 | |||
626 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
626 | strip(0): if 1, strip string values of leading/trailinig whitespace. | |
627 |
|
627 | |||
628 | warn(1): warning level if requested keys are not found in file. |
|
628 | warn(1): warning level if requested keys are not found in file. | |
629 | - 0: silently ignore. |
|
629 | - 0: silently ignore. | |
630 | - 1: inform but proceed. |
|
630 | - 1: inform but proceed. | |
631 | - 2: raise KeyError exception. |
|
631 | - 2: raise KeyError exception. | |
632 |
|
632 | |||
633 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
633 | no_empty(0): if 1, remove keys with whitespace strings as a value. | |
634 |
|
634 | |||
635 | unique([]): list of keys (or space separated string) which can't be |
|
635 | unique([]): list of keys (or space separated string) which can't be | |
636 | repeated. If one such key is found in the file, each new instance |
|
636 | repeated. If one such key is found in the file, each new instance | |
637 | overwrites the previous one. For keys not listed here, the behavior is |
|
637 | overwrites the previous one. For keys not listed here, the behavior is | |
638 | to make a list of all appearances. |
|
638 | to make a list of all appearances. | |
639 |
|
639 | |||
640 | Example: |
|
640 | Example: | |
641 | If the input file test.ini has: |
|
641 | If the input file test.ini has: | |
642 | i 3 |
|
642 | i 3 | |
643 | x 4.5 |
|
643 | x 4.5 | |
644 | y 5.5 |
|
644 | y 5.5 | |
645 | s hi ho |
|
645 | s hi ho | |
646 | Then: |
|
646 | Then: | |
647 |
|
647 | |||
648 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
648 | >>> type_conv={int:'i',float:'x',None:'s'} | |
649 | >>> read_dict('test.ini') |
|
649 | >>> read_dict('test.ini') | |
650 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} |
|
650 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} | |
651 | >>> read_dict('test.ini',type_conv) |
|
651 | >>> read_dict('test.ini',type_conv) | |
652 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} |
|
652 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} | |
653 | >>> read_dict('test.ini',type_conv,purge=1) |
|
653 | >>> read_dict('test.ini',type_conv,purge=1) | |
654 | {'i': 3, 's': 'hi ho', 'x': 4.5} |
|
654 | {'i': 3, 's': 'hi ho', 'x': 4.5} | |
655 | """ |
|
655 | """ | |
656 |
|
656 | |||
657 | # starting config |
|
657 | # starting config | |
658 | opt.setdefault('purge',0) |
|
658 | opt.setdefault('purge',0) | |
659 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
659 | opt.setdefault('fs',None) # field sep defaults to any whitespace | |
660 | opt.setdefault('strip',0) |
|
660 | opt.setdefault('strip',0) | |
661 | opt.setdefault('warn',1) |
|
661 | opt.setdefault('warn',1) | |
662 | opt.setdefault('no_empty',0) |
|
662 | opt.setdefault('no_empty',0) | |
663 | opt.setdefault('unique','') |
|
663 | opt.setdefault('unique','') | |
664 | if type(opt['unique']) in StringTypes: |
|
664 | if type(opt['unique']) in StringTypes: | |
665 | unique_keys = qw(opt['unique']) |
|
665 | unique_keys = qw(opt['unique']) | |
666 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
666 | elif type(opt['unique']) in (types.TupleType,types.ListType): | |
667 | unique_keys = opt['unique'] |
|
667 | unique_keys = opt['unique'] | |
668 | else: |
|
668 | else: | |
669 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
669 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' | |
670 |
|
670 | |||
671 | dict = {} |
|
671 | dict = {} | |
672 | # first read in table of values as strings |
|
672 | # first read in table of values as strings | |
673 | file = open(filename,'r') |
|
673 | file = open(filename,'r') | |
674 | for line in file.readlines(): |
|
674 | for line in file.readlines(): | |
675 | line = line.strip() |
|
675 | line = line.strip() | |
676 | if len(line) and line[0]=='#': continue |
|
676 | if len(line) and line[0]=='#': continue | |
677 | if len(line)>0: |
|
677 | if len(line)>0: | |
678 | lsplit = line.split(opt['fs'],1) |
|
678 | lsplit = line.split(opt['fs'],1) | |
679 | try: |
|
679 | try: | |
680 | key,val = lsplit |
|
680 | key,val = lsplit | |
681 | except ValueError: |
|
681 | except ValueError: | |
682 | key,val = lsplit[0],'' |
|
682 | key,val = lsplit[0],'' | |
683 | key = key.strip() |
|
683 | key = key.strip() | |
684 | if opt['strip']: val = val.strip() |
|
684 | if opt['strip']: val = val.strip() | |
685 | if val == "''" or val == '""': val = '' |
|
685 | if val == "''" or val == '""': val = '' | |
686 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
686 | if opt['no_empty'] and (val=='' or val.isspace()): | |
687 | continue |
|
687 | continue | |
688 | # if a key is found more than once in the file, build a list |
|
688 | # if a key is found more than once in the file, build a list | |
689 | # unless it's in the 'unique' list. In that case, last found in file |
|
689 | # unless it's in the 'unique' list. In that case, last found in file | |
690 | # takes precedence. User beware. |
|
690 | # takes precedence. User beware. | |
691 | try: |
|
691 | try: | |
692 | if dict[key] and key in unique_keys: |
|
692 | if dict[key] and key in unique_keys: | |
693 | dict[key] = val |
|
693 | dict[key] = val | |
694 | elif type(dict[key]) is types.ListType: |
|
694 | elif type(dict[key]) is types.ListType: | |
695 | dict[key].append(val) |
|
695 | dict[key].append(val) | |
696 | else: |
|
696 | else: | |
697 | dict[key] = [dict[key],val] |
|
697 | dict[key] = [dict[key],val] | |
698 | except KeyError: |
|
698 | except KeyError: | |
699 | dict[key] = val |
|
699 | dict[key] = val | |
700 | # purge if requested |
|
700 | # purge if requested | |
701 | if opt['purge']: |
|
701 | if opt['purge']: | |
702 | accepted_keys = qwflat(type_conv.values()) |
|
702 | accepted_keys = qwflat(type_conv.values()) | |
703 | for key in dict.keys(): |
|
703 | for key in dict.keys(): | |
704 | if key in accepted_keys: continue |
|
704 | if key in accepted_keys: continue | |
705 | del(dict[key]) |
|
705 | del(dict[key]) | |
706 | # now convert if requested |
|
706 | # now convert if requested | |
707 | if type_conv==None: return dict |
|
707 | if type_conv==None: return dict | |
708 | conversions = type_conv.keys() |
|
708 | conversions = type_conv.keys() | |
709 | try: conversions.remove(None) |
|
709 | try: conversions.remove(None) | |
710 | except: pass |
|
710 | except: pass | |
711 | for convert in conversions: |
|
711 | for convert in conversions: | |
712 | for val in qw(type_conv[convert]): |
|
712 | for val in qw(type_conv[convert]): | |
713 | try: |
|
713 | try: | |
714 | dict[val] = convert(dict[val]) |
|
714 | dict[val] = convert(dict[val]) | |
715 | except KeyError,e: |
|
715 | except KeyError,e: | |
716 | if opt['warn'] == 0: |
|
716 | if opt['warn'] == 0: | |
717 | pass |
|
717 | pass | |
718 | elif opt['warn'] == 1: |
|
718 | elif opt['warn'] == 1: | |
719 | print >>sys.stderr, 'Warning: key',val,\ |
|
719 | print >>sys.stderr, 'Warning: key',val,\ | |
720 | 'not found in file',filename |
|
720 | 'not found in file',filename | |
721 | elif opt['warn'] == 2: |
|
721 | elif opt['warn'] == 2: | |
722 | raise KeyError,e |
|
722 | raise KeyError,e | |
723 | else: |
|
723 | else: | |
724 | raise ValueError,'Warning level must be 0,1 or 2' |
|
724 | raise ValueError,'Warning level must be 0,1 or 2' | |
725 |
|
725 | |||
726 | return dict |
|
726 | return dict | |
727 |
|
727 | |||
728 | #---------------------------------------------------------------------------- |
|
728 | #---------------------------------------------------------------------------- | |
729 | def flag_calls(func): |
|
729 | def flag_calls(func): | |
730 | """Wrap a function to detect and flag when it gets called. |
|
730 | """Wrap a function to detect and flag when it gets called. | |
731 |
|
731 | |||
732 | This is a decorator which takes a function and wraps it in a function with |
|
732 | This is a decorator which takes a function and wraps it in a function with | |
733 | a 'called' attribute. wrapper.called is initialized to False. |
|
733 | a 'called' attribute. wrapper.called is initialized to False. | |
734 |
|
734 | |||
735 | The wrapper.called attribute is set to False right before each call to the |
|
735 | The wrapper.called attribute is set to False right before each call to the | |
736 | wrapped function, so if the call fails it remains False. After the call |
|
736 | wrapped function, so if the call fails it remains False. After the call | |
737 | completes, wrapper.called is set to True and the output is returned. |
|
737 | completes, wrapper.called is set to True and the output is returned. | |
738 |
|
738 | |||
739 | Testing for truth in wrapper.called allows you to determine if a call to |
|
739 | Testing for truth in wrapper.called allows you to determine if a call to | |
740 | func() was attempted and succeeded.""" |
|
740 | func() was attempted and succeeded.""" | |
741 |
|
741 | |||
742 | def wrapper(*args,**kw): |
|
742 | def wrapper(*args,**kw): | |
743 | wrapper.called = False |
|
743 | wrapper.called = False | |
744 | out = func(*args,**kw) |
|
744 | out = func(*args,**kw) | |
745 | wrapper.called = True |
|
745 | wrapper.called = True | |
746 | return out |
|
746 | return out | |
747 |
|
747 | |||
748 | wrapper.called = False |
|
748 | wrapper.called = False | |
749 | wrapper.__doc__ = func.__doc__ |
|
749 | wrapper.__doc__ = func.__doc__ | |
750 | return wrapper |
|
750 | return wrapper | |
751 |
|
751 | |||
752 | #---------------------------------------------------------------------------- |
|
752 | #---------------------------------------------------------------------------- | |
753 | class HomeDirError(Error): |
|
753 | class HomeDirError(Error): | |
754 | pass |
|
754 | pass | |
755 |
|
755 | |||
756 | def get_home_dir(): |
|
756 | def get_home_dir(): | |
757 | """Return the closest possible equivalent to a 'home' directory. |
|
757 | """Return the closest possible equivalent to a 'home' directory. | |
758 |
|
758 | |||
759 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
759 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. | |
760 |
|
760 | |||
761 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
761 | Currently only Posix and NT are implemented, a HomeDirError exception is | |
762 | raised for all other OSes. """ |
|
762 | raised for all other OSes. """ | |
763 |
|
763 | |||
764 | isdir = os.path.isdir |
|
764 | isdir = os.path.isdir | |
765 | env = os.environ |
|
765 | env = os.environ | |
766 | try: |
|
766 | try: | |
767 | homedir = env['HOME'] |
|
767 | homedir = env['HOME'] | |
768 | if not isdir(homedir): |
|
768 | if not isdir(homedir): | |
769 | # in case a user stuck some string which does NOT resolve to a |
|
769 | # in case a user stuck some string which does NOT resolve to a | |
770 | # valid path, it's as good as if we hadn't foud it |
|
770 | # valid path, it's as good as if we hadn't foud it | |
771 | raise KeyError |
|
771 | raise KeyError | |
772 | return homedir |
|
772 | return homedir | |
773 | except KeyError: |
|
773 | except KeyError: | |
774 | if os.name == 'posix': |
|
774 | if os.name == 'posix': | |
775 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
775 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' | |
776 | elif os.name == 'nt': |
|
776 | elif os.name == 'nt': | |
777 | # For some strange reason, win9x returns 'nt' for os.name. |
|
777 | # For some strange reason, win9x returns 'nt' for os.name. | |
778 | try: |
|
778 | try: | |
779 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
779 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) | |
780 | if not isdir(homedir): |
|
780 | if not isdir(homedir): | |
781 | homedir = os.path.join(env['USERPROFILE']) |
|
781 | homedir = os.path.join(env['USERPROFILE']) | |
782 | if not isdir(homedir): |
|
782 | if not isdir(homedir): | |
783 | raise HomeDirError |
|
783 | raise HomeDirError | |
784 | return homedir |
|
784 | return homedir | |
785 | except: |
|
785 | except: | |
786 | try: |
|
786 | try: | |
787 | # Use the registry to get the 'My Documents' folder. |
|
787 | # Use the registry to get the 'My Documents' folder. | |
788 | import _winreg as wreg |
|
788 | import _winreg as wreg | |
789 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
789 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, | |
790 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
790 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") | |
791 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
791 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
792 | key.Close() |
|
792 | key.Close() | |
793 | if not isdir(homedir): |
|
793 | if not isdir(homedir): | |
794 | e = ('Invalid "Personal" folder registry key ' |
|
794 | e = ('Invalid "Personal" folder registry key ' | |
795 | 'typically "My Documents".\n' |
|
795 | 'typically "My Documents".\n' | |
796 | 'Value: %s\n' |
|
796 | 'Value: %s\n' | |
797 | 'This is not a valid directory on your system.' % |
|
797 | 'This is not a valid directory on your system.' % | |
798 | homedir) |
|
798 | homedir) | |
799 | raise HomeDirError(e) |
|
799 | raise HomeDirError(e) | |
800 | return homedir |
|
800 | return homedir | |
801 | except HomeDirError: |
|
801 | except HomeDirError: | |
802 | raise |
|
802 | raise | |
803 | except: |
|
803 | except: | |
804 | return 'C:\\' |
|
804 | return 'C:\\' | |
805 | elif os.name == 'dos': |
|
805 | elif os.name == 'dos': | |
806 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
806 | # Desperate, may do absurd things in classic MacOS. May work under DOS. | |
807 | return 'C:\\' |
|
807 | return 'C:\\' | |
808 | else: |
|
808 | else: | |
809 | raise HomeDirError,'support for your operating system not implemented.' |
|
809 | raise HomeDirError,'support for your operating system not implemented.' | |
810 |
|
810 | |||
811 | #**************************************************************************** |
|
811 | #**************************************************************************** | |
812 | # strings and text |
|
812 | # strings and text | |
813 |
|
813 | |||
814 | class LSString(str): |
|
814 | class LSString(str): | |
815 | """String derivative with a special access attributes. |
|
815 | """String derivative with a special access attributes. | |
816 |
|
816 | |||
817 | These are normal strings, but with the special attributes: |
|
817 | These are normal strings, but with the special attributes: | |
818 |
|
818 | |||
819 | .l (or .list) : value as list (split on newlines). |
|
819 | .l (or .list) : value as list (split on newlines). | |
820 | .n (or .nlstr): original value (the string itself). |
|
820 | .n (or .nlstr): original value (the string itself). | |
821 | .s (or .spstr): value as whitespace-separated string. |
|
821 | .s (or .spstr): value as whitespace-separated string. | |
822 |
|
822 | |||
823 | Any values which require transformations are computed only once and |
|
823 | Any values which require transformations are computed only once and | |
824 | cached. |
|
824 | cached. | |
825 |
|
825 | |||
826 | Such strings are very useful to efficiently interact with the shell, which |
|
826 | Such strings are very useful to efficiently interact with the shell, which | |
827 | typically only understands whitespace-separated options for commands.""" |
|
827 | typically only understands whitespace-separated options for commands.""" | |
828 |
|
828 | |||
829 | def get_list(self): |
|
829 | def get_list(self): | |
830 | try: |
|
830 | try: | |
831 | return self.__list |
|
831 | return self.__list | |
832 | except AttributeError: |
|
832 | except AttributeError: | |
833 | self.__list = self.split('\n') |
|
833 | self.__list = self.split('\n') | |
834 | return self.__list |
|
834 | return self.__list | |
835 |
|
835 | |||
836 | l = list = property(get_list) |
|
836 | l = list = property(get_list) | |
837 |
|
837 | |||
838 | def get_spstr(self): |
|
838 | def get_spstr(self): | |
839 | try: |
|
839 | try: | |
840 | return self.__spstr |
|
840 | return self.__spstr | |
841 | except AttributeError: |
|
841 | except AttributeError: | |
842 | self.__spstr = self.replace('\n',' ') |
|
842 | self.__spstr = self.replace('\n',' ') | |
843 | return self.__spstr |
|
843 | return self.__spstr | |
844 |
|
844 | |||
845 | s = spstr = property(get_spstr) |
|
845 | s = spstr = property(get_spstr) | |
846 |
|
846 | |||
847 | def get_nlstr(self): |
|
847 | def get_nlstr(self): | |
848 | return self |
|
848 | return self | |
849 |
|
849 | |||
850 | n = nlstr = property(get_nlstr) |
|
850 | n = nlstr = property(get_nlstr) | |
851 |
|
851 | |||
852 | def get_paths(self): |
|
852 | def get_paths(self): | |
853 | try: |
|
853 | try: | |
854 | return self.__paths |
|
854 | return self.__paths | |
855 | except AttributeError: |
|
855 | except AttributeError: | |
856 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
856 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] | |
857 | return self.__paths |
|
857 | return self.__paths | |
858 |
|
858 | |||
859 | p = paths = property(get_paths) |
|
859 | p = paths = property(get_paths) | |
860 |
|
860 | |||
861 |
|
861 | |||
862 | #---------------------------------------------------------------------------- |
|
862 | #---------------------------------------------------------------------------- | |
863 | class SList(list): |
|
863 | class SList(list): | |
864 | """List derivative with a special access attributes. |
|
864 | """List derivative with a special access attributes. | |
865 |
|
865 | |||
866 | These are normal lists, but with the special attributes: |
|
866 | These are normal lists, but with the special attributes: | |
867 |
|
867 | |||
868 | .l (or .list) : value as list (the list itself). |
|
868 | .l (or .list) : value as list (the list itself). | |
869 | .n (or .nlstr): value as a string, joined on newlines. |
|
869 | .n (or .nlstr): value as a string, joined on newlines. | |
870 | .s (or .spstr): value as a string, joined on spaces. |
|
870 | .s (or .spstr): value as a string, joined on spaces. | |
871 |
|
871 | |||
872 | Any values which require transformations are computed only once and |
|
872 | Any values which require transformations are computed only once and | |
873 | cached.""" |
|
873 | cached.""" | |
874 |
|
874 | |||
875 | def get_list(self): |
|
875 | def get_list(self): | |
876 | return self |
|
876 | return self | |
877 |
|
877 | |||
878 | l = list = property(get_list) |
|
878 | l = list = property(get_list) | |
879 |
|
879 | |||
880 | def get_spstr(self): |
|
880 | def get_spstr(self): | |
881 | try: |
|
881 | try: | |
882 | return self.__spstr |
|
882 | return self.__spstr | |
883 | except AttributeError: |
|
883 | except AttributeError: | |
884 | self.__spstr = ' '.join(self) |
|
884 | self.__spstr = ' '.join(self) | |
885 | return self.__spstr |
|
885 | return self.__spstr | |
886 |
|
886 | |||
887 | s = spstr = property(get_spstr) |
|
887 | s = spstr = property(get_spstr) | |
888 |
|
888 | |||
889 | def get_nlstr(self): |
|
889 | def get_nlstr(self): | |
890 | try: |
|
890 | try: | |
891 | return self.__nlstr |
|
891 | return self.__nlstr | |
892 | except AttributeError: |
|
892 | except AttributeError: | |
893 | self.__nlstr = '\n'.join(self) |
|
893 | self.__nlstr = '\n'.join(self) | |
894 | return self.__nlstr |
|
894 | return self.__nlstr | |
895 |
|
895 | |||
896 | n = nlstr = property(get_nlstr) |
|
896 | n = nlstr = property(get_nlstr) | |
897 |
|
897 | |||
898 | def get_paths(self): |
|
898 | def get_paths(self): | |
899 | try: |
|
899 | try: | |
900 | return self.__paths |
|
900 | return self.__paths | |
901 | except AttributeError: |
|
901 | except AttributeError: | |
902 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
902 | self.__paths = [path(p) for p in self if os.path.exists(p)] | |
903 | return self.__paths |
|
903 | return self.__paths | |
904 |
|
904 | |||
905 | p = paths = property(get_paths) |
|
905 | p = paths = property(get_paths) | |
906 |
|
906 | |||
907 | #---------------------------------------------------------------------------- |
|
907 | #---------------------------------------------------------------------------- | |
908 | def esc_quotes(strng): |
|
908 | def esc_quotes(strng): | |
909 | """Return the input string with single and double quotes escaped out""" |
|
909 | """Return the input string with single and double quotes escaped out""" | |
910 |
|
910 | |||
911 | return strng.replace('"','\\"').replace("'","\\'") |
|
911 | return strng.replace('"','\\"').replace("'","\\'") | |
912 |
|
912 | |||
913 | #---------------------------------------------------------------------------- |
|
913 | #---------------------------------------------------------------------------- | |
914 | def make_quoted_expr(s): |
|
914 | def make_quoted_expr(s): | |
915 | """Return string s in appropriate quotes, using raw string if possible. |
|
915 | """Return string s in appropriate quotes, using raw string if possible. | |
916 |
|
916 | |||
917 | Effectively this turns string: cd \ao\ao\ |
|
917 | Effectively this turns string: cd \ao\ao\ | |
918 | to: r"cd \ao\ao\_"[:-1] |
|
918 | to: r"cd \ao\ao\_"[:-1] | |
919 |
|
919 | |||
920 | Note the use of raw string and padding at the end to allow trailing backslash. |
|
920 | Note the use of raw string and padding at the end to allow trailing backslash. | |
921 |
|
921 | |||
922 | """ |
|
922 | """ | |
923 |
|
923 | |||
924 | tail = '' |
|
924 | tail = '' | |
925 | tailpadding = '' |
|
925 | tailpadding = '' | |
926 | raw = '' |
|
926 | raw = '' | |
927 | if "\\" in s: |
|
927 | if "\\" in s: | |
928 | raw = 'r' |
|
928 | raw = 'r' | |
929 | if s.endswith('\\'): |
|
929 | if s.endswith('\\'): | |
930 | tail = '[:-1]' |
|
930 | tail = '[:-1]' | |
931 | tailpadding = '_' |
|
931 | tailpadding = '_' | |
932 | if '"' not in s: |
|
932 | if '"' not in s: | |
933 | quote = '"' |
|
933 | quote = '"' | |
934 | elif "'" not in s: |
|
934 | elif "'" not in s: | |
935 | quote = "'" |
|
935 | quote = "'" | |
936 | elif '"""' not in s and not s.endswith('"'): |
|
936 | elif '"""' not in s and not s.endswith('"'): | |
937 | quote = '"""' |
|
937 | quote = '"""' | |
938 | elif "'''" not in s and not s.endswith("'"): |
|
938 | elif "'''" not in s and not s.endswith("'"): | |
939 | quote = "'''" |
|
939 | quote = "'''" | |
940 | else: |
|
940 | else: | |
941 | # give up, backslash-escaped string will do |
|
941 | # give up, backslash-escaped string will do | |
942 | return '"%s"' % esc_quotes(s) |
|
942 | return '"%s"' % esc_quotes(s) | |
943 | res = itpl("$raw$quote$s$tailpadding$quote$tail") |
|
943 | res = itpl("$raw$quote$s$tailpadding$quote$tail") | |
944 | return res |
|
944 | return res | |
945 |
|
945 | |||
946 |
|
946 | |||
947 | #---------------------------------------------------------------------------- |
|
947 | #---------------------------------------------------------------------------- | |
948 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
948 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): | |
949 | """Take multiple lines of input. |
|
949 | """Take multiple lines of input. | |
950 |
|
950 | |||
951 | A list with each line of input as a separate element is returned when a |
|
951 | A list with each line of input as a separate element is returned when a | |
952 | termination string is entered (defaults to a single '.'). Input can also |
|
952 | termination string is entered (defaults to a single '.'). Input can also | |
953 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
953 | terminate via EOF (^D in Unix, ^Z-RET in Windows). | |
954 |
|
954 | |||
955 | Lines of input which end in \\ are joined into single entries (and a |
|
955 | Lines of input which end in \\ are joined into single entries (and a | |
956 | secondary continuation prompt is issued as long as the user terminates |
|
956 | secondary continuation prompt is issued as long as the user terminates | |
957 | lines with \\). This allows entering very long strings which are still |
|
957 | lines with \\). This allows entering very long strings which are still | |
958 | meant to be treated as single entities. |
|
958 | meant to be treated as single entities. | |
959 | """ |
|
959 | """ | |
960 |
|
960 | |||
961 | try: |
|
961 | try: | |
962 | if header: |
|
962 | if header: | |
963 | header += '\n' |
|
963 | header += '\n' | |
964 | lines = [raw_input(header + ps1)] |
|
964 | lines = [raw_input(header + ps1)] | |
965 | except EOFError: |
|
965 | except EOFError: | |
966 | return [] |
|
966 | return [] | |
967 | terminate = [terminate_str] |
|
967 | terminate = [terminate_str] | |
968 | try: |
|
968 | try: | |
969 | while lines[-1:] != terminate: |
|
969 | while lines[-1:] != terminate: | |
970 | new_line = raw_input(ps1) |
|
970 | new_line = raw_input(ps1) | |
971 | while new_line.endswith('\\'): |
|
971 | while new_line.endswith('\\'): | |
972 | new_line = new_line[:-1] + raw_input(ps2) |
|
972 | new_line = new_line[:-1] + raw_input(ps2) | |
973 | lines.append(new_line) |
|
973 | lines.append(new_line) | |
974 |
|
974 | |||
975 | return lines[:-1] # don't return the termination command |
|
975 | return lines[:-1] # don't return the termination command | |
976 | except EOFError: |
|
976 | except EOFError: | |
977 |
|
977 | |||
978 | return lines |
|
978 | return lines | |
979 |
|
979 | |||
980 | #---------------------------------------------------------------------------- |
|
980 | #---------------------------------------------------------------------------- | |
981 | def raw_input_ext(prompt='', ps2='... '): |
|
981 | def raw_input_ext(prompt='', ps2='... '): | |
982 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
982 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" | |
983 |
|
983 | |||
984 | line = raw_input(prompt) |
|
984 | line = raw_input(prompt) | |
985 | while line.endswith('\\'): |
|
985 | while line.endswith('\\'): | |
986 | line = line[:-1] + raw_input(ps2) |
|
986 | line = line[:-1] + raw_input(ps2) | |
987 | return line |
|
987 | return line | |
988 |
|
988 | |||
989 | #---------------------------------------------------------------------------- |
|
989 | #---------------------------------------------------------------------------- | |
990 | def ask_yes_no(prompt,default=None): |
|
990 | def ask_yes_no(prompt,default=None): | |
991 | """Asks a question and returns an integer 1/0 (y/n) answer. |
|
991 | """Asks a question and returns an integer 1/0 (y/n) answer. | |
992 |
|
992 | |||
993 | If default is given (one of 'y','n'), it is used if the user input is |
|
993 | If default is given (one of 'y','n'), it is used if the user input is | |
994 | empty. Otherwise the question is repeated until an answer is given. |
|
994 | empty. Otherwise the question is repeated until an answer is given. | |
995 | If EOF occurs 20 times consecutively, the default answer is assumed, |
|
995 | If EOF occurs 20 times consecutively, the default answer is assumed, | |
996 | or if there is no default, an exception is raised to prevent infinite |
|
996 | or if there is no default, an exception is raised to prevent infinite | |
997 | loops. |
|
997 | loops. | |
998 |
|
998 | |||
999 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
999 | Valid answers are: y/yes/n/no (match is not case sensitive).""" | |
1000 |
|
1000 | |||
1001 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
1001 | answers = {'y':True,'n':False,'yes':True,'no':False} | |
1002 | ans = None |
|
1002 | ans = None | |
1003 | eofs, max_eofs = 0, 20 |
|
1003 | eofs, max_eofs = 0, 20 | |
1004 | while ans not in answers.keys(): |
|
1004 | while ans not in answers.keys(): | |
1005 | try: |
|
1005 | try: | |
1006 | ans = raw_input(prompt+' ').lower() |
|
1006 | ans = raw_input(prompt+' ').lower() | |
1007 | if not ans: # response was an empty string |
|
1007 | if not ans: # response was an empty string | |
1008 | ans = default |
|
1008 | ans = default | |
1009 | eofs = 0 |
|
1009 | eofs = 0 | |
1010 | except (EOFError,KeyboardInterrupt): |
|
1010 | except (EOFError,KeyboardInterrupt): | |
1011 | eofs = eofs + 1 |
|
1011 | eofs = eofs + 1 | |
1012 | if eofs >= max_eofs: |
|
1012 | if eofs >= max_eofs: | |
1013 | if default in answers.keys(): |
|
1013 | if default in answers.keys(): | |
1014 | ans = default |
|
1014 | ans = default | |
1015 | else: |
|
1015 | else: | |
1016 | raise |
|
1016 | raise | |
1017 |
|
1017 | |||
1018 | return answers[ans] |
|
1018 | return answers[ans] | |
1019 |
|
1019 | |||
1020 | #---------------------------------------------------------------------------- |
|
1020 | #---------------------------------------------------------------------------- | |
1021 | def marquee(txt='',width=78,mark='*'): |
|
1021 | def marquee(txt='',width=78,mark='*'): | |
1022 | """Return the input string centered in a 'marquee'.""" |
|
1022 | """Return the input string centered in a 'marquee'.""" | |
1023 | if not txt: |
|
1023 | if not txt: | |
1024 | return (mark*width)[:width] |
|
1024 | return (mark*width)[:width] | |
1025 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
1025 | nmark = (width-len(txt)-2)/len(mark)/2 | |
1026 | if nmark < 0: nmark =0 |
|
1026 | if nmark < 0: nmark =0 | |
1027 | marks = mark*nmark |
|
1027 | marks = mark*nmark | |
1028 | return '%s %s %s' % (marks,txt,marks) |
|
1028 | return '%s %s %s' % (marks,txt,marks) | |
1029 |
|
1029 | |||
1030 | #---------------------------------------------------------------------------- |
|
1030 | #---------------------------------------------------------------------------- | |
1031 | class EvalDict: |
|
1031 | class EvalDict: | |
1032 | """ |
|
1032 | """ | |
1033 | Emulate a dict which evaluates its contents in the caller's frame. |
|
1033 | Emulate a dict which evaluates its contents in the caller's frame. | |
1034 |
|
1034 | |||
1035 | Usage: |
|
1035 | Usage: | |
1036 | >>>number = 19 |
|
1036 | >>>number = 19 | |
1037 | >>>text = "python" |
|
1037 | >>>text = "python" | |
1038 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
1038 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() | |
1039 | """ |
|
1039 | """ | |
1040 |
|
1040 | |||
1041 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
1041 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a | |
1042 | # modified (shorter) version of: |
|
1042 | # modified (shorter) version of: | |
1043 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
1043 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by | |
1044 | # Skip Montanaro (skip@pobox.com). |
|
1044 | # Skip Montanaro (skip@pobox.com). | |
1045 |
|
1045 | |||
1046 | def __getitem__(self, name): |
|
1046 | def __getitem__(self, name): | |
1047 | frame = sys._getframe(1) |
|
1047 | frame = sys._getframe(1) | |
1048 | return eval(name, frame.f_globals, frame.f_locals) |
|
1048 | return eval(name, frame.f_globals, frame.f_locals) | |
1049 |
|
1049 | |||
1050 | EvalString = EvalDict # for backwards compatibility |
|
1050 | EvalString = EvalDict # for backwards compatibility | |
1051 | #---------------------------------------------------------------------------- |
|
1051 | #---------------------------------------------------------------------------- | |
1052 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
1052 | def qw(words,flat=0,sep=None,maxsplit=-1): | |
1053 | """Similar to Perl's qw() operator, but with some more options. |
|
1053 | """Similar to Perl's qw() operator, but with some more options. | |
1054 |
|
1054 | |||
1055 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
1055 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) | |
1056 |
|
1056 | |||
1057 | words can also be a list itself, and with flat=1, the output will be |
|
1057 | words can also be a list itself, and with flat=1, the output will be | |
1058 | recursively flattened. Examples: |
|
1058 | recursively flattened. Examples: | |
1059 |
|
1059 | |||
1060 | >>> qw('1 2') |
|
1060 | >>> qw('1 2') | |
1061 | ['1', '2'] |
|
1061 | ['1', '2'] | |
1062 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1062 | >>> qw(['a b','1 2',['m n','p q']]) | |
1063 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1063 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] | |
1064 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1064 | >>> qw(['a b','1 2',['m n','p q']],flat=1) | |
1065 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ |
|
1065 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ | |
1066 |
|
1066 | |||
1067 | if type(words) in StringTypes: |
|
1067 | if type(words) in StringTypes: | |
1068 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1068 | return [word.strip() for word in words.split(sep,maxsplit) | |
1069 | if word and not word.isspace() ] |
|
1069 | if word and not word.isspace() ] | |
1070 | if flat: |
|
1070 | if flat: | |
1071 | return flatten(map(qw,words,[1]*len(words))) |
|
1071 | return flatten(map(qw,words,[1]*len(words))) | |
1072 | return map(qw,words) |
|
1072 | return map(qw,words) | |
1073 |
|
1073 | |||
1074 | #---------------------------------------------------------------------------- |
|
1074 | #---------------------------------------------------------------------------- | |
1075 | def qwflat(words,sep=None,maxsplit=-1): |
|
1075 | def qwflat(words,sep=None,maxsplit=-1): | |
1076 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1076 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" | |
1077 | return qw(words,1,sep,maxsplit) |
|
1077 | return qw(words,1,sep,maxsplit) | |
1078 |
|
1078 | |||
1079 | #---------------------------------------------------------------------------- |
|
1079 | #---------------------------------------------------------------------------- | |
1080 | def qw_lol(indata): |
|
1080 | def qw_lol(indata): | |
1081 | """qw_lol('a b') -> [['a','b']], |
|
1081 | """qw_lol('a b') -> [['a','b']], | |
1082 | otherwise it's just a call to qw(). |
|
1082 | otherwise it's just a call to qw(). | |
1083 |
|
1083 | |||
1084 | We need this to make sure the modules_some keys *always* end up as a |
|
1084 | We need this to make sure the modules_some keys *always* end up as a | |
1085 | list of lists.""" |
|
1085 | list of lists.""" | |
1086 |
|
1086 | |||
1087 | if type(indata) in StringTypes: |
|
1087 | if type(indata) in StringTypes: | |
1088 | return [qw(indata)] |
|
1088 | return [qw(indata)] | |
1089 | else: |
|
1089 | else: | |
1090 | return qw(indata) |
|
1090 | return qw(indata) | |
1091 |
|
1091 | |||
1092 | #----------------------------------------------------------------------------- |
|
1092 | #----------------------------------------------------------------------------- | |
1093 | def list_strings(arg): |
|
1093 | def list_strings(arg): | |
1094 | """Always return a list of strings, given a string or list of strings |
|
1094 | """Always return a list of strings, given a string or list of strings | |
1095 | as input.""" |
|
1095 | as input.""" | |
1096 |
|
1096 | |||
1097 | if type(arg) in StringTypes: return [arg] |
|
1097 | if type(arg) in StringTypes: return [arg] | |
1098 | else: return arg |
|
1098 | else: return arg | |
1099 |
|
1099 | |||
1100 | #---------------------------------------------------------------------------- |
|
1100 | #---------------------------------------------------------------------------- | |
1101 | def grep(pat,list,case=1): |
|
1101 | def grep(pat,list,case=1): | |
1102 | """Simple minded grep-like function. |
|
1102 | """Simple minded grep-like function. | |
1103 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1103 | grep(pat,list) returns occurrences of pat in list, None on failure. | |
1104 |
|
1104 | |||
1105 | It only does simple string matching, with no support for regexps. Use the |
|
1105 | It only does simple string matching, with no support for regexps. Use the | |
1106 | option case=0 for case-insensitive matching.""" |
|
1106 | option case=0 for case-insensitive matching.""" | |
1107 |
|
1107 | |||
1108 | # This is pretty crude. At least it should implement copying only references |
|
1108 | # This is pretty crude. At least it should implement copying only references | |
1109 | # to the original data in case it's big. Now it copies the data for output. |
|
1109 | # to the original data in case it's big. Now it copies the data for output. | |
1110 | out=[] |
|
1110 | out=[] | |
1111 | if case: |
|
1111 | if case: | |
1112 | for term in list: |
|
1112 | for term in list: | |
1113 | if term.find(pat)>-1: out.append(term) |
|
1113 | if term.find(pat)>-1: out.append(term) | |
1114 | else: |
|
1114 | else: | |
1115 | lpat=pat.lower() |
|
1115 | lpat=pat.lower() | |
1116 | for term in list: |
|
1116 | for term in list: | |
1117 | if term.lower().find(lpat)>-1: out.append(term) |
|
1117 | if term.lower().find(lpat)>-1: out.append(term) | |
1118 |
|
1118 | |||
1119 | if len(out): return out |
|
1119 | if len(out): return out | |
1120 | else: return None |
|
1120 | else: return None | |
1121 |
|
1121 | |||
1122 | #---------------------------------------------------------------------------- |
|
1122 | #---------------------------------------------------------------------------- | |
1123 | def dgrep(pat,*opts): |
|
1123 | def dgrep(pat,*opts): | |
1124 | """Return grep() on dir()+dir(__builtins__). |
|
1124 | """Return grep() on dir()+dir(__builtins__). | |
1125 |
|
1125 | |||
1126 | A very common use of grep() when working interactively.""" |
|
1126 | A very common use of grep() when working interactively.""" | |
1127 |
|
1127 | |||
1128 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1128 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) | |
1129 |
|
1129 | |||
1130 | #---------------------------------------------------------------------------- |
|
1130 | #---------------------------------------------------------------------------- | |
1131 | def idgrep(pat): |
|
1131 | def idgrep(pat): | |
1132 | """Case-insensitive dgrep()""" |
|
1132 | """Case-insensitive dgrep()""" | |
1133 |
|
1133 | |||
1134 | return dgrep(pat,0) |
|
1134 | return dgrep(pat,0) | |
1135 |
|
1135 | |||
1136 | #---------------------------------------------------------------------------- |
|
1136 | #---------------------------------------------------------------------------- | |
1137 | def igrep(pat,list): |
|
1137 | def igrep(pat,list): | |
1138 | """Synonym for case-insensitive grep.""" |
|
1138 | """Synonym for case-insensitive grep.""" | |
1139 |
|
1139 | |||
1140 | return grep(pat,list,case=0) |
|
1140 | return grep(pat,list,case=0) | |
1141 |
|
1141 | |||
1142 | #---------------------------------------------------------------------------- |
|
1142 | #---------------------------------------------------------------------------- | |
1143 | def indent(str,nspaces=4,ntabs=0): |
|
1143 | def indent(str,nspaces=4,ntabs=0): | |
1144 | """Indent a string a given number of spaces or tabstops. |
|
1144 | """Indent a string a given number of spaces or tabstops. | |
1145 |
|
1145 | |||
1146 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1146 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. | |
1147 | """ |
|
1147 | """ | |
1148 | if str is None: |
|
1148 | if str is None: | |
1149 | return |
|
1149 | return | |
1150 | ind = '\t'*ntabs+' '*nspaces |
|
1150 | ind = '\t'*ntabs+' '*nspaces | |
1151 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1151 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) | |
1152 | if outstr.endswith(os.linesep+ind): |
|
1152 | if outstr.endswith(os.linesep+ind): | |
1153 | return outstr[:-len(ind)] |
|
1153 | return outstr[:-len(ind)] | |
1154 | else: |
|
1154 | else: | |
1155 | return outstr |
|
1155 | return outstr | |
1156 |
|
1156 | |||
1157 | #----------------------------------------------------------------------------- |
|
1157 | #----------------------------------------------------------------------------- | |
1158 | def native_line_ends(filename,backup=1): |
|
1158 | def native_line_ends(filename,backup=1): | |
1159 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1159 | """Convert (in-place) a file to line-ends native to the current OS. | |
1160 |
|
1160 | |||
1161 | If the optional backup argument is given as false, no backup of the |
|
1161 | If the optional backup argument is given as false, no backup of the | |
1162 | original file is left. """ |
|
1162 | original file is left. """ | |
1163 |
|
1163 | |||
1164 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1164 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} | |
1165 |
|
1165 | |||
1166 | bak_filename = filename + backup_suffixes[os.name] |
|
1166 | bak_filename = filename + backup_suffixes[os.name] | |
1167 |
|
1167 | |||
1168 | original = open(filename).read() |
|
1168 | original = open(filename).read() | |
1169 | shutil.copy2(filename,bak_filename) |
|
1169 | shutil.copy2(filename,bak_filename) | |
1170 | try: |
|
1170 | try: | |
1171 | new = open(filename,'wb') |
|
1171 | new = open(filename,'wb') | |
1172 | new.write(os.linesep.join(original.splitlines())) |
|
1172 | new.write(os.linesep.join(original.splitlines())) | |
1173 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1173 | new.write(os.linesep) # ALWAYS put an eol at the end of the file | |
1174 | new.close() |
|
1174 | new.close() | |
1175 | except: |
|
1175 | except: | |
1176 | os.rename(bak_filename,filename) |
|
1176 | os.rename(bak_filename,filename) | |
1177 | if not backup: |
|
1177 | if not backup: | |
1178 | try: |
|
1178 | try: | |
1179 | os.remove(bak_filename) |
|
1179 | os.remove(bak_filename) | |
1180 | except: |
|
1180 | except: | |
1181 | pass |
|
1181 | pass | |
1182 |
|
1182 | |||
1183 | #---------------------------------------------------------------------------- |
|
1183 | #---------------------------------------------------------------------------- | |
1184 | def get_pager_cmd(pager_cmd = None): |
|
1184 | def get_pager_cmd(pager_cmd = None): | |
1185 | """Return a pager command. |
|
1185 | """Return a pager command. | |
1186 |
|
1186 | |||
1187 | Makes some attempts at finding an OS-correct one.""" |
|
1187 | Makes some attempts at finding an OS-correct one.""" | |
1188 |
|
1188 | |||
1189 | if os.name == 'posix': |
|
1189 | if os.name == 'posix': | |
1190 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1190 | default_pager_cmd = 'less -r' # -r for color control sequences | |
1191 | elif os.name in ['nt','dos']: |
|
1191 | elif os.name in ['nt','dos']: | |
1192 | default_pager_cmd = 'type' |
|
1192 | default_pager_cmd = 'type' | |
1193 |
|
1193 | |||
1194 | if pager_cmd is None: |
|
1194 | if pager_cmd is None: | |
1195 | try: |
|
1195 | try: | |
1196 | pager_cmd = os.environ['PAGER'] |
|
1196 | pager_cmd = os.environ['PAGER'] | |
1197 | except: |
|
1197 | except: | |
1198 | pager_cmd = default_pager_cmd |
|
1198 | pager_cmd = default_pager_cmd | |
1199 | return pager_cmd |
|
1199 | return pager_cmd | |
1200 |
|
1200 | |||
1201 | #----------------------------------------------------------------------------- |
|
1201 | #----------------------------------------------------------------------------- | |
1202 | def get_pager_start(pager,start): |
|
1202 | def get_pager_start(pager,start): | |
1203 | """Return the string for paging files with an offset. |
|
1203 | """Return the string for paging files with an offset. | |
1204 |
|
1204 | |||
1205 | This is the '+N' argument which less and more (under Unix) accept. |
|
1205 | This is the '+N' argument which less and more (under Unix) accept. | |
1206 | """ |
|
1206 | """ | |
1207 |
|
1207 | |||
1208 | if pager in ['less','more']: |
|
1208 | if pager in ['less','more']: | |
1209 | if start: |
|
1209 | if start: | |
1210 | start_string = '+' + str(start) |
|
1210 | start_string = '+' + str(start) | |
1211 | else: |
|
1211 | else: | |
1212 | start_string = '' |
|
1212 | start_string = '' | |
1213 | else: |
|
1213 | else: | |
1214 | start_string = '' |
|
1214 | start_string = '' | |
1215 | return start_string |
|
1215 | return start_string | |
1216 |
|
1216 | |||
1217 | #---------------------------------------------------------------------------- |
|
1217 | #---------------------------------------------------------------------------- | |
1218 | if os.name == "nt": |
|
1218 | if os.name == "nt": | |
1219 | import msvcrt |
|
1219 | import msvcrt | |
1220 | def page_more(): |
|
1220 | def page_more(): | |
1221 | """ Smart pausing between pages |
|
1221 | """ Smart pausing between pages | |
1222 |
|
1222 | |||
1223 | @return: True if need print more lines, False if quit |
|
1223 | @return: True if need print more lines, False if quit | |
1224 | """ |
|
1224 | """ | |
1225 | Term.cout.write('---Return to continue, q to quit--- ') |
|
1225 | Term.cout.write('---Return to continue, q to quit--- ') | |
1226 | ans = msvcrt.getch() |
|
1226 | ans = msvcrt.getch() | |
1227 | if ans in ("q", "Q"): |
|
1227 | if ans in ("q", "Q"): | |
1228 | result = False |
|
1228 | result = False | |
1229 | else: |
|
1229 | else: | |
1230 | result = True |
|
1230 | result = True | |
1231 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) |
|
1231 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) | |
1232 | return result |
|
1232 | return result | |
1233 | else: |
|
1233 | else: | |
1234 | def page_more(): |
|
1234 | def page_more(): | |
1235 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1235 | ans = raw_input('---Return to continue, q to quit--- ') | |
1236 | if ans.lower().startswith('q'): |
|
1236 | if ans.lower().startswith('q'): | |
1237 | return False |
|
1237 | return False | |
1238 | else: |
|
1238 | else: | |
1239 | return True |
|
1239 | return True | |
1240 |
|
1240 | |||
1241 | esc_re = re.compile(r"(\x1b[^m]+m)") |
|
1241 | esc_re = re.compile(r"(\x1b[^m]+m)") | |
1242 |
|
1242 | |||
1243 | def page_dumb(strng,start=0,screen_lines=25): |
|
1243 | def page_dumb(strng,start=0,screen_lines=25): | |
1244 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1244 | """Very dumb 'pager' in Python, for when nothing else works. | |
1245 |
|
1245 | |||
1246 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1246 | Only moves forward, same interface as page(), except for pager_cmd and | |
1247 | mode.""" |
|
1247 | mode.""" | |
1248 |
|
1248 | |||
1249 | out_ln = strng.splitlines()[start:] |
|
1249 | out_ln = strng.splitlines()[start:] | |
1250 | screens = chop(out_ln,screen_lines-1) |
|
1250 | screens = chop(out_ln,screen_lines-1) | |
1251 | if len(screens) == 1: |
|
1251 | if len(screens) == 1: | |
1252 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1252 | print >>Term.cout, os.linesep.join(screens[0]) | |
1253 | else: |
|
1253 | else: | |
1254 | last_escape = "" |
|
1254 | last_escape = "" | |
1255 | for scr in screens[0:-1]: |
|
1255 | for scr in screens[0:-1]: | |
1256 | hunk = os.linesep.join(scr) |
|
1256 | hunk = os.linesep.join(scr) | |
1257 | print >>Term.cout, last_escape + hunk |
|
1257 | print >>Term.cout, last_escape + hunk | |
1258 | if not page_more(): |
|
1258 | if not page_more(): | |
1259 | return |
|
1259 | return | |
1260 | esc_list = esc_re.findall(hunk) |
|
1260 | esc_list = esc_re.findall(hunk) | |
1261 | if len(esc_list) > 0: |
|
1261 | if len(esc_list) > 0: | |
1262 | last_escape = esc_list[-1] |
|
1262 | last_escape = esc_list[-1] | |
1263 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) |
|
1263 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) | |
1264 |
|
1264 | |||
1265 | #---------------------------------------------------------------------------- |
|
1265 | #---------------------------------------------------------------------------- | |
1266 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1266 | def page(strng,start=0,screen_lines=0,pager_cmd = None): | |
1267 | """Print a string, piping through a pager after a certain length. |
|
1267 | """Print a string, piping through a pager after a certain length. | |
1268 |
|
1268 | |||
1269 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1269 | The screen_lines parameter specifies the number of *usable* lines of your | |
1270 | terminal screen (total lines minus lines you need to reserve to show other |
|
1270 | terminal screen (total lines minus lines you need to reserve to show other | |
1271 | information). |
|
1271 | information). | |
1272 |
|
1272 | |||
1273 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1273 | If you set screen_lines to a number <=0, page() will try to auto-determine | |
1274 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1274 | your screen size and will only use up to (screen_size+screen_lines) for | |
1275 | printing, paging after that. That is, if you want auto-detection but need |
|
1275 | printing, paging after that. That is, if you want auto-detection but need | |
1276 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1276 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for | |
1277 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1277 | auto-detection without any lines reserved simply use screen_lines = 0. | |
1278 |
|
1278 | |||
1279 | If a string won't fit in the allowed lines, it is sent through the |
|
1279 | If a string won't fit in the allowed lines, it is sent through the | |
1280 | specified pager command. If none given, look for PAGER in the environment, |
|
1280 | specified pager command. If none given, look for PAGER in the environment, | |
1281 | and ultimately default to less. |
|
1281 | and ultimately default to less. | |
1282 |
|
1282 | |||
1283 | If no system pager works, the string is sent through a 'dumb pager' |
|
1283 | If no system pager works, the string is sent through a 'dumb pager' | |
1284 | written in python, very simplistic. |
|
1284 | written in python, very simplistic. | |
1285 | """ |
|
1285 | """ | |
1286 |
|
1286 | |||
1287 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1287 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs | |
1288 | TERM = os.environ.get('TERM','dumb') |
|
1288 | TERM = os.environ.get('TERM','dumb') | |
1289 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1289 | if TERM in ['dumb','emacs'] and os.name != 'nt': | |
1290 | print strng |
|
1290 | print strng | |
1291 | return |
|
1291 | return | |
1292 | # chop off the topmost part of the string we don't want to see |
|
1292 | # chop off the topmost part of the string we don't want to see | |
1293 | str_lines = strng.split(os.linesep)[start:] |
|
1293 | str_lines = strng.split(os.linesep)[start:] | |
1294 | str_toprint = os.linesep.join(str_lines) |
|
1294 | str_toprint = os.linesep.join(str_lines) | |
1295 | num_newlines = len(str_lines) |
|
1295 | num_newlines = len(str_lines) | |
1296 | len_str = len(str_toprint) |
|
1296 | len_str = len(str_toprint) | |
1297 |
|
1297 | |||
1298 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1298 | # Dumb heuristics to guesstimate number of on-screen lines the string | |
1299 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1299 | # takes. Very basic, but good enough for docstrings in reasonable | |
1300 | # terminals. If someone later feels like refining it, it's not hard. |
|
1300 | # terminals. If someone later feels like refining it, it's not hard. | |
1301 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1301 | numlines = max(num_newlines,int(len_str/80)+1) | |
1302 |
|
1302 | |||
1303 | if os.name == "nt": |
|
1303 | if os.name == "nt": | |
1304 | screen_lines_def = get_console_size(defaulty=25)[1] |
|
1304 | screen_lines_def = get_console_size(defaulty=25)[1] | |
1305 | else: |
|
1305 | else: | |
1306 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1306 | screen_lines_def = 25 # default value if we can't auto-determine | |
1307 |
|
1307 | |||
1308 | # auto-determine screen size |
|
1308 | # auto-determine screen size | |
1309 | if screen_lines <= 0: |
|
1309 | if screen_lines <= 0: | |
1310 | if TERM=='xterm': |
|
1310 | if TERM=='xterm': | |
1311 | try: |
|
1311 | try: | |
1312 | import curses |
|
1312 | import curses | |
1313 | if hasattr(curses,'initscr'): |
|
1313 | if hasattr(curses,'initscr'): | |
1314 | use_curses = 1 |
|
1314 | use_curses = 1 | |
1315 | else: |
|
1315 | else: | |
1316 | use_curses = 0 |
|
1316 | use_curses = 0 | |
1317 | except ImportError: |
|
1317 | except ImportError: | |
1318 | use_curses = 0 |
|
1318 | use_curses = 0 | |
1319 | else: |
|
1319 | else: | |
1320 | # curses causes problems on many terminals other than xterm. |
|
1320 | # curses causes problems on many terminals other than xterm. | |
1321 | use_curses = 0 |
|
1321 | use_curses = 0 | |
1322 | if use_curses: |
|
1322 | if use_curses: | |
1323 | scr = curses.initscr() |
|
1323 | scr = curses.initscr() | |
1324 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1324 | screen_lines_real,screen_cols = scr.getmaxyx() | |
1325 | curses.endwin() |
|
1325 | curses.endwin() | |
1326 | screen_lines += screen_lines_real |
|
1326 | screen_lines += screen_lines_real | |
1327 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1327 | #print '***Screen size:',screen_lines_real,'lines x',\ | |
1328 | #screen_cols,'columns.' # dbg |
|
1328 | #screen_cols,'columns.' # dbg | |
1329 | else: |
|
1329 | else: | |
1330 | screen_lines += screen_lines_def |
|
1330 | screen_lines += screen_lines_def | |
1331 |
|
1331 | |||
1332 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1332 | #print 'numlines',numlines,'screenlines',screen_lines # dbg | |
1333 | if numlines <= screen_lines : |
|
1333 | if numlines <= screen_lines : | |
1334 | #print '*** normal print' # dbg |
|
1334 | #print '*** normal print' # dbg | |
1335 | print >>Term.cout, str_toprint |
|
1335 | print >>Term.cout, str_toprint | |
1336 | else: |
|
1336 | else: | |
1337 | # Try to open pager and default to internal one if that fails. |
|
1337 | # Try to open pager and default to internal one if that fails. | |
1338 | # All failure modes are tagged as 'retval=1', to match the return |
|
1338 | # All failure modes are tagged as 'retval=1', to match the return | |
1339 | # value of a failed system command. If any intermediate attempt |
|
1339 | # value of a failed system command. If any intermediate attempt | |
1340 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1340 | # sets retval to 1, at the end we resort to our own page_dumb() pager. | |
1341 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1341 | pager_cmd = get_pager_cmd(pager_cmd) | |
1342 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1342 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1343 | if os.name == 'nt': |
|
1343 | if os.name == 'nt': | |
1344 | if pager_cmd.startswith('type'): |
|
1344 | if pager_cmd.startswith('type'): | |
1345 | # The default WinXP 'type' command is failing on complex strings. |
|
1345 | # The default WinXP 'type' command is failing on complex strings. | |
1346 | retval = 1 |
|
1346 | retval = 1 | |
1347 | else: |
|
1347 | else: | |
1348 | tmpname = tempfile.mktemp('.txt') |
|
1348 | tmpname = tempfile.mktemp('.txt') | |
1349 | tmpfile = file(tmpname,'wt') |
|
1349 | tmpfile = file(tmpname,'wt') | |
1350 | tmpfile.write(strng) |
|
1350 | tmpfile.write(strng) | |
1351 | tmpfile.close() |
|
1351 | tmpfile.close() | |
1352 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1352 | cmd = "%s < %s" % (pager_cmd,tmpname) | |
1353 | if os.system(cmd): |
|
1353 | if os.system(cmd): | |
1354 | retval = 1 |
|
1354 | retval = 1 | |
1355 | else: |
|
1355 | else: | |
1356 | retval = None |
|
1356 | retval = None | |
1357 | os.remove(tmpname) |
|
1357 | os.remove(tmpname) | |
1358 | else: |
|
1358 | else: | |
1359 | try: |
|
1359 | try: | |
1360 | retval = None |
|
1360 | retval = None | |
1361 | # if I use popen4, things hang. No idea why. |
|
1361 | # if I use popen4, things hang. No idea why. | |
1362 | #pager,shell_out = os.popen4(pager_cmd) |
|
1362 | #pager,shell_out = os.popen4(pager_cmd) | |
1363 | pager = os.popen(pager_cmd,'w') |
|
1363 | pager = os.popen(pager_cmd,'w') | |
1364 | pager.write(strng) |
|
1364 | pager.write(strng) | |
1365 | pager.close() |
|
1365 | pager.close() | |
1366 | retval = pager.close() # success returns None |
|
1366 | retval = pager.close() # success returns None | |
1367 | except IOError,msg: # broken pipe when user quits |
|
1367 | except IOError,msg: # broken pipe when user quits | |
1368 | if msg.args == (32,'Broken pipe'): |
|
1368 | if msg.args == (32,'Broken pipe'): | |
1369 | retval = None |
|
1369 | retval = None | |
1370 | else: |
|
1370 | else: | |
1371 | retval = 1 |
|
1371 | retval = 1 | |
1372 | except OSError: |
|
1372 | except OSError: | |
1373 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1373 | # Other strange problems, sometimes seen in Win2k/cygwin | |
1374 | retval = 1 |
|
1374 | retval = 1 | |
1375 | if retval is not None: |
|
1375 | if retval is not None: | |
1376 | page_dumb(strng,screen_lines=screen_lines) |
|
1376 | page_dumb(strng,screen_lines=screen_lines) | |
1377 |
|
1377 | |||
1378 | #---------------------------------------------------------------------------- |
|
1378 | #---------------------------------------------------------------------------- | |
1379 | def page_file(fname,start = 0, pager_cmd = None): |
|
1379 | def page_file(fname,start = 0, pager_cmd = None): | |
1380 | """Page a file, using an optional pager command and starting line. |
|
1380 | """Page a file, using an optional pager command and starting line. | |
1381 | """ |
|
1381 | """ | |
1382 |
|
1382 | |||
1383 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1383 | pager_cmd = get_pager_cmd(pager_cmd) | |
1384 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1384 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1385 |
|
1385 | |||
1386 | try: |
|
1386 | try: | |
1387 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1387 | if os.environ['TERM'] in ['emacs','dumb']: | |
1388 | raise EnvironmentError |
|
1388 | raise EnvironmentError | |
1389 | xsys(pager_cmd + ' ' + fname) |
|
1389 | xsys(pager_cmd + ' ' + fname) | |
1390 | except: |
|
1390 | except: | |
1391 | try: |
|
1391 | try: | |
1392 | if start > 0: |
|
1392 | if start > 0: | |
1393 | start -= 1 |
|
1393 | start -= 1 | |
1394 | page(open(fname).read(),start) |
|
1394 | page(open(fname).read(),start) | |
1395 | except: |
|
1395 | except: | |
1396 | print 'Unable to show file',`fname` |
|
1396 | print 'Unable to show file',`fname` | |
1397 |
|
1397 | |||
1398 | #---------------------------------------------------------------------------- |
|
1398 | #---------------------------------------------------------------------------- | |
1399 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1399 | def snip_print(str,width = 75,print_full = 0,header = ''): | |
1400 | """Print a string snipping the midsection to fit in width. |
|
1400 | """Print a string snipping the midsection to fit in width. | |
1401 |
|
1401 | |||
1402 | print_full: mode control: |
|
1402 | print_full: mode control: | |
1403 | - 0: only snip long strings |
|
1403 | - 0: only snip long strings | |
1404 | - 1: send to page() directly. |
|
1404 | - 1: send to page() directly. | |
1405 | - 2: snip long strings and ask for full length viewing with page() |
|
1405 | - 2: snip long strings and ask for full length viewing with page() | |
1406 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1406 | Return 1 if snipping was necessary, 0 otherwise.""" | |
1407 |
|
1407 | |||
1408 | if print_full == 1: |
|
1408 | if print_full == 1: | |
1409 | page(header+str) |
|
1409 | page(header+str) | |
1410 | return 0 |
|
1410 | return 0 | |
1411 |
|
1411 | |||
1412 | print header, |
|
1412 | print header, | |
1413 | if len(str) < width: |
|
1413 | if len(str) < width: | |
1414 | print str |
|
1414 | print str | |
1415 | snip = 0 |
|
1415 | snip = 0 | |
1416 | else: |
|
1416 | else: | |
1417 | whalf = int((width -5)/2) |
|
1417 | whalf = int((width -5)/2) | |
1418 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1418 | print str[:whalf] + ' <...> ' + str[-whalf:] | |
1419 | snip = 1 |
|
1419 | snip = 1 | |
1420 | if snip and print_full == 2: |
|
1420 | if snip and print_full == 2: | |
1421 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1421 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': | |
1422 | page(str) |
|
1422 | page(str) | |
1423 | return snip |
|
1423 | return snip | |
1424 |
|
1424 | |||
1425 | #**************************************************************************** |
|
1425 | #**************************************************************************** | |
1426 | # lists, dicts and structures |
|
1426 | # lists, dicts and structures | |
1427 |
|
1427 | |||
1428 | def belong(candidates,checklist): |
|
1428 | def belong(candidates,checklist): | |
1429 | """Check whether a list of items appear in a given list of options. |
|
1429 | """Check whether a list of items appear in a given list of options. | |
1430 |
|
1430 | |||
1431 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1431 | Returns a list of 1 and 0, one for each candidate given.""" | |
1432 |
|
1432 | |||
1433 | return [x in checklist for x in candidates] |
|
1433 | return [x in checklist for x in candidates] | |
1434 |
|
1434 | |||
1435 | #---------------------------------------------------------------------------- |
|
1435 | #---------------------------------------------------------------------------- | |
1436 | def uniq_stable(elems): |
|
1436 | def uniq_stable(elems): | |
1437 | """uniq_stable(elems) -> list |
|
1437 | """uniq_stable(elems) -> list | |
1438 |
|
1438 | |||
1439 | Return from an iterable, a list of all the unique elements in the input, |
|
1439 | Return from an iterable, a list of all the unique elements in the input, | |
1440 | but maintaining the order in which they first appear. |
|
1440 | but maintaining the order in which they first appear. | |
1441 |
|
1441 | |||
1442 | A naive solution to this problem which just makes a dictionary with the |
|
1442 | A naive solution to this problem which just makes a dictionary with the | |
1443 | elements as keys fails to respect the stability condition, since |
|
1443 | elements as keys fails to respect the stability condition, since | |
1444 | dictionaries are unsorted by nature. |
|
1444 | dictionaries are unsorted by nature. | |
1445 |
|
1445 | |||
1446 | Note: All elements in the input must be valid dictionary keys for this |
|
1446 | Note: All elements in the input must be valid dictionary keys for this | |
1447 | routine to work, as it internally uses a dictionary for efficiency |
|
1447 | routine to work, as it internally uses a dictionary for efficiency | |
1448 | reasons.""" |
|
1448 | reasons.""" | |
1449 |
|
1449 | |||
1450 | unique = [] |
|
1450 | unique = [] | |
1451 | unique_dict = {} |
|
1451 | unique_dict = {} | |
1452 | for nn in elems: |
|
1452 | for nn in elems: | |
1453 | if nn not in unique_dict: |
|
1453 | if nn not in unique_dict: | |
1454 | unique.append(nn) |
|
1454 | unique.append(nn) | |
1455 | unique_dict[nn] = None |
|
1455 | unique_dict[nn] = None | |
1456 | return unique |
|
1456 | return unique | |
1457 |
|
1457 | |||
1458 | #---------------------------------------------------------------------------- |
|
1458 | #---------------------------------------------------------------------------- | |
1459 | class NLprinter: |
|
1459 | class NLprinter: | |
1460 | """Print an arbitrarily nested list, indicating index numbers. |
|
1460 | """Print an arbitrarily nested list, indicating index numbers. | |
1461 |
|
1461 | |||
1462 | An instance of this class called nlprint is available and callable as a |
|
1462 | An instance of this class called nlprint is available and callable as a | |
1463 | function. |
|
1463 | function. | |
1464 |
|
1464 | |||
1465 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1465 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' | |
1466 | and using 'sep' to separate the index from the value. """ |
|
1466 | and using 'sep' to separate the index from the value. """ | |
1467 |
|
1467 | |||
1468 | def __init__(self): |
|
1468 | def __init__(self): | |
1469 | self.depth = 0 |
|
1469 | self.depth = 0 | |
1470 |
|
1470 | |||
1471 | def __call__(self,lst,pos='',**kw): |
|
1471 | def __call__(self,lst,pos='',**kw): | |
1472 | """Prints the nested list numbering levels.""" |
|
1472 | """Prints the nested list numbering levels.""" | |
1473 | kw.setdefault('indent',' ') |
|
1473 | kw.setdefault('indent',' ') | |
1474 | kw.setdefault('sep',': ') |
|
1474 | kw.setdefault('sep',': ') | |
1475 | kw.setdefault('start',0) |
|
1475 | kw.setdefault('start',0) | |
1476 | kw.setdefault('stop',len(lst)) |
|
1476 | kw.setdefault('stop',len(lst)) | |
1477 | # we need to remove start and stop from kw so they don't propagate |
|
1477 | # we need to remove start and stop from kw so they don't propagate | |
1478 | # into a recursive call for a nested list. |
|
1478 | # into a recursive call for a nested list. | |
1479 | start = kw['start']; del kw['start'] |
|
1479 | start = kw['start']; del kw['start'] | |
1480 | stop = kw['stop']; del kw['stop'] |
|
1480 | stop = kw['stop']; del kw['stop'] | |
1481 | if self.depth == 0 and 'header' in kw.keys(): |
|
1481 | if self.depth == 0 and 'header' in kw.keys(): | |
1482 | print kw['header'] |
|
1482 | print kw['header'] | |
1483 |
|
1483 | |||
1484 | for idx in range(start,stop): |
|
1484 | for idx in range(start,stop): | |
1485 | elem = lst[idx] |
|
1485 | elem = lst[idx] | |
1486 | if type(elem)==type([]): |
|
1486 | if type(elem)==type([]): | |
1487 | self.depth += 1 |
|
1487 | self.depth += 1 | |
1488 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1488 | self.__call__(elem,itpl('$pos$idx,'),**kw) | |
1489 | self.depth -= 1 |
|
1489 | self.depth -= 1 | |
1490 | else: |
|
1490 | else: | |
1491 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1491 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') | |
1492 |
|
1492 | |||
1493 | nlprint = NLprinter() |
|
1493 | nlprint = NLprinter() | |
1494 | #---------------------------------------------------------------------------- |
|
1494 | #---------------------------------------------------------------------------- | |
1495 | def all_belong(candidates,checklist): |
|
1495 | def all_belong(candidates,checklist): | |
1496 | """Check whether a list of items ALL appear in a given list of options. |
|
1496 | """Check whether a list of items ALL appear in a given list of options. | |
1497 |
|
1497 | |||
1498 | Returns a single 1 or 0 value.""" |
|
1498 | Returns a single 1 or 0 value.""" | |
1499 |
|
1499 | |||
1500 | return 1-(0 in [x in checklist for x in candidates]) |
|
1500 | return 1-(0 in [x in checklist for x in candidates]) | |
1501 |
|
1501 | |||
1502 | #---------------------------------------------------------------------------- |
|
1502 | #---------------------------------------------------------------------------- | |
1503 | def sort_compare(lst1,lst2,inplace = 1): |
|
1503 | def sort_compare(lst1,lst2,inplace = 1): | |
1504 | """Sort and compare two lists. |
|
1504 | """Sort and compare two lists. | |
1505 |
|
1505 | |||
1506 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1506 | By default it does it in place, thus modifying the lists. Use inplace = 0 | |
1507 | to avoid that (at the cost of temporary copy creation).""" |
|
1507 | to avoid that (at the cost of temporary copy creation).""" | |
1508 | if not inplace: |
|
1508 | if not inplace: | |
1509 | lst1 = lst1[:] |
|
1509 | lst1 = lst1[:] | |
1510 | lst2 = lst2[:] |
|
1510 | lst2 = lst2[:] | |
1511 | lst1.sort(); lst2.sort() |
|
1511 | lst1.sort(); lst2.sort() | |
1512 | return lst1 == lst2 |
|
1512 | return lst1 == lst2 | |
1513 |
|
1513 | |||
1514 | #---------------------------------------------------------------------------- |
|
1514 | #---------------------------------------------------------------------------- | |
1515 | def mkdict(**kwargs): |
|
1515 | def mkdict(**kwargs): | |
1516 | """Return a dict from a keyword list. |
|
1516 | """Return a dict from a keyword list. | |
1517 |
|
1517 | |||
1518 | It's just syntactic sugar for making ditcionary creation more convenient: |
|
1518 | It's just syntactic sugar for making ditcionary creation more convenient: | |
1519 | # the standard way |
|
1519 | # the standard way | |
1520 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } |
|
1520 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } | |
1521 | # a cleaner way |
|
1521 | # a cleaner way | |
1522 | >>>data = dict(red=1, green=2, blue=3) |
|
1522 | >>>data = dict(red=1, green=2, blue=3) | |
1523 |
|
1523 | |||
1524 | If you need more than this, look at the Struct() class.""" |
|
1524 | If you need more than this, look at the Struct() class.""" | |
1525 |
|
1525 | |||
1526 | return kwargs |
|
1526 | return kwargs | |
1527 |
|
1527 | |||
1528 | #---------------------------------------------------------------------------- |
|
1528 | #---------------------------------------------------------------------------- | |
1529 | def list2dict(lst): |
|
1529 | def list2dict(lst): | |
1530 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1530 | """Takes a list of (key,value) pairs and turns it into a dict.""" | |
1531 |
|
1531 | |||
1532 | dic = {} |
|
1532 | dic = {} | |
1533 | for k,v in lst: dic[k] = v |
|
1533 | for k,v in lst: dic[k] = v | |
1534 | return dic |
|
1534 | return dic | |
1535 |
|
1535 | |||
1536 | #---------------------------------------------------------------------------- |
|
1536 | #---------------------------------------------------------------------------- | |
1537 | def list2dict2(lst,default=''): |
|
1537 | def list2dict2(lst,default=''): | |
1538 | """Takes a list and turns it into a dict. |
|
1538 | """Takes a list and turns it into a dict. | |
1539 | Much slower than list2dict, but more versatile. This version can take |
|
1539 | Much slower than list2dict, but more versatile. This version can take | |
1540 | lists with sublists of arbitrary length (including sclars).""" |
|
1540 | lists with sublists of arbitrary length (including sclars).""" | |
1541 |
|
1541 | |||
1542 | dic = {} |
|
1542 | dic = {} | |
1543 | for elem in lst: |
|
1543 | for elem in lst: | |
1544 | if type(elem) in (types.ListType,types.TupleType): |
|
1544 | if type(elem) in (types.ListType,types.TupleType): | |
1545 | size = len(elem) |
|
1545 | size = len(elem) | |
1546 | if size == 0: |
|
1546 | if size == 0: | |
1547 | pass |
|
1547 | pass | |
1548 | elif size == 1: |
|
1548 | elif size == 1: | |
1549 | dic[elem] = default |
|
1549 | dic[elem] = default | |
1550 | else: |
|
1550 | else: | |
1551 | k,v = elem[0], elem[1:] |
|
1551 | k,v = elem[0], elem[1:] | |
1552 | if len(v) == 1: v = v[0] |
|
1552 | if len(v) == 1: v = v[0] | |
1553 | dic[k] = v |
|
1553 | dic[k] = v | |
1554 | else: |
|
1554 | else: | |
1555 | dic[elem] = default |
|
1555 | dic[elem] = default | |
1556 | return dic |
|
1556 | return dic | |
1557 |
|
1557 | |||
1558 | #---------------------------------------------------------------------------- |
|
1558 | #---------------------------------------------------------------------------- | |
1559 | def flatten(seq): |
|
1559 | def flatten(seq): | |
1560 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1560 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" | |
1561 |
|
1561 | |||
1562 | return [x for subseq in seq for x in subseq] |
|
1562 | return [x for subseq in seq for x in subseq] | |
1563 |
|
1563 | |||
1564 | #---------------------------------------------------------------------------- |
|
1564 | #---------------------------------------------------------------------------- | |
1565 | def get_slice(seq,start=0,stop=None,step=1): |
|
1565 | def get_slice(seq,start=0,stop=None,step=1): | |
1566 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1566 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" | |
1567 | if stop == None: |
|
1567 | if stop == None: | |
1568 | stop = len(seq) |
|
1568 | stop = len(seq) | |
1569 | item = lambda i: seq[i] |
|
1569 | item = lambda i: seq[i] | |
1570 | return map(item,xrange(start,stop,step)) |
|
1570 | return map(item,xrange(start,stop,step)) | |
1571 |
|
1571 | |||
1572 | #---------------------------------------------------------------------------- |
|
1572 | #---------------------------------------------------------------------------- | |
1573 | def chop(seq,size): |
|
1573 | def chop(seq,size): | |
1574 | """Chop a sequence into chunks of the given size.""" |
|
1574 | """Chop a sequence into chunks of the given size.""" | |
1575 | chunk = lambda i: seq[i:i+size] |
|
1575 | chunk = lambda i: seq[i:i+size] | |
1576 | return map(chunk,xrange(0,len(seq),size)) |
|
1576 | return map(chunk,xrange(0,len(seq),size)) | |
1577 |
|
1577 | |||
1578 | #---------------------------------------------------------------------------- |
|
1578 | #---------------------------------------------------------------------------- | |
1579 | def with(object, **args): |
|
1579 | # with is a keyword as of python 2.5, so this function is renamed to withobj | |
|
1580 | # from its old 'with' name. | |||
|
1581 | def with_obj(object, **args): | |||
1580 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1582 | """Set multiple attributes for an object, similar to Pascal's with. | |
1581 |
|
1583 | |||
1582 | Example: |
|
1584 | Example: | |
1583 | with(jim, |
|
1585 | with_obj(jim, | |
1584 | born = 1960, |
|
1586 | born = 1960, | |
1585 | haircolour = 'Brown', |
|
1587 | haircolour = 'Brown', | |
1586 | eyecolour = 'Green') |
|
1588 | eyecolour = 'Green') | |
1587 |
|
1589 | |||
1588 | Credit: Greg Ewing, in |
|
1590 | Credit: Greg Ewing, in | |
1589 |
http://mail.python.org/pipermail/python-list/2001-May/040703.html |
|
1591 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. | |
|
1592 | ||||
|
1593 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' | |||
|
1594 | has become a keyword for Python 2.5, so we had to rename it.""" | |||
1590 |
|
1595 | |||
1591 | object.__dict__.update(args) |
|
1596 | object.__dict__.update(args) | |
1592 |
|
1597 | |||
1593 | #---------------------------------------------------------------------------- |
|
1598 | #---------------------------------------------------------------------------- | |
1594 | def setattr_list(obj,alist,nspace = None): |
|
1599 | def setattr_list(obj,alist,nspace = None): | |
1595 | """Set a list of attributes for an object taken from a namespace. |
|
1600 | """Set a list of attributes for an object taken from a namespace. | |
1596 |
|
1601 | |||
1597 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1602 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in | |
1598 | alist with their values taken from nspace, which must be a dict (something |
|
1603 | alist with their values taken from nspace, which must be a dict (something | |
1599 | like locals() will often do) If nspace isn't given, locals() of the |
|
1604 | like locals() will often do) If nspace isn't given, locals() of the | |
1600 | *caller* is used, so in most cases you can omit it. |
|
1605 | *caller* is used, so in most cases you can omit it. | |
1601 |
|
1606 | |||
1602 | Note that alist can be given as a string, which will be automatically |
|
1607 | Note that alist can be given as a string, which will be automatically | |
1603 | split into a list on whitespace. If given as a list, it must be a list of |
|
1608 | split into a list on whitespace. If given as a list, it must be a list of | |
1604 | *strings* (the variable names themselves), not of variables.""" |
|
1609 | *strings* (the variable names themselves), not of variables.""" | |
1605 |
|
1610 | |||
1606 | # this grabs the local variables from the *previous* call frame -- that is |
|
1611 | # this grabs the local variables from the *previous* call frame -- that is | |
1607 | # the locals from the function that called setattr_list(). |
|
1612 | # the locals from the function that called setattr_list(). | |
1608 | # - snipped from weave.inline() |
|
1613 | # - snipped from weave.inline() | |
1609 | if nspace is None: |
|
1614 | if nspace is None: | |
1610 | call_frame = sys._getframe().f_back |
|
1615 | call_frame = sys._getframe().f_back | |
1611 | nspace = call_frame.f_locals |
|
1616 | nspace = call_frame.f_locals | |
1612 |
|
1617 | |||
1613 | if type(alist) in StringTypes: |
|
1618 | if type(alist) in StringTypes: | |
1614 | alist = alist.split() |
|
1619 | alist = alist.split() | |
1615 | for attr in alist: |
|
1620 | for attr in alist: | |
1616 | val = eval(attr,nspace) |
|
1621 | val = eval(attr,nspace) | |
1617 | setattr(obj,attr,val) |
|
1622 | setattr(obj,attr,val) | |
1618 |
|
1623 | |||
1619 | #---------------------------------------------------------------------------- |
|
1624 | #---------------------------------------------------------------------------- | |
1620 | def getattr_list(obj,alist,*args): |
|
1625 | def getattr_list(obj,alist,*args): | |
1621 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1626 | """getattr_list(obj,alist[, default]) -> attribute list. | |
1622 |
|
1627 | |||
1623 | Get a list of named attributes for an object. When a default argument is |
|
1628 | Get a list of named attributes for an object. When a default argument is | |
1624 | given, it is returned when the attribute doesn't exist; without it, an |
|
1629 | given, it is returned when the attribute doesn't exist; without it, an | |
1625 | exception is raised in that case. |
|
1630 | exception is raised in that case. | |
1626 |
|
1631 | |||
1627 | Note that alist can be given as a string, which will be automatically |
|
1632 | Note that alist can be given as a string, which will be automatically | |
1628 | split into a list on whitespace. If given as a list, it must be a list of |
|
1633 | split into a list on whitespace. If given as a list, it must be a list of | |
1629 | *strings* (the variable names themselves), not of variables.""" |
|
1634 | *strings* (the variable names themselves), not of variables.""" | |
1630 |
|
1635 | |||
1631 | if type(alist) in StringTypes: |
|
1636 | if type(alist) in StringTypes: | |
1632 | alist = alist.split() |
|
1637 | alist = alist.split() | |
1633 | if args: |
|
1638 | if args: | |
1634 | if len(args)==1: |
|
1639 | if len(args)==1: | |
1635 | default = args[0] |
|
1640 | default = args[0] | |
1636 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1641 | return map(lambda attr: getattr(obj,attr,default),alist) | |
1637 | else: |
|
1642 | else: | |
1638 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1643 | raise ValueError,'getattr_list() takes only one optional argument' | |
1639 | else: |
|
1644 | else: | |
1640 | return map(lambda attr: getattr(obj,attr),alist) |
|
1645 | return map(lambda attr: getattr(obj,attr),alist) | |
1641 |
|
1646 | |||
1642 | #---------------------------------------------------------------------------- |
|
1647 | #---------------------------------------------------------------------------- | |
1643 | def map_method(method,object_list,*argseq,**kw): |
|
1648 | def map_method(method,object_list,*argseq,**kw): | |
1644 | """map_method(method,object_list,*args,**kw) -> list |
|
1649 | """map_method(method,object_list,*args,**kw) -> list | |
1645 |
|
1650 | |||
1646 | Return a list of the results of applying the methods to the items of the |
|
1651 | Return a list of the results of applying the methods to the items of the | |
1647 | argument sequence(s). If more than one sequence is given, the method is |
|
1652 | argument sequence(s). If more than one sequence is given, the method is | |
1648 | called with an argument list consisting of the corresponding item of each |
|
1653 | called with an argument list consisting of the corresponding item of each | |
1649 | sequence. All sequences must be of the same length. |
|
1654 | sequence. All sequences must be of the same length. | |
1650 |
|
1655 | |||
1651 | Keyword arguments are passed verbatim to all objects called. |
|
1656 | Keyword arguments are passed verbatim to all objects called. | |
1652 |
|
1657 | |||
1653 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1658 | This is Python code, so it's not nearly as fast as the builtin map().""" | |
1654 |
|
1659 | |||
1655 | out_list = [] |
|
1660 | out_list = [] | |
1656 | idx = 0 |
|
1661 | idx = 0 | |
1657 | for object in object_list: |
|
1662 | for object in object_list: | |
1658 | try: |
|
1663 | try: | |
1659 | handler = getattr(object, method) |
|
1664 | handler = getattr(object, method) | |
1660 | except AttributeError: |
|
1665 | except AttributeError: | |
1661 | out_list.append(None) |
|
1666 | out_list.append(None) | |
1662 | else: |
|
1667 | else: | |
1663 | if argseq: |
|
1668 | if argseq: | |
1664 | args = map(lambda lst:lst[idx],argseq) |
|
1669 | args = map(lambda lst:lst[idx],argseq) | |
1665 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1670 | #print 'ob',object,'hand',handler,'ar',args # dbg | |
1666 | out_list.append(handler(args,**kw)) |
|
1671 | out_list.append(handler(args,**kw)) | |
1667 | else: |
|
1672 | else: | |
1668 | out_list.append(handler(**kw)) |
|
1673 | out_list.append(handler(**kw)) | |
1669 | idx += 1 |
|
1674 | idx += 1 | |
1670 | return out_list |
|
1675 | return out_list | |
1671 |
|
1676 | |||
1672 | #---------------------------------------------------------------------------- |
|
1677 | #---------------------------------------------------------------------------- | |
1673 | def import_fail_info(mod_name,fns=None): |
|
1678 | def import_fail_info(mod_name,fns=None): | |
1674 | """Inform load failure for a module.""" |
|
1679 | """Inform load failure for a module.""" | |
1675 |
|
1680 | |||
1676 | if fns == None: |
|
1681 | if fns == None: | |
1677 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
1682 | warn("Loading of %s failed.\n" % (mod_name,)) | |
1678 | else: |
|
1683 | else: | |
1679 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
1684 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) | |
1680 |
|
1685 | |||
1681 | #---------------------------------------------------------------------------- |
|
1686 | #---------------------------------------------------------------------------- | |
1682 | # Proposed popitem() extension, written as a method |
|
1687 | # Proposed popitem() extension, written as a method | |
1683 |
|
1688 | |||
1684 | class NotGiven: pass |
|
1689 | class NotGiven: pass | |
1685 |
|
1690 | |||
1686 | def popkey(dct,key,default=NotGiven): |
|
1691 | def popkey(dct,key,default=NotGiven): | |
1687 | """Return dct[key] and delete dct[key]. |
|
1692 | """Return dct[key] and delete dct[key]. | |
1688 |
|
1693 | |||
1689 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
1694 | If default is given, return it if dct[key] doesn't exist, otherwise raise | |
1690 | KeyError. """ |
|
1695 | KeyError. """ | |
1691 |
|
1696 | |||
1692 | try: |
|
1697 | try: | |
1693 | val = dct[key] |
|
1698 | val = dct[key] | |
1694 | except KeyError: |
|
1699 | except KeyError: | |
1695 | if default is NotGiven: |
|
1700 | if default is NotGiven: | |
1696 | raise |
|
1701 | raise | |
1697 | else: |
|
1702 | else: | |
1698 | return default |
|
1703 | return default | |
1699 | else: |
|
1704 | else: | |
1700 | del dct[key] |
|
1705 | del dct[key] | |
1701 | return val |
|
1706 | return val | |
1702 | #*************************** end of file <genutils.py> ********************** |
|
1707 | #*************************** end of file <genutils.py> ********************** | |
1703 |
|
1708 |
@@ -1,196 +1,196 b'' | |||||
1 | """hooks for IPython. |
|
1 | """hooks for IPython. | |
2 |
|
2 | |||
3 | In Python, it is possible to overwrite any method of any object if you really |
|
3 | In Python, it is possible to overwrite any method of any object if you really | |
4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to |
|
4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to | |
5 | be overwritten by users for customization purposes. This module defines the |
|
5 | be overwritten by users for customization purposes. This module defines the | |
6 | default versions of all such hooks, which get used by IPython if not |
|
6 | default versions of all such hooks, which get used by IPython if not | |
7 | overridden by the user. |
|
7 | overridden by the user. | |
8 |
|
8 | |||
9 | hooks are simple functions, but they should be declared with 'self' as their |
|
9 | hooks are simple functions, but they should be declared with 'self' as their | |
10 | first argument, because when activated they are registered into IPython as |
|
10 | first argument, because when activated they are registered into IPython as | |
11 | instance methods. The self argument will be the IPython running instance |
|
11 | instance methods. The self argument will be the IPython running instance | |
12 | itself, so hooks have full access to the entire IPython object. |
|
12 | itself, so hooks have full access to the entire IPython object. | |
13 |
|
13 | |||
14 | If you wish to define a new hook and activate it, you need to put the |
|
14 | If you wish to define a new hook and activate it, you need to put the | |
15 | necessary code into a python file which can be either imported or execfile()'d |
|
15 | necessary code into a python file which can be either imported or execfile()'d | |
16 | from within your ipythonrc configuration. |
|
16 | from within your ipythonrc configuration. | |
17 |
|
17 | |||
18 | For example, suppose that you have a module called 'myiphooks' in your |
|
18 | For example, suppose that you have a module called 'myiphooks' in your | |
19 | PYTHONPATH, which contains the following definition: |
|
19 | PYTHONPATH, which contains the following definition: | |
20 |
|
20 | |||
21 | import os |
|
21 | import os | |
22 | import IPython.ipapi |
|
22 | import IPython.ipapi | |
23 | ip = IPython.ipapi.get() |
|
23 | ip = IPython.ipapi.get() | |
24 |
|
24 | |||
25 | def calljed(self,filename, linenum): |
|
25 | def calljed(self,filename, linenum): | |
26 | "My editor hook calls the jed editor directly." |
|
26 | "My editor hook calls the jed editor directly." | |
27 | print "Calling my own editor, jed ..." |
|
27 | print "Calling my own editor, jed ..." | |
28 | os.system('jed +%d %s' % (linenum,filename)) |
|
28 | os.system('jed +%d %s' % (linenum,filename)) | |
29 |
|
29 | |||
30 | ip.set_hook('editor', calljed) |
|
30 | ip.set_hook('editor', calljed) | |
31 |
|
31 | |||
32 | You can then enable the functionality by doing 'import myiphooks' |
|
32 | You can then enable the functionality by doing 'import myiphooks' | |
33 | somewhere in your configuration files or ipython command line. |
|
33 | somewhere in your configuration files or ipython command line. | |
34 |
|
34 | |||
35 |
$Id: hooks.py 13 |
|
35 | $Id: hooks.py 1322 2006-05-24 07:51:39Z fperez $""" | |
36 |
|
36 | |||
37 | #***************************************************************************** |
|
37 | #***************************************************************************** | |
38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> |
|
38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> | |
39 | # |
|
39 | # | |
40 | # Distributed under the terms of the BSD License. The full license is in |
|
40 | # Distributed under the terms of the BSD License. The full license is in | |
41 | # the file COPYING, distributed as part of this software. |
|
41 | # the file COPYING, distributed as part of this software. | |
42 | #***************************************************************************** |
|
42 | #***************************************************************************** | |
43 |
|
43 | |||
44 | from IPython import Release |
|
44 | from IPython import Release | |
45 | from IPython import ipapi |
|
45 | from IPython import ipapi | |
46 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
46 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
47 | __license__ = Release.license |
|
47 | __license__ = Release.license | |
48 | __version__ = Release.version |
|
48 | __version__ = Release.version | |
49 |
|
49 | |||
50 | import os,bisect |
|
50 | import os,bisect | |
51 | from genutils import Term |
|
51 | from genutils import Term | |
52 | from pprint import PrettyPrinter |
|
52 | from pprint import PrettyPrinter | |
53 |
|
53 | |||
54 | # List here all the default hooks. For now it's just the editor functions |
|
54 | # List here all the default hooks. For now it's just the editor functions | |
55 | # but over time we'll move here all the public API for user-accessible things. |
|
55 | # but over time we'll move here all the public API for user-accessible things. | |
56 | __all__ = ['editor', 'fix_error_editor', 'result_display', |
|
56 | __all__ = ['editor', 'fix_error_editor', 'result_display', | |
57 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook'] |
|
57 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook'] | |
58 |
|
58 | |||
59 | pformat = PrettyPrinter().pformat |
|
59 | pformat = PrettyPrinter().pformat | |
60 |
|
60 | |||
61 | def editor(self,filename, linenum=None): |
|
61 | def editor(self,filename, linenum=None): | |
62 | """Open the default editor at the given filename and linenumber. |
|
62 | """Open the default editor at the given filename and linenumber. | |
63 |
|
63 | |||
64 | This is IPython's default editor hook, you can use it as an example to |
|
64 | This is IPython's default editor hook, you can use it as an example to | |
65 | write your own modified one. To set your own editor function as the |
|
65 | write your own modified one. To set your own editor function as the | |
66 | new editor hook, call ip.set_hook('editor',yourfunc).""" |
|
66 | new editor hook, call ip.set_hook('editor',yourfunc).""" | |
67 |
|
67 | |||
68 | # IPython configures a default editor at startup by reading $EDITOR from |
|
68 | # IPython configures a default editor at startup by reading $EDITOR from | |
69 | # the environment, and falling back on vi (unix) or notepad (win32). |
|
69 | # the environment, and falling back on vi (unix) or notepad (win32). | |
70 | editor = self.rc.editor |
|
70 | editor = self.rc.editor | |
71 |
|
71 | |||
72 | # marker for at which line to open the file (for existing objects) |
|
72 | # marker for at which line to open the file (for existing objects) | |
73 | if linenum is None or editor=='notepad': |
|
73 | if linenum is None or editor=='notepad': | |
74 | linemark = '' |
|
74 | linemark = '' | |
75 | else: |
|
75 | else: | |
76 | linemark = '+%d' % linenum |
|
76 | linemark = '+%d' % int(linenum) | |
77 |
|
77 | |||
78 | # Enclose in quotes if necessary and legal |
|
78 | # Enclose in quotes if necessary and legal | |
79 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': |
|
79 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': | |
80 | editor = '"%s"' % editor |
|
80 | editor = '"%s"' % editor | |
81 |
|
81 | |||
82 | # Call the actual editor |
|
82 | # Call the actual editor | |
83 | os.system('%s %s %s' % (editor,linemark,filename)) |
|
83 | os.system('%s %s %s' % (editor,linemark,filename)) | |
84 |
|
84 | |||
85 | import tempfile |
|
85 | import tempfile | |
86 | def fix_error_editor(self,filename,linenum,column,msg): |
|
86 | def fix_error_editor(self,filename,linenum,column,msg): | |
87 | """Open the editor at the given filename, linenumber, column and |
|
87 | """Open the editor at the given filename, linenumber, column and | |
88 | show an error message. This is used for correcting syntax errors. |
|
88 | show an error message. This is used for correcting syntax errors. | |
89 | The current implementation only has special support for the VIM editor, |
|
89 | The current implementation only has special support for the VIM editor, | |
90 | and falls back on the 'editor' hook if VIM is not used. |
|
90 | and falls back on the 'editor' hook if VIM is not used. | |
91 |
|
91 | |||
92 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, |
|
92 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, | |
93 | """ |
|
93 | """ | |
94 | def vim_quickfix_file(): |
|
94 | def vim_quickfix_file(): | |
95 | t = tempfile.NamedTemporaryFile() |
|
95 | t = tempfile.NamedTemporaryFile() | |
96 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) |
|
96 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) | |
97 | t.flush() |
|
97 | t.flush() | |
98 | return t |
|
98 | return t | |
99 | if os.path.basename(self.rc.editor) != 'vim': |
|
99 | if os.path.basename(self.rc.editor) != 'vim': | |
100 | self.hooks.editor(filename,linenum) |
|
100 | self.hooks.editor(filename,linenum) | |
101 | return |
|
101 | return | |
102 | t = vim_quickfix_file() |
|
102 | t = vim_quickfix_file() | |
103 | try: |
|
103 | try: | |
104 | os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name) |
|
104 | os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name) | |
105 | finally: |
|
105 | finally: | |
106 | t.close() |
|
106 | t.close() | |
107 |
|
107 | |||
108 |
|
108 | |||
109 | class CommandChainDispatcher: |
|
109 | class CommandChainDispatcher: | |
110 | """ Dispatch calls to a chain of commands until some func can handle it |
|
110 | """ Dispatch calls to a chain of commands until some func can handle it | |
111 |
|
111 | |||
112 | Usage: instantiate, execute "add" to add commands (with optional |
|
112 | Usage: instantiate, execute "add" to add commands (with optional | |
113 | priority), execute normally via f() calling mechanism. |
|
113 | priority), execute normally via f() calling mechanism. | |
114 |
|
114 | |||
115 | """ |
|
115 | """ | |
116 | def __init__(self,commands=None): |
|
116 | def __init__(self,commands=None): | |
117 | if commands is None: |
|
117 | if commands is None: | |
118 | self.chain = [] |
|
118 | self.chain = [] | |
119 | else: |
|
119 | else: | |
120 | self.chain = commands |
|
120 | self.chain = commands | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | def __call__(self,*args, **kw): |
|
123 | def __call__(self,*args, **kw): | |
124 | """ Command chain is called just like normal func. |
|
124 | """ Command chain is called just like normal func. | |
125 |
|
125 | |||
126 | This will call all funcs in chain with the same args as were given to this |
|
126 | This will call all funcs in chain with the same args as were given to this | |
127 | function, and return the result of first func that didn't raise |
|
127 | function, and return the result of first func that didn't raise | |
128 | TryNext """ |
|
128 | TryNext """ | |
129 |
|
129 | |||
130 | for prio,cmd in self.chain: |
|
130 | for prio,cmd in self.chain: | |
131 | #print "prio",prio,"cmd",cmd #dbg |
|
131 | #print "prio",prio,"cmd",cmd #dbg | |
132 | try: |
|
132 | try: | |
133 | ret = cmd(*args, **kw) |
|
133 | ret = cmd(*args, **kw) | |
134 | return ret |
|
134 | return ret | |
135 | except ipapi.TryNext, exc: |
|
135 | except ipapi.TryNext, exc: | |
136 | if exc.args or exc.kwargs: |
|
136 | if exc.args or exc.kwargs: | |
137 | args = exc.args |
|
137 | args = exc.args | |
138 | kw = exc.kwargs |
|
138 | kw = exc.kwargs | |
139 |
|
139 | |||
140 | def __str__(self): |
|
140 | def __str__(self): | |
141 | return str(self.chain) |
|
141 | return str(self.chain) | |
142 |
|
142 | |||
143 | def add(self, func, priority=0): |
|
143 | def add(self, func, priority=0): | |
144 | """ Add a func to the cmd chain with given priority """ |
|
144 | """ Add a func to the cmd chain with given priority """ | |
145 | bisect.insort(self.chain,(priority,func)) |
|
145 | bisect.insort(self.chain,(priority,func)) | |
146 |
|
146 | |||
147 | def result_display(self,arg): |
|
147 | def result_display(self,arg): | |
148 | """ Default display hook. |
|
148 | """ Default display hook. | |
149 |
|
149 | |||
150 | Called for displaying the result to the user. |
|
150 | Called for displaying the result to the user. | |
151 | """ |
|
151 | """ | |
152 |
|
152 | |||
153 | if self.rc.pprint: |
|
153 | if self.rc.pprint: | |
154 | out = pformat(arg) |
|
154 | out = pformat(arg) | |
155 | if '\n' in out: |
|
155 | if '\n' in out: | |
156 | # So that multi-line strings line up with the left column of |
|
156 | # So that multi-line strings line up with the left column of | |
157 | # the screen, instead of having the output prompt mess up |
|
157 | # the screen, instead of having the output prompt mess up | |
158 | # their first line. |
|
158 | # their first line. | |
159 | Term.cout.write('\n') |
|
159 | Term.cout.write('\n') | |
160 | print >>Term.cout, out |
|
160 | print >>Term.cout, out | |
161 | else: |
|
161 | else: | |
162 | # By default, the interactive prompt uses repr() to display results, |
|
162 | # By default, the interactive prompt uses repr() to display results, | |
163 | # so we should honor this. Users who'd rather use a different |
|
163 | # so we should honor this. Users who'd rather use a different | |
164 | # mechanism can easily override this hook. |
|
164 | # mechanism can easily override this hook. | |
165 | print >>Term.cout, repr(arg) |
|
165 | print >>Term.cout, repr(arg) | |
166 | # the default display hook doesn't manipulate the value to put in history |
|
166 | # the default display hook doesn't manipulate the value to put in history | |
167 | return None |
|
167 | return None | |
168 |
|
168 | |||
169 | def input_prefilter(self,line): |
|
169 | def input_prefilter(self,line): | |
170 | """ Default input prefilter |
|
170 | """ Default input prefilter | |
171 |
|
171 | |||
172 | This returns the line as unchanged, so that the interpreter |
|
172 | This returns the line as unchanged, so that the interpreter | |
173 | knows that nothing was done and proceeds with "classic" prefiltering |
|
173 | knows that nothing was done and proceeds with "classic" prefiltering | |
174 | (%magics, !shell commands etc.). |
|
174 | (%magics, !shell commands etc.). | |
175 |
|
175 | |||
176 | Note that leading whitespace is not passed to this hook. Prefilter |
|
176 | Note that leading whitespace is not passed to this hook. Prefilter | |
177 | can't alter indentation. |
|
177 | can't alter indentation. | |
178 |
|
178 | |||
179 | """ |
|
179 | """ | |
180 | #print "attempt to rewrite",line #dbg |
|
180 | #print "attempt to rewrite",line #dbg | |
181 | return line |
|
181 | return line | |
182 |
|
182 | |||
183 | def shutdown_hook(self): |
|
183 | def shutdown_hook(self): | |
184 | """ default shutdown hook |
|
184 | """ default shutdown hook | |
185 |
|
185 | |||
186 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done |
|
186 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done | |
187 | """ |
|
187 | """ | |
188 |
|
188 | |||
189 | #print "default shutdown hook ok" # dbg |
|
189 | #print "default shutdown hook ok" # dbg | |
190 | return |
|
190 | return | |
191 |
|
191 | |||
192 | def late_startup_hook(self): |
|
192 | def late_startup_hook(self): | |
193 | """ Executed after ipython has been constructed and configured |
|
193 | """ Executed after ipython has been constructed and configured | |
194 |
|
194 | |||
195 | """ |
|
195 | """ | |
196 | #print "default startup hook ok" # dbg |
|
196 | #print "default startup hook ok" # dbg |
@@ -1,294 +1,293 b'' | |||||
1 | ''' IPython customization API |
|
1 | ''' IPython customization API | |
2 |
|
2 | |||
3 | Your one-stop module for configuring & extending ipython |
|
3 | Your one-stop module for configuring & extending ipython | |
4 |
|
4 | |||
5 | The API will probably break when ipython 1.0 is released, but so |
|
5 | The API will probably break when ipython 1.0 is released, but so | |
6 | will the other configuration method (rc files). |
|
6 | will the other configuration method (rc files). | |
7 |
|
7 | |||
8 | All names prefixed by underscores are for internal use, not part |
|
8 | All names prefixed by underscores are for internal use, not part | |
9 | of the public api. |
|
9 | of the public api. | |
10 |
|
10 | |||
11 | Below is an example that you can just put to a module and import from ipython. |
|
11 | Below is an example that you can just put to a module and import from ipython. | |
12 |
|
12 | |||
13 | A good practice is to install the config script below as e.g. |
|
13 | A good practice is to install the config script below as e.g. | |
14 |
|
14 | |||
15 | ~/.ipython/my_private_conf.py |
|
15 | ~/.ipython/my_private_conf.py | |
16 |
|
16 | |||
17 | And do |
|
17 | And do | |
18 |
|
18 | |||
19 | import_mod my_private_conf |
|
19 | import_mod my_private_conf | |
20 |
|
20 | |||
21 | in ~/.ipython/ipythonrc |
|
21 | in ~/.ipython/ipythonrc | |
22 |
|
22 | |||
23 | That way the module is imported at startup and you can have all your |
|
23 | That way the module is imported at startup and you can have all your | |
24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME |
|
24 | personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME | |
25 | stuff) in there. |
|
25 | stuff) in there. | |
26 |
|
26 | |||
27 | ----------------------------------------------- |
|
27 | ----------------------------------------------- | |
28 | import IPython.ipapi |
|
28 | import IPython.ipapi | |
29 | ip = IPython.ipapi.get() |
|
29 | ip = IPython.ipapi.get() | |
30 |
|
30 | |||
31 | def ankka_f(self, arg): |
|
31 | def ankka_f(self, arg): | |
32 | print "Ankka",self,"says uppercase:",arg.upper() |
|
32 | print "Ankka",self,"says uppercase:",arg.upper() | |
33 |
|
33 | |||
34 | ip.expose_magic("ankka",ankka_f) |
|
34 | ip.expose_magic("ankka",ankka_f) | |
35 |
|
35 | |||
36 | ip.magic('alias sayhi echo "Testing, hi ok"') |
|
36 | ip.magic('alias sayhi echo "Testing, hi ok"') | |
37 | ip.magic('alias helloworld echo "Hello world"') |
|
37 | ip.magic('alias helloworld echo "Hello world"') | |
38 | ip.system('pwd') |
|
38 | ip.system('pwd') | |
39 |
|
39 | |||
40 | ip.ex('import re') |
|
40 | ip.ex('import re') | |
41 | ip.ex(""" |
|
41 | ip.ex(""" | |
42 | def funcci(a,b): |
|
42 | def funcci(a,b): | |
43 | print a+b |
|
43 | print a+b | |
44 | print funcci(3,4) |
|
44 | print funcci(3,4) | |
45 | """) |
|
45 | """) | |
46 | ip.ex("funcci(348,9)") |
|
46 | ip.ex("funcci(348,9)") | |
47 |
|
47 | |||
48 | def jed_editor(self,filename, linenum=None): |
|
48 | def jed_editor(self,filename, linenum=None): | |
49 | print "Calling my own editor, jed ... via hook!" |
|
49 | print "Calling my own editor, jed ... via hook!" | |
50 | import os |
|
50 | import os | |
51 | if linenum is None: linenum = 0 |
|
51 | if linenum is None: linenum = 0 | |
52 | os.system('jed +%d %s' % (linenum, filename)) |
|
52 | os.system('jed +%d %s' % (linenum, filename)) | |
53 | print "exiting jed" |
|
53 | print "exiting jed" | |
54 |
|
54 | |||
55 | ip.set_hook('editor',jed_editor) |
|
55 | ip.set_hook('editor',jed_editor) | |
56 |
|
56 | |||
57 | o = ip.options |
|
57 | o = ip.options | |
58 | o.autocall = 2 # FULL autocall mode |
|
58 | o.autocall = 2 # FULL autocall mode | |
59 |
|
59 | |||
60 | print "done!" |
|
60 | print "done!" | |
61 | ''' |
|
61 | ''' | |
62 |
|
62 | |||
63 | # stdlib imports |
|
63 | # stdlib imports | |
64 | import sys |
|
64 | import sys | |
65 |
|
65 | |||
66 | # our own |
|
66 | # our own | |
67 | from IPython.genutils import warn,error |
|
67 | from IPython.genutils import warn,error | |
68 |
|
68 | |||
69 | class TryNext(Exception): |
|
69 | class TryNext(Exception): | |
70 | """Try next hook exception. |
|
70 | """Try next hook exception. | |
71 |
|
71 | |||
72 | Raise this in your hook function to indicate that the next hook handler |
|
72 | Raise this in your hook function to indicate that the next hook handler | |
73 | should be used to handle the operation. If you pass arguments to the |
|
73 | should be used to handle the operation. If you pass arguments to the | |
74 | constructor those arguments will be used by the next hook instead of the |
|
74 | constructor those arguments will be used by the next hook instead of the | |
75 | original ones. |
|
75 | original ones. | |
76 | """ |
|
76 | """ | |
77 |
|
77 | |||
78 | def __init__(self, *args, **kwargs): |
|
78 | def __init__(self, *args, **kwargs): | |
79 | self.args = args |
|
79 | self.args = args | |
80 | self.kwargs = kwargs |
|
80 | self.kwargs = kwargs | |
81 |
|
81 | |||
82 | # contains the most recently instantiated IPApi |
|
82 | # contains the most recently instantiated IPApi | |
83 |
|
83 | |||
84 | class IPythonNotRunning: |
|
84 | class IPythonNotRunning: | |
85 | """Dummy do-nothing class. |
|
85 | """Dummy do-nothing class. | |
86 |
|
86 | |||
87 | Instances of this class return a dummy attribute on all accesses, which |
|
87 | Instances of this class return a dummy attribute on all accesses, which | |
88 | can be called and warns. This makes it easier to write scripts which use |
|
88 | can be called and warns. This makes it easier to write scripts which use | |
89 | the ipapi.get() object for informational purposes to operate both with and |
|
89 | the ipapi.get() object for informational purposes to operate both with and | |
90 | without ipython. Obviously code which uses the ipython object for |
|
90 | without ipython. Obviously code which uses the ipython object for | |
91 | computations will not work, but this allows a wider range of code to |
|
91 | computations will not work, but this allows a wider range of code to | |
92 | transparently work whether ipython is being used or not.""" |
|
92 | transparently work whether ipython is being used or not.""" | |
93 |
|
93 | |||
94 | def __str__(self): |
|
94 | def __str__(self): | |
95 | return "<IPythonNotRunning>" |
|
95 | return "<IPythonNotRunning>" | |
96 |
|
96 | |||
97 | __repr__ = __str__ |
|
97 | __repr__ = __str__ | |
98 |
|
98 | |||
99 | def __getattr__(self,name): |
|
99 | def __getattr__(self,name): | |
100 | return self.dummy |
|
100 | return self.dummy | |
101 |
|
101 | |||
102 | def dummy(self,*args,**kw): |
|
102 | def dummy(self,*args,**kw): | |
103 | """Dummy function, which doesn't do anything but warn.""" |
|
103 | """Dummy function, which doesn't do anything but warn.""" | |
104 | warn("IPython is not running, this is a dummy no-op function") |
|
104 | warn("IPython is not running, this is a dummy no-op function") | |
105 |
|
105 | |||
106 | _recent = None |
|
106 | _recent = None | |
107 |
|
107 | |||
108 |
|
108 | |||
109 | def get(allow_dummy=False): |
|
109 | def get(allow_dummy=False): | |
110 | """Get an IPApi object. |
|
110 | """Get an IPApi object. | |
111 |
|
111 | |||
112 | If allow_dummy is true, returns an instance of IPythonNotRunning |
|
112 | If allow_dummy is true, returns an instance of IPythonNotRunning | |
113 | instead of None if not running under IPython. |
|
113 | instead of None if not running under IPython. | |
114 |
|
114 | |||
115 | Running this should be the first thing you do when writing extensions that |
|
115 | Running this should be the first thing you do when writing extensions that | |
116 | can be imported as normal modules. You can then direct all the |
|
116 | can be imported as normal modules. You can then direct all the | |
117 | configuration operations against the returned object. |
|
117 | configuration operations against the returned object. | |
118 | """ |
|
118 | """ | |
119 | global _recent |
|
119 | global _recent | |
120 | if allow_dummy and not _recent: |
|
120 | if allow_dummy and not _recent: | |
121 | _recent = IPythonNotRunning() |
|
121 | _recent = IPythonNotRunning() | |
122 | return _recent |
|
122 | return _recent | |
123 |
|
123 | |||
124 | class IPApi: |
|
124 | class IPApi: | |
125 | """ The actual API class for configuring IPython |
|
125 | """ The actual API class for configuring IPython | |
126 |
|
126 | |||
127 | You should do all of the IPython configuration by getting an IPApi object |
|
127 | You should do all of the IPython configuration by getting an IPApi object | |
128 | with IPython.ipapi.get() and using the attributes and methods of the |
|
128 | with IPython.ipapi.get() and using the attributes and methods of the | |
129 | returned object.""" |
|
129 | returned object.""" | |
130 |
|
130 | |||
131 | def __init__(self,ip): |
|
131 | def __init__(self,ip): | |
132 |
|
132 | |||
133 | # All attributes exposed here are considered to be the public API of |
|
133 | # All attributes exposed here are considered to be the public API of | |
134 | # IPython. As needs dictate, some of these may be wrapped as |
|
134 | # IPython. As needs dictate, some of these may be wrapped as | |
135 | # properties. |
|
135 | # properties. | |
136 |
|
136 | |||
137 | self.magic = ip.ipmagic |
|
137 | self.magic = ip.ipmagic | |
138 |
|
138 | |||
139 | self.system = ip.ipsystem |
|
139 | self.system = ip.ipsystem | |
140 |
|
140 | |||
141 | self.set_hook = ip.set_hook |
|
141 | self.set_hook = ip.set_hook | |
142 |
|
142 | |||
143 | self.set_custom_exc = ip.set_custom_exc |
|
143 | self.set_custom_exc = ip.set_custom_exc | |
144 |
|
144 | |||
145 | self.user_ns = ip.user_ns |
|
145 | self.user_ns = ip.user_ns | |
146 |
|
146 | |||
147 | # Session-specific data store, which can be used to store |
|
147 | # Session-specific data store, which can be used to store | |
148 | # data that should persist through the ipython session. |
|
148 | # data that should persist through the ipython session. | |
149 | self.meta = ip.meta |
|
149 | self.meta = ip.meta | |
150 |
|
150 | |||
151 | # The ipython instance provided |
|
151 | # The ipython instance provided | |
152 | self.IP = ip |
|
152 | self.IP = ip | |
153 |
|
153 | |||
154 | global _recent |
|
154 | global _recent | |
155 | _recent = self |
|
155 | _recent = self | |
156 |
|
156 | |||
157 | # Use a property for some things which are added to the instance very |
|
157 | # Use a property for some things which are added to the instance very | |
158 | # late. I don't have time right now to disentangle the initialization |
|
158 | # late. I don't have time right now to disentangle the initialization | |
159 | # order issues, so a property lets us delay item extraction while |
|
159 | # order issues, so a property lets us delay item extraction while | |
160 | # providing a normal attribute API. |
|
160 | # providing a normal attribute API. | |
161 | def get_db(self): |
|
161 | def get_db(self): | |
162 | """A handle to persistent dict-like database (a PickleShareDB object)""" |
|
162 | """A handle to persistent dict-like database (a PickleShareDB object)""" | |
163 | return self.IP.db |
|
163 | return self.IP.db | |
164 |
|
164 | |||
165 | db = property(get_db,None,None,get_db.__doc__) |
|
165 | db = property(get_db,None,None,get_db.__doc__) | |
166 |
|
166 | |||
167 | def get_options(self): |
|
167 | def get_options(self): | |
168 | """All configurable variables.""" |
|
168 | """All configurable variables.""" | |
169 | return self.IP.rc |
|
169 | return self.IP.rc | |
170 |
|
170 | |||
171 | options = property(get_options,None,None,get_options.__doc__) |
|
171 | options = property(get_options,None,None,get_options.__doc__) | |
172 |
|
172 | |||
173 | def expose_magic(self,magicname, func): |
|
173 | def expose_magic(self,magicname, func): | |
174 | ''' Expose own function as magic function for ipython |
|
174 | ''' Expose own function as magic function for ipython | |
175 |
|
175 | |||
176 | def foo_impl(self,parameter_s=''): |
|
176 | def foo_impl(self,parameter_s=''): | |
177 | """My very own magic!. (Use docstrings, IPython reads them).""" |
|
177 | """My very own magic!. (Use docstrings, IPython reads them).""" | |
178 | print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>' |
|
178 | print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>' | |
179 | print 'The self object is:',self |
|
179 | print 'The self object is:',self | |
180 |
|
180 | |||
181 | ipapi.expose_magic("foo",foo_impl) |
|
181 | ipapi.expose_magic("foo",foo_impl) | |
182 | ''' |
|
182 | ''' | |
183 |
|
183 | |||
184 | import new |
|
184 | import new | |
185 | im = new.instancemethod(func,self.IP, self.IP.__class__) |
|
185 | im = new.instancemethod(func,self.IP, self.IP.__class__) | |
186 | setattr(self.IP, "magic_" + magicname, im) |
|
186 | setattr(self.IP, "magic_" + magicname, im) | |
187 |
|
187 | |||
188 | def ex(self,cmd): |
|
188 | def ex(self,cmd): | |
189 | """ Execute a normal python statement in user namespace """ |
|
189 | """ Execute a normal python statement in user namespace """ | |
190 | exec cmd in self.user_ns |
|
190 | exec cmd in self.user_ns | |
191 |
|
191 | |||
192 | def ev(self,expr): |
|
192 | def ev(self,expr): | |
193 | """ Evaluate python expression expr in user namespace |
|
193 | """ Evaluate python expression expr in user namespace | |
194 |
|
194 | |||
195 | Returns the result of evaluation""" |
|
195 | Returns the result of evaluation""" | |
196 | return eval(expr,self.user_ns) |
|
196 | return eval(expr,self.user_ns) | |
197 |
|
197 | |||
198 | def runlines(self,lines): |
|
198 | def runlines(self,lines): | |
199 | """ Run the specified lines in interpreter, honoring ipython directives. |
|
199 | """ Run the specified lines in interpreter, honoring ipython directives. | |
200 |
|
200 | |||
201 | This allows %magic and !shell escape notations. |
|
201 | This allows %magic and !shell escape notations. | |
202 |
|
202 | |||
203 | Takes either all lines in one string or list of lines. |
|
203 | Takes either all lines in one string or list of lines. | |
204 | """ |
|
204 | """ | |
205 | if isinstance(lines,basestring): |
|
205 | if isinstance(lines,basestring): | |
206 | self.IP.runlines(lines) |
|
206 | self.IP.runlines(lines) | |
207 | else: |
|
207 | else: | |
208 | self.IP.runlines('\n'.join(lines)) |
|
208 | self.IP.runlines('\n'.join(lines)) | |
209 |
|
209 | |||
210 | def to_user_ns(self,vars): |
|
210 | def to_user_ns(self,vars): | |
211 | """Inject a group of variables into the IPython user namespace. |
|
211 | """Inject a group of variables into the IPython user namespace. | |
212 |
|
212 | |||
213 | Inputs: |
|
213 | Inputs: | |
214 |
|
214 | |||
215 | - vars: string with variable names separated by whitespace |
|
215 | - vars: string with variable names separated by whitespace | |
216 |
|
216 | |||
217 | This utility routine is meant to ease interactive debugging work, |
|
217 | This utility routine is meant to ease interactive debugging work, | |
218 | where you want to easily propagate some internal variable in your code |
|
218 | where you want to easily propagate some internal variable in your code | |
219 | up to the interactive namespace for further exploration. |
|
219 | up to the interactive namespace for further exploration. | |
220 |
|
220 | |||
221 | When you run code via %run, globals in your script become visible at |
|
221 | When you run code via %run, globals in your script become visible at | |
222 | the interactive prompt, but this doesn't happen for locals inside your |
|
222 | the interactive prompt, but this doesn't happen for locals inside your | |
223 | own functions and methods. Yet when debugging, it is common to want |
|
223 | own functions and methods. Yet when debugging, it is common to want | |
224 | to explore some internal variables further at the interactive propmt. |
|
224 | to explore some internal variables further at the interactive propmt. | |
225 |
|
225 | |||
226 | Examples: |
|
226 | Examples: | |
227 |
|
227 | |||
228 | To use this, you first must obtain a handle on the ipython object as |
|
228 | To use this, you first must obtain a handle on the ipython object as | |
229 | indicated above, via: |
|
229 | indicated above, via: | |
230 |
|
230 | |||
231 | import IPython.ipapi |
|
231 | import IPython.ipapi | |
232 | ip = IPython.ipapi.get() |
|
232 | ip = IPython.ipapi.get() | |
233 |
|
233 | |||
234 | Once this is done, inside a routine foo() where you want to expose |
|
234 | Once this is done, inside a routine foo() where you want to expose | |
235 | variables x and y, you do the following: |
|
235 | variables x and y, you do the following: | |
236 |
|
236 | |||
237 | def foo(): |
|
237 | def foo(): | |
238 | ... |
|
238 | ... | |
239 | x = your_computation() |
|
239 | x = your_computation() | |
240 | y = something_else() |
|
240 | y = something_else() | |
241 |
|
241 | |||
242 | # This pushes x and y to the interactive prompt immediately, even |
|
242 | # This pushes x and y to the interactive prompt immediately, even | |
243 | # if this routine crashes on the next line after: |
|
243 | # if this routine crashes on the next line after: | |
244 | ip.to_user_ns('x y') |
|
244 | ip.to_user_ns('x y') | |
245 | ... |
|
245 | ... | |
246 | # return |
|
246 | # return | |
247 |
|
247 | |||
248 | If you need to rename variables, just use ip.user_ns with dict |
|
248 | If you need to rename variables, just use ip.user_ns with dict | |
249 | and update: |
|
249 | and update: | |
250 |
|
250 | |||
251 | # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython |
|
251 | # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython | |
252 | # user namespace |
|
252 | # user namespace | |
253 | ip.user_ns.update(dict(x=foo,y=bar)) |
|
253 | ip.user_ns.update(dict(x=foo,y=bar)) | |
254 |
|
||||
255 | """ |
|
254 | """ | |
256 |
|
255 | |||
257 | # print 'vars given:',vars # dbg |
|
256 | # print 'vars given:',vars # dbg | |
258 | # Get the caller's frame to evaluate the given names in |
|
257 | # Get the caller's frame to evaluate the given names in | |
259 | cf = sys._getframe(1) |
|
258 | cf = sys._getframe(1) | |
260 |
|
259 | |||
261 | user_ns = self.user_ns |
|
260 | user_ns = self.user_ns | |
262 |
|
261 | |||
263 | for name in vars.split(): |
|
262 | for name in vars.split(): | |
264 | try: |
|
263 | try: | |
265 | user_ns[name] = eval(name,cf.f_globals,cf.f_locals) |
|
264 | user_ns[name] = eval(name,cf.f_globals,cf.f_locals) | |
266 | except: |
|
265 | except: | |
267 | error('could not get var. %s from %s' % |
|
266 | error('could not get var. %s from %s' % | |
268 | (name,cf.f_code.co_name)) |
|
267 | (name,cf.f_code.co_name)) | |
269 |
|
268 | |||
270 | def launch_new_instance(user_ns = None): |
|
269 | def launch_new_instance(user_ns = None): | |
271 | """ Create and start a new ipython instance. |
|
270 | """ Create and start a new ipython instance. | |
272 |
|
271 | |||
273 | This can be called even without having an already initialized |
|
272 | This can be called even without having an already initialized | |
274 | ipython session running. |
|
273 | ipython session running. | |
275 |
|
274 | |||
276 | This is also used as the egg entry point for the 'ipython' script. |
|
275 | This is also used as the egg entry point for the 'ipython' script. | |
277 |
|
276 | |||
278 | """ |
|
277 | """ | |
279 | ses = create_session(user_ns) |
|
278 | ses = create_session(user_ns) | |
280 | ses.mainloop() |
|
279 | ses.mainloop() | |
281 |
|
280 | |||
282 |
|
281 | |||
283 | def create_session(user_ns = None): |
|
282 | def create_session(user_ns = None): | |
284 | """ Creates, but does not launch an IPython session. |
|
283 | """ Creates, but does not launch an IPython session. | |
285 |
|
284 | |||
286 | Later on you can call obj.mainloop() on the returned object. |
|
285 | Later on you can call obj.mainloop() on the returned object. | |
287 |
|
286 | |||
288 | This should *not* be run when a session exists already. |
|
287 | This should *not* be run when a session exists already. | |
289 |
|
288 | |||
290 | """ |
|
289 | """ | |
291 | if user_ns is not None: |
|
290 | if user_ns is not None: | |
292 | user_ns["__name__"] = user_ns.get("__name__",'ipy_session') |
|
291 | user_ns["__name__"] = user_ns.get("__name__",'ipy_session') | |
293 | import IPython |
|
292 | import IPython | |
294 | return IPython.Shell.start(user_ns = user_ns) |
|
293 | return IPython.Shell.start(user_ns = user_ns) |
@@ -1,2284 +1,2295 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | Requires Python 2.3 or newer. |
|
5 | Requires Python 2.3 or newer. | |
6 |
|
6 | |||
7 | This file contains all the classes and helper functions specific to IPython. |
|
7 | This file contains all the classes and helper functions specific to IPython. | |
8 |
|
8 | |||
9 |
$Id: iplib.py 13 |
|
9 | $Id: iplib.py 1322 2006-05-24 07:51:39Z fperez $ | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
14 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
14 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
15 | # |
|
15 | # | |
16 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | # Distributed under the terms of the BSD License. The full license is in | |
17 | # the file COPYING, distributed as part of this software. |
|
17 | # the file COPYING, distributed as part of this software. | |
18 | # |
|
18 | # | |
19 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
19 | # Note: this code originally subclassed code.InteractiveConsole from the | |
20 | # Python standard library. Over time, all of that class has been copied |
|
20 | # Python standard library. Over time, all of that class has been copied | |
21 | # verbatim here for modifications which could not be accomplished by |
|
21 | # verbatim here for modifications which could not be accomplished by | |
22 | # subclassing. At this point, there are no dependencies at all on the code |
|
22 | # subclassing. At this point, there are no dependencies at all on the code | |
23 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
23 | # module anymore (it is not even imported). The Python License (sec. 2) | |
24 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
24 | # allows for this, but it's always nice to acknowledge credit where credit is | |
25 | # due. |
|
25 | # due. | |
26 | #***************************************************************************** |
|
26 | #***************************************************************************** | |
27 |
|
27 | |||
28 | #**************************************************************************** |
|
28 | #**************************************************************************** | |
29 | # Modules and globals |
|
29 | # Modules and globals | |
30 |
|
30 | |||
31 | from IPython import Release |
|
31 | from IPython import Release | |
32 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
32 | __author__ = '%s <%s>\n%s <%s>' % \ | |
33 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
33 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
34 | __license__ = Release.license |
|
34 | __license__ = Release.license | |
35 | __version__ = Release.version |
|
35 | __version__ = Release.version | |
36 |
|
36 | |||
37 | # Python standard modules |
|
37 | # Python standard modules | |
38 | import __main__ |
|
38 | import __main__ | |
39 | import __builtin__ |
|
39 | import __builtin__ | |
40 | import StringIO |
|
40 | import StringIO | |
41 | import bdb |
|
41 | import bdb | |
42 | import cPickle as pickle |
|
42 | import cPickle as pickle | |
43 | import codeop |
|
43 | import codeop | |
44 | import exceptions |
|
44 | import exceptions | |
45 | import glob |
|
45 | import glob | |
46 | import inspect |
|
46 | import inspect | |
47 | import keyword |
|
47 | import keyword | |
48 | import new |
|
48 | import new | |
49 | import os |
|
49 | import os | |
50 | import pdb |
|
50 | import pdb | |
51 | import pydoc |
|
51 | import pydoc | |
52 | import re |
|
52 | import re | |
53 | import shutil |
|
53 | import shutil | |
54 | import string |
|
54 | import string | |
55 | import sys |
|
55 | import sys | |
56 | import tempfile |
|
56 | import tempfile | |
57 | import traceback |
|
57 | import traceback | |
58 | import types |
|
58 | import types | |
59 | import pickleshare |
|
59 | import pickleshare | |
60 |
|
60 | |||
61 | from pprint import pprint, pformat |
|
61 | from pprint import pprint, pformat | |
62 |
|
62 | |||
63 | # IPython's own modules |
|
63 | # IPython's own modules | |
64 | import IPython |
|
64 | import IPython | |
65 | from IPython import OInspect,PyColorize,ultraTB |
|
65 | from IPython import OInspect,PyColorize,ultraTB | |
66 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
66 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names | |
67 | from IPython.FakeModule import FakeModule |
|
67 | from IPython.FakeModule import FakeModule | |
68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
69 | from IPython.Logger import Logger |
|
69 | from IPython.Logger import Logger | |
70 | from IPython.Magic import Magic |
|
70 | from IPython.Magic import Magic | |
71 | from IPython.Prompts import CachedOutput |
|
71 | from IPython.Prompts import CachedOutput | |
72 | from IPython.ipstruct import Struct |
|
72 | from IPython.ipstruct import Struct | |
73 | from IPython.background_jobs import BackgroundJobManager |
|
73 | from IPython.background_jobs import BackgroundJobManager | |
74 | from IPython.usage import cmd_line_usage,interactive_usage |
|
74 | from IPython.usage import cmd_line_usage,interactive_usage | |
75 | from IPython.genutils import * |
|
75 | from IPython.genutils import * | |
76 | import IPython.ipapi |
|
76 | import IPython.ipapi | |
77 |
|
77 | |||
78 | # Globals |
|
78 | # Globals | |
79 |
|
79 | |||
80 | # store the builtin raw_input globally, and use this always, in case user code |
|
80 | # store the builtin raw_input globally, and use this always, in case user code | |
81 | # overwrites it (like wx.py.PyShell does) |
|
81 | # overwrites it (like wx.py.PyShell does) | |
82 | raw_input_original = raw_input |
|
82 | raw_input_original = raw_input | |
83 |
|
83 | |||
84 | # compiled regexps for autoindent management |
|
84 | # compiled regexps for autoindent management | |
85 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
85 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
86 |
|
86 | |||
87 |
|
87 | |||
88 | #**************************************************************************** |
|
88 | #**************************************************************************** | |
89 | # Some utility function definitions |
|
89 | # Some utility function definitions | |
90 |
|
90 | |||
91 | ini_spaces_re = re.compile(r'^(\s+)') |
|
91 | ini_spaces_re = re.compile(r'^(\s+)') | |
92 |
|
92 | |||
93 | def num_ini_spaces(strng): |
|
93 | def num_ini_spaces(strng): | |
94 | """Return the number of initial spaces in a string""" |
|
94 | """Return the number of initial spaces in a string""" | |
95 |
|
95 | |||
96 | ini_spaces = ini_spaces_re.match(strng) |
|
96 | ini_spaces = ini_spaces_re.match(strng) | |
97 | if ini_spaces: |
|
97 | if ini_spaces: | |
98 | return ini_spaces.end() |
|
98 | return ini_spaces.end() | |
99 | else: |
|
99 | else: | |
100 | return 0 |
|
100 | return 0 | |
101 |
|
101 | |||
102 | def softspace(file, newvalue): |
|
102 | def softspace(file, newvalue): | |
103 | """Copied from code.py, to remove the dependency""" |
|
103 | """Copied from code.py, to remove the dependency""" | |
104 |
|
104 | |||
105 | oldvalue = 0 |
|
105 | oldvalue = 0 | |
106 | try: |
|
106 | try: | |
107 | oldvalue = file.softspace |
|
107 | oldvalue = file.softspace | |
108 | except AttributeError: |
|
108 | except AttributeError: | |
109 | pass |
|
109 | pass | |
110 | try: |
|
110 | try: | |
111 | file.softspace = newvalue |
|
111 | file.softspace = newvalue | |
112 | except (AttributeError, TypeError): |
|
112 | except (AttributeError, TypeError): | |
113 | # "attribute-less object" or "read-only attributes" |
|
113 | # "attribute-less object" or "read-only attributes" | |
114 | pass |
|
114 | pass | |
115 | return oldvalue |
|
115 | return oldvalue | |
116 |
|
116 | |||
117 |
|
117 | |||
118 | #**************************************************************************** |
|
118 | #**************************************************************************** | |
119 | # Local use exceptions |
|
119 | # Local use exceptions | |
120 | class SpaceInInput(exceptions.Exception): pass |
|
120 | class SpaceInInput(exceptions.Exception): pass | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | #**************************************************************************** |
|
123 | #**************************************************************************** | |
124 | # Local use classes |
|
124 | # Local use classes | |
125 | class Bunch: pass |
|
125 | class Bunch: pass | |
126 |
|
126 | |||
127 | class Undefined: pass |
|
127 | class Undefined: pass | |
128 |
|
128 | |||
129 | class InputList(list): |
|
129 | class InputList(list): | |
130 | """Class to store user input. |
|
130 | """Class to store user input. | |
131 |
|
131 | |||
132 | It's basically a list, but slices return a string instead of a list, thus |
|
132 | It's basically a list, but slices return a string instead of a list, thus | |
133 | allowing things like (assuming 'In' is an instance): |
|
133 | allowing things like (assuming 'In' is an instance): | |
134 |
|
134 | |||
135 | exec In[4:7] |
|
135 | exec In[4:7] | |
136 |
|
136 | |||
137 | or |
|
137 | or | |
138 |
|
138 | |||
139 | exec In[5:9] + In[14] + In[21:25]""" |
|
139 | exec In[5:9] + In[14] + In[21:25]""" | |
140 |
|
140 | |||
141 | def __getslice__(self,i,j): |
|
141 | def __getslice__(self,i,j): | |
142 | return ''.join(list.__getslice__(self,i,j)) |
|
142 | return ''.join(list.__getslice__(self,i,j)) | |
143 |
|
143 | |||
144 | class SyntaxTB(ultraTB.ListTB): |
|
144 | class SyntaxTB(ultraTB.ListTB): | |
145 | """Extension which holds some state: the last exception value""" |
|
145 | """Extension which holds some state: the last exception value""" | |
146 |
|
146 | |||
147 | def __init__(self,color_scheme = 'NoColor'): |
|
147 | def __init__(self,color_scheme = 'NoColor'): | |
148 | ultraTB.ListTB.__init__(self,color_scheme) |
|
148 | ultraTB.ListTB.__init__(self,color_scheme) | |
149 | self.last_syntax_error = None |
|
149 | self.last_syntax_error = None | |
150 |
|
150 | |||
151 | def __call__(self, etype, value, elist): |
|
151 | def __call__(self, etype, value, elist): | |
152 | self.last_syntax_error = value |
|
152 | self.last_syntax_error = value | |
153 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
153 | ultraTB.ListTB.__call__(self,etype,value,elist) | |
154 |
|
154 | |||
155 | def clear_err_state(self): |
|
155 | def clear_err_state(self): | |
156 | """Return the current error state and clear it""" |
|
156 | """Return the current error state and clear it""" | |
157 | e = self.last_syntax_error |
|
157 | e = self.last_syntax_error | |
158 | self.last_syntax_error = None |
|
158 | self.last_syntax_error = None | |
159 | return e |
|
159 | return e | |
160 |
|
160 | |||
161 | #**************************************************************************** |
|
161 | #**************************************************************************** | |
162 | # Main IPython class |
|
162 | # Main IPython class | |
163 |
|
163 | |||
164 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
164 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |
165 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
165 | # until a full rewrite is made. I've cleaned all cross-class uses of | |
166 | # attributes and methods, but too much user code out there relies on the |
|
166 | # attributes and methods, but too much user code out there relies on the | |
167 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
167 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |
168 | # |
|
168 | # | |
169 | # But at least now, all the pieces have been separated and we could, in |
|
169 | # But at least now, all the pieces have been separated and we could, in | |
170 | # principle, stop using the mixin. This will ease the transition to the |
|
170 | # principle, stop using the mixin. This will ease the transition to the | |
171 | # chainsaw branch. |
|
171 | # chainsaw branch. | |
172 |
|
172 | |||
173 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
173 | # For reference, the following is the list of 'self.foo' uses in the Magic | |
174 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
174 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |
175 | # class, to prevent clashes. |
|
175 | # class, to prevent clashes. | |
176 |
|
176 | |||
177 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
177 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |
178 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
178 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |
179 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
179 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |
180 | # 'self.value'] |
|
180 | # 'self.value'] | |
181 |
|
181 | |||
182 | class InteractiveShell(object,Magic): |
|
182 | class InteractiveShell(object,Magic): | |
183 | """An enhanced console for Python.""" |
|
183 | """An enhanced console for Python.""" | |
184 |
|
184 | |||
185 | # class attribute to indicate whether the class supports threads or not. |
|
185 | # class attribute to indicate whether the class supports threads or not. | |
186 | # Subclasses with thread support should override this as needed. |
|
186 | # Subclasses with thread support should override this as needed. | |
187 | isthreaded = False |
|
187 | isthreaded = False | |
188 |
|
188 | |||
189 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
189 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
190 | user_ns = None,user_global_ns=None,banner2='', |
|
190 | user_ns = None,user_global_ns=None,banner2='', | |
191 | custom_exceptions=((),None),embedded=False): |
|
191 | custom_exceptions=((),None),embedded=False): | |
192 |
|
192 | |||
193 |
|
193 | |||
194 | # log system |
|
194 | # log system | |
195 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
195 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
196 |
|
196 | |||
197 | # some minimal strict typechecks. For some core data structures, I |
|
197 | # some minimal strict typechecks. For some core data structures, I | |
198 | # want actual basic python types, not just anything that looks like |
|
198 | # want actual basic python types, not just anything that looks like | |
199 | # one. This is especially true for namespaces. |
|
199 | # one. This is especially true for namespaces. | |
200 | for ns in (user_ns,user_global_ns): |
|
200 | for ns in (user_ns,user_global_ns): | |
201 | if ns is not None and type(ns) != types.DictType: |
|
201 | if ns is not None and type(ns) != types.DictType: | |
202 | raise TypeError,'namespace must be a dictionary' |
|
202 | raise TypeError,'namespace must be a dictionary' | |
203 |
|
203 | |||
204 | # Job manager (for jobs run as background threads) |
|
204 | # Job manager (for jobs run as background threads) | |
205 | self.jobs = BackgroundJobManager() |
|
205 | self.jobs = BackgroundJobManager() | |
206 |
|
206 | |||
207 | # Do the intuitively correct thing for quit/exit: we remove the |
|
|||
208 | # builtins if they exist, and our own magics will deal with this |
|
|||
209 | try: |
|
|||
210 | del __builtin__.exit, __builtin__.quit |
|
|||
211 | except AttributeError: |
|
|||
212 | pass |
|
|||
213 |
|
||||
214 | # Store the actual shell's name |
|
207 | # Store the actual shell's name | |
215 | self.name = name |
|
208 | self.name = name | |
216 |
|
209 | |||
217 | # We need to know whether the instance is meant for embedding, since |
|
210 | # We need to know whether the instance is meant for embedding, since | |
218 | # global/local namespaces need to be handled differently in that case |
|
211 | # global/local namespaces need to be handled differently in that case | |
219 | self.embedded = embedded |
|
212 | self.embedded = embedded | |
220 |
|
213 | |||
221 | # command compiler |
|
214 | # command compiler | |
222 | self.compile = codeop.CommandCompiler() |
|
215 | self.compile = codeop.CommandCompiler() | |
223 |
|
216 | |||
224 | # User input buffer |
|
217 | # User input buffer | |
225 | self.buffer = [] |
|
218 | self.buffer = [] | |
226 |
|
219 | |||
227 | # Default name given in compilation of code |
|
220 | # Default name given in compilation of code | |
228 | self.filename = '<ipython console>' |
|
221 | self.filename = '<ipython console>' | |
229 |
|
222 | |||
230 | # Make an empty namespace, which extension writers can rely on both |
|
223 | # Make an empty namespace, which extension writers can rely on both | |
231 | # existing and NEVER being used by ipython itself. This gives them a |
|
224 | # existing and NEVER being used by ipython itself. This gives them a | |
232 | # convenient location for storing additional information and state |
|
225 | # convenient location for storing additional information and state | |
233 | # their extensions may require, without fear of collisions with other |
|
226 | # their extensions may require, without fear of collisions with other | |
234 | # ipython names that may develop later. |
|
227 | # ipython names that may develop later. | |
235 | self.meta = Struct() |
|
228 | self.meta = Struct() | |
236 |
|
229 | |||
237 | # Create the namespace where the user will operate. user_ns is |
|
230 | # Create the namespace where the user will operate. user_ns is | |
238 | # normally the only one used, and it is passed to the exec calls as |
|
231 | # normally the only one used, and it is passed to the exec calls as | |
239 | # the locals argument. But we do carry a user_global_ns namespace |
|
232 | # the locals argument. But we do carry a user_global_ns namespace | |
240 | # given as the exec 'globals' argument, This is useful in embedding |
|
233 | # given as the exec 'globals' argument, This is useful in embedding | |
241 | # situations where the ipython shell opens in a context where the |
|
234 | # situations where the ipython shell opens in a context where the | |
242 | # distinction between locals and globals is meaningful. |
|
235 | # distinction between locals and globals is meaningful. | |
243 |
|
236 | |||
244 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
237 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
245 | # level as a dict instead of a module. This is a manual fix, but I |
|
238 | # level as a dict instead of a module. This is a manual fix, but I | |
246 | # should really track down where the problem is coming from. Alex |
|
239 | # should really track down where the problem is coming from. Alex | |
247 | # Schmolck reported this problem first. |
|
240 | # Schmolck reported this problem first. | |
248 |
|
241 | |||
249 | # A useful post by Alex Martelli on this topic: |
|
242 | # A useful post by Alex Martelli on this topic: | |
250 | # Re: inconsistent value from __builtins__ |
|
243 | # Re: inconsistent value from __builtins__ | |
251 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
244 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
252 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
245 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
253 | # Gruppen: comp.lang.python |
|
246 | # Gruppen: comp.lang.python | |
254 |
|
247 | |||
255 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
248 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
256 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
249 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
257 | # > <type 'dict'> |
|
250 | # > <type 'dict'> | |
258 | # > >>> print type(__builtins__) |
|
251 | # > >>> print type(__builtins__) | |
259 | # > <type 'module'> |
|
252 | # > <type 'module'> | |
260 | # > Is this difference in return value intentional? |
|
253 | # > Is this difference in return value intentional? | |
261 |
|
254 | |||
262 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
255 | # Well, it's documented that '__builtins__' can be either a dictionary | |
263 | # or a module, and it's been that way for a long time. Whether it's |
|
256 | # or a module, and it's been that way for a long time. Whether it's | |
264 | # intentional (or sensible), I don't know. In any case, the idea is |
|
257 | # intentional (or sensible), I don't know. In any case, the idea is | |
265 | # that if you need to access the built-in namespace directly, you |
|
258 | # that if you need to access the built-in namespace directly, you | |
266 | # should start with "import __builtin__" (note, no 's') which will |
|
259 | # should start with "import __builtin__" (note, no 's') which will | |
267 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
260 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
268 |
|
261 | |||
269 | if user_ns is None: |
|
262 | if user_ns is None: | |
270 | # Set __name__ to __main__ to better match the behavior of the |
|
263 | # Set __name__ to __main__ to better match the behavior of the | |
271 | # normal interpreter. |
|
264 | # normal interpreter. | |
272 | user_ns = {'__name__' :'__main__', |
|
265 | user_ns = {'__name__' :'__main__', | |
273 | '__builtins__' : __builtin__, |
|
266 | '__builtins__' : __builtin__, | |
274 | } |
|
267 | } | |
275 |
|
268 | |||
276 | if user_global_ns is None: |
|
269 | if user_global_ns is None: | |
277 | user_global_ns = {} |
|
270 | user_global_ns = {} | |
278 |
|
271 | |||
279 | # Assign namespaces |
|
272 | # Assign namespaces | |
280 | # This is the namespace where all normal user variables live |
|
273 | # This is the namespace where all normal user variables live | |
281 | self.user_ns = user_ns |
|
274 | self.user_ns = user_ns | |
282 | # Embedded instances require a separate namespace for globals. |
|
275 | # Embedded instances require a separate namespace for globals. | |
283 | # Normally this one is unused by non-embedded instances. |
|
276 | # Normally this one is unused by non-embedded instances. | |
284 | self.user_global_ns = user_global_ns |
|
277 | self.user_global_ns = user_global_ns | |
285 | # A namespace to keep track of internal data structures to prevent |
|
278 | # A namespace to keep track of internal data structures to prevent | |
286 | # them from cluttering user-visible stuff. Will be updated later |
|
279 | # them from cluttering user-visible stuff. Will be updated later | |
287 | self.internal_ns = {} |
|
280 | self.internal_ns = {} | |
288 |
|
281 | |||
289 | # Namespace of system aliases. Each entry in the alias |
|
282 | # Namespace of system aliases. Each entry in the alias | |
290 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
283 | # table must be a 2-tuple of the form (N,name), where N is the number | |
291 | # of positional arguments of the alias. |
|
284 | # of positional arguments of the alias. | |
292 | self.alias_table = {} |
|
285 | self.alias_table = {} | |
293 |
|
286 | |||
294 | # A table holding all the namespaces IPython deals with, so that |
|
287 | # A table holding all the namespaces IPython deals with, so that | |
295 | # introspection facilities can search easily. |
|
288 | # introspection facilities can search easily. | |
296 | self.ns_table = {'user':user_ns, |
|
289 | self.ns_table = {'user':user_ns, | |
297 | 'user_global':user_global_ns, |
|
290 | 'user_global':user_global_ns, | |
298 | 'alias':self.alias_table, |
|
291 | 'alias':self.alias_table, | |
299 | 'internal':self.internal_ns, |
|
292 | 'internal':self.internal_ns, | |
300 | 'builtin':__builtin__.__dict__ |
|
293 | 'builtin':__builtin__.__dict__ | |
301 | } |
|
294 | } | |
302 |
|
295 | |||
303 | # The user namespace MUST have a pointer to the shell itself. |
|
296 | # The user namespace MUST have a pointer to the shell itself. | |
304 | self.user_ns[name] = self |
|
297 | self.user_ns[name] = self | |
305 |
|
298 | |||
306 | # We need to insert into sys.modules something that looks like a |
|
299 | # We need to insert into sys.modules something that looks like a | |
307 | # module but which accesses the IPython namespace, for shelve and |
|
300 | # module but which accesses the IPython namespace, for shelve and | |
308 | # pickle to work interactively. Normally they rely on getting |
|
301 | # pickle to work interactively. Normally they rely on getting | |
309 | # everything out of __main__, but for embedding purposes each IPython |
|
302 | # everything out of __main__, but for embedding purposes each IPython | |
310 | # instance has its own private namespace, so we can't go shoving |
|
303 | # instance has its own private namespace, so we can't go shoving | |
311 | # everything into __main__. |
|
304 | # everything into __main__. | |
312 |
|
305 | |||
313 | # note, however, that we should only do this for non-embedded |
|
306 | # note, however, that we should only do this for non-embedded | |
314 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
307 | # ipythons, which really mimic the __main__.__dict__ with their own | |
315 | # namespace. Embedded instances, on the other hand, should not do |
|
308 | # namespace. Embedded instances, on the other hand, should not do | |
316 | # this because they need to manage the user local/global namespaces |
|
309 | # this because they need to manage the user local/global namespaces | |
317 | # only, but they live within a 'normal' __main__ (meaning, they |
|
310 | # only, but they live within a 'normal' __main__ (meaning, they | |
318 | # shouldn't overtake the execution environment of the script they're |
|
311 | # shouldn't overtake the execution environment of the script they're | |
319 | # embedded in). |
|
312 | # embedded in). | |
320 |
|
313 | |||
321 | if not embedded: |
|
314 | if not embedded: | |
322 | try: |
|
315 | try: | |
323 | main_name = self.user_ns['__name__'] |
|
316 | main_name = self.user_ns['__name__'] | |
324 | except KeyError: |
|
317 | except KeyError: | |
325 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
318 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
326 | else: |
|
319 | else: | |
327 | #print "pickle hack in place" # dbg |
|
320 | #print "pickle hack in place" # dbg | |
328 | #print 'main_name:',main_name # dbg |
|
321 | #print 'main_name:',main_name # dbg | |
329 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
322 | sys.modules[main_name] = FakeModule(self.user_ns) | |
330 |
|
323 | |||
331 | # List of input with multi-line handling. |
|
324 | # List of input with multi-line handling. | |
332 | # Fill its zero entry, user counter starts at 1 |
|
325 | # Fill its zero entry, user counter starts at 1 | |
333 | self.input_hist = InputList(['\n']) |
|
326 | self.input_hist = InputList(['\n']) | |
334 | # This one will hold the 'raw' input history, without any |
|
327 | # This one will hold the 'raw' input history, without any | |
335 | # pre-processing. This will allow users to retrieve the input just as |
|
328 | # pre-processing. This will allow users to retrieve the input just as | |
336 | # it was exactly typed in by the user, with %hist -r. |
|
329 | # it was exactly typed in by the user, with %hist -r. | |
337 | self.input_hist_raw = InputList(['\n']) |
|
330 | self.input_hist_raw = InputList(['\n']) | |
338 |
|
331 | |||
339 | # list of visited directories |
|
332 | # list of visited directories | |
340 | try: |
|
333 | try: | |
341 | self.dir_hist = [os.getcwd()] |
|
334 | self.dir_hist = [os.getcwd()] | |
342 | except IOError, e: |
|
335 | except IOError, e: | |
343 | self.dir_hist = [] |
|
336 | self.dir_hist = [] | |
344 |
|
337 | |||
345 | # dict of output history |
|
338 | # dict of output history | |
346 | self.output_hist = {} |
|
339 | self.output_hist = {} | |
347 |
|
340 | |||
348 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
341 | # dict of things NOT to alias (keywords, builtins and some magics) | |
349 | no_alias = {} |
|
342 | no_alias = {} | |
350 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
343 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
351 | for key in keyword.kwlist + no_alias_magics: |
|
344 | for key in keyword.kwlist + no_alias_magics: | |
352 | no_alias[key] = 1 |
|
345 | no_alias[key] = 1 | |
353 | no_alias.update(__builtin__.__dict__) |
|
346 | no_alias.update(__builtin__.__dict__) | |
354 | self.no_alias = no_alias |
|
347 | self.no_alias = no_alias | |
355 |
|
348 | |||
356 | # make global variables for user access to these |
|
349 | # make global variables for user access to these | |
357 | self.user_ns['_ih'] = self.input_hist |
|
350 | self.user_ns['_ih'] = self.input_hist | |
358 | self.user_ns['_oh'] = self.output_hist |
|
351 | self.user_ns['_oh'] = self.output_hist | |
359 | self.user_ns['_dh'] = self.dir_hist |
|
352 | self.user_ns['_dh'] = self.dir_hist | |
360 |
|
353 | |||
361 | # user aliases to input and output histories |
|
354 | # user aliases to input and output histories | |
362 | self.user_ns['In'] = self.input_hist |
|
355 | self.user_ns['In'] = self.input_hist | |
363 | self.user_ns['Out'] = self.output_hist |
|
356 | self.user_ns['Out'] = self.output_hist | |
364 |
|
357 | |||
365 | # Object variable to store code object waiting execution. This is |
|
358 | # Object variable to store code object waiting execution. This is | |
366 | # used mainly by the multithreaded shells, but it can come in handy in |
|
359 | # used mainly by the multithreaded shells, but it can come in handy in | |
367 | # other situations. No need to use a Queue here, since it's a single |
|
360 | # other situations. No need to use a Queue here, since it's a single | |
368 | # item which gets cleared once run. |
|
361 | # item which gets cleared once run. | |
369 | self.code_to_run = None |
|
362 | self.code_to_run = None | |
370 |
|
363 | |||
371 | # escapes for automatic behavior on the command line |
|
364 | # escapes for automatic behavior on the command line | |
372 | self.ESC_SHELL = '!' |
|
365 | self.ESC_SHELL = '!' | |
373 | self.ESC_HELP = '?' |
|
366 | self.ESC_HELP = '?' | |
374 | self.ESC_MAGIC = '%' |
|
367 | self.ESC_MAGIC = '%' | |
375 | self.ESC_QUOTE = ',' |
|
368 | self.ESC_QUOTE = ',' | |
376 | self.ESC_QUOTE2 = ';' |
|
369 | self.ESC_QUOTE2 = ';' | |
377 | self.ESC_PAREN = '/' |
|
370 | self.ESC_PAREN = '/' | |
378 |
|
371 | |||
379 | # And their associated handlers |
|
372 | # And their associated handlers | |
380 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
373 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
381 | self.ESC_QUOTE : self.handle_auto, |
|
374 | self.ESC_QUOTE : self.handle_auto, | |
382 | self.ESC_QUOTE2 : self.handle_auto, |
|
375 | self.ESC_QUOTE2 : self.handle_auto, | |
383 | self.ESC_MAGIC : self.handle_magic, |
|
376 | self.ESC_MAGIC : self.handle_magic, | |
384 | self.ESC_HELP : self.handle_help, |
|
377 | self.ESC_HELP : self.handle_help, | |
385 | self.ESC_SHELL : self.handle_shell_escape, |
|
378 | self.ESC_SHELL : self.handle_shell_escape, | |
386 | } |
|
379 | } | |
387 |
|
380 | |||
388 | # class initializations |
|
381 | # class initializations | |
389 | Magic.__init__(self,self) |
|
382 | Magic.__init__(self,self) | |
390 |
|
383 | |||
391 | # Python source parser/formatter for syntax highlighting |
|
384 | # Python source parser/formatter for syntax highlighting | |
392 | pyformat = PyColorize.Parser().format |
|
385 | pyformat = PyColorize.Parser().format | |
393 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
386 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |
394 |
|
387 | |||
395 | # hooks holds pointers used for user-side customizations |
|
388 | # hooks holds pointers used for user-side customizations | |
396 | self.hooks = Struct() |
|
389 | self.hooks = Struct() | |
397 |
|
390 | |||
398 | # Set all default hooks, defined in the IPython.hooks module. |
|
391 | # Set all default hooks, defined in the IPython.hooks module. | |
399 | hooks = IPython.hooks |
|
392 | hooks = IPython.hooks | |
400 | for hook_name in hooks.__all__: |
|
393 | for hook_name in hooks.__all__: | |
401 | # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority |
|
394 | # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority | |
402 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
395 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
403 | #print "bound hook",hook_name |
|
396 | #print "bound hook",hook_name | |
404 |
|
397 | |||
405 | # Flag to mark unconditional exit |
|
398 | # Flag to mark unconditional exit | |
406 | self.exit_now = False |
|
399 | self.exit_now = False | |
407 |
|
400 | |||
408 | self.usage_min = """\ |
|
401 | self.usage_min = """\ | |
409 | An enhanced console for Python. |
|
402 | An enhanced console for Python. | |
410 | Some of its features are: |
|
403 | Some of its features are: | |
411 | - Readline support if the readline library is present. |
|
404 | - Readline support if the readline library is present. | |
412 | - Tab completion in the local namespace. |
|
405 | - Tab completion in the local namespace. | |
413 | - Logging of input, see command-line options. |
|
406 | - Logging of input, see command-line options. | |
414 | - System shell escape via ! , eg !ls. |
|
407 | - System shell escape via ! , eg !ls. | |
415 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
408 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
416 | - Keeps track of locally defined variables via %who, %whos. |
|
409 | - Keeps track of locally defined variables via %who, %whos. | |
417 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
410 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
418 | """ |
|
411 | """ | |
419 | if usage: self.usage = usage |
|
412 | if usage: self.usage = usage | |
420 | else: self.usage = self.usage_min |
|
413 | else: self.usage = self.usage_min | |
421 |
|
414 | |||
422 | # Storage |
|
415 | # Storage | |
423 | self.rc = rc # This will hold all configuration information |
|
416 | self.rc = rc # This will hold all configuration information | |
424 | self.pager = 'less' |
|
417 | self.pager = 'less' | |
425 | # temporary files used for various purposes. Deleted at exit. |
|
418 | # temporary files used for various purposes. Deleted at exit. | |
426 | self.tempfiles = [] |
|
419 | self.tempfiles = [] | |
427 |
|
420 | |||
428 | # Keep track of readline usage (later set by init_readline) |
|
421 | # Keep track of readline usage (later set by init_readline) | |
429 | self.has_readline = False |
|
422 | self.has_readline = False | |
430 |
|
423 | |||
431 | # template for logfile headers. It gets resolved at runtime by the |
|
424 | # template for logfile headers. It gets resolved at runtime by the | |
432 | # logstart method. |
|
425 | # logstart method. | |
433 | self.loghead_tpl = \ |
|
426 | self.loghead_tpl = \ | |
434 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
427 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
435 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
428 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
436 | #log# opts = %s |
|
429 | #log# opts = %s | |
437 | #log# args = %s |
|
430 | #log# args = %s | |
438 | #log# It is safe to make manual edits below here. |
|
431 | #log# It is safe to make manual edits below here. | |
439 | #log#----------------------------------------------------------------------- |
|
432 | #log#----------------------------------------------------------------------- | |
440 | """ |
|
433 | """ | |
441 | # for pushd/popd management |
|
434 | # for pushd/popd management | |
442 | try: |
|
435 | try: | |
443 | self.home_dir = get_home_dir() |
|
436 | self.home_dir = get_home_dir() | |
444 | except HomeDirError,msg: |
|
437 | except HomeDirError,msg: | |
445 | fatal(msg) |
|
438 | fatal(msg) | |
446 |
|
439 | |||
447 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] |
|
440 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] | |
448 |
|
441 | |||
449 | # Functions to call the underlying shell. |
|
442 | # Functions to call the underlying shell. | |
450 |
|
443 | |||
451 | # utility to expand user variables via Itpl |
|
444 | # utility to expand user variables via Itpl | |
452 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), |
|
445 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), | |
453 | self.user_ns)) |
|
446 | self.user_ns)) | |
454 | # The first is similar to os.system, but it doesn't return a value, |
|
447 | # The first is similar to os.system, but it doesn't return a value, | |
455 | # and it allows interpolation of variables in the user's namespace. |
|
448 | # and it allows interpolation of variables in the user's namespace. | |
456 | self.system = lambda cmd: shell(self.var_expand(cmd), |
|
449 | self.system = lambda cmd: shell(self.var_expand(cmd), | |
457 | header='IPython system call: ', |
|
450 | header='IPython system call: ', | |
458 | verbose=self.rc.system_verbose) |
|
451 | verbose=self.rc.system_verbose) | |
459 | # These are for getoutput and getoutputerror: |
|
452 | # These are for getoutput and getoutputerror: | |
460 | self.getoutput = lambda cmd: \ |
|
453 | self.getoutput = lambda cmd: \ | |
461 | getoutput(self.var_expand(cmd), |
|
454 | getoutput(self.var_expand(cmd), | |
462 | header='IPython system call: ', |
|
455 | header='IPython system call: ', | |
463 | verbose=self.rc.system_verbose) |
|
456 | verbose=self.rc.system_verbose) | |
464 | self.getoutputerror = lambda cmd: \ |
|
457 | self.getoutputerror = lambda cmd: \ | |
465 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), |
|
458 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), | |
466 | self.user_ns)), |
|
459 | self.user_ns)), | |
467 | header='IPython system call: ', |
|
460 | header='IPython system call: ', | |
468 | verbose=self.rc.system_verbose) |
|
461 | verbose=self.rc.system_verbose) | |
469 |
|
462 | |||
470 | # RegExp for splitting line contents into pre-char//first |
|
463 | # RegExp for splitting line contents into pre-char//first | |
471 | # word-method//rest. For clarity, each group in on one line. |
|
464 | # word-method//rest. For clarity, each group in on one line. | |
472 |
|
465 | |||
473 | # WARNING: update the regexp if the above escapes are changed, as they |
|
466 | # WARNING: update the regexp if the above escapes are changed, as they | |
474 | # are hardwired in. |
|
467 | # are hardwired in. | |
475 |
|
468 | |||
476 | # Don't get carried away with trying to make the autocalling catch too |
|
469 | # Don't get carried away with trying to make the autocalling catch too | |
477 | # much: it's better to be conservative rather than to trigger hidden |
|
470 | # much: it's better to be conservative rather than to trigger hidden | |
478 | # evals() somewhere and end up causing side effects. |
|
471 | # evals() somewhere and end up causing side effects. | |
479 |
|
472 | |||
480 | self.line_split = re.compile(r'^([\s*,;/])' |
|
473 | self.line_split = re.compile(r'^([\s*,;/])' | |
481 | r'([\?\w\.]+\w*\s*)' |
|
474 | r'([\?\w\.]+\w*\s*)' | |
482 | r'(\(?.*$)') |
|
475 | r'(\(?.*$)') | |
483 |
|
476 | |||
484 | # Original re, keep around for a while in case changes break something |
|
477 | # Original re, keep around for a while in case changes break something | |
485 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' |
|
478 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' | |
486 | # r'(\s*[\?\w\.]+\w*\s*)' |
|
479 | # r'(\s*[\?\w\.]+\w*\s*)' | |
487 | # r'(\(?.*$)') |
|
480 | # r'(\(?.*$)') | |
488 |
|
481 | |||
489 | # RegExp to identify potential function names |
|
482 | # RegExp to identify potential function names | |
490 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
483 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
491 |
|
484 | |||
492 | # RegExp to exclude strings with this start from autocalling. In |
|
485 | # RegExp to exclude strings with this start from autocalling. In | |
493 | # particular, all binary operators should be excluded, so that if foo |
|
486 | # particular, all binary operators should be excluded, so that if foo | |
494 | # is callable, foo OP bar doesn't become foo(OP bar), which is |
|
487 | # is callable, foo OP bar doesn't become foo(OP bar), which is | |
495 | # invalid. The characters '!=()' don't need to be checked for, as the |
|
488 | # invalid. The characters '!=()' don't need to be checked for, as the | |
496 | # _prefilter routine explicitely does so, to catch direct calls and |
|
489 | # _prefilter routine explicitely does so, to catch direct calls and | |
497 | # rebindings of existing names. |
|
490 | # rebindings of existing names. | |
498 |
|
491 | |||
499 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
492 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise | |
500 | # it affects the rest of the group in square brackets. |
|
493 | # it affects the rest of the group in square brackets. | |
501 | self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]' |
|
494 | self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]' | |
502 | '|^is |^not |^in |^and |^or ') |
|
495 | '|^is |^not |^in |^and |^or ') | |
503 |
|
496 | |||
504 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
497 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
505 | # (experimental). For this to work, the line_split regexp would need |
|
498 | # (experimental). For this to work, the line_split regexp would need | |
506 | # to be modified so it wouldn't break things at '['. That line is |
|
499 | # to be modified so it wouldn't break things at '['. That line is | |
507 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
500 | # nasty enough that I shouldn't change it until I can test it _well_. | |
508 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
501 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
509 |
|
502 | |||
510 | # keep track of where we started running (mainly for crash post-mortem) |
|
503 | # keep track of where we started running (mainly for crash post-mortem) | |
511 | self.starting_dir = os.getcwd() |
|
504 | self.starting_dir = os.getcwd() | |
512 |
|
505 | |||
513 | # Various switches which can be set |
|
506 | # Various switches which can be set | |
514 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
507 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
515 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
508 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
516 | self.banner2 = banner2 |
|
509 | self.banner2 = banner2 | |
517 |
|
510 | |||
518 | # TraceBack handlers: |
|
511 | # TraceBack handlers: | |
519 |
|
512 | |||
520 | # Syntax error handler. |
|
513 | # Syntax error handler. | |
521 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
514 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
522 |
|
515 | |||
523 | # The interactive one is initialized with an offset, meaning we always |
|
516 | # The interactive one is initialized with an offset, meaning we always | |
524 | # want to remove the topmost item in the traceback, which is our own |
|
517 | # want to remove the topmost item in the traceback, which is our own | |
525 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
518 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
526 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
519 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
527 | color_scheme='NoColor', |
|
520 | color_scheme='NoColor', | |
528 | tb_offset = 1) |
|
521 | tb_offset = 1) | |
529 |
|
522 | |||
530 | # IPython itself shouldn't crash. This will produce a detailed |
|
523 | # IPython itself shouldn't crash. This will produce a detailed | |
531 | # post-mortem if it does. But we only install the crash handler for |
|
524 | # post-mortem if it does. But we only install the crash handler for | |
532 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
525 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
533 | # and lose the crash handler. This is because exceptions in the main |
|
526 | # and lose the crash handler. This is because exceptions in the main | |
534 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
527 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
535 | # and there's no point in printing crash dumps for every user exception. |
|
528 | # and there's no point in printing crash dumps for every user exception. | |
536 | if self.isthreaded: |
|
529 | if self.isthreaded: | |
537 | sys.excepthook = ultraTB.FormattedTB() |
|
530 | sys.excepthook = ultraTB.FormattedTB() | |
538 | else: |
|
531 | else: | |
539 | from IPython import CrashHandler |
|
532 | from IPython import CrashHandler | |
540 | sys.excepthook = CrashHandler.CrashHandler(self) |
|
533 | sys.excepthook = CrashHandler.CrashHandler(self) | |
541 |
|
534 | |||
542 | # The instance will store a pointer to this, so that runtime code |
|
535 | # The instance will store a pointer to this, so that runtime code | |
543 | # (such as magics) can access it. This is because during the |
|
536 | # (such as magics) can access it. This is because during the | |
544 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
537 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
545 | # frameworks). |
|
538 | # frameworks). | |
546 | self.sys_excepthook = sys.excepthook |
|
539 | self.sys_excepthook = sys.excepthook | |
547 |
|
540 | |||
548 | # and add any custom exception handlers the user may have specified |
|
541 | # and add any custom exception handlers the user may have specified | |
549 | self.set_custom_exc(*custom_exceptions) |
|
542 | self.set_custom_exc(*custom_exceptions) | |
550 |
|
543 | |||
551 | # Object inspector |
|
544 | # Object inspector | |
552 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
545 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
553 | PyColorize.ANSICodeColors, |
|
546 | PyColorize.ANSICodeColors, | |
554 | 'NoColor') |
|
547 | 'NoColor') | |
555 | # indentation management |
|
548 | # indentation management | |
556 | self.autoindent = False |
|
549 | self.autoindent = False | |
557 | self.indent_current_nsp = 0 |
|
550 | self.indent_current_nsp = 0 | |
558 |
|
551 | |||
559 | # Make some aliases automatically |
|
552 | # Make some aliases automatically | |
560 | # Prepare list of shell aliases to auto-define |
|
553 | # Prepare list of shell aliases to auto-define | |
561 | if os.name == 'posix': |
|
554 | if os.name == 'posix': | |
562 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
555 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
563 | 'mv mv -i','rm rm -i','cp cp -i', |
|
556 | 'mv mv -i','rm rm -i','cp cp -i', | |
564 | 'cat cat','less less','clear clear', |
|
557 | 'cat cat','less less','clear clear', | |
565 | # a better ls |
|
558 | # a better ls | |
566 | 'ls ls -F', |
|
559 | 'ls ls -F', | |
567 | # long ls |
|
560 | # long ls | |
568 | 'll ls -lF', |
|
561 | 'll ls -lF', | |
569 | # color ls |
|
562 | # color ls | |
570 | 'lc ls -F -o --color', |
|
563 | 'lc ls -F -o --color', | |
571 | # ls normal files only |
|
564 | # ls normal files only | |
572 | 'lf ls -F -o --color %l | grep ^-', |
|
565 | 'lf ls -F -o --color %l | grep ^-', | |
573 | # ls symbolic links |
|
566 | # ls symbolic links | |
574 | 'lk ls -F -o --color %l | grep ^l', |
|
567 | 'lk ls -F -o --color %l | grep ^l', | |
575 | # directories or links to directories, |
|
568 | # directories or links to directories, | |
576 | 'ldir ls -F -o --color %l | grep /$', |
|
569 | 'ldir ls -F -o --color %l | grep /$', | |
577 | # things which are executable |
|
570 | # things which are executable | |
578 | 'lx ls -F -o --color %l | grep ^-..x', |
|
571 | 'lx ls -F -o --color %l | grep ^-..x', | |
579 | ) |
|
572 | ) | |
580 | elif os.name in ['nt','dos']: |
|
573 | elif os.name in ['nt','dos']: | |
581 | auto_alias = ('dir dir /on', 'ls dir /on', |
|
574 | auto_alias = ('dir dir /on', 'ls dir /on', | |
582 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
575 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
583 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
576 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
584 | 'ren ren','cls cls','copy copy') |
|
577 | 'ren ren','cls cls','copy copy') | |
585 | else: |
|
578 | else: | |
586 | auto_alias = () |
|
579 | auto_alias = () | |
587 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) |
|
580 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) | |
588 | # Call the actual (public) initializer |
|
581 | # Call the actual (public) initializer | |
589 | self.init_auto_alias() |
|
582 | self.init_auto_alias() | |
590 |
|
583 | |||
591 | # Produce a public API instance |
|
584 | # Produce a public API instance | |
592 | self.api = IPython.ipapi.IPApi(self) |
|
585 | self.api = IPython.ipapi.IPApi(self) | |
593 |
|
586 | |||
594 | # track which builtins we add, so we can clean up later |
|
587 | # track which builtins we add, so we can clean up later | |
595 | self.builtins_added = {} |
|
588 | self.builtins_added = {} | |
596 | # This method will add the necessary builtins for operation, but |
|
589 | # This method will add the necessary builtins for operation, but | |
597 | # tracking what it did via the builtins_added dict. |
|
590 | # tracking what it did via the builtins_added dict. | |
598 | self.add_builtins() |
|
591 | self.add_builtins() | |
599 |
|
592 | |||
600 | # end __init__ |
|
593 | # end __init__ | |
601 |
|
594 | |||
602 | def pre_config_initialization(self): |
|
595 | def pre_config_initialization(self): | |
603 | """Pre-configuration init method |
|
596 | """Pre-configuration init method | |
604 |
|
597 | |||
605 | This is called before the configuration files are processed to |
|
598 | This is called before the configuration files are processed to | |
606 | prepare the services the config files might need. |
|
599 | prepare the services the config files might need. | |
607 |
|
600 | |||
608 | self.rc already has reasonable default values at this point. |
|
601 | self.rc already has reasonable default values at this point. | |
609 | """ |
|
602 | """ | |
610 | rc = self.rc |
|
603 | rc = self.rc | |
611 |
|
604 | |||
612 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
605 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") | |
613 |
|
606 | |||
614 | def post_config_initialization(self): |
|
607 | def post_config_initialization(self): | |
615 | """Post configuration init method |
|
608 | """Post configuration init method | |
616 |
|
609 | |||
617 | This is called after the configuration files have been processed to |
|
610 | This is called after the configuration files have been processed to | |
618 | 'finalize' the initialization.""" |
|
611 | 'finalize' the initialization.""" | |
619 |
|
612 | |||
620 | rc = self.rc |
|
613 | rc = self.rc | |
621 |
|
614 | |||
622 | # Load readline proper |
|
615 | # Load readline proper | |
623 | if rc.readline: |
|
616 | if rc.readline: | |
624 | self.init_readline() |
|
617 | self.init_readline() | |
625 |
|
618 | |||
626 | # local shortcut, this is used a LOT |
|
619 | # local shortcut, this is used a LOT | |
627 | self.log = self.logger.log |
|
620 | self.log = self.logger.log | |
628 |
|
621 | |||
629 | # Initialize cache, set in/out prompts and printing system |
|
622 | # Initialize cache, set in/out prompts and printing system | |
630 | self.outputcache = CachedOutput(self, |
|
623 | self.outputcache = CachedOutput(self, | |
631 | rc.cache_size, |
|
624 | rc.cache_size, | |
632 | rc.pprint, |
|
625 | rc.pprint, | |
633 | input_sep = rc.separate_in, |
|
626 | input_sep = rc.separate_in, | |
634 | output_sep = rc.separate_out, |
|
627 | output_sep = rc.separate_out, | |
635 | output_sep2 = rc.separate_out2, |
|
628 | output_sep2 = rc.separate_out2, | |
636 | ps1 = rc.prompt_in1, |
|
629 | ps1 = rc.prompt_in1, | |
637 | ps2 = rc.prompt_in2, |
|
630 | ps2 = rc.prompt_in2, | |
638 | ps_out = rc.prompt_out, |
|
631 | ps_out = rc.prompt_out, | |
639 | pad_left = rc.prompts_pad_left) |
|
632 | pad_left = rc.prompts_pad_left) | |
640 |
|
633 | |||
641 | # user may have over-ridden the default print hook: |
|
634 | # user may have over-ridden the default print hook: | |
642 | try: |
|
635 | try: | |
643 | self.outputcache.__class__.display = self.hooks.display |
|
636 | self.outputcache.__class__.display = self.hooks.display | |
644 | except AttributeError: |
|
637 | except AttributeError: | |
645 | pass |
|
638 | pass | |
646 |
|
639 | |||
647 | # I don't like assigning globally to sys, because it means when embedding |
|
640 | # I don't like assigning globally to sys, because it means when embedding | |
648 | # instances, each embedded instance overrides the previous choice. But |
|
641 | # instances, each embedded instance overrides the previous choice. But | |
649 | # sys.displayhook seems to be called internally by exec, so I don't see a |
|
642 | # sys.displayhook seems to be called internally by exec, so I don't see a | |
650 | # way around it. |
|
643 | # way around it. | |
651 | sys.displayhook = self.outputcache |
|
644 | sys.displayhook = self.outputcache | |
652 |
|
645 | |||
653 | # Set user colors (don't do it in the constructor above so that it |
|
646 | # Set user colors (don't do it in the constructor above so that it | |
654 | # doesn't crash if colors option is invalid) |
|
647 | # doesn't crash if colors option is invalid) | |
655 | self.magic_colors(rc.colors) |
|
648 | self.magic_colors(rc.colors) | |
656 |
|
649 | |||
657 | # Set calling of pdb on exceptions |
|
650 | # Set calling of pdb on exceptions | |
658 | self.call_pdb = rc.pdb |
|
651 | self.call_pdb = rc.pdb | |
659 |
|
652 | |||
660 | # Load user aliases |
|
653 | # Load user aliases | |
661 | for alias in rc.alias: |
|
654 | for alias in rc.alias: | |
662 | self.magic_alias(alias) |
|
655 | self.magic_alias(alias) | |
663 | self.hooks.late_startup_hook() |
|
656 | self.hooks.late_startup_hook() | |
664 |
|
657 | |||
665 | for batchfile in [path(arg) for arg in self.rc.args |
|
658 | for batchfile in [path(arg) for arg in self.rc.args | |
666 | if arg.lower().endswith('.ipy')]: |
|
659 | if arg.lower().endswith('.ipy')]: | |
667 | if not batchfile.isfile(): |
|
660 | if not batchfile.isfile(): | |
668 | print "No such batch file:", batchfile |
|
661 | print "No such batch file:", batchfile | |
669 | continue |
|
662 | continue | |
670 | self.api.runlines(batchfile.text()) |
|
663 | self.api.runlines(batchfile.text()) | |
671 |
|
664 | |||
672 | def add_builtins(self): |
|
665 | def add_builtins(self): | |
673 | """Store ipython references into the builtin namespace. |
|
666 | """Store ipython references into the builtin namespace. | |
674 |
|
667 | |||
675 | Some parts of ipython operate via builtins injected here, which hold a |
|
668 | Some parts of ipython operate via builtins injected here, which hold a | |
676 | reference to IPython itself.""" |
|
669 | reference to IPython itself.""" | |
677 |
|
670 | |||
678 | # TODO: deprecate all except _ip; 'jobs' should be installed |
|
671 | # TODO: deprecate all except _ip; 'jobs' should be installed | |
679 | # by an extension and the rest are under _ip, ipalias is redundant |
|
672 | # by an extension and the rest are under _ip, ipalias is redundant | |
680 | builtins_new = dict(__IPYTHON__ = self, |
|
673 | builtins_new = dict(__IPYTHON__ = self, | |
681 | ip_set_hook = self.set_hook, |
|
674 | ip_set_hook = self.set_hook, | |
682 | jobs = self.jobs, |
|
675 | jobs = self.jobs, | |
683 | ipmagic = self.ipmagic, |
|
676 | ipmagic = self.ipmagic, | |
684 | ipalias = self.ipalias, |
|
677 | ipalias = self.ipalias, | |
685 | ipsystem = self.ipsystem, |
|
678 | ipsystem = self.ipsystem, | |
686 | _ip = self.api |
|
679 | _ip = self.api | |
687 | ) |
|
680 | ) | |
688 | for biname,bival in builtins_new.items(): |
|
681 | for biname,bival in builtins_new.items(): | |
689 | try: |
|
682 | try: | |
690 | # store the orignal value so we can restore it |
|
683 | # store the orignal value so we can restore it | |
691 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
684 | self.builtins_added[biname] = __builtin__.__dict__[biname] | |
692 | except KeyError: |
|
685 | except KeyError: | |
693 | # or mark that it wasn't defined, and we'll just delete it at |
|
686 | # or mark that it wasn't defined, and we'll just delete it at | |
694 | # cleanup |
|
687 | # cleanup | |
695 | self.builtins_added[biname] = Undefined |
|
688 | self.builtins_added[biname] = Undefined | |
696 | __builtin__.__dict__[biname] = bival |
|
689 | __builtin__.__dict__[biname] = bival | |
697 |
|
690 | |||
698 | # Keep in the builtins a flag for when IPython is active. We set it |
|
691 | # Keep in the builtins a flag for when IPython is active. We set it | |
699 | # with setdefault so that multiple nested IPythons don't clobber one |
|
692 | # with setdefault so that multiple nested IPythons don't clobber one | |
700 | # another. Each will increase its value by one upon being activated, |
|
693 | # another. Each will increase its value by one upon being activated, | |
701 | # which also gives us a way to determine the nesting level. |
|
694 | # which also gives us a way to determine the nesting level. | |
702 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
695 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
703 |
|
696 | |||
704 | def clean_builtins(self): |
|
697 | def clean_builtins(self): | |
705 | """Remove any builtins which might have been added by add_builtins, or |
|
698 | """Remove any builtins which might have been added by add_builtins, or | |
706 | restore overwritten ones to their previous values.""" |
|
699 | restore overwritten ones to their previous values.""" | |
707 | for biname,bival in self.builtins_added.items(): |
|
700 | for biname,bival in self.builtins_added.items(): | |
708 | if bival is Undefined: |
|
701 | if bival is Undefined: | |
709 | del __builtin__.__dict__[biname] |
|
702 | del __builtin__.__dict__[biname] | |
710 | else: |
|
703 | else: | |
711 | __builtin__.__dict__[biname] = bival |
|
704 | __builtin__.__dict__[biname] = bival | |
712 | self.builtins_added.clear() |
|
705 | self.builtins_added.clear() | |
713 |
|
706 | |||
714 | def set_hook(self,name,hook, priority = 50): |
|
707 | def set_hook(self,name,hook, priority = 50): | |
715 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
708 | """set_hook(name,hook) -> sets an internal IPython hook. | |
716 |
|
709 | |||
717 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
710 | IPython exposes some of its internal API as user-modifiable hooks. By | |
718 | adding your function to one of these hooks, you can modify IPython's |
|
711 | adding your function to one of these hooks, you can modify IPython's | |
719 | behavior to call at runtime your own routines.""" |
|
712 | behavior to call at runtime your own routines.""" | |
720 |
|
713 | |||
721 | # At some point in the future, this should validate the hook before it |
|
714 | # At some point in the future, this should validate the hook before it | |
722 | # accepts it. Probably at least check that the hook takes the number |
|
715 | # accepts it. Probably at least check that the hook takes the number | |
723 | # of args it's supposed to. |
|
716 | # of args it's supposed to. | |
724 | dp = getattr(self.hooks, name, None) |
|
717 | dp = getattr(self.hooks, name, None) | |
725 | if name not in IPython.hooks.__all__: |
|
718 | if name not in IPython.hooks.__all__: | |
726 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
719 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) | |
727 | if not dp: |
|
720 | if not dp: | |
728 | dp = IPython.hooks.CommandChainDispatcher() |
|
721 | dp = IPython.hooks.CommandChainDispatcher() | |
729 |
|
722 | |||
730 | f = new.instancemethod(hook,self,self.__class__) |
|
723 | f = new.instancemethod(hook,self,self.__class__) | |
731 | try: |
|
724 | try: | |
732 | dp.add(f,priority) |
|
725 | dp.add(f,priority) | |
733 | except AttributeError: |
|
726 | except AttributeError: | |
734 | # it was not commandchain, plain old func - replace |
|
727 | # it was not commandchain, plain old func - replace | |
735 | dp = f |
|
728 | dp = f | |
736 |
|
729 | |||
737 | setattr(self.hooks,name, dp) |
|
730 | setattr(self.hooks,name, dp) | |
738 |
|
731 | |||
739 |
|
732 | |||
740 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
733 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
741 |
|
734 | |||
742 | def set_custom_exc(self,exc_tuple,handler): |
|
735 | def set_custom_exc(self,exc_tuple,handler): | |
743 | """set_custom_exc(exc_tuple,handler) |
|
736 | """set_custom_exc(exc_tuple,handler) | |
744 |
|
737 | |||
745 | Set a custom exception handler, which will be called if any of the |
|
738 | Set a custom exception handler, which will be called if any of the | |
746 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
739 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
747 | runcode() method. |
|
740 | runcode() method. | |
748 |
|
741 | |||
749 | Inputs: |
|
742 | Inputs: | |
750 |
|
743 | |||
751 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
744 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
752 | handler for. It is very important that you use a tuple, and NOT A |
|
745 | handler for. It is very important that you use a tuple, and NOT A | |
753 | LIST here, because of the way Python's except statement works. If |
|
746 | LIST here, because of the way Python's except statement works. If | |
754 | you only want to trap a single exception, use a singleton tuple: |
|
747 | you only want to trap a single exception, use a singleton tuple: | |
755 |
|
748 | |||
756 | exc_tuple == (MyCustomException,) |
|
749 | exc_tuple == (MyCustomException,) | |
757 |
|
750 | |||
758 | - handler: this must be defined as a function with the following |
|
751 | - handler: this must be defined as a function with the following | |
759 | basic interface: def my_handler(self,etype,value,tb). |
|
752 | basic interface: def my_handler(self,etype,value,tb). | |
760 |
|
753 | |||
761 | This will be made into an instance method (via new.instancemethod) |
|
754 | This will be made into an instance method (via new.instancemethod) | |
762 | of IPython itself, and it will be called if any of the exceptions |
|
755 | of IPython itself, and it will be called if any of the exceptions | |
763 | listed in the exc_tuple are caught. If the handler is None, an |
|
756 | listed in the exc_tuple are caught. If the handler is None, an | |
764 | internal basic one is used, which just prints basic info. |
|
757 | internal basic one is used, which just prints basic info. | |
765 |
|
758 | |||
766 | WARNING: by putting in your own exception handler into IPython's main |
|
759 | WARNING: by putting in your own exception handler into IPython's main | |
767 | execution loop, you run a very good chance of nasty crashes. This |
|
760 | execution loop, you run a very good chance of nasty crashes. This | |
768 | facility should only be used if you really know what you are doing.""" |
|
761 | facility should only be used if you really know what you are doing.""" | |
769 |
|
762 | |||
770 | assert type(exc_tuple)==type(()) , \ |
|
763 | assert type(exc_tuple)==type(()) , \ | |
771 | "The custom exceptions must be given AS A TUPLE." |
|
764 | "The custom exceptions must be given AS A TUPLE." | |
772 |
|
765 | |||
773 | def dummy_handler(self,etype,value,tb): |
|
766 | def dummy_handler(self,etype,value,tb): | |
774 | print '*** Simple custom exception handler ***' |
|
767 | print '*** Simple custom exception handler ***' | |
775 | print 'Exception type :',etype |
|
768 | print 'Exception type :',etype | |
776 | print 'Exception value:',value |
|
769 | print 'Exception value:',value | |
777 | print 'Traceback :',tb |
|
770 | print 'Traceback :',tb | |
778 | print 'Source code :','\n'.join(self.buffer) |
|
771 | print 'Source code :','\n'.join(self.buffer) | |
779 |
|
772 | |||
780 | if handler is None: handler = dummy_handler |
|
773 | if handler is None: handler = dummy_handler | |
781 |
|
774 | |||
782 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
775 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
783 | self.custom_exceptions = exc_tuple |
|
776 | self.custom_exceptions = exc_tuple | |
784 |
|
777 | |||
785 | def set_custom_completer(self,completer,pos=0): |
|
778 | def set_custom_completer(self,completer,pos=0): | |
786 | """set_custom_completer(completer,pos=0) |
|
779 | """set_custom_completer(completer,pos=0) | |
787 |
|
780 | |||
788 | Adds a new custom completer function. |
|
781 | Adds a new custom completer function. | |
789 |
|
782 | |||
790 | The position argument (defaults to 0) is the index in the completers |
|
783 | The position argument (defaults to 0) is the index in the completers | |
791 | list where you want the completer to be inserted.""" |
|
784 | list where you want the completer to be inserted.""" | |
792 |
|
785 | |||
793 | newcomp = new.instancemethod(completer,self.Completer, |
|
786 | newcomp = new.instancemethod(completer,self.Completer, | |
794 | self.Completer.__class__) |
|
787 | self.Completer.__class__) | |
795 | self.Completer.matchers.insert(pos,newcomp) |
|
788 | self.Completer.matchers.insert(pos,newcomp) | |
796 |
|
789 | |||
797 | def _get_call_pdb(self): |
|
790 | def _get_call_pdb(self): | |
798 | return self._call_pdb |
|
791 | return self._call_pdb | |
799 |
|
792 | |||
800 | def _set_call_pdb(self,val): |
|
793 | def _set_call_pdb(self,val): | |
801 |
|
794 | |||
802 | if val not in (0,1,False,True): |
|
795 | if val not in (0,1,False,True): | |
803 | raise ValueError,'new call_pdb value must be boolean' |
|
796 | raise ValueError,'new call_pdb value must be boolean' | |
804 |
|
797 | |||
805 | # store value in instance |
|
798 | # store value in instance | |
806 | self._call_pdb = val |
|
799 | self._call_pdb = val | |
807 |
|
800 | |||
808 | # notify the actual exception handlers |
|
801 | # notify the actual exception handlers | |
809 | self.InteractiveTB.call_pdb = val |
|
802 | self.InteractiveTB.call_pdb = val | |
810 | if self.isthreaded: |
|
803 | if self.isthreaded: | |
811 | try: |
|
804 | try: | |
812 | self.sys_excepthook.call_pdb = val |
|
805 | self.sys_excepthook.call_pdb = val | |
813 | except: |
|
806 | except: | |
814 | warn('Failed to activate pdb for threaded exception handler') |
|
807 | warn('Failed to activate pdb for threaded exception handler') | |
815 |
|
808 | |||
816 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
809 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
817 | 'Control auto-activation of pdb at exceptions') |
|
810 | 'Control auto-activation of pdb at exceptions') | |
818 |
|
811 | |||
819 |
|
812 | |||
820 | # These special functions get installed in the builtin namespace, to |
|
813 | # These special functions get installed in the builtin namespace, to | |
821 | # provide programmatic (pure python) access to magics, aliases and system |
|
814 | # provide programmatic (pure python) access to magics, aliases and system | |
822 | # calls. This is important for logging, user scripting, and more. |
|
815 | # calls. This is important for logging, user scripting, and more. | |
823 |
|
816 | |||
824 | # We are basically exposing, via normal python functions, the three |
|
817 | # We are basically exposing, via normal python functions, the three | |
825 | # mechanisms in which ipython offers special call modes (magics for |
|
818 | # mechanisms in which ipython offers special call modes (magics for | |
826 | # internal control, aliases for direct system access via pre-selected |
|
819 | # internal control, aliases for direct system access via pre-selected | |
827 | # names, and !cmd for calling arbitrary system commands). |
|
820 | # names, and !cmd for calling arbitrary system commands). | |
828 |
|
821 | |||
829 | def ipmagic(self,arg_s): |
|
822 | def ipmagic(self,arg_s): | |
830 | """Call a magic function by name. |
|
823 | """Call a magic function by name. | |
831 |
|
824 | |||
832 | Input: a string containing the name of the magic function to call and any |
|
825 | Input: a string containing the name of the magic function to call and any | |
833 | additional arguments to be passed to the magic. |
|
826 | additional arguments to be passed to the magic. | |
834 |
|
827 | |||
835 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
828 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
836 | prompt: |
|
829 | prompt: | |
837 |
|
830 | |||
838 | In[1]: %name -opt foo bar |
|
831 | In[1]: %name -opt foo bar | |
839 |
|
832 | |||
840 | To call a magic without arguments, simply use ipmagic('name'). |
|
833 | To call a magic without arguments, simply use ipmagic('name'). | |
841 |
|
834 | |||
842 | This provides a proper Python function to call IPython's magics in any |
|
835 | This provides a proper Python function to call IPython's magics in any | |
843 | valid Python code you can type at the interpreter, including loops and |
|
836 | valid Python code you can type at the interpreter, including loops and | |
844 | compound statements. It is added by IPython to the Python builtin |
|
837 | compound statements. It is added by IPython to the Python builtin | |
845 | namespace upon initialization.""" |
|
838 | namespace upon initialization.""" | |
846 |
|
839 | |||
847 | args = arg_s.split(' ',1) |
|
840 | args = arg_s.split(' ',1) | |
848 | magic_name = args[0] |
|
841 | magic_name = args[0] | |
849 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
842 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
850 |
|
843 | |||
851 | try: |
|
844 | try: | |
852 | magic_args = args[1] |
|
845 | magic_args = args[1] | |
853 | except IndexError: |
|
846 | except IndexError: | |
854 | magic_args = '' |
|
847 | magic_args = '' | |
855 | fn = getattr(self,'magic_'+magic_name,None) |
|
848 | fn = getattr(self,'magic_'+magic_name,None) | |
856 | if fn is None: |
|
849 | if fn is None: | |
857 | error("Magic function `%s` not found." % magic_name) |
|
850 | error("Magic function `%s` not found." % magic_name) | |
858 | else: |
|
851 | else: | |
859 | magic_args = self.var_expand(magic_args) |
|
852 | magic_args = self.var_expand(magic_args) | |
860 | return fn(magic_args) |
|
853 | return fn(magic_args) | |
861 |
|
854 | |||
862 | def ipalias(self,arg_s): |
|
855 | def ipalias(self,arg_s): | |
863 | """Call an alias by name. |
|
856 | """Call an alias by name. | |
864 |
|
857 | |||
865 | Input: a string containing the name of the alias to call and any |
|
858 | Input: a string containing the name of the alias to call and any | |
866 | additional arguments to be passed to the magic. |
|
859 | additional arguments to be passed to the magic. | |
867 |
|
860 | |||
868 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
861 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
869 | prompt: |
|
862 | prompt: | |
870 |
|
863 | |||
871 | In[1]: name -opt foo bar |
|
864 | In[1]: name -opt foo bar | |
872 |
|
865 | |||
873 | To call an alias without arguments, simply use ipalias('name'). |
|
866 | To call an alias without arguments, simply use ipalias('name'). | |
874 |
|
867 | |||
875 | This provides a proper Python function to call IPython's aliases in any |
|
868 | This provides a proper Python function to call IPython's aliases in any | |
876 | valid Python code you can type at the interpreter, including loops and |
|
869 | valid Python code you can type at the interpreter, including loops and | |
877 | compound statements. It is added by IPython to the Python builtin |
|
870 | compound statements. It is added by IPython to the Python builtin | |
878 | namespace upon initialization.""" |
|
871 | namespace upon initialization.""" | |
879 |
|
872 | |||
880 | args = arg_s.split(' ',1) |
|
873 | args = arg_s.split(' ',1) | |
881 | alias_name = args[0] |
|
874 | alias_name = args[0] | |
882 | try: |
|
875 | try: | |
883 | alias_args = args[1] |
|
876 | alias_args = args[1] | |
884 | except IndexError: |
|
877 | except IndexError: | |
885 | alias_args = '' |
|
878 | alias_args = '' | |
886 | if alias_name in self.alias_table: |
|
879 | if alias_name in self.alias_table: | |
887 | self.call_alias(alias_name,alias_args) |
|
880 | self.call_alias(alias_name,alias_args) | |
888 | else: |
|
881 | else: | |
889 | error("Alias `%s` not found." % alias_name) |
|
882 | error("Alias `%s` not found." % alias_name) | |
890 |
|
883 | |||
891 | def ipsystem(self,arg_s): |
|
884 | def ipsystem(self,arg_s): | |
892 | """Make a system call, using IPython.""" |
|
885 | """Make a system call, using IPython.""" | |
893 |
|
886 | |||
894 | self.system(arg_s) |
|
887 | self.system(arg_s) | |
895 |
|
888 | |||
896 | def complete(self,text): |
|
889 | def complete(self,text): | |
897 | """Return a sorted list of all possible completions on text. |
|
890 | """Return a sorted list of all possible completions on text. | |
898 |
|
891 | |||
899 | Inputs: |
|
892 | Inputs: | |
900 |
|
893 | |||
901 | - text: a string of text to be completed on. |
|
894 | - text: a string of text to be completed on. | |
902 |
|
895 | |||
903 | This is a wrapper around the completion mechanism, similar to what |
|
896 | This is a wrapper around the completion mechanism, similar to what | |
904 | readline does at the command line when the TAB key is hit. By |
|
897 | readline does at the command line when the TAB key is hit. By | |
905 | exposing it as a method, it can be used by other non-readline |
|
898 | exposing it as a method, it can be used by other non-readline | |
906 | environments (such as GUIs) for text completion. |
|
899 | environments (such as GUIs) for text completion. | |
907 |
|
900 | |||
908 | Simple usage example: |
|
901 | Simple usage example: | |
909 |
|
902 | |||
910 | In [1]: x = 'hello' |
|
903 | In [1]: x = 'hello' | |
911 |
|
904 | |||
912 | In [2]: __IP.complete('x.l') |
|
905 | In [2]: __IP.complete('x.l') | |
913 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
906 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" | |
914 |
|
907 | |||
915 | complete = self.Completer.complete |
|
908 | complete = self.Completer.complete | |
916 | state = 0 |
|
909 | state = 0 | |
917 | # use a dict so we get unique keys, since ipyhton's multiple |
|
910 | # use a dict so we get unique keys, since ipyhton's multiple | |
918 | # completers can return duplicates. |
|
911 | # completers can return duplicates. | |
919 | comps = {} |
|
912 | comps = {} | |
920 | while True: |
|
913 | while True: | |
921 | newcomp = complete(text,state) |
|
914 | newcomp = complete(text,state) | |
922 | if newcomp is None: |
|
915 | if newcomp is None: | |
923 | break |
|
916 | break | |
924 | comps[newcomp] = 1 |
|
917 | comps[newcomp] = 1 | |
925 | state += 1 |
|
918 | state += 1 | |
926 | outcomps = comps.keys() |
|
919 | outcomps = comps.keys() | |
927 | outcomps.sort() |
|
920 | outcomps.sort() | |
928 | return outcomps |
|
921 | return outcomps | |
929 |
|
922 | |||
930 | def set_completer_frame(self, frame=None): |
|
923 | def set_completer_frame(self, frame=None): | |
931 | if frame: |
|
924 | if frame: | |
932 | self.Completer.namespace = frame.f_locals |
|
925 | self.Completer.namespace = frame.f_locals | |
933 | self.Completer.global_namespace = frame.f_globals |
|
926 | self.Completer.global_namespace = frame.f_globals | |
934 | else: |
|
927 | else: | |
935 | self.Completer.namespace = self.user_ns |
|
928 | self.Completer.namespace = self.user_ns | |
936 | self.Completer.global_namespace = self.user_global_ns |
|
929 | self.Completer.global_namespace = self.user_global_ns | |
937 |
|
930 | |||
938 | def init_auto_alias(self): |
|
931 | def init_auto_alias(self): | |
939 | """Define some aliases automatically. |
|
932 | """Define some aliases automatically. | |
940 |
|
933 | |||
941 | These are ALL parameter-less aliases""" |
|
934 | These are ALL parameter-less aliases""" | |
942 |
|
935 | |||
943 | for alias,cmd in self.auto_alias: |
|
936 | for alias,cmd in self.auto_alias: | |
944 | self.alias_table[alias] = (0,cmd) |
|
937 | self.alias_table[alias] = (0,cmd) | |
945 |
|
938 | |||
946 | def alias_table_validate(self,verbose=0): |
|
939 | def alias_table_validate(self,verbose=0): | |
947 | """Update information about the alias table. |
|
940 | """Update information about the alias table. | |
948 |
|
941 | |||
949 | In particular, make sure no Python keywords/builtins are in it.""" |
|
942 | In particular, make sure no Python keywords/builtins are in it.""" | |
950 |
|
943 | |||
951 | no_alias = self.no_alias |
|
944 | no_alias = self.no_alias | |
952 | for k in self.alias_table.keys(): |
|
945 | for k in self.alias_table.keys(): | |
953 | if k in no_alias: |
|
946 | if k in no_alias: | |
954 | del self.alias_table[k] |
|
947 | del self.alias_table[k] | |
955 | if verbose: |
|
948 | if verbose: | |
956 | print ("Deleting alias <%s>, it's a Python " |
|
949 | print ("Deleting alias <%s>, it's a Python " | |
957 | "keyword or builtin." % k) |
|
950 | "keyword or builtin." % k) | |
958 |
|
951 | |||
959 | def set_autoindent(self,value=None): |
|
952 | def set_autoindent(self,value=None): | |
960 | """Set the autoindent flag, checking for readline support. |
|
953 | """Set the autoindent flag, checking for readline support. | |
961 |
|
954 | |||
962 | If called with no arguments, it acts as a toggle.""" |
|
955 | If called with no arguments, it acts as a toggle.""" | |
963 |
|
956 | |||
964 | if not self.has_readline: |
|
957 | if not self.has_readline: | |
965 | if os.name == 'posix': |
|
958 | if os.name == 'posix': | |
966 | warn("The auto-indent feature requires the readline library") |
|
959 | warn("The auto-indent feature requires the readline library") | |
967 | self.autoindent = 0 |
|
960 | self.autoindent = 0 | |
968 | return |
|
961 | return | |
969 | if value is None: |
|
962 | if value is None: | |
970 | self.autoindent = not self.autoindent |
|
963 | self.autoindent = not self.autoindent | |
971 | else: |
|
964 | else: | |
972 | self.autoindent = value |
|
965 | self.autoindent = value | |
973 |
|
966 | |||
974 | def rc_set_toggle(self,rc_field,value=None): |
|
967 | def rc_set_toggle(self,rc_field,value=None): | |
975 | """Set or toggle a field in IPython's rc config. structure. |
|
968 | """Set or toggle a field in IPython's rc config. structure. | |
976 |
|
969 | |||
977 | If called with no arguments, it acts as a toggle. |
|
970 | If called with no arguments, it acts as a toggle. | |
978 |
|
971 | |||
979 | If called with a non-existent field, the resulting AttributeError |
|
972 | If called with a non-existent field, the resulting AttributeError | |
980 | exception will propagate out.""" |
|
973 | exception will propagate out.""" | |
981 |
|
974 | |||
982 | rc_val = getattr(self.rc,rc_field) |
|
975 | rc_val = getattr(self.rc,rc_field) | |
983 | if value is None: |
|
976 | if value is None: | |
984 | value = not rc_val |
|
977 | value = not rc_val | |
985 | setattr(self.rc,rc_field,value) |
|
978 | setattr(self.rc,rc_field,value) | |
986 |
|
979 | |||
987 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
980 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
988 | """Install the user configuration directory. |
|
981 | """Install the user configuration directory. | |
989 |
|
982 | |||
990 | Can be called when running for the first time or to upgrade the user's |
|
983 | Can be called when running for the first time or to upgrade the user's | |
991 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
984 | .ipython/ directory with the mode parameter. Valid modes are 'install' | |
992 | and 'upgrade'.""" |
|
985 | and 'upgrade'.""" | |
993 |
|
986 | |||
994 | def wait(): |
|
987 | def wait(): | |
995 | try: |
|
988 | try: | |
996 | raw_input("Please press <RETURN> to start IPython.") |
|
989 | raw_input("Please press <RETURN> to start IPython.") | |
997 | except EOFError: |
|
990 | except EOFError: | |
998 | print >> Term.cout |
|
991 | print >> Term.cout | |
999 | print '*'*70 |
|
992 | print '*'*70 | |
1000 |
|
993 | |||
1001 | cwd = os.getcwd() # remember where we started |
|
994 | cwd = os.getcwd() # remember where we started | |
1002 | glb = glob.glob |
|
995 | glb = glob.glob | |
1003 | print '*'*70 |
|
996 | print '*'*70 | |
1004 | if mode == 'install': |
|
997 | if mode == 'install': | |
1005 | print \ |
|
998 | print \ | |
1006 | """Welcome to IPython. I will try to create a personal configuration directory |
|
999 | """Welcome to IPython. I will try to create a personal configuration directory | |
1007 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1000 | where you can customize many aspects of IPython's functionality in:\n""" | |
1008 | else: |
|
1001 | else: | |
1009 | print 'I am going to upgrade your configuration in:' |
|
1002 | print 'I am going to upgrade your configuration in:' | |
1010 |
|
1003 | |||
1011 | print ipythondir |
|
1004 | print ipythondir | |
1012 |
|
1005 | |||
1013 | rcdirend = os.path.join('IPython','UserConfig') |
|
1006 | rcdirend = os.path.join('IPython','UserConfig') | |
1014 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1007 | cfg = lambda d: os.path.join(d,rcdirend) | |
1015 | try: |
|
1008 | try: | |
1016 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1009 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
1017 | except IOError: |
|
1010 | except IOError: | |
1018 | warning = """ |
|
1011 | warning = """ | |
1019 | Installation error. IPython's directory was not found. |
|
1012 | Installation error. IPython's directory was not found. | |
1020 |
|
1013 | |||
1021 | Check the following: |
|
1014 | Check the following: | |
1022 |
|
1015 | |||
1023 | The ipython/IPython directory should be in a directory belonging to your |
|
1016 | The ipython/IPython directory should be in a directory belonging to your | |
1024 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1017 | PYTHONPATH environment variable (that is, it should be in a directory | |
1025 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1018 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
1026 |
|
1019 | |||
1027 | IPython will proceed with builtin defaults. |
|
1020 | IPython will proceed with builtin defaults. | |
1028 | """ |
|
1021 | """ | |
1029 | warn(warning) |
|
1022 | warn(warning) | |
1030 | wait() |
|
1023 | wait() | |
1031 | return |
|
1024 | return | |
1032 |
|
1025 | |||
1033 | if mode == 'install': |
|
1026 | if mode == 'install': | |
1034 | try: |
|
1027 | try: | |
1035 | shutil.copytree(rcdir,ipythondir) |
|
1028 | shutil.copytree(rcdir,ipythondir) | |
1036 | os.chdir(ipythondir) |
|
1029 | os.chdir(ipythondir) | |
1037 | rc_files = glb("ipythonrc*") |
|
1030 | rc_files = glb("ipythonrc*") | |
1038 | for rc_file in rc_files: |
|
1031 | for rc_file in rc_files: | |
1039 | os.rename(rc_file,rc_file+rc_suffix) |
|
1032 | os.rename(rc_file,rc_file+rc_suffix) | |
1040 | except: |
|
1033 | except: | |
1041 | warning = """ |
|
1034 | warning = """ | |
1042 |
|
1035 | |||
1043 | There was a problem with the installation: |
|
1036 | There was a problem with the installation: | |
1044 | %s |
|
1037 | %s | |
1045 | Try to correct it or contact the developers if you think it's a bug. |
|
1038 | Try to correct it or contact the developers if you think it's a bug. | |
1046 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1039 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
1047 | warn(warning) |
|
1040 | warn(warning) | |
1048 | wait() |
|
1041 | wait() | |
1049 | return |
|
1042 | return | |
1050 |
|
1043 | |||
1051 | elif mode == 'upgrade': |
|
1044 | elif mode == 'upgrade': | |
1052 | try: |
|
1045 | try: | |
1053 | os.chdir(ipythondir) |
|
1046 | os.chdir(ipythondir) | |
1054 | except: |
|
1047 | except: | |
1055 | print """ |
|
1048 | print """ | |
1056 | Can not upgrade: changing to directory %s failed. Details: |
|
1049 | Can not upgrade: changing to directory %s failed. Details: | |
1057 | %s |
|
1050 | %s | |
1058 | """ % (ipythondir,sys.exc_info()[1]) |
|
1051 | """ % (ipythondir,sys.exc_info()[1]) | |
1059 | wait() |
|
1052 | wait() | |
1060 | return |
|
1053 | return | |
1061 | else: |
|
1054 | else: | |
1062 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1055 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
1063 | for new_full_path in sources: |
|
1056 | for new_full_path in sources: | |
1064 | new_filename = os.path.basename(new_full_path) |
|
1057 | new_filename = os.path.basename(new_full_path) | |
1065 | if new_filename.startswith('ipythonrc'): |
|
1058 | if new_filename.startswith('ipythonrc'): | |
1066 | new_filename = new_filename + rc_suffix |
|
1059 | new_filename = new_filename + rc_suffix | |
1067 | # The config directory should only contain files, skip any |
|
1060 | # The config directory should only contain files, skip any | |
1068 | # directories which may be there (like CVS) |
|
1061 | # directories which may be there (like CVS) | |
1069 | if os.path.isdir(new_full_path): |
|
1062 | if os.path.isdir(new_full_path): | |
1070 | continue |
|
1063 | continue | |
1071 | if os.path.exists(new_filename): |
|
1064 | if os.path.exists(new_filename): | |
1072 | old_file = new_filename+'.old' |
|
1065 | old_file = new_filename+'.old' | |
1073 | if os.path.exists(old_file): |
|
1066 | if os.path.exists(old_file): | |
1074 | os.remove(old_file) |
|
1067 | os.remove(old_file) | |
1075 | os.rename(new_filename,old_file) |
|
1068 | os.rename(new_filename,old_file) | |
1076 | shutil.copy(new_full_path,new_filename) |
|
1069 | shutil.copy(new_full_path,new_filename) | |
1077 | else: |
|
1070 | else: | |
1078 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1071 | raise ValueError,'unrecognized mode for install:',`mode` | |
1079 |
|
1072 | |||
1080 | # Fix line-endings to those native to each platform in the config |
|
1073 | # Fix line-endings to those native to each platform in the config | |
1081 | # directory. |
|
1074 | # directory. | |
1082 | try: |
|
1075 | try: | |
1083 | os.chdir(ipythondir) |
|
1076 | os.chdir(ipythondir) | |
1084 | except: |
|
1077 | except: | |
1085 | print """ |
|
1078 | print """ | |
1086 | Problem: changing to directory %s failed. |
|
1079 | Problem: changing to directory %s failed. | |
1087 | Details: |
|
1080 | Details: | |
1088 | %s |
|
1081 | %s | |
1089 |
|
1082 | |||
1090 | Some configuration files may have incorrect line endings. This should not |
|
1083 | Some configuration files may have incorrect line endings. This should not | |
1091 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1084 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) | |
1092 | wait() |
|
1085 | wait() | |
1093 | else: |
|
1086 | else: | |
1094 | for fname in glb('ipythonrc*'): |
|
1087 | for fname in glb('ipythonrc*'): | |
1095 | try: |
|
1088 | try: | |
1096 | native_line_ends(fname,backup=0) |
|
1089 | native_line_ends(fname,backup=0) | |
1097 | except IOError: |
|
1090 | except IOError: | |
1098 | pass |
|
1091 | pass | |
1099 |
|
1092 | |||
1100 | if mode == 'install': |
|
1093 | if mode == 'install': | |
1101 | print """ |
|
1094 | print """ | |
1102 | Successful installation! |
|
1095 | Successful installation! | |
1103 |
|
1096 | |||
1104 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1097 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
1105 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1098 | IPython manual (there are both HTML and PDF versions supplied with the | |
1106 | distribution) to make sure that your system environment is properly configured |
|
1099 | distribution) to make sure that your system environment is properly configured | |
1107 | to take advantage of IPython's features. |
|
1100 | to take advantage of IPython's features. | |
1108 |
|
1101 | |||
1109 | Important note: the configuration system has changed! The old system is |
|
1102 | Important note: the configuration system has changed! The old system is | |
1110 | still in place, but its setting may be partly overridden by the settings in |
|
1103 | still in place, but its setting may be partly overridden by the settings in | |
1111 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1104 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
1112 | if some of the new settings bother you. |
|
1105 | if some of the new settings bother you. | |
1113 |
|
1106 | |||
1114 | """ |
|
1107 | """ | |
1115 | else: |
|
1108 | else: | |
1116 | print """ |
|
1109 | print """ | |
1117 | Successful upgrade! |
|
1110 | Successful upgrade! | |
1118 |
|
1111 | |||
1119 | All files in your directory: |
|
1112 | All files in your directory: | |
1120 | %(ipythondir)s |
|
1113 | %(ipythondir)s | |
1121 | which would have been overwritten by the upgrade were backed up with a .old |
|
1114 | which would have been overwritten by the upgrade were backed up with a .old | |
1122 | extension. If you had made particular customizations in those files you may |
|
1115 | extension. If you had made particular customizations in those files you may | |
1123 | want to merge them back into the new files.""" % locals() |
|
1116 | want to merge them back into the new files.""" % locals() | |
1124 | wait() |
|
1117 | wait() | |
1125 | os.chdir(cwd) |
|
1118 | os.chdir(cwd) | |
1126 | # end user_setup() |
|
1119 | # end user_setup() | |
1127 |
|
1120 | |||
1128 | def atexit_operations(self): |
|
1121 | def atexit_operations(self): | |
1129 | """This will be executed at the time of exit. |
|
1122 | """This will be executed at the time of exit. | |
1130 |
|
1123 | |||
1131 | Saving of persistent data should be performed here. """ |
|
1124 | Saving of persistent data should be performed here. """ | |
1132 |
|
1125 | |||
1133 | #print '*** IPython exit cleanup ***' # dbg |
|
1126 | #print '*** IPython exit cleanup ***' # dbg | |
1134 | # input history |
|
1127 | # input history | |
1135 | self.savehist() |
|
1128 | self.savehist() | |
1136 |
|
1129 | |||
1137 | # Cleanup all tempfiles left around |
|
1130 | # Cleanup all tempfiles left around | |
1138 | for tfile in self.tempfiles: |
|
1131 | for tfile in self.tempfiles: | |
1139 | try: |
|
1132 | try: | |
1140 | os.unlink(tfile) |
|
1133 | os.unlink(tfile) | |
1141 | except OSError: |
|
1134 | except OSError: | |
1142 | pass |
|
1135 | pass | |
1143 |
|
1136 | |||
1144 | # save the "persistent data" catch-all dictionary |
|
1137 | # save the "persistent data" catch-all dictionary | |
1145 | self.hooks.shutdown_hook() |
|
1138 | self.hooks.shutdown_hook() | |
1146 |
|
1139 | |||
1147 | def savehist(self): |
|
1140 | def savehist(self): | |
1148 | """Save input history to a file (via readline library).""" |
|
1141 | """Save input history to a file (via readline library).""" | |
1149 | try: |
|
1142 | try: | |
1150 | self.readline.write_history_file(self.histfile) |
|
1143 | self.readline.write_history_file(self.histfile) | |
1151 | except: |
|
1144 | except: | |
1152 | print 'Unable to save IPython command history to file: ' + \ |
|
1145 | print 'Unable to save IPython command history to file: ' + \ | |
1153 | `self.histfile` |
|
1146 | `self.histfile` | |
1154 |
|
1147 | |||
1155 | def pre_readline(self): |
|
1148 | def pre_readline(self): | |
1156 | """readline hook to be used at the start of each line. |
|
1149 | """readline hook to be used at the start of each line. | |
1157 |
|
1150 | |||
1158 | Currently it handles auto-indent only.""" |
|
1151 | Currently it handles auto-indent only.""" | |
1159 |
|
1152 | |||
1160 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1153 | #debugx('self.indent_current_nsp','pre_readline:') | |
1161 | self.readline.insert_text(self.indent_current_str()) |
|
1154 | self.readline.insert_text(self.indent_current_str()) | |
1162 |
|
1155 | |||
1163 | def init_readline(self): |
|
1156 | def init_readline(self): | |
1164 | """Command history completion/saving/reloading.""" |
|
1157 | """Command history completion/saving/reloading.""" | |
1165 |
|
1158 | |||
1166 | import IPython.rlineimpl as readline |
|
1159 | import IPython.rlineimpl as readline | |
1167 | if not readline.have_readline: |
|
1160 | if not readline.have_readline: | |
1168 | self.has_readline = 0 |
|
1161 | self.has_readline = 0 | |
1169 | self.readline = None |
|
1162 | self.readline = None | |
1170 | # no point in bugging windows users with this every time: |
|
1163 | # no point in bugging windows users with this every time: | |
1171 | warn('Readline services not available on this platform.') |
|
1164 | warn('Readline services not available on this platform.') | |
1172 | else: |
|
1165 | else: | |
1173 | sys.modules['readline'] = readline |
|
1166 | sys.modules['readline'] = readline | |
1174 | import atexit |
|
1167 | import atexit | |
1175 | from IPython.completer import IPCompleter |
|
1168 | from IPython.completer import IPCompleter | |
1176 | self.Completer = IPCompleter(self, |
|
1169 | self.Completer = IPCompleter(self, | |
1177 | self.user_ns, |
|
1170 | self.user_ns, | |
1178 | self.user_global_ns, |
|
1171 | self.user_global_ns, | |
1179 | self.rc.readline_omit__names, |
|
1172 | self.rc.readline_omit__names, | |
1180 | self.alias_table) |
|
1173 | self.alias_table) | |
1181 |
|
1174 | |||
1182 | # Platform-specific configuration |
|
1175 | # Platform-specific configuration | |
1183 | if os.name == 'nt': |
|
1176 | if os.name == 'nt': | |
1184 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1177 | self.readline_startup_hook = readline.set_pre_input_hook | |
1185 | else: |
|
1178 | else: | |
1186 | self.readline_startup_hook = readline.set_startup_hook |
|
1179 | self.readline_startup_hook = readline.set_startup_hook | |
1187 |
|
1180 | |||
1188 | # Load user's initrc file (readline config) |
|
1181 | # Load user's initrc file (readline config) | |
1189 | inputrc_name = os.environ.get('INPUTRC') |
|
1182 | inputrc_name = os.environ.get('INPUTRC') | |
1190 | if inputrc_name is None: |
|
1183 | if inputrc_name is None: | |
1191 | home_dir = get_home_dir() |
|
1184 | home_dir = get_home_dir() | |
1192 | if home_dir is not None: |
|
1185 | if home_dir is not None: | |
1193 | inputrc_name = os.path.join(home_dir,'.inputrc') |
|
1186 | inputrc_name = os.path.join(home_dir,'.inputrc') | |
1194 | if os.path.isfile(inputrc_name): |
|
1187 | if os.path.isfile(inputrc_name): | |
1195 | try: |
|
1188 | try: | |
1196 | readline.read_init_file(inputrc_name) |
|
1189 | readline.read_init_file(inputrc_name) | |
1197 | except: |
|
1190 | except: | |
1198 | warn('Problems reading readline initialization file <%s>' |
|
1191 | warn('Problems reading readline initialization file <%s>' | |
1199 | % inputrc_name) |
|
1192 | % inputrc_name) | |
1200 |
|
1193 | |||
1201 | self.has_readline = 1 |
|
1194 | self.has_readline = 1 | |
1202 | self.readline = readline |
|
1195 | self.readline = readline | |
1203 | # save this in sys so embedded copies can restore it properly |
|
1196 | # save this in sys so embedded copies can restore it properly | |
1204 | sys.ipcompleter = self.Completer.complete |
|
1197 | sys.ipcompleter = self.Completer.complete | |
1205 | readline.set_completer(self.Completer.complete) |
|
1198 | readline.set_completer(self.Completer.complete) | |
1206 |
|
1199 | |||
1207 | # Configure readline according to user's prefs |
|
1200 | # Configure readline according to user's prefs | |
1208 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1201 | for rlcommand in self.rc.readline_parse_and_bind: | |
1209 | readline.parse_and_bind(rlcommand) |
|
1202 | readline.parse_and_bind(rlcommand) | |
1210 |
|
1203 | |||
1211 | # remove some chars from the delimiters list |
|
1204 | # remove some chars from the delimiters list | |
1212 | delims = readline.get_completer_delims() |
|
1205 | delims = readline.get_completer_delims() | |
1213 | delims = delims.translate(string._idmap, |
|
1206 | delims = delims.translate(string._idmap, | |
1214 | self.rc.readline_remove_delims) |
|
1207 | self.rc.readline_remove_delims) | |
1215 | readline.set_completer_delims(delims) |
|
1208 | readline.set_completer_delims(delims) | |
1216 | # otherwise we end up with a monster history after a while: |
|
1209 | # otherwise we end up with a monster history after a while: | |
1217 | readline.set_history_length(1000) |
|
1210 | readline.set_history_length(1000) | |
1218 | try: |
|
1211 | try: | |
1219 | #print '*** Reading readline history' # dbg |
|
1212 | #print '*** Reading readline history' # dbg | |
1220 | readline.read_history_file(self.histfile) |
|
1213 | readline.read_history_file(self.histfile) | |
1221 | except IOError: |
|
1214 | except IOError: | |
1222 | pass # It doesn't exist yet. |
|
1215 | pass # It doesn't exist yet. | |
1223 |
|
1216 | |||
1224 | atexit.register(self.atexit_operations) |
|
1217 | atexit.register(self.atexit_operations) | |
1225 | del atexit |
|
1218 | del atexit | |
1226 |
|
1219 | |||
1227 | # Configure auto-indent for all platforms |
|
1220 | # Configure auto-indent for all platforms | |
1228 | self.set_autoindent(self.rc.autoindent) |
|
1221 | self.set_autoindent(self.rc.autoindent) | |
1229 |
|
1222 | |||
1230 | def _should_recompile(self,e): |
|
1223 | def _should_recompile(self,e): | |
1231 | """Utility routine for edit_syntax_error""" |
|
1224 | """Utility routine for edit_syntax_error""" | |
1232 |
|
1225 | |||
1233 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1226 | if e.filename in ('<ipython console>','<input>','<string>', | |
1234 |
'<console>', |
|
1227 | '<console>','<BackgroundJob compilation>', | |
|
1228 | None): | |||
1235 |
|
1229 | |||
1236 | return False |
|
1230 | return False | |
1237 | try: |
|
1231 | try: | |
1238 | if (self.rc.autoedit_syntax and |
|
1232 | if (self.rc.autoedit_syntax and | |
1239 | not ask_yes_no('Return to editor to correct syntax error? ' |
|
1233 | not ask_yes_no('Return to editor to correct syntax error? ' | |
1240 | '[Y/n] ','y')): |
|
1234 | '[Y/n] ','y')): | |
1241 | return False |
|
1235 | return False | |
1242 | except EOFError: |
|
1236 | except EOFError: | |
1243 | return False |
|
1237 | return False | |
1244 |
|
1238 | |||
1245 | def int0(x): |
|
1239 | def int0(x): | |
1246 | try: |
|
1240 | try: | |
1247 | return int(x) |
|
1241 | return int(x) | |
1248 | except TypeError: |
|
1242 | except TypeError: | |
1249 | return 0 |
|
1243 | return 0 | |
1250 | # always pass integer line and offset values to editor hook |
|
1244 | # always pass integer line and offset values to editor hook | |
1251 | self.hooks.fix_error_editor(e.filename, |
|
1245 | self.hooks.fix_error_editor(e.filename, | |
1252 | int0(e.lineno),int0(e.offset),e.msg) |
|
1246 | int0(e.lineno),int0(e.offset),e.msg) | |
1253 | return True |
|
1247 | return True | |
1254 |
|
1248 | |||
1255 | def edit_syntax_error(self): |
|
1249 | def edit_syntax_error(self): | |
1256 | """The bottom half of the syntax error handler called in the main loop. |
|
1250 | """The bottom half of the syntax error handler called in the main loop. | |
1257 |
|
1251 | |||
1258 | Loop until syntax error is fixed or user cancels. |
|
1252 | Loop until syntax error is fixed or user cancels. | |
1259 | """ |
|
1253 | """ | |
1260 |
|
1254 | |||
1261 | while self.SyntaxTB.last_syntax_error: |
|
1255 | while self.SyntaxTB.last_syntax_error: | |
1262 | # copy and clear last_syntax_error |
|
1256 | # copy and clear last_syntax_error | |
1263 | err = self.SyntaxTB.clear_err_state() |
|
1257 | err = self.SyntaxTB.clear_err_state() | |
1264 | if not self._should_recompile(err): |
|
1258 | if not self._should_recompile(err): | |
1265 | return |
|
1259 | return | |
1266 | try: |
|
1260 | try: | |
1267 | # may set last_syntax_error again if a SyntaxError is raised |
|
1261 | # may set last_syntax_error again if a SyntaxError is raised | |
1268 | self.safe_execfile(err.filename,self.shell.user_ns) |
|
1262 | self.safe_execfile(err.filename,self.shell.user_ns) | |
1269 | except: |
|
1263 | except: | |
1270 | self.showtraceback() |
|
1264 | self.showtraceback() | |
1271 | else: |
|
1265 | else: | |
|
1266 | try: | |||
1272 | f = file(err.filename) |
|
1267 | f = file(err.filename) | |
1273 | try: |
|
1268 | try: | |
1274 | sys.displayhook(f.read()) |
|
1269 | sys.displayhook(f.read()) | |
1275 | finally: |
|
1270 | finally: | |
1276 | f.close() |
|
1271 | f.close() | |
|
1272 | except: | |||
|
1273 | self.showtraceback() | |||
1277 |
|
1274 | |||
1278 | def showsyntaxerror(self, filename=None): |
|
1275 | def showsyntaxerror(self, filename=None): | |
1279 | """Display the syntax error that just occurred. |
|
1276 | """Display the syntax error that just occurred. | |
1280 |
|
1277 | |||
1281 | This doesn't display a stack trace because there isn't one. |
|
1278 | This doesn't display a stack trace because there isn't one. | |
1282 |
|
1279 | |||
1283 | If a filename is given, it is stuffed in the exception instead |
|
1280 | If a filename is given, it is stuffed in the exception instead | |
1284 | of what was there before (because Python's parser always uses |
|
1281 | of what was there before (because Python's parser always uses | |
1285 | "<string>" when reading from a string). |
|
1282 | "<string>" when reading from a string). | |
1286 | """ |
|
1283 | """ | |
1287 | etype, value, last_traceback = sys.exc_info() |
|
1284 | etype, value, last_traceback = sys.exc_info() | |
1288 |
|
1285 | |||
1289 | # See note about these variables in showtraceback() below |
|
1286 | # See note about these variables in showtraceback() below | |
1290 | sys.last_type = etype |
|
1287 | sys.last_type = etype | |
1291 | sys.last_value = value |
|
1288 | sys.last_value = value | |
1292 | sys.last_traceback = last_traceback |
|
1289 | sys.last_traceback = last_traceback | |
1293 |
|
1290 | |||
1294 | if filename and etype is SyntaxError: |
|
1291 | if filename and etype is SyntaxError: | |
1295 | # Work hard to stuff the correct filename in the exception |
|
1292 | # Work hard to stuff the correct filename in the exception | |
1296 | try: |
|
1293 | try: | |
1297 | msg, (dummy_filename, lineno, offset, line) = value |
|
1294 | msg, (dummy_filename, lineno, offset, line) = value | |
1298 | except: |
|
1295 | except: | |
1299 | # Not the format we expect; leave it alone |
|
1296 | # Not the format we expect; leave it alone | |
1300 | pass |
|
1297 | pass | |
1301 | else: |
|
1298 | else: | |
1302 | # Stuff in the right filename |
|
1299 | # Stuff in the right filename | |
1303 | try: |
|
1300 | try: | |
1304 | # Assume SyntaxError is a class exception |
|
1301 | # Assume SyntaxError is a class exception | |
1305 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1302 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1306 | except: |
|
1303 | except: | |
1307 | # If that failed, assume SyntaxError is a string |
|
1304 | # If that failed, assume SyntaxError is a string | |
1308 | value = msg, (filename, lineno, offset, line) |
|
1305 | value = msg, (filename, lineno, offset, line) | |
1309 | self.SyntaxTB(etype,value,[]) |
|
1306 | self.SyntaxTB(etype,value,[]) | |
1310 |
|
1307 | |||
1311 | def debugger(self): |
|
1308 | def debugger(self): | |
1312 | """Call the pdb debugger.""" |
|
1309 | """Call the pdb debugger.""" | |
1313 |
|
1310 | |||
1314 | if not self.rc.pdb: |
|
1311 | if not self.rc.pdb: | |
1315 | return |
|
1312 | return | |
1316 | pdb.pm() |
|
1313 | pdb.pm() | |
1317 |
|
1314 | |||
1318 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1315 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1319 |
"""Display the exception that just occurred. |
|
1316 | """Display the exception that just occurred. | |
|
1317 | ||||
|
1318 | If nothing is known about the exception, this is the method which | |||
|
1319 | should be used throughout the code for presenting user tracebacks, | |||
|
1320 | rather htan directly invoking the InteractiveTB object. | |||
|
1321 | ||||
|
1322 | A specific showsyntaxerror() also exists, but this method can take | |||
|
1323 | care of calling it if needed, so unless you are explicitly catching a | |||
|
1324 | SyntaxError exception, don't try to analyze the stack manually and | |||
|
1325 | simply call this method.""" | |||
1320 |
|
1326 | |||
1321 | # Though this won't be called by syntax errors in the input line, |
|
1327 | # Though this won't be called by syntax errors in the input line, | |
1322 | # there may be SyntaxError cases whith imported code. |
|
1328 | # there may be SyntaxError cases whith imported code. | |
1323 | if exc_tuple is None: |
|
1329 | if exc_tuple is None: | |
1324 | etype, value, tb = sys.exc_info() |
|
1330 | etype, value, tb = sys.exc_info() | |
1325 | else: |
|
1331 | else: | |
1326 | etype, value, tb = exc_tuple |
|
1332 | etype, value, tb = exc_tuple | |
1327 | if etype is SyntaxError: |
|
1333 | if etype is SyntaxError: | |
1328 | self.showsyntaxerror(filename) |
|
1334 | self.showsyntaxerror(filename) | |
1329 | else: |
|
1335 | else: | |
1330 | # WARNING: these variables are somewhat deprecated and not |
|
1336 | # WARNING: these variables are somewhat deprecated and not | |
1331 | # necessarily safe to use in a threaded environment, but tools |
|
1337 | # necessarily safe to use in a threaded environment, but tools | |
1332 | # like pdb depend on their existence, so let's set them. If we |
|
1338 | # like pdb depend on their existence, so let's set them. If we | |
1333 | # find problems in the field, we'll need to revisit their use. |
|
1339 | # find problems in the field, we'll need to revisit their use. | |
1334 | sys.last_type = etype |
|
1340 | sys.last_type = etype | |
1335 | sys.last_value = value |
|
1341 | sys.last_value = value | |
1336 | sys.last_traceback = tb |
|
1342 | sys.last_traceback = tb | |
1337 |
|
1343 | |||
1338 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1344 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1339 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1345 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1340 | # pdb mucks up readline, fix it back |
|
1346 | # pdb mucks up readline, fix it back | |
1341 | self.readline.set_completer(self.Completer.complete) |
|
1347 | self.readline.set_completer(self.Completer.complete) | |
1342 |
|
1348 | |||
1343 | def mainloop(self,banner=None): |
|
1349 | def mainloop(self,banner=None): | |
1344 | """Creates the local namespace and starts the mainloop. |
|
1350 | """Creates the local namespace and starts the mainloop. | |
1345 |
|
1351 | |||
1346 | If an optional banner argument is given, it will override the |
|
1352 | If an optional banner argument is given, it will override the | |
1347 | internally created default banner.""" |
|
1353 | internally created default banner.""" | |
1348 |
|
1354 | |||
1349 | if self.rc.c: # Emulate Python's -c option |
|
1355 | if self.rc.c: # Emulate Python's -c option | |
1350 | self.exec_init_cmd() |
|
1356 | self.exec_init_cmd() | |
1351 | if banner is None: |
|
1357 | if banner is None: | |
1352 | if not self.rc.banner: |
|
1358 | if not self.rc.banner: | |
1353 | banner = '' |
|
1359 | banner = '' | |
1354 | # banner is string? Use it directly! |
|
1360 | # banner is string? Use it directly! | |
1355 | elif isinstance(self.rc.banner,basestring): |
|
1361 | elif isinstance(self.rc.banner,basestring): | |
1356 | banner = self.rc.banner |
|
1362 | banner = self.rc.banner | |
1357 | else: |
|
1363 | else: | |
1358 | banner = self.BANNER+self.banner2 |
|
1364 | banner = self.BANNER+self.banner2 | |
1359 |
|
1365 | |||
1360 | self.interact(banner) |
|
1366 | self.interact(banner) | |
1361 |
|
1367 | |||
1362 | def exec_init_cmd(self): |
|
1368 | def exec_init_cmd(self): | |
1363 | """Execute a command given at the command line. |
|
1369 | """Execute a command given at the command line. | |
1364 |
|
1370 | |||
1365 | This emulates Python's -c option.""" |
|
1371 | This emulates Python's -c option.""" | |
1366 |
|
1372 | |||
1367 | #sys.argv = ['-c'] |
|
1373 | #sys.argv = ['-c'] | |
1368 | self.push(self.rc.c) |
|
1374 | self.push(self.rc.c) | |
1369 |
|
1375 | |||
1370 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1376 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1371 | """Embeds IPython into a running python program. |
|
1377 | """Embeds IPython into a running python program. | |
1372 |
|
1378 | |||
1373 | Input: |
|
1379 | Input: | |
1374 |
|
1380 | |||
1375 | - header: An optional header message can be specified. |
|
1381 | - header: An optional header message can be specified. | |
1376 |
|
1382 | |||
1377 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1383 | - local_ns, global_ns: working namespaces. If given as None, the | |
1378 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1384 | IPython-initialized one is updated with __main__.__dict__, so that | |
1379 | program variables become visible but user-specific configuration |
|
1385 | program variables become visible but user-specific configuration | |
1380 | remains possible. |
|
1386 | remains possible. | |
1381 |
|
1387 | |||
1382 | - stack_depth: specifies how many levels in the stack to go to |
|
1388 | - stack_depth: specifies how many levels in the stack to go to | |
1383 | looking for namespaces (when local_ns and global_ns are None). This |
|
1389 | looking for namespaces (when local_ns and global_ns are None). This | |
1384 | allows an intermediate caller to make sure that this function gets |
|
1390 | allows an intermediate caller to make sure that this function gets | |
1385 | the namespace from the intended level in the stack. By default (0) |
|
1391 | the namespace from the intended level in the stack. By default (0) | |
1386 | it will get its locals and globals from the immediate caller. |
|
1392 | it will get its locals and globals from the immediate caller. | |
1387 |
|
1393 | |||
1388 | Warning: it's possible to use this in a program which is being run by |
|
1394 | Warning: it's possible to use this in a program which is being run by | |
1389 | IPython itself (via %run), but some funny things will happen (a few |
|
1395 | IPython itself (via %run), but some funny things will happen (a few | |
1390 | globals get overwritten). In the future this will be cleaned up, as |
|
1396 | globals get overwritten). In the future this will be cleaned up, as | |
1391 | there is no fundamental reason why it can't work perfectly.""" |
|
1397 | there is no fundamental reason why it can't work perfectly.""" | |
1392 |
|
1398 | |||
1393 | # Get locals and globals from caller |
|
1399 | # Get locals and globals from caller | |
1394 | if local_ns is None or global_ns is None: |
|
1400 | if local_ns is None or global_ns is None: | |
1395 | call_frame = sys._getframe(stack_depth).f_back |
|
1401 | call_frame = sys._getframe(stack_depth).f_back | |
1396 |
|
1402 | |||
1397 | if local_ns is None: |
|
1403 | if local_ns is None: | |
1398 | local_ns = call_frame.f_locals |
|
1404 | local_ns = call_frame.f_locals | |
1399 | if global_ns is None: |
|
1405 | if global_ns is None: | |
1400 | global_ns = call_frame.f_globals |
|
1406 | global_ns = call_frame.f_globals | |
1401 |
|
1407 | |||
1402 | # Update namespaces and fire up interpreter |
|
1408 | # Update namespaces and fire up interpreter | |
1403 |
|
1409 | |||
1404 | # The global one is easy, we can just throw it in |
|
1410 | # The global one is easy, we can just throw it in | |
1405 | self.user_global_ns = global_ns |
|
1411 | self.user_global_ns = global_ns | |
1406 |
|
1412 | |||
1407 | # but the user/local one is tricky: ipython needs it to store internal |
|
1413 | # but the user/local one is tricky: ipython needs it to store internal | |
1408 | # data, but we also need the locals. We'll copy locals in the user |
|
1414 | # data, but we also need the locals. We'll copy locals in the user | |
1409 | # one, but will track what got copied so we can delete them at exit. |
|
1415 | # one, but will track what got copied so we can delete them at exit. | |
1410 | # This is so that a later embedded call doesn't see locals from a |
|
1416 | # This is so that a later embedded call doesn't see locals from a | |
1411 | # previous call (which most likely existed in a separate scope). |
|
1417 | # previous call (which most likely existed in a separate scope). | |
1412 | local_varnames = local_ns.keys() |
|
1418 | local_varnames = local_ns.keys() | |
1413 | self.user_ns.update(local_ns) |
|
1419 | self.user_ns.update(local_ns) | |
1414 |
|
1420 | |||
1415 | # Patch for global embedding to make sure that things don't overwrite |
|
1421 | # Patch for global embedding to make sure that things don't overwrite | |
1416 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1422 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1417 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1423 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1418 | if local_ns is None and global_ns is None: |
|
1424 | if local_ns is None and global_ns is None: | |
1419 | self.user_global_ns.update(__main__.__dict__) |
|
1425 | self.user_global_ns.update(__main__.__dict__) | |
1420 |
|
1426 | |||
1421 | # make sure the tab-completer has the correct frame information, so it |
|
1427 | # make sure the tab-completer has the correct frame information, so it | |
1422 | # actually completes using the frame's locals/globals |
|
1428 | # actually completes using the frame's locals/globals | |
1423 | self.set_completer_frame() |
|
1429 | self.set_completer_frame() | |
1424 |
|
1430 | |||
1425 | # before activating the interactive mode, we need to make sure that |
|
1431 | # before activating the interactive mode, we need to make sure that | |
1426 | # all names in the builtin namespace needed by ipython point to |
|
1432 | # all names in the builtin namespace needed by ipython point to | |
1427 | # ourselves, and not to other instances. |
|
1433 | # ourselves, and not to other instances. | |
1428 | self.add_builtins() |
|
1434 | self.add_builtins() | |
1429 |
|
1435 | |||
1430 | self.interact(header) |
|
1436 | self.interact(header) | |
1431 |
|
1437 | |||
1432 | # now, purge out the user namespace from anything we might have added |
|
1438 | # now, purge out the user namespace from anything we might have added | |
1433 | # from the caller's local namespace |
|
1439 | # from the caller's local namespace | |
1434 | delvar = self.user_ns.pop |
|
1440 | delvar = self.user_ns.pop | |
1435 | for var in local_varnames: |
|
1441 | for var in local_varnames: | |
1436 | delvar(var,None) |
|
1442 | delvar(var,None) | |
1437 | # and clean builtins we may have overridden |
|
1443 | # and clean builtins we may have overridden | |
1438 | self.clean_builtins() |
|
1444 | self.clean_builtins() | |
1439 |
|
1445 | |||
1440 | def interact(self, banner=None): |
|
1446 | def interact(self, banner=None): | |
1441 | """Closely emulate the interactive Python console. |
|
1447 | """Closely emulate the interactive Python console. | |
1442 |
|
1448 | |||
1443 | The optional banner argument specify the banner to print |
|
1449 | The optional banner argument specify the banner to print | |
1444 | before the first interaction; by default it prints a banner |
|
1450 | before the first interaction; by default it prints a banner | |
1445 | similar to the one printed by the real Python interpreter, |
|
1451 | similar to the one printed by the real Python interpreter, | |
1446 | followed by the current class name in parentheses (so as not |
|
1452 | followed by the current class name in parentheses (so as not | |
1447 | to confuse this with the real interpreter -- since it's so |
|
1453 | to confuse this with the real interpreter -- since it's so | |
1448 | close!). |
|
1454 | close!). | |
1449 |
|
1455 | |||
1450 | """ |
|
1456 | """ | |
1451 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1457 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1452 | if banner is None: |
|
1458 | if banner is None: | |
1453 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1459 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1454 | (sys.version, sys.platform, cprt, |
|
1460 | (sys.version, sys.platform, cprt, | |
1455 | self.__class__.__name__)) |
|
1461 | self.__class__.__name__)) | |
1456 | else: |
|
1462 | else: | |
1457 | self.write(banner) |
|
1463 | self.write(banner) | |
1458 |
|
1464 | |||
1459 | more = 0 |
|
1465 | more = 0 | |
1460 |
|
1466 | |||
1461 | # Mark activity in the builtins |
|
1467 | # Mark activity in the builtins | |
1462 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1468 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1463 |
|
1469 | |||
1464 | # exit_now is set by a call to %Exit or %Quit |
|
1470 | # exit_now is set by a call to %Exit or %Quit | |
1465 | self.exit_now = False |
|
1471 | self.exit_now = False | |
1466 | while not self.exit_now: |
|
1472 | while not self.exit_now: | |
1467 | if more: |
|
1473 | if more: | |
1468 | prompt = self.outputcache.prompt2 |
|
1474 | prompt = self.outputcache.prompt2 | |
1469 | if self.autoindent: |
|
1475 | if self.autoindent: | |
1470 | self.readline_startup_hook(self.pre_readline) |
|
1476 | self.readline_startup_hook(self.pre_readline) | |
1471 | else: |
|
1477 | else: | |
1472 | prompt = self.outputcache.prompt1 |
|
1478 | prompt = self.outputcache.prompt1 | |
1473 | try: |
|
1479 | try: | |
1474 | line = self.raw_input(prompt,more) |
|
1480 | line = self.raw_input(prompt,more) | |
1475 | if self.autoindent: |
|
1481 | if self.autoindent: | |
1476 | self.readline_startup_hook(None) |
|
1482 | self.readline_startup_hook(None) | |
1477 | except KeyboardInterrupt: |
|
1483 | except KeyboardInterrupt: | |
1478 | self.write('\nKeyboardInterrupt\n') |
|
1484 | self.write('\nKeyboardInterrupt\n') | |
1479 | self.resetbuffer() |
|
1485 | self.resetbuffer() | |
1480 | # keep cache in sync with the prompt counter: |
|
1486 | # keep cache in sync with the prompt counter: | |
1481 | self.outputcache.prompt_count -= 1 |
|
1487 | self.outputcache.prompt_count -= 1 | |
1482 |
|
1488 | |||
1483 | if self.autoindent: |
|
1489 | if self.autoindent: | |
1484 | self.indent_current_nsp = 0 |
|
1490 | self.indent_current_nsp = 0 | |
1485 | more = 0 |
|
1491 | more = 0 | |
1486 | except EOFError: |
|
1492 | except EOFError: | |
1487 | if self.autoindent: |
|
1493 | if self.autoindent: | |
1488 | self.readline_startup_hook(None) |
|
1494 | self.readline_startup_hook(None) | |
1489 | self.write('\n') |
|
1495 | self.write('\n') | |
1490 | self.exit() |
|
1496 | self.exit() | |
1491 | except bdb.BdbQuit: |
|
1497 | except bdb.BdbQuit: | |
1492 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1498 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1493 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1499 | 'Because of how pdb handles the stack, it is impossible\n' | |
1494 | 'for IPython to properly format this particular exception.\n' |
|
1500 | 'for IPython to properly format this particular exception.\n' | |
1495 | 'IPython will resume normal operation.') |
|
1501 | 'IPython will resume normal operation.') | |
1496 | except: |
|
1502 | except: | |
1497 | # exceptions here are VERY RARE, but they can be triggered |
|
1503 | # exceptions here are VERY RARE, but they can be triggered | |
1498 | # asynchronously by signal handlers, for example. |
|
1504 | # asynchronously by signal handlers, for example. | |
1499 | self.showtraceback() |
|
1505 | self.showtraceback() | |
1500 | else: |
|
1506 | else: | |
1501 | more = self.push(line) |
|
1507 | more = self.push(line) | |
1502 | if (self.SyntaxTB.last_syntax_error and |
|
1508 | if (self.SyntaxTB.last_syntax_error and | |
1503 | self.rc.autoedit_syntax): |
|
1509 | self.rc.autoedit_syntax): | |
1504 | self.edit_syntax_error() |
|
1510 | self.edit_syntax_error() | |
1505 |
|
1511 | |||
1506 | # We are off again... |
|
1512 | # We are off again... | |
1507 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1513 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1508 |
|
1514 | |||
1509 | def excepthook(self, etype, value, tb): |
|
1515 | def excepthook(self, etype, value, tb): | |
1510 | """One more defense for GUI apps that call sys.excepthook. |
|
1516 | """One more defense for GUI apps that call sys.excepthook. | |
1511 |
|
1517 | |||
1512 | GUI frameworks like wxPython trap exceptions and call |
|
1518 | GUI frameworks like wxPython trap exceptions and call | |
1513 | sys.excepthook themselves. I guess this is a feature that |
|
1519 | sys.excepthook themselves. I guess this is a feature that | |
1514 | enables them to keep running after exceptions that would |
|
1520 | enables them to keep running after exceptions that would | |
1515 | otherwise kill their mainloop. This is a bother for IPython |
|
1521 | otherwise kill their mainloop. This is a bother for IPython | |
1516 | which excepts to catch all of the program exceptions with a try: |
|
1522 | which excepts to catch all of the program exceptions with a try: | |
1517 | except: statement. |
|
1523 | except: statement. | |
1518 |
|
1524 | |||
1519 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1525 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1520 | any app directly invokes sys.excepthook, it will look to the user like |
|
1526 | any app directly invokes sys.excepthook, it will look to the user like | |
1521 | IPython crashed. In order to work around this, we can disable the |
|
1527 | IPython crashed. In order to work around this, we can disable the | |
1522 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1528 | CrashHandler and replace it with this excepthook instead, which prints a | |
1523 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1529 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1524 | call sys.excepthook will generate a regular-looking exception from |
|
1530 | call sys.excepthook will generate a regular-looking exception from | |
1525 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1531 | IPython, and the CrashHandler will only be triggered by real IPython | |
1526 | crashes. |
|
1532 | crashes. | |
1527 |
|
1533 | |||
1528 | This hook should be used sparingly, only in places which are not likely |
|
1534 | This hook should be used sparingly, only in places which are not likely | |
1529 | to be true IPython errors. |
|
1535 | to be true IPython errors. | |
1530 | """ |
|
1536 | """ | |
1531 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1537 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1532 |
|
1538 | |||
1533 | def transform_alias(self, alias,rest=''): |
|
1539 | def transform_alias(self, alias,rest=''): | |
1534 | """ Transform alias to system command string |
|
1540 | """ Transform alias to system command string | |
1535 |
|
1541 | |||
1536 | """ |
|
1542 | """ | |
1537 | nargs,cmd = self.alias_table[alias] |
|
1543 | nargs,cmd = self.alias_table[alias] | |
1538 | if ' ' in cmd and os.path.isfile(cmd): |
|
1544 | if ' ' in cmd and os.path.isfile(cmd): | |
1539 | cmd = '"%s"' % cmd |
|
1545 | cmd = '"%s"' % cmd | |
1540 |
|
1546 | |||
1541 | # Expand the %l special to be the user's input line |
|
1547 | # Expand the %l special to be the user's input line | |
1542 | if cmd.find('%l') >= 0: |
|
1548 | if cmd.find('%l') >= 0: | |
1543 | cmd = cmd.replace('%l',rest) |
|
1549 | cmd = cmd.replace('%l',rest) | |
1544 | rest = '' |
|
1550 | rest = '' | |
1545 | if nargs==0: |
|
1551 | if nargs==0: | |
1546 | # Simple, argument-less aliases |
|
1552 | # Simple, argument-less aliases | |
1547 | cmd = '%s %s' % (cmd,rest) |
|
1553 | cmd = '%s %s' % (cmd,rest) | |
1548 | else: |
|
1554 | else: | |
1549 | # Handle aliases with positional arguments |
|
1555 | # Handle aliases with positional arguments | |
1550 | args = rest.split(None,nargs) |
|
1556 | args = rest.split(None,nargs) | |
1551 | if len(args)< nargs: |
|
1557 | if len(args)< nargs: | |
1552 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1558 | error('Alias <%s> requires %s arguments, %s given.' % | |
1553 | (alias,nargs,len(args))) |
|
1559 | (alias,nargs,len(args))) | |
1554 | return None |
|
1560 | return None | |
1555 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1561 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
1556 | # Now call the macro, evaluating in the user's namespace |
|
1562 | # Now call the macro, evaluating in the user's namespace | |
1557 |
|
1563 | |||
1558 | return cmd |
|
1564 | return cmd | |
1559 |
|
1565 | |||
1560 | def call_alias(self,alias,rest=''): |
|
1566 | def call_alias(self,alias,rest=''): | |
1561 | """Call an alias given its name and the rest of the line. |
|
1567 | """Call an alias given its name and the rest of the line. | |
1562 |
|
1568 | |||
1563 | This is only used to provide backwards compatibility for users of |
|
1569 | This is only used to provide backwards compatibility for users of | |
1564 | ipalias(), use of which is not recommended for anymore.""" |
|
1570 | ipalias(), use of which is not recommended for anymore.""" | |
1565 |
|
1571 | |||
1566 | # Now call the macro, evaluating in the user's namespace |
|
1572 | # Now call the macro, evaluating in the user's namespace | |
1567 | cmd = self.transform_alias(alias, rest) |
|
1573 | cmd = self.transform_alias(alias, rest) | |
1568 | try: |
|
1574 | try: | |
1569 | self.system(cmd) |
|
1575 | self.system(cmd) | |
1570 | except: |
|
1576 | except: | |
1571 | self.showtraceback() |
|
1577 | self.showtraceback() | |
1572 |
|
1578 | |||
1573 | def indent_current_str(self): |
|
1579 | def indent_current_str(self): | |
1574 | """return the current level of indentation as a string""" |
|
1580 | """return the current level of indentation as a string""" | |
1575 | return self.indent_current_nsp * ' ' |
|
1581 | return self.indent_current_nsp * ' ' | |
1576 |
|
1582 | |||
1577 | def autoindent_update(self,line): |
|
1583 | def autoindent_update(self,line): | |
1578 | """Keep track of the indent level.""" |
|
1584 | """Keep track of the indent level.""" | |
1579 |
|
1585 | |||
1580 | #debugx('line') |
|
1586 | #debugx('line') | |
1581 | #debugx('self.indent_current_nsp') |
|
1587 | #debugx('self.indent_current_nsp') | |
1582 | if self.autoindent: |
|
1588 | if self.autoindent: | |
1583 | if line: |
|
1589 | if line: | |
1584 | inisp = num_ini_spaces(line) |
|
1590 | inisp = num_ini_spaces(line) | |
1585 | if inisp < self.indent_current_nsp: |
|
1591 | if inisp < self.indent_current_nsp: | |
1586 | self.indent_current_nsp = inisp |
|
1592 | self.indent_current_nsp = inisp | |
1587 |
|
1593 | |||
1588 | if line[-1] == ':': |
|
1594 | if line[-1] == ':': | |
1589 | self.indent_current_nsp += 4 |
|
1595 | self.indent_current_nsp += 4 | |
1590 | elif dedent_re.match(line): |
|
1596 | elif dedent_re.match(line): | |
1591 | self.indent_current_nsp -= 4 |
|
1597 | self.indent_current_nsp -= 4 | |
1592 | else: |
|
1598 | else: | |
1593 | self.indent_current_nsp = 0 |
|
1599 | self.indent_current_nsp = 0 | |
1594 |
|
1600 | |||
1595 | def runlines(self,lines): |
|
1601 | def runlines(self,lines): | |
1596 | """Run a string of one or more lines of source. |
|
1602 | """Run a string of one or more lines of source. | |
1597 |
|
1603 | |||
1598 | This method is capable of running a string containing multiple source |
|
1604 | This method is capable of running a string containing multiple source | |
1599 | lines, as if they had been entered at the IPython prompt. Since it |
|
1605 | lines, as if they had been entered at the IPython prompt. Since it | |
1600 | exposes IPython's processing machinery, the given strings can contain |
|
1606 | exposes IPython's processing machinery, the given strings can contain | |
1601 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1607 | magic calls (%magic), special shell access (!cmd), etc.""" | |
1602 |
|
1608 | |||
1603 | # We must start with a clean buffer, in case this is run from an |
|
1609 | # We must start with a clean buffer, in case this is run from an | |
1604 | # interactive IPython session (via a magic, for example). |
|
1610 | # interactive IPython session (via a magic, for example). | |
1605 | self.resetbuffer() |
|
1611 | self.resetbuffer() | |
1606 | lines = lines.split('\n') |
|
1612 | lines = lines.split('\n') | |
1607 | more = 0 |
|
1613 | more = 0 | |
1608 | for line in lines: |
|
1614 | for line in lines: | |
1609 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1615 | # skip blank lines so we don't mess up the prompt counter, but do | |
1610 | # NOT skip even a blank line if we are in a code block (more is |
|
1616 | # NOT skip even a blank line if we are in a code block (more is | |
1611 | # true) |
|
1617 | # true) | |
1612 | if line or more: |
|
1618 | if line or more: | |
1613 | more = self.push(self.prefilter(line,more)) |
|
1619 | more = self.push(self.prefilter(line,more)) | |
1614 | # IPython's runsource returns None if there was an error |
|
1620 | # IPython's runsource returns None if there was an error | |
1615 | # compiling the code. This allows us to stop processing right |
|
1621 | # compiling the code. This allows us to stop processing right | |
1616 | # away, so the user gets the error message at the right place. |
|
1622 | # away, so the user gets the error message at the right place. | |
1617 | if more is None: |
|
1623 | if more is None: | |
1618 | break |
|
1624 | break | |
1619 | # final newline in case the input didn't have it, so that the code |
|
1625 | # final newline in case the input didn't have it, so that the code | |
1620 | # actually does get executed |
|
1626 | # actually does get executed | |
1621 | if more: |
|
1627 | if more: | |
1622 | self.push('\n') |
|
1628 | self.push('\n') | |
1623 |
|
1629 | |||
1624 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1630 | def runsource(self, source, filename='<input>', symbol='single'): | |
1625 | """Compile and run some source in the interpreter. |
|
1631 | """Compile and run some source in the interpreter. | |
1626 |
|
1632 | |||
1627 | Arguments are as for compile_command(). |
|
1633 | Arguments are as for compile_command(). | |
1628 |
|
1634 | |||
1629 | One several things can happen: |
|
1635 | One several things can happen: | |
1630 |
|
1636 | |||
1631 | 1) The input is incorrect; compile_command() raised an |
|
1637 | 1) The input is incorrect; compile_command() raised an | |
1632 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1638 | exception (SyntaxError or OverflowError). A syntax traceback | |
1633 | will be printed by calling the showsyntaxerror() method. |
|
1639 | will be printed by calling the showsyntaxerror() method. | |
1634 |
|
1640 | |||
1635 | 2) The input is incomplete, and more input is required; |
|
1641 | 2) The input is incomplete, and more input is required; | |
1636 | compile_command() returned None. Nothing happens. |
|
1642 | compile_command() returned None. Nothing happens. | |
1637 |
|
1643 | |||
1638 | 3) The input is complete; compile_command() returned a code |
|
1644 | 3) The input is complete; compile_command() returned a code | |
1639 | object. The code is executed by calling self.runcode() (which |
|
1645 | object. The code is executed by calling self.runcode() (which | |
1640 | also handles run-time exceptions, except for SystemExit). |
|
1646 | also handles run-time exceptions, except for SystemExit). | |
1641 |
|
1647 | |||
1642 | The return value is: |
|
1648 | The return value is: | |
1643 |
|
1649 | |||
1644 | - True in case 2 |
|
1650 | - True in case 2 | |
1645 |
|
1651 | |||
1646 | - False in the other cases, unless an exception is raised, where |
|
1652 | - False in the other cases, unless an exception is raised, where | |
1647 | None is returned instead. This can be used by external callers to |
|
1653 | None is returned instead. This can be used by external callers to | |
1648 | know whether to continue feeding input or not. |
|
1654 | know whether to continue feeding input or not. | |
1649 |
|
1655 | |||
1650 | The return value can be used to decide whether to use sys.ps1 or |
|
1656 | The return value can be used to decide whether to use sys.ps1 or | |
1651 | sys.ps2 to prompt the next line.""" |
|
1657 | sys.ps2 to prompt the next line.""" | |
1652 |
|
1658 | |||
1653 | try: |
|
1659 | try: | |
1654 | code = self.compile(source,filename,symbol) |
|
1660 | code = self.compile(source,filename,symbol) | |
1655 | except (OverflowError, SyntaxError, ValueError): |
|
1661 | except (OverflowError, SyntaxError, ValueError): | |
1656 | # Case 1 |
|
1662 | # Case 1 | |
1657 | self.showsyntaxerror(filename) |
|
1663 | self.showsyntaxerror(filename) | |
1658 | return None |
|
1664 | return None | |
1659 |
|
1665 | |||
1660 | if code is None: |
|
1666 | if code is None: | |
1661 | # Case 2 |
|
1667 | # Case 2 | |
1662 | return True |
|
1668 | return True | |
1663 |
|
1669 | |||
1664 | # Case 3 |
|
1670 | # Case 3 | |
1665 | # We store the code object so that threaded shells and |
|
1671 | # We store the code object so that threaded shells and | |
1666 | # custom exception handlers can access all this info if needed. |
|
1672 | # custom exception handlers can access all this info if needed. | |
1667 | # The source corresponding to this can be obtained from the |
|
1673 | # The source corresponding to this can be obtained from the | |
1668 | # buffer attribute as '\n'.join(self.buffer). |
|
1674 | # buffer attribute as '\n'.join(self.buffer). | |
1669 | self.code_to_run = code |
|
1675 | self.code_to_run = code | |
1670 | # now actually execute the code object |
|
1676 | # now actually execute the code object | |
1671 | if self.runcode(code) == 0: |
|
1677 | if self.runcode(code) == 0: | |
1672 | return False |
|
1678 | return False | |
1673 | else: |
|
1679 | else: | |
1674 | return None |
|
1680 | return None | |
1675 |
|
1681 | |||
1676 | def runcode(self,code_obj): |
|
1682 | def runcode(self,code_obj): | |
1677 | """Execute a code object. |
|
1683 | """Execute a code object. | |
1678 |
|
1684 | |||
1679 | When an exception occurs, self.showtraceback() is called to display a |
|
1685 | When an exception occurs, self.showtraceback() is called to display a | |
1680 | traceback. |
|
1686 | traceback. | |
1681 |
|
1687 | |||
1682 | Return value: a flag indicating whether the code to be run completed |
|
1688 | Return value: a flag indicating whether the code to be run completed | |
1683 | successfully: |
|
1689 | successfully: | |
1684 |
|
1690 | |||
1685 | - 0: successful execution. |
|
1691 | - 0: successful execution. | |
1686 | - 1: an error occurred. |
|
1692 | - 1: an error occurred. | |
1687 | """ |
|
1693 | """ | |
1688 |
|
1694 | |||
1689 | # Set our own excepthook in case the user code tries to call it |
|
1695 | # Set our own excepthook in case the user code tries to call it | |
1690 | # directly, so that the IPython crash handler doesn't get triggered |
|
1696 | # directly, so that the IPython crash handler doesn't get triggered | |
1691 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1697 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
1692 |
|
1698 | |||
1693 | # we save the original sys.excepthook in the instance, in case config |
|
1699 | # we save the original sys.excepthook in the instance, in case config | |
1694 | # code (such as magics) needs access to it. |
|
1700 | # code (such as magics) needs access to it. | |
1695 | self.sys_excepthook = old_excepthook |
|
1701 | self.sys_excepthook = old_excepthook | |
1696 | outflag = 1 # happens in more places, so it's easier as default |
|
1702 | outflag = 1 # happens in more places, so it's easier as default | |
1697 | try: |
|
1703 | try: | |
1698 | try: |
|
1704 | try: | |
1699 | # Embedded instances require separate global/local namespaces |
|
1705 | # Embedded instances require separate global/local namespaces | |
1700 | # so they can see both the surrounding (local) namespace and |
|
1706 | # so they can see both the surrounding (local) namespace and | |
1701 | # the module-level globals when called inside another function. |
|
1707 | # the module-level globals when called inside another function. | |
1702 | if self.embedded: |
|
1708 | if self.embedded: | |
1703 | exec code_obj in self.user_global_ns, self.user_ns |
|
1709 | exec code_obj in self.user_global_ns, self.user_ns | |
1704 | # Normal (non-embedded) instances should only have a single |
|
1710 | # Normal (non-embedded) instances should only have a single | |
1705 | # namespace for user code execution, otherwise functions won't |
|
1711 | # namespace for user code execution, otherwise functions won't | |
1706 | # see interactive top-level globals. |
|
1712 | # see interactive top-level globals. | |
1707 | else: |
|
1713 | else: | |
1708 | exec code_obj in self.user_ns |
|
1714 | exec code_obj in self.user_ns | |
1709 | finally: |
|
1715 | finally: | |
1710 | # Reset our crash handler in place |
|
1716 | # Reset our crash handler in place | |
1711 | sys.excepthook = old_excepthook |
|
1717 | sys.excepthook = old_excepthook | |
1712 | except SystemExit: |
|
1718 | except SystemExit: | |
1713 | self.resetbuffer() |
|
1719 | self.resetbuffer() | |
1714 | self.showtraceback() |
|
1720 | self.showtraceback() | |
1715 | warn("Type exit or quit to exit IPython " |
|
1721 | warn("Type exit or quit to exit IPython " | |
1716 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
1722 | "(%Exit or %Quit do so unconditionally).",level=1) | |
1717 | except self.custom_exceptions: |
|
1723 | except self.custom_exceptions: | |
1718 | etype,value,tb = sys.exc_info() |
|
1724 | etype,value,tb = sys.exc_info() | |
1719 | self.CustomTB(etype,value,tb) |
|
1725 | self.CustomTB(etype,value,tb) | |
1720 | except: |
|
1726 | except: | |
1721 | self.showtraceback() |
|
1727 | self.showtraceback() | |
1722 | else: |
|
1728 | else: | |
1723 | outflag = 0 |
|
1729 | outflag = 0 | |
1724 | if softspace(sys.stdout, 0): |
|
1730 | if softspace(sys.stdout, 0): | |
1725 |
|
1731 | |||
1726 | # Flush out code object which has been run (and source) |
|
1732 | # Flush out code object which has been run (and source) | |
1727 | self.code_to_run = None |
|
1733 | self.code_to_run = None | |
1728 | return outflag |
|
1734 | return outflag | |
1729 |
|
1735 | |||
1730 | def push(self, line): |
|
1736 | def push(self, line): | |
1731 | """Push a line to the interpreter. |
|
1737 | """Push a line to the interpreter. | |
1732 |
|
1738 | |||
1733 | The line should not have a trailing newline; it may have |
|
1739 | The line should not have a trailing newline; it may have | |
1734 | internal newlines. The line is appended to a buffer and the |
|
1740 | internal newlines. The line is appended to a buffer and the | |
1735 | interpreter's runsource() method is called with the |
|
1741 | interpreter's runsource() method is called with the | |
1736 | concatenated contents of the buffer as source. If this |
|
1742 | concatenated contents of the buffer as source. If this | |
1737 | indicates that the command was executed or invalid, the buffer |
|
1743 | indicates that the command was executed or invalid, the buffer | |
1738 | is reset; otherwise, the command is incomplete, and the buffer |
|
1744 | is reset; otherwise, the command is incomplete, and the buffer | |
1739 | is left as it was after the line was appended. The return |
|
1745 | is left as it was after the line was appended. The return | |
1740 | value is 1 if more input is required, 0 if the line was dealt |
|
1746 | value is 1 if more input is required, 0 if the line was dealt | |
1741 | with in some way (this is the same as runsource()). |
|
1747 | with in some way (this is the same as runsource()). | |
1742 | """ |
|
1748 | """ | |
1743 |
|
1749 | |||
1744 | # autoindent management should be done here, and not in the |
|
1750 | # autoindent management should be done here, and not in the | |
1745 | # interactive loop, since that one is only seen by keyboard input. We |
|
1751 | # interactive loop, since that one is only seen by keyboard input. We | |
1746 | # need this done correctly even for code run via runlines (which uses |
|
1752 | # need this done correctly even for code run via runlines (which uses | |
1747 | # push). |
|
1753 | # push). | |
1748 |
|
1754 | |||
1749 | #print 'push line: <%s>' % line # dbg |
|
1755 | #print 'push line: <%s>' % line # dbg | |
1750 | self.autoindent_update(line) |
|
1756 | self.autoindent_update(line) | |
1751 |
|
1757 | |||
1752 | self.buffer.append(line) |
|
1758 | self.buffer.append(line) | |
1753 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
1759 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
1754 | if not more: |
|
1760 | if not more: | |
1755 | self.resetbuffer() |
|
1761 | self.resetbuffer() | |
1756 | return more |
|
1762 | return more | |
1757 |
|
1763 | |||
1758 | def resetbuffer(self): |
|
1764 | def resetbuffer(self): | |
1759 | """Reset the input buffer.""" |
|
1765 | """Reset the input buffer.""" | |
1760 | self.buffer[:] = [] |
|
1766 | self.buffer[:] = [] | |
1761 |
|
1767 | |||
1762 | def raw_input(self,prompt='',continue_prompt=False): |
|
1768 | def raw_input(self,prompt='',continue_prompt=False): | |
1763 | """Write a prompt and read a line. |
|
1769 | """Write a prompt and read a line. | |
1764 |
|
1770 | |||
1765 | The returned line does not include the trailing newline. |
|
1771 | The returned line does not include the trailing newline. | |
1766 | When the user enters the EOF key sequence, EOFError is raised. |
|
1772 | When the user enters the EOF key sequence, EOFError is raised. | |
1767 |
|
1773 | |||
1768 | Optional inputs: |
|
1774 | Optional inputs: | |
1769 |
|
1775 | |||
1770 | - prompt(''): a string to be printed to prompt the user. |
|
1776 | - prompt(''): a string to be printed to prompt the user. | |
1771 |
|
1777 | |||
1772 | - continue_prompt(False): whether this line is the first one or a |
|
1778 | - continue_prompt(False): whether this line is the first one or a | |
1773 | continuation in a sequence of inputs. |
|
1779 | continuation in a sequence of inputs. | |
1774 | """ |
|
1780 | """ | |
1775 |
|
1781 | |||
1776 | line = raw_input_original(prompt) |
|
1782 | line = raw_input_original(prompt) | |
1777 |
|
1783 | |||
1778 | # Try to be reasonably smart about not re-indenting pasted input more |
|
1784 | # Try to be reasonably smart about not re-indenting pasted input more | |
1779 | # than necessary. We do this by trimming out the auto-indent initial |
|
1785 | # than necessary. We do this by trimming out the auto-indent initial | |
1780 | # spaces, if the user's actual input started itself with whitespace. |
|
1786 | # spaces, if the user's actual input started itself with whitespace. | |
1781 | #debugx('self.buffer[-1]') |
|
1787 | #debugx('self.buffer[-1]') | |
1782 |
|
1788 | |||
1783 | if self.autoindent: |
|
1789 | if self.autoindent: | |
1784 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
1790 | if num_ini_spaces(line) > self.indent_current_nsp: | |
1785 | line = line[self.indent_current_nsp:] |
|
1791 | line = line[self.indent_current_nsp:] | |
1786 | self.indent_current_nsp = 0 |
|
1792 | self.indent_current_nsp = 0 | |
1787 |
|
1793 | |||
1788 | # store the unfiltered input before the user has any chance to modify |
|
1794 | # store the unfiltered input before the user has any chance to modify | |
1789 | # it. |
|
1795 | # it. | |
1790 | if line.strip(): |
|
1796 | if line.strip(): | |
1791 | if continue_prompt: |
|
1797 | if continue_prompt: | |
1792 | self.input_hist_raw[-1] += '%s\n' % line |
|
1798 | self.input_hist_raw[-1] += '%s\n' % line | |
1793 | else: |
|
1799 | else: | |
1794 | self.input_hist_raw.append('%s\n' % line) |
|
1800 | self.input_hist_raw.append('%s\n' % line) | |
1795 |
|
1801 | |||
|
1802 | try: | |||
1796 | lineout = self.prefilter(line,continue_prompt) |
|
1803 | lineout = self.prefilter(line,continue_prompt) | |
|
1804 | except: | |||
|
1805 | # blanket except, in case a user-defined prefilter crashes, so it | |||
|
1806 | # can't take all of ipython with it. | |||
|
1807 | self.showtraceback() | |||
1797 | return lineout |
|
1808 | return lineout | |
1798 |
|
1809 | |||
1799 | def split_user_input(self,line): |
|
1810 | def split_user_input(self,line): | |
1800 | """Split user input into pre-char, function part and rest.""" |
|
1811 | """Split user input into pre-char, function part and rest.""" | |
1801 |
|
1812 | |||
1802 | lsplit = self.line_split.match(line) |
|
1813 | lsplit = self.line_split.match(line) | |
1803 | if lsplit is None: # no regexp match returns None |
|
1814 | if lsplit is None: # no regexp match returns None | |
1804 | try: |
|
1815 | try: | |
1805 | iFun,theRest = line.split(None,1) |
|
1816 | iFun,theRest = line.split(None,1) | |
1806 | except ValueError: |
|
1817 | except ValueError: | |
1807 | iFun,theRest = line,'' |
|
1818 | iFun,theRest = line,'' | |
1808 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
1819 | pre = re.match('^(\s*)(.*)',line).groups()[0] | |
1809 | else: |
|
1820 | else: | |
1810 | pre,iFun,theRest = lsplit.groups() |
|
1821 | pre,iFun,theRest = lsplit.groups() | |
1811 |
|
1822 | |||
1812 | #print 'line:<%s>' % line # dbg |
|
1823 | #print 'line:<%s>' % line # dbg | |
1813 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
1824 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg | |
1814 | return pre,iFun.strip(),theRest |
|
1825 | return pre,iFun.strip(),theRest | |
1815 |
|
1826 | |||
1816 | def _prefilter(self, line, continue_prompt): |
|
1827 | def _prefilter(self, line, continue_prompt): | |
1817 | """Calls different preprocessors, depending on the form of line.""" |
|
1828 | """Calls different preprocessors, depending on the form of line.""" | |
1818 |
|
1829 | |||
1819 | # All handlers *must* return a value, even if it's blank (''). |
|
1830 | # All handlers *must* return a value, even if it's blank (''). | |
1820 |
|
1831 | |||
1821 | # Lines are NOT logged here. Handlers should process the line as |
|
1832 | # Lines are NOT logged here. Handlers should process the line as | |
1822 | # needed, update the cache AND log it (so that the input cache array |
|
1833 | # needed, update the cache AND log it (so that the input cache array | |
1823 | # stays synced). |
|
1834 | # stays synced). | |
1824 |
|
1835 | |||
1825 | # This function is _very_ delicate, and since it's also the one which |
|
1836 | # This function is _very_ delicate, and since it's also the one which | |
1826 | # determines IPython's response to user input, it must be as efficient |
|
1837 | # determines IPython's response to user input, it must be as efficient | |
1827 | # as possible. For this reason it has _many_ returns in it, trying |
|
1838 | # as possible. For this reason it has _many_ returns in it, trying | |
1828 | # always to exit as quickly as it can figure out what it needs to do. |
|
1839 | # always to exit as quickly as it can figure out what it needs to do. | |
1829 |
|
1840 | |||
1830 | # This function is the main responsible for maintaining IPython's |
|
1841 | # This function is the main responsible for maintaining IPython's | |
1831 | # behavior respectful of Python's semantics. So be _very_ careful if |
|
1842 | # behavior respectful of Python's semantics. So be _very_ careful if | |
1832 | # making changes to anything here. |
|
1843 | # making changes to anything here. | |
1833 |
|
1844 | |||
1834 | #..................................................................... |
|
1845 | #..................................................................... | |
1835 | # Code begins |
|
1846 | # Code begins | |
1836 |
|
1847 | |||
1837 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
1848 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
1838 |
|
1849 | |||
1839 | # save the line away in case we crash, so the post-mortem handler can |
|
1850 | # save the line away in case we crash, so the post-mortem handler can | |
1840 | # record it |
|
1851 | # record it | |
1841 | self._last_input_line = line |
|
1852 | self._last_input_line = line | |
1842 |
|
1853 | |||
1843 | #print '***line: <%s>' % line # dbg |
|
1854 | #print '***line: <%s>' % line # dbg | |
1844 |
|
1855 | |||
1845 | # the input history needs to track even empty lines |
|
1856 | # the input history needs to track even empty lines | |
1846 | stripped = line.strip() |
|
1857 | stripped = line.strip() | |
1847 |
|
1858 | |||
1848 | if not stripped: |
|
1859 | if not stripped: | |
1849 | if not continue_prompt: |
|
1860 | if not continue_prompt: | |
1850 | self.outputcache.prompt_count -= 1 |
|
1861 | self.outputcache.prompt_count -= 1 | |
1851 | return self.handle_normal(line,continue_prompt) |
|
1862 | return self.handle_normal(line,continue_prompt) | |
1852 | #return self.handle_normal('',continue_prompt) |
|
1863 | #return self.handle_normal('',continue_prompt) | |
1853 |
|
1864 | |||
1854 | # print '***cont',continue_prompt # dbg |
|
1865 | # print '***cont',continue_prompt # dbg | |
1855 | # special handlers are only allowed for single line statements |
|
1866 | # special handlers are only allowed for single line statements | |
1856 | if continue_prompt and not self.rc.multi_line_specials: |
|
1867 | if continue_prompt and not self.rc.multi_line_specials: | |
1857 | return self.handle_normal(line,continue_prompt) |
|
1868 | return self.handle_normal(line,continue_prompt) | |
1858 |
|
1869 | |||
1859 |
|
1870 | |||
1860 | # For the rest, we need the structure of the input |
|
1871 | # For the rest, we need the structure of the input | |
1861 | pre,iFun,theRest = self.split_user_input(line) |
|
1872 | pre,iFun,theRest = self.split_user_input(line) | |
1862 |
|
1873 | |||
1863 | # See whether any pre-existing handler can take care of it |
|
1874 | # See whether any pre-existing handler can take care of it | |
1864 |
|
1875 | |||
1865 | rewritten = self.hooks.input_prefilter(stripped) |
|
1876 | rewritten = self.hooks.input_prefilter(stripped) | |
1866 | if rewritten != stripped: # ok, some prefilter did something |
|
1877 | if rewritten != stripped: # ok, some prefilter did something | |
1867 | rewritten = pre + rewritten # add indentation |
|
1878 | rewritten = pre + rewritten # add indentation | |
1868 | return self.handle_normal(rewritten) |
|
1879 | return self.handle_normal(rewritten) | |
1869 |
|
1880 | |||
1870 |
|
1881 | |||
1871 |
|
1882 | |||
1872 |
|
1883 | |||
1873 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1884 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
1874 |
|
1885 | |||
1875 | # First check for explicit escapes in the last/first character |
|
1886 | # First check for explicit escapes in the last/first character | |
1876 | handler = None |
|
1887 | handler = None | |
1877 | if line[-1] == self.ESC_HELP: |
|
1888 | if line[-1] == self.ESC_HELP: | |
1878 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end |
|
1889 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end | |
1879 | if handler is None: |
|
1890 | if handler is None: | |
1880 | # look at the first character of iFun, NOT of line, so we skip |
|
1891 | # look at the first character of iFun, NOT of line, so we skip | |
1881 | # leading whitespace in multiline input |
|
1892 | # leading whitespace in multiline input | |
1882 | handler = self.esc_handlers.get(iFun[0:1]) |
|
1893 | handler = self.esc_handlers.get(iFun[0:1]) | |
1883 | if handler is not None: |
|
1894 | if handler is not None: | |
1884 | return handler(line,continue_prompt,pre,iFun,theRest) |
|
1895 | return handler(line,continue_prompt,pre,iFun,theRest) | |
1885 | # Emacs ipython-mode tags certain input lines |
|
1896 | # Emacs ipython-mode tags certain input lines | |
1886 | if line.endswith('# PYTHON-MODE'): |
|
1897 | if line.endswith('# PYTHON-MODE'): | |
1887 | return self.handle_emacs(line,continue_prompt) |
|
1898 | return self.handle_emacs(line,continue_prompt) | |
1888 |
|
1899 | |||
1889 | # Next, check if we can automatically execute this thing |
|
1900 | # Next, check if we can automatically execute this thing | |
1890 |
|
1901 | |||
1891 | # Allow ! in multi-line statements if multi_line_specials is on: |
|
1902 | # Allow ! in multi-line statements if multi_line_specials is on: | |
1892 | if continue_prompt and self.rc.multi_line_specials and \ |
|
1903 | if continue_prompt and self.rc.multi_line_specials and \ | |
1893 | iFun.startswith(self.ESC_SHELL): |
|
1904 | iFun.startswith(self.ESC_SHELL): | |
1894 | return self.handle_shell_escape(line,continue_prompt, |
|
1905 | return self.handle_shell_escape(line,continue_prompt, | |
1895 | pre=pre,iFun=iFun, |
|
1906 | pre=pre,iFun=iFun, | |
1896 | theRest=theRest) |
|
1907 | theRest=theRest) | |
1897 |
|
1908 | |||
1898 | # Let's try to find if the input line is a magic fn |
|
1909 | # Let's try to find if the input line is a magic fn | |
1899 | oinfo = None |
|
1910 | oinfo = None | |
1900 | if hasattr(self,'magic_'+iFun): |
|
1911 | if hasattr(self,'magic_'+iFun): | |
1901 | # WARNING: _ofind uses getattr(), so it can consume generators and |
|
1912 | # WARNING: _ofind uses getattr(), so it can consume generators and | |
1902 | # cause other side effects. |
|
1913 | # cause other side effects. | |
1903 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1914 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
1904 | if oinfo['ismagic']: |
|
1915 | if oinfo['ismagic']: | |
1905 | # Be careful not to call magics when a variable assignment is |
|
1916 | # Be careful not to call magics when a variable assignment is | |
1906 | # being made (ls='hi', for example) |
|
1917 | # being made (ls='hi', for example) | |
1907 | if self.rc.automagic and \ |
|
1918 | if self.rc.automagic and \ | |
1908 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ |
|
1919 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ | |
1909 | (self.rc.multi_line_specials or not continue_prompt): |
|
1920 | (self.rc.multi_line_specials or not continue_prompt): | |
1910 | return self.handle_magic(line,continue_prompt, |
|
1921 | return self.handle_magic(line,continue_prompt, | |
1911 | pre,iFun,theRest) |
|
1922 | pre,iFun,theRest) | |
1912 | else: |
|
1923 | else: | |
1913 | return self.handle_normal(line,continue_prompt) |
|
1924 | return self.handle_normal(line,continue_prompt) | |
1914 |
|
1925 | |||
1915 | # If the rest of the line begins with an (in)equality, assginment or |
|
1926 | # If the rest of the line begins with an (in)equality, assginment or | |
1916 | # function call, we should not call _ofind but simply execute it. |
|
1927 | # function call, we should not call _ofind but simply execute it. | |
1917 | # This avoids spurious geattr() accesses on objects upon assignment. |
|
1928 | # This avoids spurious geattr() accesses on objects upon assignment. | |
1918 | # |
|
1929 | # | |
1919 | # It also allows users to assign to either alias or magic names true |
|
1930 | # It also allows users to assign to either alias or magic names true | |
1920 | # python variables (the magic/alias systems always take second seat to |
|
1931 | # python variables (the magic/alias systems always take second seat to | |
1921 | # true python code). |
|
1932 | # true python code). | |
1922 | if theRest and theRest[0] in '!=()': |
|
1933 | if theRest and theRest[0] in '!=()': | |
1923 | return self.handle_normal(line,continue_prompt) |
|
1934 | return self.handle_normal(line,continue_prompt) | |
1924 |
|
1935 | |||
1925 | if oinfo is None: |
|
1936 | if oinfo is None: | |
1926 | # let's try to ensure that _oinfo is ONLY called when autocall is |
|
1937 | # let's try to ensure that _oinfo is ONLY called when autocall is | |
1927 | # on. Since it has inevitable potential side effects, at least |
|
1938 | # on. Since it has inevitable potential side effects, at least | |
1928 | # having autocall off should be a guarantee to the user that no |
|
1939 | # having autocall off should be a guarantee to the user that no | |
1929 | # weird things will happen. |
|
1940 | # weird things will happen. | |
1930 |
|
1941 | |||
1931 | if self.rc.autocall: |
|
1942 | if self.rc.autocall: | |
1932 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1943 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
1933 | else: |
|
1944 | else: | |
1934 | # in this case, all that's left is either an alias or |
|
1945 | # in this case, all that's left is either an alias or | |
1935 | # processing the line normally. |
|
1946 | # processing the line normally. | |
1936 | if iFun in self.alias_table: |
|
1947 | if iFun in self.alias_table: | |
1937 | return self.handle_alias(line,continue_prompt, |
|
1948 | return self.handle_alias(line,continue_prompt, | |
1938 | pre,iFun,theRest) |
|
1949 | pre,iFun,theRest) | |
1939 |
|
1950 | |||
1940 | else: |
|
1951 | else: | |
1941 | return self.handle_normal(line,continue_prompt) |
|
1952 | return self.handle_normal(line,continue_prompt) | |
1942 |
|
1953 | |||
1943 | if not oinfo['found']: |
|
1954 | if not oinfo['found']: | |
1944 | return self.handle_normal(line,continue_prompt) |
|
1955 | return self.handle_normal(line,continue_prompt) | |
1945 | else: |
|
1956 | else: | |
1946 | #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1957 | #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
1947 | if oinfo['isalias']: |
|
1958 | if oinfo['isalias']: | |
1948 | return self.handle_alias(line,continue_prompt, |
|
1959 | return self.handle_alias(line,continue_prompt, | |
1949 | pre,iFun,theRest) |
|
1960 | pre,iFun,theRest) | |
1950 |
|
1961 | |||
1951 | if (self.rc.autocall |
|
1962 | if (self.rc.autocall | |
1952 | and |
|
1963 | and | |
1953 | ( |
|
1964 | ( | |
1954 | #only consider exclusion re if not "," or ";" autoquoting |
|
1965 | #only consider exclusion re if not "," or ";" autoquoting | |
1955 | (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2 |
|
1966 | (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2 | |
1956 | or pre == self.ESC_PAREN) or |
|
1967 | or pre == self.ESC_PAREN) or | |
1957 | (not self.re_exclude_auto.match(theRest))) |
|
1968 | (not self.re_exclude_auto.match(theRest))) | |
1958 | and |
|
1969 | and | |
1959 | self.re_fun_name.match(iFun) and |
|
1970 | self.re_fun_name.match(iFun) and | |
1960 | callable(oinfo['obj'])) : |
|
1971 | callable(oinfo['obj'])) : | |
1961 | #print 'going auto' # dbg |
|
1972 | #print 'going auto' # dbg | |
1962 | return self.handle_auto(line,continue_prompt, |
|
1973 | return self.handle_auto(line,continue_prompt, | |
1963 | pre,iFun,theRest,oinfo['obj']) |
|
1974 | pre,iFun,theRest,oinfo['obj']) | |
1964 | else: |
|
1975 | else: | |
1965 | #print 'was callable?', callable(oinfo['obj']) # dbg |
|
1976 | #print 'was callable?', callable(oinfo['obj']) # dbg | |
1966 | return self.handle_normal(line,continue_prompt) |
|
1977 | return self.handle_normal(line,continue_prompt) | |
1967 |
|
1978 | |||
1968 | # If we get here, we have a normal Python line. Log and return. |
|
1979 | # If we get here, we have a normal Python line. Log and return. | |
1969 | return self.handle_normal(line,continue_prompt) |
|
1980 | return self.handle_normal(line,continue_prompt) | |
1970 |
|
1981 | |||
1971 | def _prefilter_dumb(self, line, continue_prompt): |
|
1982 | def _prefilter_dumb(self, line, continue_prompt): | |
1972 | """simple prefilter function, for debugging""" |
|
1983 | """simple prefilter function, for debugging""" | |
1973 | return self.handle_normal(line,continue_prompt) |
|
1984 | return self.handle_normal(line,continue_prompt) | |
1974 |
|
1985 | |||
1975 | # Set the default prefilter() function (this can be user-overridden) |
|
1986 | # Set the default prefilter() function (this can be user-overridden) | |
1976 | prefilter = _prefilter |
|
1987 | prefilter = _prefilter | |
1977 |
|
1988 | |||
1978 | def handle_normal(self,line,continue_prompt=None, |
|
1989 | def handle_normal(self,line,continue_prompt=None, | |
1979 | pre=None,iFun=None,theRest=None): |
|
1990 | pre=None,iFun=None,theRest=None): | |
1980 | """Handle normal input lines. Use as a template for handlers.""" |
|
1991 | """Handle normal input lines. Use as a template for handlers.""" | |
1981 |
|
1992 | |||
1982 | # With autoindent on, we need some way to exit the input loop, and I |
|
1993 | # With autoindent on, we need some way to exit the input loop, and I | |
1983 | # don't want to force the user to have to backspace all the way to |
|
1994 | # don't want to force the user to have to backspace all the way to | |
1984 | # clear the line. The rule will be in this case, that either two |
|
1995 | # clear the line. The rule will be in this case, that either two | |
1985 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
1996 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
1986 | # of a size different to the indent level, will exit the input loop. |
|
1997 | # of a size different to the indent level, will exit the input loop. | |
1987 |
|
1998 | |||
1988 | if (continue_prompt and self.autoindent and line.isspace() and |
|
1999 | if (continue_prompt and self.autoindent and line.isspace() and | |
1989 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2000 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
1990 | (self.buffer[-1]).isspace() )): |
|
2001 | (self.buffer[-1]).isspace() )): | |
1991 | line = '' |
|
2002 | line = '' | |
1992 |
|
2003 | |||
1993 | self.log(line,continue_prompt) |
|
2004 | self.log(line,continue_prompt) | |
1994 | return line |
|
2005 | return line | |
1995 |
|
2006 | |||
1996 | def handle_alias(self,line,continue_prompt=None, |
|
2007 | def handle_alias(self,line,continue_prompt=None, | |
1997 | pre=None,iFun=None,theRest=None): |
|
2008 | pre=None,iFun=None,theRest=None): | |
1998 | """Handle alias input lines. """ |
|
2009 | """Handle alias input lines. """ | |
1999 |
|
2010 | |||
2000 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2011 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2001 | # aliases won't work in indented sections. |
|
2012 | # aliases won't work in indented sections. | |
2002 | transformed = self.transform_alias(iFun, theRest) |
|
2013 | transformed = self.transform_alias(iFun, theRest) | |
2003 | line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed )) |
|
2014 | line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed )) | |
2004 | self.log(line_out,continue_prompt) |
|
2015 | self.log(line_out,continue_prompt) | |
2005 | return line_out |
|
2016 | return line_out | |
2006 |
|
2017 | |||
2007 | def handle_shell_escape(self, line, continue_prompt=None, |
|
2018 | def handle_shell_escape(self, line, continue_prompt=None, | |
2008 | pre=None,iFun=None,theRest=None): |
|
2019 | pre=None,iFun=None,theRest=None): | |
2009 | """Execute the line in a shell, empty return value""" |
|
2020 | """Execute the line in a shell, empty return value""" | |
2010 |
|
2021 | |||
2011 | #print 'line in :', `line` # dbg |
|
2022 | #print 'line in :', `line` # dbg | |
2012 | # Example of a special handler. Others follow a similar pattern. |
|
2023 | # Example of a special handler. Others follow a similar pattern. | |
2013 | if line.lstrip().startswith('!!'): |
|
2024 | if line.lstrip().startswith('!!'): | |
2014 | # rewrite iFun/theRest to properly hold the call to %sx and |
|
2025 | # rewrite iFun/theRest to properly hold the call to %sx and | |
2015 | # the actual command to be executed, so handle_magic can work |
|
2026 | # the actual command to be executed, so handle_magic can work | |
2016 | # correctly |
|
2027 | # correctly | |
2017 | theRest = '%s %s' % (iFun[2:],theRest) |
|
2028 | theRest = '%s %s' % (iFun[2:],theRest) | |
2018 | iFun = 'sx' |
|
2029 | iFun = 'sx' | |
2019 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC, |
|
2030 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC, | |
2020 | line.lstrip()[2:]), |
|
2031 | line.lstrip()[2:]), | |
2021 | continue_prompt,pre,iFun,theRest) |
|
2032 | continue_prompt,pre,iFun,theRest) | |
2022 | else: |
|
2033 | else: | |
2023 | cmd=line.lstrip().lstrip('!') |
|
2034 | cmd=line.lstrip().lstrip('!') | |
2024 | line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd)) |
|
2035 | line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd)) | |
2025 | # update cache/log and return |
|
2036 | # update cache/log and return | |
2026 | self.log(line_out,continue_prompt) |
|
2037 | self.log(line_out,continue_prompt) | |
2027 | return line_out |
|
2038 | return line_out | |
2028 |
|
2039 | |||
2029 | def handle_magic(self, line, continue_prompt=None, |
|
2040 | def handle_magic(self, line, continue_prompt=None, | |
2030 | pre=None,iFun=None,theRest=None): |
|
2041 | pre=None,iFun=None,theRest=None): | |
2031 | """Execute magic functions.""" |
|
2042 | """Execute magic functions.""" | |
2032 |
|
2043 | |||
2033 |
|
2044 | |||
2034 | cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest)) |
|
2045 | cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest)) | |
2035 | self.log(cmd,continue_prompt) |
|
2046 | self.log(cmd,continue_prompt) | |
2036 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2047 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2037 | return cmd |
|
2048 | return cmd | |
2038 |
|
2049 | |||
2039 | def handle_auto(self, line, continue_prompt=None, |
|
2050 | def handle_auto(self, line, continue_prompt=None, | |
2040 | pre=None,iFun=None,theRest=None,obj=None): |
|
2051 | pre=None,iFun=None,theRest=None,obj=None): | |
2041 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2052 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2042 |
|
2053 | |||
2043 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2054 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2044 |
|
2055 | |||
2045 | # This should only be active for single-line input! |
|
2056 | # This should only be active for single-line input! | |
2046 | if continue_prompt: |
|
2057 | if continue_prompt: | |
2047 | self.log(line,continue_prompt) |
|
2058 | self.log(line,continue_prompt) | |
2048 | return line |
|
2059 | return line | |
2049 |
|
2060 | |||
2050 | auto_rewrite = True |
|
2061 | auto_rewrite = True | |
2051 |
|
2062 | |||
2052 | if pre == self.ESC_QUOTE: |
|
2063 | if pre == self.ESC_QUOTE: | |
2053 | # Auto-quote splitting on whitespace |
|
2064 | # Auto-quote splitting on whitespace | |
2054 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2065 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2055 | elif pre == self.ESC_QUOTE2: |
|
2066 | elif pre == self.ESC_QUOTE2: | |
2056 | # Auto-quote whole string |
|
2067 | # Auto-quote whole string | |
2057 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2068 | newcmd = '%s("%s")' % (iFun,theRest) | |
2058 | elif pre == self.ESC_PAREN: |
|
2069 | elif pre == self.ESC_PAREN: | |
2059 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2070 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2060 | else: |
|
2071 | else: | |
2061 | # Auto-paren. |
|
2072 | # Auto-paren. | |
2062 | # We only apply it to argument-less calls if the autocall |
|
2073 | # We only apply it to argument-less calls if the autocall | |
2063 | # parameter is set to 2. We only need to check that autocall is < |
|
2074 | # parameter is set to 2. We only need to check that autocall is < | |
2064 | # 2, since this function isn't called unless it's at least 1. |
|
2075 | # 2, since this function isn't called unless it's at least 1. | |
2065 | if not theRest and (self.rc.autocall < 2): |
|
2076 | if not theRest and (self.rc.autocall < 2): | |
2066 | newcmd = '%s %s' % (iFun,theRest) |
|
2077 | newcmd = '%s %s' % (iFun,theRest) | |
2067 | auto_rewrite = False |
|
2078 | auto_rewrite = False | |
2068 | else: |
|
2079 | else: | |
2069 | if theRest.startswith('['): |
|
2080 | if theRest.startswith('['): | |
2070 | if hasattr(obj,'__getitem__'): |
|
2081 | if hasattr(obj,'__getitem__'): | |
2071 | # Don't autocall in this case: item access for an object |
|
2082 | # Don't autocall in this case: item access for an object | |
2072 | # which is BOTH callable and implements __getitem__. |
|
2083 | # which is BOTH callable and implements __getitem__. | |
2073 | newcmd = '%s %s' % (iFun,theRest) |
|
2084 | newcmd = '%s %s' % (iFun,theRest) | |
2074 | auto_rewrite = False |
|
2085 | auto_rewrite = False | |
2075 | else: |
|
2086 | else: | |
2076 | # if the object doesn't support [] access, go ahead and |
|
2087 | # if the object doesn't support [] access, go ahead and | |
2077 | # autocall |
|
2088 | # autocall | |
2078 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2089 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2079 | elif theRest.endswith(';'): |
|
2090 | elif theRest.endswith(';'): | |
2080 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2091 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2081 | else: |
|
2092 | else: | |
2082 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2093 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2083 |
|
2094 | |||
2084 | if auto_rewrite: |
|
2095 | if auto_rewrite: | |
2085 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2096 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd | |
2086 | # log what is now valid Python, not the actual user input (without the |
|
2097 | # log what is now valid Python, not the actual user input (without the | |
2087 | # final newline) |
|
2098 | # final newline) | |
2088 | self.log(newcmd,continue_prompt) |
|
2099 | self.log(newcmd,continue_prompt) | |
2089 | return newcmd |
|
2100 | return newcmd | |
2090 |
|
2101 | |||
2091 | def handle_help(self, line, continue_prompt=None, |
|
2102 | def handle_help(self, line, continue_prompt=None, | |
2092 | pre=None,iFun=None,theRest=None): |
|
2103 | pre=None,iFun=None,theRest=None): | |
2093 | """Try to get some help for the object. |
|
2104 | """Try to get some help for the object. | |
2094 |
|
2105 | |||
2095 | obj? or ?obj -> basic information. |
|
2106 | obj? or ?obj -> basic information. | |
2096 | obj?? or ??obj -> more details. |
|
2107 | obj?? or ??obj -> more details. | |
2097 | """ |
|
2108 | """ | |
2098 |
|
2109 | |||
2099 | # We need to make sure that we don't process lines which would be |
|
2110 | # We need to make sure that we don't process lines which would be | |
2100 | # otherwise valid python, such as "x=1 # what?" |
|
2111 | # otherwise valid python, such as "x=1 # what?" | |
2101 | try: |
|
2112 | try: | |
2102 | codeop.compile_command(line) |
|
2113 | codeop.compile_command(line) | |
2103 | except SyntaxError: |
|
2114 | except SyntaxError: | |
2104 | # We should only handle as help stuff which is NOT valid syntax |
|
2115 | # We should only handle as help stuff which is NOT valid syntax | |
2105 | if line[0]==self.ESC_HELP: |
|
2116 | if line[0]==self.ESC_HELP: | |
2106 | line = line[1:] |
|
2117 | line = line[1:] | |
2107 | elif line[-1]==self.ESC_HELP: |
|
2118 | elif line[-1]==self.ESC_HELP: | |
2108 | line = line[:-1] |
|
2119 | line = line[:-1] | |
2109 | self.log('#?'+line) |
|
2120 | self.log('#?'+line) | |
2110 | if line: |
|
2121 | if line: | |
2111 | self.magic_pinfo(line) |
|
2122 | self.magic_pinfo(line) | |
2112 | else: |
|
2123 | else: | |
2113 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2124 | page(self.usage,screen_lines=self.rc.screen_length) | |
2114 | return '' # Empty string is needed here! |
|
2125 | return '' # Empty string is needed here! | |
2115 | except: |
|
2126 | except: | |
2116 | # Pass any other exceptions through to the normal handler |
|
2127 | # Pass any other exceptions through to the normal handler | |
2117 | return self.handle_normal(line,continue_prompt) |
|
2128 | return self.handle_normal(line,continue_prompt) | |
2118 | else: |
|
2129 | else: | |
2119 | # If the code compiles ok, we should handle it normally |
|
2130 | # If the code compiles ok, we should handle it normally | |
2120 | return self.handle_normal(line,continue_prompt) |
|
2131 | return self.handle_normal(line,continue_prompt) | |
2121 |
|
2132 | |||
2122 | def getapi(self): |
|
2133 | def getapi(self): | |
2123 | """ Get an IPApi object for this shell instance |
|
2134 | """ Get an IPApi object for this shell instance | |
2124 |
|
2135 | |||
2125 | Getting an IPApi object is always preferable to accessing the shell |
|
2136 | Getting an IPApi object is always preferable to accessing the shell | |
2126 | directly, but this holds true especially for extensions. |
|
2137 | directly, but this holds true especially for extensions. | |
2127 |
|
2138 | |||
2128 | It should always be possible to implement an extension with IPApi |
|
2139 | It should always be possible to implement an extension with IPApi | |
2129 | alone. If not, contact maintainer to request an addition. |
|
2140 | alone. If not, contact maintainer to request an addition. | |
2130 |
|
2141 | |||
2131 | """ |
|
2142 | """ | |
2132 | return self.api |
|
2143 | return self.api | |
2133 |
|
2144 | |||
2134 | def handle_emacs(self,line,continue_prompt=None, |
|
2145 | def handle_emacs(self,line,continue_prompt=None, | |
2135 | pre=None,iFun=None,theRest=None): |
|
2146 | pre=None,iFun=None,theRest=None): | |
2136 | """Handle input lines marked by python-mode.""" |
|
2147 | """Handle input lines marked by python-mode.""" | |
2137 |
|
2148 | |||
2138 | # Currently, nothing is done. Later more functionality can be added |
|
2149 | # Currently, nothing is done. Later more functionality can be added | |
2139 | # here if needed. |
|
2150 | # here if needed. | |
2140 |
|
2151 | |||
2141 | # The input cache shouldn't be updated |
|
2152 | # The input cache shouldn't be updated | |
2142 |
|
2153 | |||
2143 | return line |
|
2154 | return line | |
2144 |
|
2155 | |||
2145 | def mktempfile(self,data=None): |
|
2156 | def mktempfile(self,data=None): | |
2146 | """Make a new tempfile and return its filename. |
|
2157 | """Make a new tempfile and return its filename. | |
2147 |
|
2158 | |||
2148 | This makes a call to tempfile.mktemp, but it registers the created |
|
2159 | This makes a call to tempfile.mktemp, but it registers the created | |
2149 | filename internally so ipython cleans it up at exit time. |
|
2160 | filename internally so ipython cleans it up at exit time. | |
2150 |
|
2161 | |||
2151 | Optional inputs: |
|
2162 | Optional inputs: | |
2152 |
|
2163 | |||
2153 | - data(None): if data is given, it gets written out to the temp file |
|
2164 | - data(None): if data is given, it gets written out to the temp file | |
2154 | immediately, and the file is closed again.""" |
|
2165 | immediately, and the file is closed again.""" | |
2155 |
|
2166 | |||
2156 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2167 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2157 | self.tempfiles.append(filename) |
|
2168 | self.tempfiles.append(filename) | |
2158 |
|
2169 | |||
2159 | if data: |
|
2170 | if data: | |
2160 | tmp_file = open(filename,'w') |
|
2171 | tmp_file = open(filename,'w') | |
2161 | tmp_file.write(data) |
|
2172 | tmp_file.write(data) | |
2162 | tmp_file.close() |
|
2173 | tmp_file.close() | |
2163 | return filename |
|
2174 | return filename | |
2164 |
|
2175 | |||
2165 | def write(self,data): |
|
2176 | def write(self,data): | |
2166 | """Write a string to the default output""" |
|
2177 | """Write a string to the default output""" | |
2167 | Term.cout.write(data) |
|
2178 | Term.cout.write(data) | |
2168 |
|
2179 | |||
2169 | def write_err(self,data): |
|
2180 | def write_err(self,data): | |
2170 | """Write a string to the default error output""" |
|
2181 | """Write a string to the default error output""" | |
2171 | Term.cerr.write(data) |
|
2182 | Term.cerr.write(data) | |
2172 |
|
2183 | |||
2173 | def exit(self): |
|
2184 | def exit(self): | |
2174 | """Handle interactive exit. |
|
2185 | """Handle interactive exit. | |
2175 |
|
2186 | |||
2176 | This method sets the exit_now attribute.""" |
|
2187 | This method sets the exit_now attribute.""" | |
2177 |
|
2188 | |||
2178 | if self.rc.confirm_exit: |
|
2189 | if self.rc.confirm_exit: | |
2179 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2190 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2180 | self.exit_now = True |
|
2191 | self.exit_now = True | |
2181 | else: |
|
2192 | else: | |
2182 | self.exit_now = True |
|
2193 | self.exit_now = True | |
2183 | return self.exit_now |
|
2194 | return self.exit_now | |
2184 |
|
2195 | |||
2185 | def safe_execfile(self,fname,*where,**kw): |
|
2196 | def safe_execfile(self,fname,*where,**kw): | |
2186 | fname = os.path.expanduser(fname) |
|
2197 | fname = os.path.expanduser(fname) | |
2187 |
|
2198 | |||
2188 | # find things also in current directory |
|
2199 | # find things also in current directory | |
2189 | dname = os.path.dirname(fname) |
|
2200 | dname = os.path.dirname(fname) | |
2190 | if not sys.path.count(dname): |
|
2201 | if not sys.path.count(dname): | |
2191 | sys.path.append(dname) |
|
2202 | sys.path.append(dname) | |
2192 |
|
2203 | |||
2193 | try: |
|
2204 | try: | |
2194 | xfile = open(fname) |
|
2205 | xfile = open(fname) | |
2195 | except: |
|
2206 | except: | |
2196 | print >> Term.cerr, \ |
|
2207 | print >> Term.cerr, \ | |
2197 | 'Could not open file <%s> for safe execution.' % fname |
|
2208 | 'Could not open file <%s> for safe execution.' % fname | |
2198 | return None |
|
2209 | return None | |
2199 |
|
2210 | |||
2200 | kw.setdefault('islog',0) |
|
2211 | kw.setdefault('islog',0) | |
2201 | kw.setdefault('quiet',1) |
|
2212 | kw.setdefault('quiet',1) | |
2202 | kw.setdefault('exit_ignore',0) |
|
2213 | kw.setdefault('exit_ignore',0) | |
2203 | first = xfile.readline() |
|
2214 | first = xfile.readline() | |
2204 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2215 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2205 | xfile.close() |
|
2216 | xfile.close() | |
2206 | # line by line execution |
|
2217 | # line by line execution | |
2207 | if first.startswith(loghead) or kw['islog']: |
|
2218 | if first.startswith(loghead) or kw['islog']: | |
2208 | print 'Loading log file <%s> one line at a time...' % fname |
|
2219 | print 'Loading log file <%s> one line at a time...' % fname | |
2209 | if kw['quiet']: |
|
2220 | if kw['quiet']: | |
2210 | stdout_save = sys.stdout |
|
2221 | stdout_save = sys.stdout | |
2211 | sys.stdout = StringIO.StringIO() |
|
2222 | sys.stdout = StringIO.StringIO() | |
2212 | try: |
|
2223 | try: | |
2213 | globs,locs = where[0:2] |
|
2224 | globs,locs = where[0:2] | |
2214 | except: |
|
2225 | except: | |
2215 | try: |
|
2226 | try: | |
2216 | globs = locs = where[0] |
|
2227 | globs = locs = where[0] | |
2217 | except: |
|
2228 | except: | |
2218 | globs = locs = globals() |
|
2229 | globs = locs = globals() | |
2219 | badblocks = [] |
|
2230 | badblocks = [] | |
2220 |
|
2231 | |||
2221 | # we also need to identify indented blocks of code when replaying |
|
2232 | # we also need to identify indented blocks of code when replaying | |
2222 | # logs and put them together before passing them to an exec |
|
2233 | # logs and put them together before passing them to an exec | |
2223 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2234 | # statement. This takes a bit of regexp and look-ahead work in the | |
2224 | # file. It's easiest if we swallow the whole thing in memory |
|
2235 | # file. It's easiest if we swallow the whole thing in memory | |
2225 | # first, and manually walk through the lines list moving the |
|
2236 | # first, and manually walk through the lines list moving the | |
2226 | # counter ourselves. |
|
2237 | # counter ourselves. | |
2227 | indent_re = re.compile('\s+\S') |
|
2238 | indent_re = re.compile('\s+\S') | |
2228 | xfile = open(fname) |
|
2239 | xfile = open(fname) | |
2229 | filelines = xfile.readlines() |
|
2240 | filelines = xfile.readlines() | |
2230 | xfile.close() |
|
2241 | xfile.close() | |
2231 | nlines = len(filelines) |
|
2242 | nlines = len(filelines) | |
2232 | lnum = 0 |
|
2243 | lnum = 0 | |
2233 | while lnum < nlines: |
|
2244 | while lnum < nlines: | |
2234 | line = filelines[lnum] |
|
2245 | line = filelines[lnum] | |
2235 | lnum += 1 |
|
2246 | lnum += 1 | |
2236 | # don't re-insert logger status info into cache |
|
2247 | # don't re-insert logger status info into cache | |
2237 | if line.startswith('#log#'): |
|
2248 | if line.startswith('#log#'): | |
2238 | continue |
|
2249 | continue | |
2239 | else: |
|
2250 | else: | |
2240 | # build a block of code (maybe a single line) for execution |
|
2251 | # build a block of code (maybe a single line) for execution | |
2241 | block = line |
|
2252 | block = line | |
2242 | try: |
|
2253 | try: | |
2243 | next = filelines[lnum] # lnum has already incremented |
|
2254 | next = filelines[lnum] # lnum has already incremented | |
2244 | except: |
|
2255 | except: | |
2245 | next = None |
|
2256 | next = None | |
2246 | while next and indent_re.match(next): |
|
2257 | while next and indent_re.match(next): | |
2247 | block += next |
|
2258 | block += next | |
2248 | lnum += 1 |
|
2259 | lnum += 1 | |
2249 | try: |
|
2260 | try: | |
2250 | next = filelines[lnum] |
|
2261 | next = filelines[lnum] | |
2251 | except: |
|
2262 | except: | |
2252 | next = None |
|
2263 | next = None | |
2253 | # now execute the block of one or more lines |
|
2264 | # now execute the block of one or more lines | |
2254 | try: |
|
2265 | try: | |
2255 | exec block in globs,locs |
|
2266 | exec block in globs,locs | |
2256 | except SystemExit: |
|
2267 | except SystemExit: | |
2257 | pass |
|
2268 | pass | |
2258 | except: |
|
2269 | except: | |
2259 | badblocks.append(block.rstrip()) |
|
2270 | badblocks.append(block.rstrip()) | |
2260 | if kw['quiet']: # restore stdout |
|
2271 | if kw['quiet']: # restore stdout | |
2261 | sys.stdout.close() |
|
2272 | sys.stdout.close() | |
2262 | sys.stdout = stdout_save |
|
2273 | sys.stdout = stdout_save | |
2263 | print 'Finished replaying log file <%s>' % fname |
|
2274 | print 'Finished replaying log file <%s>' % fname | |
2264 | if badblocks: |
|
2275 | if badblocks: | |
2265 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2276 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2266 | '<%s> reported errors:' % fname) |
|
2277 | '<%s> reported errors:' % fname) | |
2267 |
|
2278 | |||
2268 | for badline in badblocks: |
|
2279 | for badline in badblocks: | |
2269 | print >> sys.stderr, badline |
|
2280 | print >> sys.stderr, badline | |
2270 | else: # regular file execution |
|
2281 | else: # regular file execution | |
2271 | try: |
|
2282 | try: | |
2272 | execfile(fname,*where) |
|
2283 | execfile(fname,*where) | |
2273 | except SyntaxError: |
|
2284 | except SyntaxError: | |
2274 | self.showsyntaxerror() |
|
2285 | self.showsyntaxerror() | |
2275 | warn('Failure executing file: <%s>' % fname) |
|
2286 | warn('Failure executing file: <%s>' % fname) | |
2276 | except SystemExit,status: |
|
2287 | except SystemExit,status: | |
2277 | if not kw['exit_ignore']: |
|
2288 | if not kw['exit_ignore']: | |
2278 | self.showtraceback() |
|
2289 | self.showtraceback() | |
2279 | warn('Failure executing file: <%s>' % fname) |
|
2290 | warn('Failure executing file: <%s>' % fname) | |
2280 | except: |
|
2291 | except: | |
2281 | self.showtraceback() |
|
2292 | self.showtraceback() | |
2282 | warn('Failure executing file: <%s>' % fname) |
|
2293 | warn('Failure executing file: <%s>' % fname) | |
2283 |
|
2294 | |||
2284 | #************************* end of file <iplib.py> ***************************** |
|
2295 | #************************* end of file <iplib.py> ***************************** |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now