Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,2474 +1,2452 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 90 |
|
4 | $Id: Magic.py 908 2005-09-26 16:05:48Z 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-2004 Fernando Perez <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2004 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 os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time |
|
24 | import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time | |
25 | try: |
|
25 | try: | |
26 | import profile,pstats |
|
26 | import profile,pstats | |
27 | except ImportError: |
|
27 | except ImportError: | |
28 | profile = pstats = None |
|
28 | profile = pstats = None | |
29 | from getopt import getopt |
|
29 | from getopt import getopt | |
30 | from pprint import pprint, pformat |
|
30 | from pprint import pprint, pformat | |
31 | from cStringIO import StringIO |
|
31 | from cStringIO import StringIO | |
32 |
|
32 | |||
33 | # Homebrewed |
|
33 | # Homebrewed | |
34 | from IPython.Struct import Struct |
|
34 | from IPython.Struct import Struct | |
35 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
35 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
36 | from IPython.FakeModule import FakeModule |
|
36 | from IPython.FakeModule import FakeModule | |
37 | from IPython import OInspect |
|
37 | from IPython import OInspect | |
38 | from IPython.PyColorize import Parser |
|
38 | from IPython.PyColorize import Parser | |
39 | from IPython.genutils import * |
|
39 | from IPython.genutils import * | |
40 |
|
40 | |||
41 | # Globals to be set later by Magic constructor |
|
41 | # Globals to be set later by Magic constructor | |
42 | MAGIC_PREFIX = '' |
|
42 | MAGIC_PREFIX = '' | |
43 | MAGIC_ESCAPE = '' |
|
43 | MAGIC_ESCAPE = '' | |
44 |
|
44 | |||
45 | #*************************************************************************** |
|
45 | #*************************************************************************** | |
46 | # Utility functions |
|
46 | # Utility functions | |
47 | def magic2python(cmd): |
|
47 | def magic2python(cmd): | |
48 | """Convert a command string of magic syntax to valid Python code.""" |
|
48 | """Convert a command string of magic syntax to valid Python code.""" | |
49 |
|
49 | |||
50 | if cmd.startswith('#'+MAGIC_ESCAPE) or \ |
|
50 | if cmd.startswith('#'+MAGIC_ESCAPE) or \ | |
51 | cmd.startswith(MAGIC_ESCAPE): |
|
51 | cmd.startswith(MAGIC_ESCAPE): | |
52 | if cmd[0]=='#': |
|
52 | if cmd[0]=='#': | |
53 | cmd = cmd[1:] |
|
53 | cmd = cmd[1:] | |
54 | # we need to return the proper line end later |
|
54 | # we need to return the proper line end later | |
55 | if cmd[-1] == '\n': |
|
55 | if cmd[-1] == '\n': | |
56 | endl = '\n' |
|
56 | endl = '\n' | |
57 | else: |
|
57 | else: | |
58 | endl = '' |
|
58 | endl = '' | |
59 | try: |
|
59 | try: | |
60 | func,args = cmd[1:].split(' ',1) |
|
60 | func,args = cmd[1:].split(' ',1) | |
61 | except: |
|
61 | except: | |
62 | func,args = cmd[1:].rstrip(),'' |
|
62 | func,args = cmd[1:].rstrip(),'' | |
63 | args = args.replace('"','\\"').replace("'","\\'").rstrip() |
|
63 | args = args.replace('"','\\"').replace("'","\\'").rstrip() | |
64 | return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl) |
|
64 | return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl) | |
65 | else: |
|
65 | else: | |
66 | return cmd |
|
66 | return cmd | |
67 |
|
67 | |||
68 | def on_off(tag): |
|
68 | def on_off(tag): | |
69 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
69 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
70 | return ['OFF','ON'][tag] |
|
70 | return ['OFF','ON'][tag] | |
71 |
|
71 | |||
72 | def get_py_filename(name): |
|
|||
73 | """Return a valid python filename in the current directory. |
|
|||
74 |
|
||||
75 | If the given name is not a file, it adds '.py' and searches again. |
|
|||
76 | Raises IOError with an informative message if the file isn't found.""" |
|
|||
77 |
|
||||
78 | name = os.path.expanduser(name) |
|
|||
79 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
|||
80 | name += '.py' |
|
|||
81 | if os.path.isfile(name): |
|
|||
82 | return name |
|
|||
83 | else: |
|
|||
84 | raise IOError,'File `%s` not found.' % name |
|
|||
85 |
|
||||
86 |
|
72 | |||
87 | #**************************************************************************** |
|
73 | #**************************************************************************** | |
88 | # Utility classes |
|
74 | # Utility classes | |
89 | class Macro: |
|
75 | class Macro: | |
90 | """Simple class to store the value of macros as strings. |
|
76 | """Simple class to store the value of macros as strings. | |
91 |
|
77 | |||
92 | This allows us to later exec them by checking when something is an |
|
78 | This allows us to later exec them by checking when something is an | |
93 | instance of this class.""" |
|
79 | instance of this class.""" | |
94 |
|
80 | |||
95 | def __init__(self,cmds): |
|
81 | def __init__(self,cmds): | |
96 | """Build a macro from a list of commands.""" |
|
82 | """Build a macro from a list of commands.""" | |
97 |
|
83 | |||
98 | # Since the list may include multi-line entries, first make sure that |
|
84 | # Since the list may include multi-line entries, first make sure that | |
99 | # they've been all broken up before passing it to magic2python |
|
85 | # they've been all broken up before passing it to magic2python | |
100 | cmdlist = map(magic2python,''.join(cmds).split('\n')) |
|
86 | cmdlist = map(magic2python,''.join(cmds).split('\n')) | |
101 | self.value = '\n'.join(cmdlist) |
|
87 | self.value = '\n'.join(cmdlist) | |
102 |
|
88 | |||
103 | def __str__(self): |
|
89 | def __str__(self): | |
104 | return self.value |
|
90 | return self.value | |
105 |
|
91 | |||
106 | #*************************************************************************** |
|
92 | #*************************************************************************** | |
107 | # Main class implementing Magic functionality |
|
93 | # Main class implementing Magic functionality | |
108 | class Magic: |
|
94 | class Magic: | |
109 | """Magic functions for InteractiveShell. |
|
95 | """Magic functions for InteractiveShell. | |
110 |
|
96 | |||
111 | Shell functions which can be reached as %function_name. All magic |
|
97 | Shell functions which can be reached as %function_name. All magic | |
112 | functions should accept a string, which they can parse for their own |
|
98 | functions should accept a string, which they can parse for their own | |
113 | needs. This can make some functions easier to type, eg `%cd ../` |
|
99 | needs. This can make some functions easier to type, eg `%cd ../` | |
114 | vs. `%cd("../")` |
|
100 | vs. `%cd("../")` | |
115 |
|
101 | |||
116 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
102 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
117 | at the command line, but it is is needed in the definition. """ |
|
103 | at the command line, but it is is needed in the definition. """ | |
118 |
|
104 | |||
119 | # class globals |
|
105 | # class globals | |
120 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
106 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
121 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
107 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
122 |
|
108 | |||
123 | #...................................................................... |
|
109 | #...................................................................... | |
124 | # some utility functions |
|
110 | # some utility functions | |
125 |
|
111 | |||
126 | def __init__(self,shell): |
|
112 | def __init__(self,shell): | |
127 | # XXX This is hackish, clean up later to avoid these messy globals |
|
113 | # XXX This is hackish, clean up later to avoid these messy globals | |
128 | global MAGIC_PREFIX, MAGIC_ESCAPE |
|
114 | global MAGIC_PREFIX, MAGIC_ESCAPE | |
129 |
|
115 | |||
130 | self.options_table = {} |
|
116 | self.options_table = {} | |
131 | MAGIC_PREFIX = shell.name+'.magic_' |
|
117 | MAGIC_PREFIX = shell.name+'.magic_' | |
132 | MAGIC_ESCAPE = shell.ESC_MAGIC |
|
118 | MAGIC_ESCAPE = shell.ESC_MAGIC | |
133 | if profile is None: |
|
119 | if profile is None: | |
134 | self.magic_prun = self.profile_missing_notice |
|
120 | self.magic_prun = self.profile_missing_notice | |
135 |
|
121 | |||
136 | def profile_missing_notice(self, *args, **kwargs): |
|
122 | def profile_missing_notice(self, *args, **kwargs): | |
137 | error("""\ |
|
123 | error("""\ | |
138 | The profile module could not be found. If you are a Debian user, |
|
124 | The profile module could not be found. If you are a Debian user, | |
139 | it has been removed from the standard Debian package because of its non-free |
|
125 | it has been removed from the standard Debian package because of its non-free | |
140 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
126 | license. To use profiling, please install"python2.3-profiler" from non-free.""") | |
141 |
|
127 | |||
142 | def default_option(self,fn,optstr): |
|
128 | def default_option(self,fn,optstr): | |
143 | """Make an entry in the options_table for fn, with value optstr""" |
|
129 | """Make an entry in the options_table for fn, with value optstr""" | |
144 |
|
130 | |||
145 | if fn not in self.lsmagic(): |
|
131 | if fn not in self.lsmagic(): | |
146 | error("%s is not a magic function" % fn) |
|
132 | error("%s is not a magic function" % fn) | |
147 | self.options_table[fn] = optstr |
|
133 | self.options_table[fn] = optstr | |
148 |
|
134 | |||
149 | def lsmagic(self): |
|
135 | def lsmagic(self): | |
150 | """Return a list of currently available magic functions. |
|
136 | """Return a list of currently available magic functions. | |
151 |
|
137 | |||
152 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
138 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
153 | ['magic_ls','magic_cd',...]""" |
|
139 | ['magic_ls','magic_cd',...]""" | |
154 |
|
140 | |||
155 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
141 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
156 |
|
142 | |||
157 | # magics in class definition |
|
143 | # magics in class definition | |
158 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
144 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
159 | callable(Magic.__dict__[fn]) |
|
145 | callable(Magic.__dict__[fn]) | |
160 | # in instance namespace (run-time user additions) |
|
146 | # in instance namespace (run-time user additions) | |
161 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
147 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
162 | callable(self.__dict__[fn]) |
|
148 | callable(self.__dict__[fn]) | |
163 | # and bound magics by user (so they can access self): |
|
149 | # and bound magics by user (so they can access self): | |
164 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
150 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
165 | callable(self.__class__.__dict__[fn]) |
|
151 | callable(self.__class__.__dict__[fn]) | |
166 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
152 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
167 | filter(inst_magic,self.__dict__.keys()) + \ |
|
153 | filter(inst_magic,self.__dict__.keys()) + \ | |
168 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
154 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
169 | out = [] |
|
155 | out = [] | |
170 | for fn in magics: |
|
156 | for fn in magics: | |
171 | out.append(fn.replace('magic_','',1)) |
|
157 | out.append(fn.replace('magic_','',1)) | |
172 | out.sort() |
|
158 | out.sort() | |
173 | return out |
|
159 | return out | |
174 |
|
160 | |||
175 | def set_shell(self,shell): |
|
161 | def set_shell(self,shell): | |
176 | self.shell = shell |
|
162 | self.shell = shell | |
177 | self.alias_table = shell.alias_table |
|
163 | self.alias_table = shell.alias_table | |
178 |
|
164 | |||
179 | def extract_input_slices(self,slices): |
|
165 | def extract_input_slices(self,slices): | |
180 | """Return as a string a set of input history slices. |
|
166 | """Return as a string a set of input history slices. | |
181 |
|
167 | |||
182 | The set of slices is given as a list of strings (like ['1','4:8','9'], |
|
168 | The set of slices is given as a list of strings (like ['1','4:8','9'], | |
183 | since this function is for use by magic functions which get their |
|
169 | since this function is for use by magic functions which get their | |
184 | arguments as strings.""" |
|
170 | arguments as strings.""" | |
185 |
|
171 | |||
186 | cmds = [] |
|
172 | cmds = [] | |
187 | for chunk in slices: |
|
173 | for chunk in slices: | |
188 | if ':' in chunk: |
|
174 | if ':' in chunk: | |
189 | ini,fin = map(int,chunk.split(':')) |
|
175 | ini,fin = map(int,chunk.split(':')) | |
190 | else: |
|
176 | else: | |
191 | ini = int(chunk) |
|
177 | ini = int(chunk) | |
192 | fin = ini+1 |
|
178 | fin = ini+1 | |
193 | cmds.append(self.shell.input_hist[ini:fin]) |
|
179 | cmds.append(self.shell.input_hist[ini:fin]) | |
194 | return cmds |
|
180 | return cmds | |
195 |
|
181 | |||
196 | def _ofind(self,oname): |
|
182 | def _ofind(self,oname): | |
197 | """Find an object in the available namespaces. |
|
183 | """Find an object in the available namespaces. | |
198 |
|
184 | |||
199 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
185 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
200 |
|
186 | |||
201 | Has special code to detect magic functions. |
|
187 | Has special code to detect magic functions. | |
202 | """ |
|
188 | """ | |
203 |
|
189 | |||
204 | oname = oname.strip() |
|
190 | oname = oname.strip() | |
205 |
|
191 | |||
206 | # Namespaces to search in: |
|
192 | # Namespaces to search in: | |
207 | user_ns = self.shell.user_ns |
|
193 | user_ns = self.shell.user_ns | |
208 | internal_ns = self.shell.internal_ns |
|
194 | internal_ns = self.shell.internal_ns | |
209 | builtin_ns = __builtin__.__dict__ |
|
195 | builtin_ns = __builtin__.__dict__ | |
210 | alias_ns = self.shell.alias_table |
|
196 | alias_ns = self.shell.alias_table | |
211 |
|
197 | |||
212 | # Put them in a list. The order is important so that we find things in |
|
198 | # Put them in a list. The order is important so that we find things in | |
213 | # the same order that Python finds them. |
|
199 | # the same order that Python finds them. | |
214 | namespaces = [ ('Interactive',user_ns), |
|
200 | namespaces = [ ('Interactive',user_ns), | |
215 | ('IPython internal',internal_ns), |
|
201 | ('IPython internal',internal_ns), | |
216 | ('Python builtin',builtin_ns), |
|
202 | ('Python builtin',builtin_ns), | |
217 | ('Alias',alias_ns), |
|
203 | ('Alias',alias_ns), | |
218 | ] |
|
204 | ] | |
219 |
|
205 | |||
220 | # initialize results to 'null' |
|
206 | # initialize results to 'null' | |
221 | found = 0; obj = None; ospace = None; ds = None; |
|
207 | found = 0; obj = None; ospace = None; ds = None; | |
222 | ismagic = 0; isalias = 0 |
|
208 | ismagic = 0; isalias = 0 | |
223 |
|
209 | |||
224 | # Look for the given name by splitting it in parts. If the head is |
|
210 | # Look for the given name by splitting it in parts. If the head is | |
225 | # found, then we look for all the remaining parts as members, and only |
|
211 | # found, then we look for all the remaining parts as members, and only | |
226 | # declare success if we can find them all. |
|
212 | # declare success if we can find them all. | |
227 | oname_parts = oname.split('.') |
|
213 | oname_parts = oname.split('.') | |
228 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
214 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
229 | for nsname,ns in namespaces: |
|
215 | for nsname,ns in namespaces: | |
230 | try: |
|
216 | try: | |
231 | obj = ns[oname_head] |
|
217 | obj = ns[oname_head] | |
232 | except KeyError: |
|
218 | except KeyError: | |
233 | continue |
|
219 | continue | |
234 | else: |
|
220 | else: | |
235 | for part in oname_rest: |
|
221 | for part in oname_rest: | |
236 | try: |
|
222 | try: | |
237 | obj = getattr(obj,part) |
|
223 | obj = getattr(obj,part) | |
238 | except: |
|
224 | except: | |
239 | # Blanket except b/c some badly implemented objects |
|
225 | # Blanket except b/c some badly implemented objects | |
240 | # allow __getattr__ to raise exceptions other than |
|
226 | # allow __getattr__ to raise exceptions other than | |
241 | # AttributeError, which then crashes IPython. |
|
227 | # AttributeError, which then crashes IPython. | |
242 | break |
|
228 | break | |
243 | else: |
|
229 | else: | |
244 | # If we finish the for loop (no break), we got all members |
|
230 | # If we finish the for loop (no break), we got all members | |
245 | found = 1 |
|
231 | found = 1 | |
246 | ospace = nsname |
|
232 | ospace = nsname | |
247 | if ns == alias_ns: |
|
233 | if ns == alias_ns: | |
248 | isalias = 1 |
|
234 | isalias = 1 | |
249 | break # namespace loop |
|
235 | break # namespace loop | |
250 |
|
236 | |||
251 | # Try to see if it's magic |
|
237 | # Try to see if it's magic | |
252 | if not found: |
|
238 | if not found: | |
253 | if oname.startswith(self.shell.ESC_MAGIC): |
|
239 | if oname.startswith(self.shell.ESC_MAGIC): | |
254 | oname = oname[1:] |
|
240 | oname = oname[1:] | |
255 | obj = getattr(self,'magic_'+oname,None) |
|
241 | obj = getattr(self,'magic_'+oname,None) | |
256 | if obj is not None: |
|
242 | if obj is not None: | |
257 | found = 1 |
|
243 | found = 1 | |
258 | ospace = 'IPython internal' |
|
244 | ospace = 'IPython internal' | |
259 | ismagic = 1 |
|
245 | ismagic = 1 | |
260 |
|
246 | |||
261 | # Last try: special-case some literals like '', [], {}, etc: |
|
247 | # Last try: special-case some literals like '', [], {}, etc: | |
262 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
248 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
263 | obj = eval(oname_head) |
|
249 | obj = eval(oname_head) | |
264 | found = 1 |
|
250 | found = 1 | |
265 | ospace = 'Interactive' |
|
251 | ospace = 'Interactive' | |
266 |
|
252 | |||
267 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
253 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
268 | 'ismagic':ismagic, 'isalias':isalias} |
|
254 | 'ismagic':ismagic, 'isalias':isalias} | |
269 |
|
255 | |||
270 | def arg_err(self,func): |
|
256 | def arg_err(self,func): | |
271 | """Print docstring if incorrect arguments were passed""" |
|
257 | """Print docstring if incorrect arguments were passed""" | |
272 | print 'Error in arguments:' |
|
258 | print 'Error in arguments:' | |
273 | print OInspect.getdoc(func) |
|
259 | print OInspect.getdoc(func) | |
274 |
|
260 | |||
275 |
|
261 | |||
276 | def format_latex(self,str): |
|
262 | def format_latex(self,str): | |
277 | """Format a string for latex inclusion.""" |
|
263 | """Format a string for latex inclusion.""" | |
278 |
|
264 | |||
279 | # Characters that need to be escaped for latex: |
|
265 | # Characters that need to be escaped for latex: | |
280 | escape_re = re.compile(r'(%|_|\$)',re.MULTILINE) |
|
266 | escape_re = re.compile(r'(%|_|\$)',re.MULTILINE) | |
281 | # Magic command names as headers: |
|
267 | # Magic command names as headers: | |
282 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
268 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
283 | re.MULTILINE) |
|
269 | re.MULTILINE) | |
284 | # Magic commands |
|
270 | # Magic commands | |
285 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
271 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
286 | re.MULTILINE) |
|
272 | re.MULTILINE) | |
287 | # Paragraph continue |
|
273 | # Paragraph continue | |
288 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
274 | par_re = re.compile(r'\\$',re.MULTILINE) | |
289 |
|
275 | |||
290 | str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str) |
|
276 | str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str) | |
291 | str = cmd_re.sub(r'\\texttt{\g<cmd>}',str) |
|
277 | str = cmd_re.sub(r'\\texttt{\g<cmd>}',str) | |
292 | str = par_re.sub(r'\\\\',str) |
|
278 | str = par_re.sub(r'\\\\',str) | |
293 | str = escape_re.sub(r'\\\1',str) |
|
279 | str = escape_re.sub(r'\\\1',str) | |
294 | return str |
|
280 | return str | |
295 |
|
281 | |||
296 | def format_screen(self,str): |
|
282 | def format_screen(self,str): | |
297 | """Format a string for screen printing. |
|
283 | """Format a string for screen printing. | |
298 |
|
284 | |||
299 | This removes some latex-type format codes.""" |
|
285 | This removes some latex-type format codes.""" | |
300 | # Paragraph continue |
|
286 | # Paragraph continue | |
301 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
287 | par_re = re.compile(r'\\$',re.MULTILINE) | |
302 | str = par_re.sub('',str) |
|
288 | str = par_re.sub('',str) | |
303 | return str |
|
289 | return str | |
304 |
|
290 | |||
305 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
291 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
306 | """Parse options passed to an argument string. |
|
292 | """Parse options passed to an argument string. | |
307 |
|
293 | |||
308 | The interface is similar to that of getopt(), but it returns back a |
|
294 | The interface is similar to that of getopt(), but it returns back a | |
309 | Struct with the options as keys and the stripped argument string still |
|
295 | Struct with the options as keys and the stripped argument string still | |
310 | as a string. |
|
296 | as a string. | |
311 |
|
297 | |||
312 | arg_str is quoted as a true sys.argv vector by calling on the fly a |
|
298 | arg_str is quoted as a true sys.argv vector by calling on the fly a | |
313 | python process in a subshell. This allows us to easily expand |
|
299 | python process in a subshell. This allows us to easily expand | |
314 | variables, glob files, quote arguments, etc, with all the power and |
|
300 | variables, glob files, quote arguments, etc, with all the power and | |
315 | correctness of the underlying system shell. |
|
301 | correctness of the underlying system shell. | |
316 |
|
302 | |||
317 | Options: |
|
303 | Options: | |
318 | -mode: default 'string'. If given as 'list', the argument string is |
|
304 | -mode: default 'string'. If given as 'list', the argument string is | |
319 | returned as a list (split on whitespace) instead of a string. |
|
305 | returned as a list (split on whitespace) instead of a string. | |
320 |
|
306 | |||
321 | -list_all: put all option values in lists. Normally only options |
|
307 | -list_all: put all option values in lists. Normally only options | |
322 | appearing more than once are put in a list.""" |
|
308 | appearing more than once are put in a list.""" | |
323 |
|
309 | |||
324 | # inject default options at the beginning of the input line |
|
310 | # inject default options at the beginning of the input line | |
325 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
311 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
326 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
312 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
327 |
|
313 | |||
328 | mode = kw.get('mode','string') |
|
314 | mode = kw.get('mode','string') | |
329 | if mode not in ['string','list']: |
|
315 | if mode not in ['string','list']: | |
330 | raise ValueError,'incorrect mode given: %s' % mode |
|
316 | raise ValueError,'incorrect mode given: %s' % mode | |
331 | # Get options |
|
317 | # Get options | |
332 | list_all = kw.get('list_all',0) |
|
318 | list_all = kw.get('list_all',0) | |
333 |
|
319 | |||
334 | # Check if we have more than one argument to warrant extra processing: |
|
320 | # Check if we have more than one argument to warrant extra processing: | |
335 | odict = {} # Dictionary with options |
|
321 | odict = {} # Dictionary with options | |
336 | args = arg_str.split() |
|
322 | args = arg_str.split() | |
337 | if len(args) >= 1: |
|
323 | if len(args) >= 1: | |
338 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
324 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
339 | # need to look for options |
|
325 | # need to look for options | |
340 | argv = shlex_split(arg_str) |
|
326 | argv = shlex_split(arg_str) | |
341 | # Do regular option processing |
|
327 | # Do regular option processing | |
342 | opts,args = getopt(argv,opt_str,*long_opts) |
|
328 | opts,args = getopt(argv,opt_str,*long_opts) | |
343 | for o,a in opts: |
|
329 | for o,a in opts: | |
344 | if o.startswith('--'): |
|
330 | if o.startswith('--'): | |
345 | o = o[2:] |
|
331 | o = o[2:] | |
346 | else: |
|
332 | else: | |
347 | o = o[1:] |
|
333 | o = o[1:] | |
348 | try: |
|
334 | try: | |
349 | odict[o].append(a) |
|
335 | odict[o].append(a) | |
350 | except AttributeError: |
|
336 | except AttributeError: | |
351 | odict[o] = [odict[o],a] |
|
337 | odict[o] = [odict[o],a] | |
352 | except KeyError: |
|
338 | except KeyError: | |
353 | if list_all: |
|
339 | if list_all: | |
354 | odict[o] = [a] |
|
340 | odict[o] = [a] | |
355 | else: |
|
341 | else: | |
356 | odict[o] = a |
|
342 | odict[o] = a | |
357 |
|
343 | |||
358 | # Prepare opts,args for return |
|
344 | # Prepare opts,args for return | |
359 | opts = Struct(odict) |
|
345 | opts = Struct(odict) | |
360 | if mode == 'string': |
|
346 | if mode == 'string': | |
361 | args = ' '.join(args) |
|
347 | args = ' '.join(args) | |
362 |
|
348 | |||
363 | return opts,args |
|
349 | return opts,args | |
364 |
|
350 | |||
365 | #...................................................................... |
|
351 | #...................................................................... | |
366 | # And now the actual magic functions |
|
352 | # And now the actual magic functions | |
367 |
|
353 | |||
368 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
354 | # Functions for IPython shell work (vars,funcs, config, etc) | |
369 | def magic_lsmagic(self, parameter_s = ''): |
|
355 | def magic_lsmagic(self, parameter_s = ''): | |
370 | """List currently available magic functions.""" |
|
356 | """List currently available magic functions.""" | |
371 | mesc = self.shell.ESC_MAGIC |
|
357 | mesc = self.shell.ESC_MAGIC | |
372 | print 'Available magic functions:\n'+mesc+\ |
|
358 | print 'Available magic functions:\n'+mesc+\ | |
373 | (' '+mesc).join(self.lsmagic()) |
|
359 | (' '+mesc).join(self.lsmagic()) | |
374 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
360 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
375 | return None |
|
361 | return None | |
376 |
|
362 | |||
377 | def magic_magic(self, parameter_s = ''): |
|
363 | def magic_magic(self, parameter_s = ''): | |
378 | """Print information about the magic function system.""" |
|
364 | """Print information about the magic function system.""" | |
379 |
|
365 | |||
380 | mode = '' |
|
366 | mode = '' | |
381 | try: |
|
367 | try: | |
382 | if parameter_s.split()[0] == '-latex': |
|
368 | if parameter_s.split()[0] == '-latex': | |
383 | mode = 'latex' |
|
369 | mode = 'latex' | |
384 | except: |
|
370 | except: | |
385 | pass |
|
371 | pass | |
386 |
|
372 | |||
387 | magic_docs = [] |
|
373 | magic_docs = [] | |
388 | for fname in self.lsmagic(): |
|
374 | for fname in self.lsmagic(): | |
389 | mname = 'magic_' + fname |
|
375 | mname = 'magic_' + fname | |
390 | for space in (Magic,self,self.__class__): |
|
376 | for space in (Magic,self,self.__class__): | |
391 | try: |
|
377 | try: | |
392 | fn = space.__dict__[mname] |
|
378 | fn = space.__dict__[mname] | |
393 | except KeyError: |
|
379 | except KeyError: | |
394 | pass |
|
380 | pass | |
395 | else: |
|
381 | else: | |
396 | break |
|
382 | break | |
397 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
383 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
398 | fname,fn.__doc__)) |
|
384 | fname,fn.__doc__)) | |
399 | magic_docs = ''.join(magic_docs) |
|
385 | magic_docs = ''.join(magic_docs) | |
400 |
|
386 | |||
401 | if mode == 'latex': |
|
387 | if mode == 'latex': | |
402 | print self.format_latex(magic_docs) |
|
388 | print self.format_latex(magic_docs) | |
403 | return |
|
389 | return | |
404 | else: |
|
390 | else: | |
405 | magic_docs = self.format_screen(magic_docs) |
|
391 | magic_docs = self.format_screen(magic_docs) | |
406 |
|
392 | |||
407 | outmsg = """ |
|
393 | outmsg = """ | |
408 | IPython's 'magic' functions |
|
394 | IPython's 'magic' functions | |
409 | =========================== |
|
395 | =========================== | |
410 |
|
396 | |||
411 | The magic function system provides a series of functions which allow you to |
|
397 | The magic function system provides a series of functions which allow you to | |
412 | control the behavior of IPython itself, plus a lot of system-type |
|
398 | control the behavior of IPython itself, plus a lot of system-type | |
413 | features. All these functions are prefixed with a % character, but parameters |
|
399 | features. All these functions are prefixed with a % character, but parameters | |
414 | are given without parentheses or quotes. |
|
400 | are given without parentheses or quotes. | |
415 |
|
401 | |||
416 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
402 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
417 | %automagic function), you don't need to type in the % explicitly. By default, |
|
403 | %automagic function), you don't need to type in the % explicitly. By default, | |
418 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
404 | IPython ships with automagic on, so you should only rarely need the % escape. | |
419 |
|
405 | |||
420 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
406 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
421 | to 'mydir', if it exists. |
|
407 | to 'mydir', if it exists. | |
422 |
|
408 | |||
423 | You can define your own magic functions to extend the system. See the supplied |
|
409 | You can define your own magic functions to extend the system. See the supplied | |
424 | ipythonrc and example-magic.py files for details (in your ipython |
|
410 | ipythonrc and example-magic.py files for details (in your ipython | |
425 | configuration directory, typically $HOME/.ipython/). |
|
411 | configuration directory, typically $HOME/.ipython/). | |
426 |
|
412 | |||
427 | You can also define your own aliased names for magic functions. In your |
|
413 | You can also define your own aliased names for magic functions. In your | |
428 | ipythonrc file, placing a line like: |
|
414 | ipythonrc file, placing a line like: | |
429 |
|
415 | |||
430 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
416 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
431 |
|
417 | |||
432 | will define %pf as a new name for %profile. |
|
418 | will define %pf as a new name for %profile. | |
433 |
|
419 | |||
434 | You can also call magics in code using the ipmagic() function, which IPython |
|
420 | You can also call magics in code using the ipmagic() function, which IPython | |
435 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
421 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
436 |
|
422 | |||
437 | For a list of the available magic functions, use %lsmagic. For a description |
|
423 | For a list of the available magic functions, use %lsmagic. For a description | |
438 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
424 | of any of them, type %magic_name?, e.g. '%cd?'. | |
439 |
|
425 | |||
440 | Currently the magic system has the following functions:\n""" |
|
426 | Currently the magic system has the following functions:\n""" | |
441 |
|
427 | |||
442 | mesc = self.shell.ESC_MAGIC |
|
428 | mesc = self.shell.ESC_MAGIC | |
443 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
429 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
444 | "\n\n%s%s\n\n%s" % (outmsg, |
|
430 | "\n\n%s%s\n\n%s" % (outmsg, | |
445 | magic_docs,mesc,mesc, |
|
431 | magic_docs,mesc,mesc, | |
446 | (' '+mesc).join(self.lsmagic()), |
|
432 | (' '+mesc).join(self.lsmagic()), | |
447 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
433 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
448 |
|
434 | |||
449 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
435 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
450 |
|
436 | |||
451 | def magic_automagic(self, parameter_s = ''): |
|
437 | def magic_automagic(self, parameter_s = ''): | |
452 | """Make magic functions callable without having to type the initial %. |
|
438 | """Make magic functions callable without having to type the initial %. | |
453 |
|
439 | |||
454 | Toggles on/off (when off, you must call it as %automagic, of |
|
440 | Toggles on/off (when off, you must call it as %automagic, of | |
455 | course). Note that magic functions have lowest priority, so if there's |
|
441 | course). Note that magic functions have lowest priority, so if there's | |
456 | a variable whose name collides with that of a magic fn, automagic |
|
442 | a variable whose name collides with that of a magic fn, automagic | |
457 | won't work for that function (you get the variable instead). However, |
|
443 | won't work for that function (you get the variable instead). However, | |
458 | if you delete the variable (del var), the previously shadowed magic |
|
444 | if you delete the variable (del var), the previously shadowed magic | |
459 | function becomes visible to automagic again.""" |
|
445 | function becomes visible to automagic again.""" | |
460 |
|
446 | |||
461 | rc = self.shell.rc |
|
447 | rc = self.shell.rc | |
462 | rc.automagic = not rc.automagic |
|
448 | rc.automagic = not rc.automagic | |
463 | print '\n' + Magic.auto_status[rc.automagic] |
|
449 | print '\n' + Magic.auto_status[rc.automagic] | |
464 |
|
450 | |||
465 | def magic_autocall(self, parameter_s = ''): |
|
451 | def magic_autocall(self, parameter_s = ''): | |
466 | """Make functions callable without having to type parentheses. |
|
452 | """Make functions callable without having to type parentheses. | |
467 |
|
453 | |||
468 | This toggles the autocall command line option on and off.""" |
|
454 | This toggles the autocall command line option on and off.""" | |
469 |
|
455 | |||
470 | rc = self.shell.rc |
|
456 | rc = self.shell.rc | |
471 | rc.autocall = not rc.autocall |
|
457 | rc.autocall = not rc.autocall | |
472 | print "Automatic calling is:",['OFF','ON'][rc.autocall] |
|
458 | print "Automatic calling is:",['OFF','ON'][rc.autocall] | |
473 |
|
459 | |||
474 | def magic_autoindent(self, parameter_s = ''): |
|
460 | def magic_autoindent(self, parameter_s = ''): | |
475 | """Toggle autoindent on/off (if available).""" |
|
461 | """Toggle autoindent on/off (if available).""" | |
476 |
|
462 | |||
477 | self.shell.set_autoindent() |
|
463 | self.shell.set_autoindent() | |
478 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
464 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
479 |
|
465 | |||
480 | def magic_system_verbose(self, parameter_s = ''): |
|
466 | def magic_system_verbose(self, parameter_s = ''): | |
481 | """Toggle verbose printing of system calls on/off.""" |
|
467 | """Toggle verbose printing of system calls on/off.""" | |
482 |
|
468 | |||
483 | self.shell.rc_set_toggle('system_verbose') |
|
469 | self.shell.rc_set_toggle('system_verbose') | |
484 | print "System verbose printing is:",\ |
|
470 | print "System verbose printing is:",\ | |
485 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
471 | ['OFF','ON'][self.shell.rc.system_verbose] | |
486 |
|
472 | |||
487 | def magic_history(self, parameter_s = ''): |
|
473 | def magic_history(self, parameter_s = ''): | |
488 | """Print input history (_i<n> variables), with most recent last. |
|
474 | """Print input history (_i<n> variables), with most recent last. | |
489 |
|
475 | |||
490 | %history [-n] -> print at most 40 inputs (some may be multi-line)\\ |
|
476 | %history [-n] -> print at most 40 inputs (some may be multi-line)\\ | |
491 | %history [-n] n -> print at most n inputs\\ |
|
477 | %history [-n] n -> print at most n inputs\\ | |
492 | %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
478 | %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
493 |
|
479 | |||
494 | Each input's number <n> is shown, and is accessible as the |
|
480 | Each input's number <n> is shown, and is accessible as the | |
495 | automatically generated variable _i<n>. Multi-line statements are |
|
481 | automatically generated variable _i<n>. Multi-line statements are | |
496 | printed starting at a new line for easy copy/paste. |
|
482 | printed starting at a new line for easy copy/paste. | |
497 |
|
483 | |||
498 | If option -n is used, input numbers are not printed. This is useful if |
|
484 | If option -n is used, input numbers are not printed. This is useful if | |
499 | you want to get a printout of many lines which can be directly pasted |
|
485 | you want to get a printout of many lines which can be directly pasted | |
500 | into a text editor. |
|
486 | into a text editor. | |
501 |
|
487 | |||
502 | This feature is only available if numbered prompts are in use.""" |
|
488 | This feature is only available if numbered prompts are in use.""" | |
503 |
|
489 | |||
504 | if not self.do_full_cache: |
|
490 | if not self.do_full_cache: | |
505 | print 'This feature is only available if numbered prompts are in use.' |
|
491 | print 'This feature is only available if numbered prompts are in use.' | |
506 | return |
|
492 | return | |
507 | opts,args = self.parse_options(parameter_s,'n',mode='list') |
|
493 | opts,args = self.parse_options(parameter_s,'n',mode='list') | |
508 |
|
494 | |||
509 | default_length = 40 |
|
495 | default_length = 40 | |
510 | if len(args) == 0: |
|
496 | if len(args) == 0: | |
511 | final = self.outputcache.prompt_count |
|
497 | final = self.outputcache.prompt_count | |
512 | init = max(1,final-default_length) |
|
498 | init = max(1,final-default_length) | |
513 | elif len(args) == 1: |
|
499 | elif len(args) == 1: | |
514 | final = self.outputcache.prompt_count |
|
500 | final = self.outputcache.prompt_count | |
515 | init = max(1,final-int(args[0])) |
|
501 | init = max(1,final-int(args[0])) | |
516 | elif len(args) == 2: |
|
502 | elif len(args) == 2: | |
517 | init,final = map(int,args) |
|
503 | init,final = map(int,args) | |
518 | else: |
|
504 | else: | |
519 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
505 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
520 | print self.magic_hist.__doc__ |
|
506 | print self.magic_hist.__doc__ | |
521 | return |
|
507 | return | |
522 | width = len(str(final)) |
|
508 | width = len(str(final)) | |
523 | line_sep = ['','\n'] |
|
509 | line_sep = ['','\n'] | |
524 | input_hist = self.shell.input_hist |
|
510 | input_hist = self.shell.input_hist | |
525 | print_nums = not opts.has_key('n') |
|
511 | print_nums = not opts.has_key('n') | |
526 | for in_num in range(init,final): |
|
512 | for in_num in range(init,final): | |
527 | inline = input_hist[in_num] |
|
513 | inline = input_hist[in_num] | |
528 | multiline = inline.count('\n') > 1 |
|
514 | multiline = inline.count('\n') > 1 | |
529 | if print_nums: |
|
515 | if print_nums: | |
530 | print str(in_num).ljust(width)+':'+ line_sep[multiline], |
|
516 | print str(in_num).ljust(width)+':'+ line_sep[multiline], | |
531 | if inline.startswith('#'+self.shell.ESC_MAGIC) or \ |
|
517 | if inline.startswith('#'+self.shell.ESC_MAGIC) or \ | |
532 | inline.startswith('#!'): |
|
518 | inline.startswith('#!'): | |
533 | print inline[1:], |
|
519 | print inline[1:], | |
534 | else: |
|
520 | else: | |
535 | print inline, |
|
521 | print inline, | |
536 |
|
522 | |||
537 | def magic_hist(self, parameter_s=''): |
|
523 | def magic_hist(self, parameter_s=''): | |
538 | """Alternate name for %history.""" |
|
524 | """Alternate name for %history.""" | |
539 | return self.magic_history(parameter_s) |
|
525 | return self.magic_history(parameter_s) | |
540 |
|
526 | |||
541 | def magic_p(self, parameter_s=''): |
|
527 | def magic_p(self, parameter_s=''): | |
542 | """Just a short alias for Python's 'print'.""" |
|
528 | """Just a short alias for Python's 'print'.""" | |
543 | exec 'print ' + parameter_s in self.shell.user_ns |
|
529 | exec 'print ' + parameter_s in self.shell.user_ns | |
544 |
|
530 | |||
545 | def magic_r(self, parameter_s=''): |
|
531 | def magic_r(self, parameter_s=''): | |
546 | """Repeat previous input. |
|
532 | """Repeat previous input. | |
547 |
|
533 | |||
548 | If given an argument, repeats the previous command which starts with |
|
534 | If given an argument, repeats the previous command which starts with | |
549 | the same string, otherwise it just repeats the previous input. |
|
535 | the same string, otherwise it just repeats the previous input. | |
550 |
|
536 | |||
551 | Shell escaped commands (with ! as first character) are not recognized |
|
537 | Shell escaped commands (with ! as first character) are not recognized | |
552 | by this system, only pure python code and magic commands. |
|
538 | by this system, only pure python code and magic commands. | |
553 | """ |
|
539 | """ | |
554 |
|
540 | |||
555 | start = parameter_s.strip() |
|
541 | start = parameter_s.strip() | |
556 | esc_magic = self.shell.ESC_MAGIC |
|
542 | esc_magic = self.shell.ESC_MAGIC | |
557 | # Identify magic commands even if automagic is on (which means |
|
543 | # Identify magic commands even if automagic is on (which means | |
558 | # the in-memory version is different from that typed by the user). |
|
544 | # the in-memory version is different from that typed by the user). | |
559 | if self.shell.rc.automagic: |
|
545 | if self.shell.rc.automagic: | |
560 | start_magic = esc_magic+start |
|
546 | start_magic = esc_magic+start | |
561 | else: |
|
547 | else: | |
562 | start_magic = start |
|
548 | start_magic = start | |
563 | # Look through the input history in reverse |
|
549 | # Look through the input history in reverse | |
564 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
550 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
565 | input = self.shell.input_hist[n] |
|
551 | input = self.shell.input_hist[n] | |
566 | # skip plain 'r' lines so we don't recurse to infinity |
|
552 | # skip plain 'r' lines so we don't recurse to infinity | |
567 | if input != 'ipmagic("r")\n' and \ |
|
553 | if input != 'ipmagic("r")\n' and \ | |
568 | (input.startswith(start) or input.startswith(start_magic)): |
|
554 | (input.startswith(start) or input.startswith(start_magic)): | |
569 | #print 'match',`input` # dbg |
|
555 | #print 'match',`input` # dbg | |
570 | if input.startswith(esc_magic): |
|
556 | if input.startswith(esc_magic): | |
571 | input = magic2python(input) |
|
557 | input = magic2python(input) | |
572 | #print 'modified',`input` # dbg |
|
558 | #print 'modified',`input` # dbg | |
573 | print 'Executing:',input, |
|
559 | print 'Executing:',input, | |
574 | exec input in self.shell.user_ns |
|
560 | exec input in self.shell.user_ns | |
575 | return |
|
561 | return | |
576 | print 'No previous input matching `%s` found.' % start |
|
562 | print 'No previous input matching `%s` found.' % start | |
577 |
|
563 | |||
578 | def magic_page(self, parameter_s=''): |
|
564 | def magic_page(self, parameter_s=''): | |
579 | """Pretty print the object and display it through a pager. |
|
565 | """Pretty print the object and display it through a pager. | |
580 |
|
566 | |||
581 | If no parameter is given, use _ (last output).""" |
|
567 | If no parameter is given, use _ (last output).""" | |
582 | # After a function contributed by Olivier Aubert, slightly modified. |
|
568 | # After a function contributed by Olivier Aubert, slightly modified. | |
583 |
|
569 | |||
584 | oname = parameter_s and parameter_s or '_' |
|
570 | oname = parameter_s and parameter_s or '_' | |
585 | info = self._ofind(oname) |
|
571 | info = self._ofind(oname) | |
586 | if info['found']: |
|
572 | if info['found']: | |
587 | page(pformat(info['obj'])) |
|
573 | page(pformat(info['obj'])) | |
588 | else: |
|
574 | else: | |
589 | print 'Object `%s` not found' % oname |
|
575 | print 'Object `%s` not found' % oname | |
590 |
|
576 | |||
591 | def magic_profile(self, parameter_s=''): |
|
577 | def magic_profile(self, parameter_s=''): | |
592 | """Print your currently active IPyhton profile.""" |
|
578 | """Print your currently active IPyhton profile.""" | |
593 | if self.shell.rc.profile: |
|
579 | if self.shell.rc.profile: | |
594 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
580 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
595 | else: |
|
581 | else: | |
596 | print 'No profile active.' |
|
582 | print 'No profile active.' | |
597 |
|
583 | |||
598 | def _inspect(self,meth,oname,**kw): |
|
584 | def _inspect(self,meth,oname,**kw): | |
599 | """Generic interface to the inspector system. |
|
585 | """Generic interface to the inspector system. | |
600 |
|
586 | |||
601 | This function is meant to be called by pdef, pdoc & friends.""" |
|
587 | This function is meant to be called by pdef, pdoc & friends.""" | |
602 |
|
588 | |||
603 | oname = oname.strip() |
|
589 | oname = oname.strip() | |
604 | info = Struct(self._ofind(oname)) |
|
590 | info = Struct(self._ofind(oname)) | |
605 | if info.found: |
|
591 | if info.found: | |
606 | pmethod = getattr(self.shell.inspector,meth) |
|
592 | pmethod = getattr(self.shell.inspector,meth) | |
607 | formatter = info.ismagic and self.format_screen or None |
|
593 | formatter = info.ismagic and self.format_screen or None | |
608 | if meth == 'pdoc': |
|
594 | if meth == 'pdoc': | |
609 | pmethod(info.obj,oname,formatter) |
|
595 | pmethod(info.obj,oname,formatter) | |
610 | elif meth == 'pinfo': |
|
596 | elif meth == 'pinfo': | |
611 | pmethod(info.obj,oname,formatter,info,**kw) |
|
597 | pmethod(info.obj,oname,formatter,info,**kw) | |
612 | else: |
|
598 | else: | |
613 | pmethod(info.obj,oname) |
|
599 | pmethod(info.obj,oname) | |
614 | else: |
|
600 | else: | |
615 | print 'Object `%s` not found.' % oname |
|
601 | print 'Object `%s` not found.' % oname | |
616 | return 'not found' # so callers can take other action |
|
602 | return 'not found' # so callers can take other action | |
617 |
|
603 | |||
618 | def magic_pdef(self, parameter_s=''): |
|
604 | def magic_pdef(self, parameter_s=''): | |
619 | """Print the definition header for any callable object. |
|
605 | """Print the definition header for any callable object. | |
620 |
|
606 | |||
621 | If the object is a class, print the constructor information.""" |
|
607 | If the object is a class, print the constructor information.""" | |
622 | self._inspect('pdef',parameter_s) |
|
608 | self._inspect('pdef',parameter_s) | |
623 |
|
609 | |||
624 | def magic_pdoc(self, parameter_s=''): |
|
610 | def magic_pdoc(self, parameter_s=''): | |
625 | """Print the docstring for an object. |
|
611 | """Print the docstring for an object. | |
626 |
|
612 | |||
627 | If the given object is a class, it will print both the class and the |
|
613 | If the given object is a class, it will print both the class and the | |
628 | constructor docstrings.""" |
|
614 | constructor docstrings.""" | |
629 | self._inspect('pdoc',parameter_s) |
|
615 | self._inspect('pdoc',parameter_s) | |
630 |
|
616 | |||
631 | def magic_psource(self, parameter_s=''): |
|
617 | def magic_psource(self, parameter_s=''): | |
632 | """Print (or run through pager) the source code for an object.""" |
|
618 | """Print (or run through pager) the source code for an object.""" | |
633 | self._inspect('psource',parameter_s) |
|
619 | self._inspect('psource',parameter_s) | |
634 |
|
620 | |||
635 | def magic_pfile(self, parameter_s=''): |
|
621 | def magic_pfile(self, parameter_s=''): | |
636 | """Print (or run through pager) the file where an object is defined. |
|
622 | """Print (or run through pager) the file where an object is defined. | |
637 |
|
623 | |||
638 | The file opens at the line where the object definition begins. IPython |
|
624 | The file opens at the line where the object definition begins. IPython | |
639 | will honor the environment variable PAGER if set, and otherwise will |
|
625 | will honor the environment variable PAGER if set, and otherwise will | |
640 | do its best to print the file in a convenient form. |
|
626 | do its best to print the file in a convenient form. | |
641 |
|
627 | |||
642 | If the given argument is not an object currently defined, IPython will |
|
628 | If the given argument is not an object currently defined, IPython will | |
643 | try to interpret it as a filename (automatically adding a .py extension |
|
629 | try to interpret it as a filename (automatically adding a .py extension | |
644 | if needed). You can thus use %pfile as a syntax highlighting code |
|
630 | if needed). You can thus use %pfile as a syntax highlighting code | |
645 | viewer.""" |
|
631 | viewer.""" | |
646 |
|
632 | |||
647 | # first interpret argument as an object name |
|
633 | # first interpret argument as an object name | |
648 | out = self._inspect('pfile',parameter_s) |
|
634 | out = self._inspect('pfile',parameter_s) | |
649 | # if not, try the input as a filename |
|
635 | # if not, try the input as a filename | |
650 | if out == 'not found': |
|
636 | if out == 'not found': | |
651 | try: |
|
637 | try: | |
652 | filename = get_py_filename(parameter_s) |
|
638 | filename = get_py_filename(parameter_s) | |
653 | except IOError,msg: |
|
639 | except IOError,msg: | |
654 | print msg |
|
640 | print msg | |
655 | return |
|
641 | return | |
656 | page(self.shell.inspector.format(file(filename).read())) |
|
642 | page(self.shell.inspector.format(file(filename).read())) | |
657 |
|
643 | |||
658 | def magic_pinfo(self, parameter_s=''): |
|
644 | def magic_pinfo(self, parameter_s=''): | |
659 | """Provide detailed information about an object. |
|
645 | """Provide detailed information about an object. | |
660 |
|
646 | |||
661 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
647 | '%pinfo object' is just a synonym for object? or ?object.""" | |
662 |
|
648 | |||
663 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
649 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
664 |
|
650 | |||
665 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
651 | # detail_level: 0 -> obj? , 1 -> obj?? | |
666 | detail_level = 0 |
|
652 | detail_level = 0 | |
667 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
653 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
668 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
654 | # happen if the user types 'pinfo foo?' at the cmd line. | |
669 | pinfo,qmark1,oname,qmark2 = \ |
|
655 | pinfo,qmark1,oname,qmark2 = \ | |
670 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
656 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
671 | if pinfo or qmark1 or qmark2: |
|
657 | if pinfo or qmark1 or qmark2: | |
672 | detail_level = 1 |
|
658 | detail_level = 1 | |
673 | self._inspect('pinfo',oname,detail_level=detail_level) |
|
659 | self._inspect('pinfo',oname,detail_level=detail_level) | |
674 |
|
660 | |||
675 | def magic_who_ls(self, parameter_s=''): |
|
661 | def magic_who_ls(self, parameter_s=''): | |
676 | """Return a sorted list of all interactive variables. |
|
662 | """Return a sorted list of all interactive variables. | |
677 |
|
663 | |||
678 | If arguments are given, only variables of types matching these |
|
664 | If arguments are given, only variables of types matching these | |
679 | arguments are returned.""" |
|
665 | arguments are returned.""" | |
680 |
|
666 | |||
681 | user_ns = self.shell.user_ns |
|
667 | user_ns = self.shell.user_ns | |
682 | out = [] |
|
668 | out = [] | |
683 | typelist = parameter_s.split() |
|
669 | typelist = parameter_s.split() | |
684 | for i in self.shell.user_ns.keys(): |
|
670 | for i in self.shell.user_ns.keys(): | |
685 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
671 | if not (i.startswith('_') or i.startswith('_i')) \ | |
686 | and not (self.internal_ns.has_key(i) or |
|
672 | and not (self.internal_ns.has_key(i) or | |
687 | self.user_config_ns.has_key(i)): |
|
673 | self.user_config_ns.has_key(i)): | |
688 | if typelist: |
|
674 | if typelist: | |
689 | if type(user_ns[i]).__name__ in typelist: |
|
675 | if type(user_ns[i]).__name__ in typelist: | |
690 | out.append(i) |
|
676 | out.append(i) | |
691 | else: |
|
677 | else: | |
692 | out.append(i) |
|
678 | out.append(i) | |
693 | out.sort() |
|
679 | out.sort() | |
694 | return out |
|
680 | return out | |
695 |
|
681 | |||
696 | def magic_who(self, parameter_s=''): |
|
682 | def magic_who(self, parameter_s=''): | |
697 | """Print all interactive variables, with some minimal formatting. |
|
683 | """Print all interactive variables, with some minimal formatting. | |
698 |
|
684 | |||
699 | If any arguments are given, only variables whose type matches one of |
|
685 | If any arguments are given, only variables whose type matches one of | |
700 | these are printed. For example: |
|
686 | these are printed. For example: | |
701 |
|
687 | |||
702 | %who function str |
|
688 | %who function str | |
703 |
|
689 | |||
704 | will only list functions and strings, excluding all other types of |
|
690 | will only list functions and strings, excluding all other types of | |
705 | variables. To find the proper type names, simply use type(var) at a |
|
691 | variables. To find the proper type names, simply use type(var) at a | |
706 | command line to see how python prints type names. For example: |
|
692 | command line to see how python prints type names. For example: | |
707 |
|
693 | |||
708 | In [1]: type('hello')\\ |
|
694 | In [1]: type('hello')\\ | |
709 | Out[1]: <type 'str'> |
|
695 | Out[1]: <type 'str'> | |
710 |
|
696 | |||
711 | indicates that the type name for strings is 'str'. |
|
697 | indicates that the type name for strings is 'str'. | |
712 |
|
698 | |||
713 | %who always excludes executed names loaded through your configuration |
|
699 | %who always excludes executed names loaded through your configuration | |
714 | file and things which are internal to IPython. |
|
700 | file and things which are internal to IPython. | |
715 |
|
701 | |||
716 | This is deliberate, as typically you may load many modules and the |
|
702 | This is deliberate, as typically you may load many modules and the | |
717 | purpose of %who is to show you only what you've manually defined.""" |
|
703 | purpose of %who is to show you only what you've manually defined.""" | |
718 |
|
704 | |||
719 | varlist = self.magic_who_ls(parameter_s) |
|
705 | varlist = self.magic_who_ls(parameter_s) | |
720 | if not varlist: |
|
706 | if not varlist: | |
721 | print 'Interactive namespace is empty.' |
|
707 | print 'Interactive namespace is empty.' | |
722 | return |
|
708 | return | |
723 |
|
709 | |||
724 | # if we have variables, move on... |
|
710 | # if we have variables, move on... | |
725 |
|
711 | |||
726 | # stupid flushing problem: when prompts have no separators, stdout is |
|
712 | # stupid flushing problem: when prompts have no separators, stdout is | |
727 | # getting lost. I'm starting to think this is a python bug. I'm having |
|
713 | # getting lost. I'm starting to think this is a python bug. I'm having | |
728 | # to force a flush with a print because even a sys.stdout.flush |
|
714 | # to force a flush with a print because even a sys.stdout.flush | |
729 | # doesn't seem to do anything! |
|
715 | # doesn't seem to do anything! | |
730 |
|
716 | |||
731 | count = 0 |
|
717 | count = 0 | |
732 | for i in varlist: |
|
718 | for i in varlist: | |
733 | print i+'\t', |
|
719 | print i+'\t', | |
734 | count += 1 |
|
720 | count += 1 | |
735 | if count > 8: |
|
721 | if count > 8: | |
736 | count = 0 |
|
722 | count = 0 | |
737 |
|
723 | |||
738 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? |
|
724 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? | |
739 |
|
725 | |||
740 | print # well, this does force a flush at the expense of an extra \n |
|
726 | print # well, this does force a flush at the expense of an extra \n | |
741 |
|
727 | |||
742 | def magic_whos(self, parameter_s=''): |
|
728 | def magic_whos(self, parameter_s=''): | |
743 | """Like %who, but gives some extra information about each variable. |
|
729 | """Like %who, but gives some extra information about each variable. | |
744 |
|
730 | |||
745 | The same type filtering of %who can be applied here. |
|
731 | The same type filtering of %who can be applied here. | |
746 |
|
732 | |||
747 | For all variables, the type is printed. Additionally it prints: |
|
733 | For all variables, the type is printed. Additionally it prints: | |
748 |
|
734 | |||
749 | - For {},[],(): their length. |
|
735 | - For {},[],(): their length. | |
750 |
|
736 | |||
751 | - For Numeric arrays, a summary with shape, number of elements, |
|
737 | - For Numeric arrays, a summary with shape, number of elements, | |
752 | typecode and size in memory. |
|
738 | typecode and size in memory. | |
753 |
|
739 | |||
754 | - Everything else: a string representation, snipping their middle if |
|
740 | - Everything else: a string representation, snipping their middle if | |
755 | too long.""" |
|
741 | too long.""" | |
756 |
|
742 | |||
757 | varnames = self.magic_who_ls(parameter_s) |
|
743 | varnames = self.magic_who_ls(parameter_s) | |
758 | if not varnames: |
|
744 | if not varnames: | |
759 | print 'Interactive namespace is empty.' |
|
745 | print 'Interactive namespace is empty.' | |
760 | return |
|
746 | return | |
761 |
|
747 | |||
762 | # if we have variables, move on... |
|
748 | # if we have variables, move on... | |
763 |
|
749 | |||
764 | # for these types, show len() instead of data: |
|
750 | # for these types, show len() instead of data: | |
765 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
751 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
766 |
|
752 | |||
767 | # for Numeric arrays, display summary info |
|
753 | # for Numeric arrays, display summary info | |
768 | try: |
|
754 | try: | |
769 | import Numeric |
|
755 | import Numeric | |
770 | except ImportError: |
|
756 | except ImportError: | |
771 | array_type = None |
|
757 | array_type = None | |
772 | else: |
|
758 | else: | |
773 | array_type = Numeric.ArrayType.__name__ |
|
759 | array_type = Numeric.ArrayType.__name__ | |
774 |
|
760 | |||
775 | # Find all variable names and types so we can figure out column sizes |
|
761 | # Find all variable names and types so we can figure out column sizes | |
776 | get_vars = lambda i: self.locals[i] |
|
762 | get_vars = lambda i: self.locals[i] | |
777 | type_name = lambda v: type(v).__name__ |
|
763 | type_name = lambda v: type(v).__name__ | |
778 | varlist = map(get_vars,varnames) |
|
764 | varlist = map(get_vars,varnames) | |
779 | typelist = map(type_name,varlist) |
|
765 | typelist = map(type_name,varlist) | |
780 | # column labels and # of spaces as separator |
|
766 | # column labels and # of spaces as separator | |
781 | varlabel = 'Variable' |
|
767 | varlabel = 'Variable' | |
782 | typelabel = 'Type' |
|
768 | typelabel = 'Type' | |
783 | datalabel = 'Data/Info' |
|
769 | datalabel = 'Data/Info' | |
784 | colsep = 3 |
|
770 | colsep = 3 | |
785 | # variable format strings |
|
771 | # variable format strings | |
786 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
772 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
787 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
773 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
788 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
774 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
789 | # find the size of the columns to format the output nicely |
|
775 | # find the size of the columns to format the output nicely | |
790 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
776 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
791 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
777 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
792 | # table header |
|
778 | # table header | |
793 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
779 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
794 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
780 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
795 | # and the table itself |
|
781 | # and the table itself | |
796 | kb = 1024 |
|
782 | kb = 1024 | |
797 | Mb = 1048576 # kb**2 |
|
783 | Mb = 1048576 # kb**2 | |
798 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
784 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
799 | print itpl(vformat), |
|
785 | print itpl(vformat), | |
800 | if vtype in seq_types: |
|
786 | if vtype in seq_types: | |
801 | print len(var) |
|
787 | print len(var) | |
802 | elif vtype==array_type: |
|
788 | elif vtype==array_type: | |
803 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
789 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
804 | vsize = Numeric.size(var) |
|
790 | vsize = Numeric.size(var) | |
805 | vbytes = vsize*var.itemsize() |
|
791 | vbytes = vsize*var.itemsize() | |
806 | if vbytes < 100000: |
|
792 | if vbytes < 100000: | |
807 | print aformat % (vshape,vsize,var.typecode(),vbytes) |
|
793 | print aformat % (vshape,vsize,var.typecode(),vbytes) | |
808 | else: |
|
794 | else: | |
809 | print aformat % (vshape,vsize,var.typecode(),vbytes), |
|
795 | print aformat % (vshape,vsize,var.typecode(),vbytes), | |
810 | if vbytes < Mb: |
|
796 | if vbytes < Mb: | |
811 | print '(%s kb)' % (vbytes/kb,) |
|
797 | print '(%s kb)' % (vbytes/kb,) | |
812 | else: |
|
798 | else: | |
813 | print '(%s Mb)' % (vbytes/Mb,) |
|
799 | print '(%s Mb)' % (vbytes/Mb,) | |
814 | else: |
|
800 | else: | |
815 | vstr = str(var) |
|
801 | vstr = str(var) | |
816 | if len(vstr) < 50: |
|
802 | if len(vstr) < 50: | |
817 | print vstr |
|
803 | print vstr | |
818 | else: |
|
804 | else: | |
819 | printpl(vfmt_short) |
|
805 | printpl(vfmt_short) | |
820 |
|
806 | |||
821 | def magic_reset(self, parameter_s=''): |
|
807 | def magic_reset(self, parameter_s=''): | |
822 | """Resets the namespace by removing all names defined by the user. |
|
808 | """Resets the namespace by removing all names defined by the user. | |
823 |
|
809 | |||
824 | Input/Output history are left around in case you need them.""" |
|
810 | Input/Output history are left around in case you need them.""" | |
825 |
|
811 | |||
826 | ans = raw_input( |
|
812 | ans = raw_input( | |
827 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") |
|
813 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") | |
828 | if not ans.lower() == 'y': |
|
814 | if not ans.lower() == 'y': | |
829 | print 'Nothing done.' |
|
815 | print 'Nothing done.' | |
830 | return |
|
816 | return | |
831 | for i in self.magic_who_ls(): |
|
817 | for i in self.magic_who_ls(): | |
832 | del(self.locals[i]) |
|
818 | del(self.locals[i]) | |
833 |
|
819 | |||
834 | def magic_config(self,parameter_s=''): |
|
820 | def magic_config(self,parameter_s=''): | |
835 | """Show IPython's internal configuration.""" |
|
821 | """Show IPython's internal configuration.""" | |
836 |
|
822 | |||
837 | page('Current configuration structure:\n'+ |
|
823 | page('Current configuration structure:\n'+ | |
838 | pformat(self.shell.rc.dict())) |
|
824 | pformat(self.shell.rc.dict())) | |
839 |
|
825 | |||
840 | def magic_logstart(self,parameter_s=''): |
|
826 | def magic_logstart(self,parameter_s=''): | |
841 | """Start logging anywhere in a session. |
|
827 | """Start logging anywhere in a session. | |
842 |
|
828 | |||
843 | %logstart [log_name [log_mode]] |
|
829 | %logstart [log_name [log_mode]] | |
844 |
|
830 | |||
845 | If no name is given, it defaults to a file named 'ipython.log' in your |
|
831 | If no name is given, it defaults to a file named 'ipython.log' in your | |
846 | current directory, in 'rotate' mode (see below). |
|
832 | current directory, in 'rotate' mode (see below). | |
847 |
|
833 | |||
848 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
834 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
849 | history up to that point and then continues logging. |
|
835 | history up to that point and then continues logging. | |
850 |
|
836 | |||
851 | %logstart takes a second optional parameter: logging mode. This can be one |
|
837 | %logstart takes a second optional parameter: logging mode. This can be one | |
852 | of (note that the modes are given unquoted):\\ |
|
838 | of (note that the modes are given unquoted):\\ | |
853 | over: overwrite existing log.\\ |
|
839 | over: overwrite existing log.\\ | |
854 | backup: rename (if exists) to name~ and start name.\\ |
|
840 | backup: rename (if exists) to name~ and start name.\\ | |
855 | append: well, that says it.\\ |
|
841 | append: well, that says it.\\ | |
856 | rotate: create rotating logs name.1~, name.2~, etc. |
|
842 | rotate: create rotating logs name.1~, name.2~, etc. | |
857 | """ |
|
843 | """ | |
858 |
|
844 | |||
859 | #FIXME. This function should all be moved to the Logger class. |
|
845 | #FIXME. This function should all be moved to the Logger class. | |
860 |
|
846 | |||
861 | valid_modes = qw('over backup append rotate') |
|
847 | valid_modes = qw('over backup append rotate') | |
862 | if self.LOG: |
|
848 | if self.LOG: | |
863 | print 'Logging is already in place. Logfile:',self.LOG |
|
849 | print 'Logging is already in place. Logfile:',self.LOG | |
864 | return |
|
850 | return | |
865 |
|
851 | |||
866 | par = parameter_s.strip() |
|
852 | par = parameter_s.strip() | |
867 | if not par: |
|
853 | if not par: | |
868 | logname = self.LOGDEF |
|
854 | logname = self.LOGDEF | |
869 | logmode = 'rotate' # use rotate for the auto-generated logs |
|
855 | logmode = 'rotate' # use rotate for the auto-generated logs | |
870 | else: |
|
856 | else: | |
871 | try: |
|
857 | try: | |
872 | logname,logmode = par.split() |
|
858 | logname,logmode = par.split() | |
873 | except: |
|
859 | except: | |
874 | try: |
|
860 | try: | |
875 | logname = par |
|
861 | logname = par | |
876 | logmode = 'backup' |
|
862 | logmode = 'backup' | |
877 | except: |
|
863 | except: | |
878 | warn('Usage: %log [log_name [log_mode]]') |
|
864 | warn('Usage: %log [log_name [log_mode]]') | |
879 | return |
|
865 | return | |
880 | if not logmode in valid_modes: |
|
866 | if not logmode in valid_modes: | |
881 | warn('Logging NOT activated.\n' |
|
867 | warn('Logging NOT activated.\n' | |
882 | 'Usage: %log [log_name [log_mode]]\n' |
|
868 | 'Usage: %log [log_name [log_mode]]\n' | |
883 | 'Valid modes: '+str(valid_modes)) |
|
869 | 'Valid modes: '+str(valid_modes)) | |
884 | return |
|
870 | return | |
885 |
|
871 | |||
886 | # If we made it this far, I think we're ok: |
|
872 | # If we made it this far, I think we're ok: | |
887 | print 'Activating auto-logging.' |
|
873 | print 'Activating auto-logging.' | |
888 | print 'Current session state plus future input saved to:',logname |
|
874 | print 'Current session state plus future input saved to:',logname | |
889 | print 'Logging mode: ',logmode |
|
875 | print 'Logging mode: ',logmode | |
890 | # put logname into rc struct as if it had been called on the command line, |
|
876 | # put logname into rc struct as if it had been called on the command line, | |
891 | # so it ends up saved in the log header |
|
877 | # so it ends up saved in the log header | |
892 | # Save it in case we need to restore it... |
|
878 | # Save it in case we need to restore it... | |
893 | old_logfile = self.shell.rc.opts.get('logfile','') |
|
879 | old_logfile = self.shell.rc.opts.get('logfile','') | |
894 | logname = os.path.expanduser(logname) |
|
880 | logname = os.path.expanduser(logname) | |
895 | self.shell.rc.opts.logfile = logname |
|
881 | self.shell.rc.opts.logfile = logname | |
896 | self.LOGMODE = logmode # FIXME: this should be set through a function. |
|
882 | self.LOGMODE = logmode # FIXME: this should be set through a function. | |
897 | try: |
|
883 | try: | |
898 | header = str(self.LOGHEAD) |
|
884 | header = str(self.LOGHEAD) | |
899 | self.create_log(header,logname) |
|
885 | self.create_log(header,logname) | |
900 | self.logstart(header,logname) |
|
886 | self.logstart(header,logname) | |
901 | except: |
|
887 | except: | |
902 | self.LOG = '' # we are NOT logging, something went wrong |
|
888 | self.LOG = '' # we are NOT logging, something went wrong | |
903 | self.shell.rc.opts.logfile = old_logfile |
|
889 | self.shell.rc.opts.logfile = old_logfile | |
904 | warn("Couldn't start log: "+str(sys.exc_info()[1])) |
|
890 | warn("Couldn't start log: "+str(sys.exc_info()[1])) | |
905 | else: # log input history up to this point |
|
891 | else: # log input history up to this point | |
906 | self.logfile.write(self.shell.user_ns['_ih'][1:]) |
|
892 | self.logfile.write(self.shell.user_ns['_ih'][1:]) | |
907 | self.logfile.flush() |
|
893 | self.logfile.flush() | |
908 |
|
894 | |||
909 | def magic_logoff(self,parameter_s=''): |
|
895 | def magic_logoff(self,parameter_s=''): | |
910 | """Temporarily stop logging. |
|
896 | """Temporarily stop logging. | |
911 |
|
897 | |||
912 | You must have previously started logging.""" |
|
898 | You must have previously started logging.""" | |
913 | self.switch_log(0) |
|
899 | self.switch_log(0) | |
914 |
|
900 | |||
915 | def magic_logon(self,parameter_s=''): |
|
901 | def magic_logon(self,parameter_s=''): | |
916 | """Restart logging. |
|
902 | """Restart logging. | |
917 |
|
903 | |||
918 | This function is for restarting logging which you've temporarily |
|
904 | This function is for restarting logging which you've temporarily | |
919 | stopped with %logoff. For starting logging for the first time, you |
|
905 | stopped with %logoff. For starting logging for the first time, you | |
920 | must use the %logstart function, which allows you to specify an |
|
906 | must use the %logstart function, which allows you to specify an | |
921 | optional log filename.""" |
|
907 | optional log filename.""" | |
922 |
|
908 | |||
923 | self.switch_log(1) |
|
909 | self.switch_log(1) | |
924 |
|
910 | |||
925 | def magic_logstate(self,parameter_s=''): |
|
911 | def magic_logstate(self,parameter_s=''): | |
926 | """Print the status of the logging system.""" |
|
912 | """Print the status of the logging system.""" | |
927 |
|
913 | |||
928 | self.logstate() |
|
914 | self.logstate() | |
929 |
|
915 | |||
930 | def magic_pdb(self, parameter_s=''): |
|
916 | def magic_pdb(self, parameter_s=''): | |
931 | """Control the calling of the pdb interactive debugger. |
|
917 | """Control the calling of the pdb interactive debugger. | |
932 |
|
918 | |||
933 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
919 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
934 | argument it works as a toggle. |
|
920 | argument it works as a toggle. | |
935 |
|
921 | |||
936 | When an exception is triggered, IPython can optionally call the |
|
922 | When an exception is triggered, IPython can optionally call the | |
937 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
923 | interactive pdb debugger after the traceback printout. %pdb toggles | |
938 | this feature on and off.""" |
|
924 | this feature on and off.""" | |
939 |
|
925 | |||
940 | par = parameter_s.strip().lower() |
|
926 | par = parameter_s.strip().lower() | |
941 |
|
927 | |||
942 | if par: |
|
928 | if par: | |
943 | try: |
|
929 | try: | |
944 | pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
930 | pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
945 | except KeyError: |
|
931 | except KeyError: | |
946 | print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.' |
|
932 | print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.' | |
947 | return |
|
933 | return | |
948 | else: |
|
934 | else: | |
949 | self.shell.InteractiveTB.call_pdb = pdb |
|
935 | self.shell.InteractiveTB.call_pdb = pdb | |
950 | else: |
|
936 | else: | |
951 | self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb |
|
937 | self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb | |
952 | print 'Automatic pdb calling has been turned',\ |
|
938 | print 'Automatic pdb calling has been turned',\ | |
953 | on_off(self.shell.InteractiveTB.call_pdb) |
|
939 | on_off(self.shell.InteractiveTB.call_pdb) | |
954 |
|
940 | |||
955 |
|
941 | |||
956 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
942 | def magic_prun(self, parameter_s ='',user_mode=1, | |
957 | opts=None,arg_lst=None,prog_ns=None): |
|
943 | opts=None,arg_lst=None,prog_ns=None): | |
958 |
|
944 | |||
959 | """Run a statement through the python code profiler. |
|
945 | """Run a statement through the python code profiler. | |
960 |
|
946 | |||
961 | Usage:\\ |
|
947 | Usage:\\ | |
962 | %prun [options] statement |
|
948 | %prun [options] statement | |
963 |
|
949 | |||
964 | The given statement (which doesn't require quote marks) is run via the |
|
950 | The given statement (which doesn't require quote marks) is run via the | |
965 | python profiler in a manner similar to the profile.run() function. |
|
951 | python profiler in a manner similar to the profile.run() function. | |
966 | Namespaces are internally managed to work correctly; profile.run |
|
952 | Namespaces are internally managed to work correctly; profile.run | |
967 | cannot be used in IPython because it makes certain assumptions about |
|
953 | cannot be used in IPython because it makes certain assumptions about | |
968 | namespaces which do not hold under IPython. |
|
954 | namespaces which do not hold under IPython. | |
969 |
|
955 | |||
970 | Options: |
|
956 | Options: | |
971 |
|
957 | |||
972 | -l <limit>: you can place restrictions on what or how much of the |
|
958 | -l <limit>: you can place restrictions on what or how much of the | |
973 | profile gets printed. The limit value can be: |
|
959 | profile gets printed. The limit value can be: | |
974 |
|
960 | |||
975 | * A string: only information for function names containing this string |
|
961 | * A string: only information for function names containing this string | |
976 | is printed. |
|
962 | is printed. | |
977 |
|
963 | |||
978 | * An integer: only these many lines are printed. |
|
964 | * An integer: only these many lines are printed. | |
979 |
|
965 | |||
980 | * A float (between 0 and 1): this fraction of the report is printed |
|
966 | * A float (between 0 and 1): this fraction of the report is printed | |
981 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
967 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
982 |
|
968 | |||
983 | You can combine several limits with repeated use of the option. For |
|
969 | You can combine several limits with repeated use of the option. For | |
984 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
970 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
985 | information about class constructors. |
|
971 | information about class constructors. | |
986 |
|
972 | |||
987 | -r: return the pstats.Stats object generated by the profiling. This |
|
973 | -r: return the pstats.Stats object generated by the profiling. This | |
988 | object has all the information about the profile in it, and you can |
|
974 | object has all the information about the profile in it, and you can | |
989 | later use it for further analysis or in other functions. |
|
975 | later use it for further analysis or in other functions. | |
990 |
|
976 | |||
991 | Since magic functions have a particular form of calling which prevents |
|
977 | Since magic functions have a particular form of calling which prevents | |
992 | you from writing something like:\\ |
|
978 | you from writing something like:\\ | |
993 | In [1]: p = %prun -r print 4 # invalid!\\ |
|
979 | In [1]: p = %prun -r print 4 # invalid!\\ | |
994 | you must instead use IPython's automatic variables to assign this:\\ |
|
980 | you must instead use IPython's automatic variables to assign this:\\ | |
995 | In [1]: %prun -r print 4 \\ |
|
981 | In [1]: %prun -r print 4 \\ | |
996 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ |
|
982 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ | |
997 | In [2]: stats = _ |
|
983 | In [2]: stats = _ | |
998 |
|
984 | |||
999 | If you really need to assign this value via an explicit function call, |
|
985 | If you really need to assign this value via an explicit function call, | |
1000 | you can always tap directly into the true name of the magic function |
|
986 | you can always tap directly into the true name of the magic function | |
1001 | by using the ipmagic function (which IPython automatically adds to the |
|
987 | by using the ipmagic function (which IPython automatically adds to the | |
1002 | builtins):\\ |
|
988 | builtins):\\ | |
1003 | In [3]: stats = ipmagic('prun','-r print 4') |
|
989 | In [3]: stats = ipmagic('prun','-r print 4') | |
1004 |
|
990 | |||
1005 | You can type ipmagic? for more details on ipmagic. |
|
991 | You can type ipmagic? for more details on ipmagic. | |
1006 |
|
992 | |||
1007 | -s <key>: sort profile by given key. You can provide more than one key |
|
993 | -s <key>: sort profile by given key. You can provide more than one key | |
1008 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
994 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1009 | default sorting key is 'time'. |
|
995 | default sorting key is 'time'. | |
1010 |
|
996 | |||
1011 | The following is copied verbatim from the profile documentation |
|
997 | The following is copied verbatim from the profile documentation | |
1012 | referenced below: |
|
998 | referenced below: | |
1013 |
|
999 | |||
1014 | When more than one key is provided, additional keys are used as |
|
1000 | When more than one key is provided, additional keys are used as | |
1015 | secondary criteria when the there is equality in all keys selected |
|
1001 | secondary criteria when the there is equality in all keys selected | |
1016 | before them. |
|
1002 | before them. | |
1017 |
|
1003 | |||
1018 | Abbreviations can be used for any key names, as long as the |
|
1004 | Abbreviations can be used for any key names, as long as the | |
1019 | abbreviation is unambiguous. The following are the keys currently |
|
1005 | abbreviation is unambiguous. The following are the keys currently | |
1020 | defined: |
|
1006 | defined: | |
1021 |
|
1007 | |||
1022 | Valid Arg Meaning\\ |
|
1008 | Valid Arg Meaning\\ | |
1023 | "calls" call count\\ |
|
1009 | "calls" call count\\ | |
1024 | "cumulative" cumulative time\\ |
|
1010 | "cumulative" cumulative time\\ | |
1025 | "file" file name\\ |
|
1011 | "file" file name\\ | |
1026 | "module" file name\\ |
|
1012 | "module" file name\\ | |
1027 | "pcalls" primitive call count\\ |
|
1013 | "pcalls" primitive call count\\ | |
1028 | "line" line number\\ |
|
1014 | "line" line number\\ | |
1029 | "name" function name\\ |
|
1015 | "name" function name\\ | |
1030 | "nfl" name/file/line\\ |
|
1016 | "nfl" name/file/line\\ | |
1031 | "stdname" standard name\\ |
|
1017 | "stdname" standard name\\ | |
1032 | "time" internal time |
|
1018 | "time" internal time | |
1033 |
|
1019 | |||
1034 | Note that all sorts on statistics are in descending order (placing |
|
1020 | Note that all sorts on statistics are in descending order (placing | |
1035 | most time consuming items first), where as name, file, and line number |
|
1021 | most time consuming items first), where as name, file, and line number | |
1036 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1022 | searches are in ascending order (i.e., alphabetical). The subtle | |
1037 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1023 | distinction between "nfl" and "stdname" is that the standard name is a | |
1038 | sort of the name as printed, which means that the embedded line |
|
1024 | sort of the name as printed, which means that the embedded line | |
1039 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1025 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1040 | would (if the file names were the same) appear in the string order |
|
1026 | would (if the file names were the same) appear in the string order | |
1041 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1027 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1042 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1028 | line numbers. In fact, sort_stats("nfl") is the same as | |
1043 | sort_stats("name", "file", "line"). |
|
1029 | sort_stats("name", "file", "line"). | |
1044 |
|
1030 | |||
1045 | -T <filename>: save profile results as shown on screen to a text |
|
1031 | -T <filename>: save profile results as shown on screen to a text | |
1046 | file. The profile is still shown on screen. |
|
1032 | file. The profile is still shown on screen. | |
1047 |
|
1033 | |||
1048 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1034 | -D <filename>: save (via dump_stats) profile statistics to given | |
1049 | filename. This data is in a format understod by the pstats module, and |
|
1035 | filename. This data is in a format understod by the pstats module, and | |
1050 | is generated by a call to the dump_stats() method of profile |
|
1036 | is generated by a call to the dump_stats() method of profile | |
1051 | objects. The profile is still shown on screen. |
|
1037 | objects. The profile is still shown on screen. | |
1052 |
|
1038 | |||
1053 | If you want to run complete programs under the profiler's control, use |
|
1039 | If you want to run complete programs under the profiler's control, use | |
1054 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1040 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1055 | contains profiler specific options as described here. |
|
1041 | contains profiler specific options as described here. | |
1056 |
|
1042 | |||
1057 | You can read the complete documentation for the profile module with:\\ |
|
1043 | You can read the complete documentation for the profile module with:\\ | |
1058 | In [1]: import profile; profile.help() """ |
|
1044 | In [1]: import profile; profile.help() """ | |
1059 |
|
1045 | |||
1060 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1046 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1061 | # protect user quote marks |
|
1047 | # protect user quote marks | |
1062 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1048 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1063 |
|
1049 | |||
1064 | if user_mode: # regular user call |
|
1050 | if user_mode: # regular user call | |
1065 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1051 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1066 | list_all=1) |
|
1052 | list_all=1) | |
1067 | namespace = self.shell.user_ns |
|
1053 | namespace = self.shell.user_ns | |
1068 | else: # called to run a program by %run -p |
|
1054 | else: # called to run a program by %run -p | |
1069 | try: |
|
1055 | try: | |
1070 | filename = get_py_filename(arg_lst[0]) |
|
1056 | filename = get_py_filename(arg_lst[0]) | |
1071 | except IOError,msg: |
|
1057 | except IOError,msg: | |
1072 | error(msg) |
|
1058 | error(msg) | |
1073 | return |
|
1059 | return | |
1074 |
|
1060 | |||
1075 | arg_str = 'execfile(filename,prog_ns)' |
|
1061 | arg_str = 'execfile(filename,prog_ns)' | |
1076 | namespace = locals() |
|
1062 | namespace = locals() | |
1077 |
|
1063 | |||
1078 | opts.merge(opts_def) |
|
1064 | opts.merge(opts_def) | |
1079 |
|
1065 | |||
1080 | prof = profile.Profile() |
|
1066 | prof = profile.Profile() | |
1081 | try: |
|
1067 | try: | |
1082 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1068 | prof = prof.runctx(arg_str,namespace,namespace) | |
1083 | sys_exit = '' |
|
1069 | sys_exit = '' | |
1084 | except SystemExit: |
|
1070 | except SystemExit: | |
1085 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1071 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1086 |
|
1072 | |||
1087 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1073 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1088 |
|
1074 | |||
1089 | lims = opts.l |
|
1075 | lims = opts.l | |
1090 | if lims: |
|
1076 | if lims: | |
1091 | lims = [] # rebuild lims with ints/floats/strings |
|
1077 | lims = [] # rebuild lims with ints/floats/strings | |
1092 | for lim in opts.l: |
|
1078 | for lim in opts.l: | |
1093 | try: |
|
1079 | try: | |
1094 | lims.append(int(lim)) |
|
1080 | lims.append(int(lim)) | |
1095 | except ValueError: |
|
1081 | except ValueError: | |
1096 | try: |
|
1082 | try: | |
1097 | lims.append(float(lim)) |
|
1083 | lims.append(float(lim)) | |
1098 | except ValueError: |
|
1084 | except ValueError: | |
1099 | lims.append(lim) |
|
1085 | lims.append(lim) | |
1100 |
|
1086 | |||
1101 | # trap output |
|
1087 | # trap output | |
1102 | sys_stdout = sys.stdout |
|
1088 | sys_stdout = sys.stdout | |
1103 | stdout_trap = StringIO() |
|
1089 | stdout_trap = StringIO() | |
1104 | try: |
|
1090 | try: | |
1105 | sys.stdout = stdout_trap |
|
1091 | sys.stdout = stdout_trap | |
1106 | stats.print_stats(*lims) |
|
1092 | stats.print_stats(*lims) | |
1107 | finally: |
|
1093 | finally: | |
1108 | sys.stdout = sys_stdout |
|
1094 | sys.stdout = sys_stdout | |
1109 | output = stdout_trap.getvalue() |
|
1095 | output = stdout_trap.getvalue() | |
1110 | output = output.rstrip() |
|
1096 | output = output.rstrip() | |
1111 |
|
1097 | |||
1112 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1098 | page(output,screen_lines=self.shell.rc.screen_length) | |
1113 | print sys_exit, |
|
1099 | print sys_exit, | |
1114 |
|
1100 | |||
1115 | dump_file = opts.D[0] |
|
1101 | dump_file = opts.D[0] | |
1116 | text_file = opts.T[0] |
|
1102 | text_file = opts.T[0] | |
1117 | if dump_file: |
|
1103 | if dump_file: | |
1118 | prof.dump_stats(dump_file) |
|
1104 | prof.dump_stats(dump_file) | |
1119 | print '\n*** Profile stats marshalled to file',\ |
|
1105 | print '\n*** Profile stats marshalled to file',\ | |
1120 | `dump_file`+'.',sys_exit |
|
1106 | `dump_file`+'.',sys_exit | |
1121 | if text_file: |
|
1107 | if text_file: | |
1122 | file(text_file,'w').write(output) |
|
1108 | file(text_file,'w').write(output) | |
1123 | print '\n*** Profile printout saved to text file',\ |
|
1109 | print '\n*** Profile printout saved to text file',\ | |
1124 | `text_file`+'.',sys_exit |
|
1110 | `text_file`+'.',sys_exit | |
1125 |
|
1111 | |||
1126 | if opts.has_key('r'): |
|
1112 | if opts.has_key('r'): | |
1127 | return stats |
|
1113 | return stats | |
1128 | else: |
|
1114 | else: | |
1129 | return None |
|
1115 | return None | |
1130 |
|
1116 | |||
1131 | def magic_run(self, parameter_s ='',runner=None): |
|
1117 | def magic_run(self, parameter_s ='',runner=None): | |
1132 | """Run the named file inside IPython as a program. |
|
1118 | """Run the named file inside IPython as a program. | |
1133 |
|
1119 | |||
1134 | Usage:\\ |
|
1120 | Usage:\\ | |
1135 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1121 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1136 |
|
1122 | |||
1137 | Parameters after the filename are passed as command-line arguments to |
|
1123 | Parameters after the filename are passed as command-line arguments to | |
1138 | the program (put in sys.argv). Then, control returns to IPython's |
|
1124 | the program (put in sys.argv). Then, control returns to IPython's | |
1139 | prompt. |
|
1125 | prompt. | |
1140 |
|
1126 | |||
1141 | This is similar to running at a system prompt:\\ |
|
1127 | This is similar to running at a system prompt:\\ | |
1142 | $ python file args\\ |
|
1128 | $ python file args\\ | |
1143 | but with the advantage of giving you IPython's tracebacks, and of |
|
1129 | but with the advantage of giving you IPython's tracebacks, and of | |
1144 | loading all variables into your interactive namespace for further use |
|
1130 | loading all variables into your interactive namespace for further use | |
1145 | (unless -p is used, see below). |
|
1131 | (unless -p is used, see below). | |
1146 |
|
1132 | |||
1147 | The file is executed in a namespace initially consisting only of |
|
1133 | The file is executed in a namespace initially consisting only of | |
1148 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1134 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1149 | sees its environment as if it were being run as a stand-alone |
|
1135 | sees its environment as if it were being run as a stand-alone | |
1150 | program. But after execution, the IPython interactive namespace gets |
|
1136 | program. But after execution, the IPython interactive namespace gets | |
1151 | updated with all variables defined in the program (except for __name__ |
|
1137 | updated with all variables defined in the program (except for __name__ | |
1152 | and sys.argv). This allows for very convenient loading of code for |
|
1138 | and sys.argv). This allows for very convenient loading of code for | |
1153 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1139 | interactive work, while giving each program a 'clean sheet' to run in. | |
1154 |
|
1140 | |||
1155 | Options: |
|
1141 | Options: | |
1156 |
|
1142 | |||
1157 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1143 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1158 | without extension (as python does under import). This allows running |
|
1144 | without extension (as python does under import). This allows running | |
1159 | scripts and reloading the definitions in them without calling code |
|
1145 | scripts and reloading the definitions in them without calling code | |
1160 | protected by an ' if __name__ == "__main__" ' clause. |
|
1146 | protected by an ' if __name__ == "__main__" ' clause. | |
1161 |
|
1147 | |||
1162 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1148 | -i: run the file in IPython's namespace instead of an empty one. This | |
1163 | is useful if you are experimenting with code written in a text editor |
|
1149 | is useful if you are experimenting with code written in a text editor | |
1164 | which depends on variables defined interactively. |
|
1150 | which depends on variables defined interactively. | |
1165 |
|
1151 | |||
1166 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1152 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1167 | being run. This is particularly useful if IPython is being used to |
|
1153 | being run. This is particularly useful if IPython is being used to | |
1168 | run unittests, which always exit with a sys.exit() call. In such |
|
1154 | run unittests, which always exit with a sys.exit() call. In such | |
1169 | cases you are interested in the output of the test results, not in |
|
1155 | cases you are interested in the output of the test results, not in | |
1170 | seeing a traceback of the unittest module. |
|
1156 | seeing a traceback of the unittest module. | |
1171 |
|
1157 | |||
1172 | -t: print timing information at the end of the run. IPython will give |
|
1158 | -t: print timing information at the end of the run. IPython will give | |
1173 | you an estimated CPU time consumption for your script, which under |
|
1159 | you an estimated CPU time consumption for your script, which under | |
1174 | Unix uses the resource module to avoid the wraparound problems of |
|
1160 | Unix uses the resource module to avoid the wraparound problems of | |
1175 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1161 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1176 | is also given (for Windows platforms this is reported as 0.0). |
|
1162 | is also given (for Windows platforms this is reported as 0.0). | |
1177 |
|
1163 | |||
1178 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1164 | If -t is given, an additional -N<N> option can be given, where <N> | |
1179 | must be an integer indicating how many times you want the script to |
|
1165 | must be an integer indicating how many times you want the script to | |
1180 | run. The final timing report will include total and per run results. |
|
1166 | run. The final timing report will include total and per run results. | |
1181 |
|
1167 | |||
1182 | For example (testing the script uniq_stable.py): |
|
1168 | For example (testing the script uniq_stable.py): | |
1183 |
|
1169 | |||
1184 | In [1]: run -t uniq_stable |
|
1170 | In [1]: run -t uniq_stable | |
1185 |
|
1171 | |||
1186 | IPython CPU timings (estimated):\\ |
|
1172 | IPython CPU timings (estimated):\\ | |
1187 | User : 0.19597 s.\\ |
|
1173 | User : 0.19597 s.\\ | |
1188 | System: 0.0 s.\\ |
|
1174 | System: 0.0 s.\\ | |
1189 |
|
1175 | |||
1190 | In [2]: run -t -N5 uniq_stable |
|
1176 | In [2]: run -t -N5 uniq_stable | |
1191 |
|
1177 | |||
1192 | IPython CPU timings (estimated):\\ |
|
1178 | IPython CPU timings (estimated):\\ | |
1193 | Total runs performed: 5\\ |
|
1179 | Total runs performed: 5\\ | |
1194 | Times : Total Per run\\ |
|
1180 | Times : Total Per run\\ | |
1195 | User : 0.910862 s, 0.1821724 s.\\ |
|
1181 | User : 0.910862 s, 0.1821724 s.\\ | |
1196 | System: 0.0 s, 0.0 s. |
|
1182 | System: 0.0 s, 0.0 s. | |
1197 |
|
1183 | |||
1198 | -d: run your program under the control of pdb, the Python debugger. |
|
1184 | -d: run your program under the control of pdb, the Python debugger. | |
1199 | This allows you to execute your program step by step, watch variables, |
|
1185 | This allows you to execute your program step by step, watch variables, | |
1200 | etc. Internally, what IPython does is similar to calling: |
|
1186 | etc. Internally, what IPython does is similar to calling: | |
1201 |
|
1187 | |||
1202 | pdb.run('execfile("YOURFILENAME")') |
|
1188 | pdb.run('execfile("YOURFILENAME")') | |
1203 |
|
1189 | |||
1204 | with a breakpoint set on line 1 of your file. You can change the line |
|
1190 | with a breakpoint set on line 1 of your file. You can change the line | |
1205 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1191 | number for this automatic breakpoint to be <N> by using the -bN option | |
1206 | (where N must be an integer). For example: |
|
1192 | (where N must be an integer). For example: | |
1207 |
|
1193 | |||
1208 | %run -d -b40 myscript |
|
1194 | %run -d -b40 myscript | |
1209 |
|
1195 | |||
1210 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1196 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1211 | the first breakpoint must be set on a line which actually does |
|
1197 | the first breakpoint must be set on a line which actually does | |
1212 | something (not a comment or docstring) for it to stop execution. |
|
1198 | something (not a comment or docstring) for it to stop execution. | |
1213 |
|
1199 | |||
1214 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1200 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1215 | first enter 'c' (without qoutes) to start execution up to the first |
|
1201 | first enter 'c' (without qoutes) to start execution up to the first | |
1216 | breakpoint. |
|
1202 | breakpoint. | |
1217 |
|
1203 | |||
1218 | Entering 'help' gives information about the use of the debugger. You |
|
1204 | Entering 'help' gives information about the use of the debugger. You | |
1219 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1205 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1220 | at a prompt. |
|
1206 | at a prompt. | |
1221 |
|
1207 | |||
1222 | -p: run program under the control of the Python profiler module (which |
|
1208 | -p: run program under the control of the Python profiler module (which | |
1223 | prints a detailed report of execution times, function calls, etc). |
|
1209 | prints a detailed report of execution times, function calls, etc). | |
1224 |
|
1210 | |||
1225 | You can pass other options after -p which affect the behavior of the |
|
1211 | You can pass other options after -p which affect the behavior of the | |
1226 | profiler itself. See the docs for %prun for details. |
|
1212 | profiler itself. See the docs for %prun for details. | |
1227 |
|
1213 | |||
1228 | In this mode, the program's variables do NOT propagate back to the |
|
1214 | In this mode, the program's variables do NOT propagate back to the | |
1229 | IPython interactive namespace (because they remain in the namespace |
|
1215 | IPython interactive namespace (because they remain in the namespace | |
1230 | where the profiler executes them). |
|
1216 | where the profiler executes them). | |
1231 |
|
1217 | |||
1232 | Internally this triggers a call to %prun, see its documentation for |
|
1218 | Internally this triggers a call to %prun, see its documentation for | |
1233 | details on the options available specifically for profiling.""" |
|
1219 | details on the options available specifically for profiling.""" | |
1234 |
|
1220 | |||
1235 | # get arguments and set sys.argv for program to be run. |
|
1221 | # get arguments and set sys.argv for program to be run. | |
1236 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1222 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1237 | mode='list',list_all=1) |
|
1223 | mode='list',list_all=1) | |
1238 |
|
1224 | |||
1239 | try: |
|
1225 | try: | |
1240 | filename = get_py_filename(arg_lst[0]) |
|
1226 | filename = get_py_filename(arg_lst[0]) | |
1241 | except IndexError: |
|
1227 | except IndexError: | |
1242 | warn('you must provide at least a filename.') |
|
1228 | warn('you must provide at least a filename.') | |
1243 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1229 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1244 | return |
|
1230 | return | |
1245 | except IOError,msg: |
|
1231 | except IOError,msg: | |
1246 | error(msg) |
|
1232 | error(msg) | |
1247 | return |
|
1233 | return | |
1248 |
|
1234 | |||
1249 | # Control the response to exit() calls made by the script being run |
|
1235 | # Control the response to exit() calls made by the script being run | |
1250 | exit_ignore = opts.has_key('e') |
|
1236 | exit_ignore = opts.has_key('e') | |
1251 |
|
1237 | |||
1252 | # Make sure that the running script gets a proper sys.argv as if it |
|
1238 | # Make sure that the running script gets a proper sys.argv as if it | |
1253 | # were run from a system shell. |
|
1239 | # were run from a system shell. | |
1254 | save_argv = sys.argv # save it for later restoring |
|
1240 | save_argv = sys.argv # save it for later restoring | |
1255 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1241 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1256 |
|
1242 | |||
1257 | if opts.has_key('i'): |
|
1243 | if opts.has_key('i'): | |
1258 | prog_ns = self.shell.user_ns |
|
1244 | prog_ns = self.shell.user_ns | |
1259 | __name__save = self.shell.user_ns['__name__'] |
|
1245 | __name__save = self.shell.user_ns['__name__'] | |
1260 | prog_ns['__name__'] = '__main__' |
|
1246 | prog_ns['__name__'] = '__main__' | |
1261 | else: |
|
1247 | else: | |
1262 | if opts.has_key('n'): |
|
1248 | if opts.has_key('n'): | |
1263 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1249 | name = os.path.splitext(os.path.basename(filename))[0] | |
1264 | else: |
|
1250 | else: | |
1265 | name = '__main__' |
|
1251 | name = '__main__' | |
1266 | prog_ns = {'__name__':name} |
|
1252 | prog_ns = {'__name__':name} | |
1267 |
|
1253 | |||
1268 | # pickle fix. See iplib for an explanation |
|
1254 | # pickle fix. See iplib for an explanation | |
1269 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1255 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) | |
1270 |
|
1256 | |||
1271 | stats = None |
|
1257 | stats = None | |
1272 | try: |
|
1258 | try: | |
1273 | if opts.has_key('p'): |
|
1259 | if opts.has_key('p'): | |
1274 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1260 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1275 | else: |
|
1261 | else: | |
1276 | if opts.has_key('d'): |
|
1262 | if opts.has_key('d'): | |
1277 | deb = pdb.Pdb() |
|
1263 | deb = pdb.Pdb() | |
1278 | # reset Breakpoint state, which is moronically kept |
|
1264 | # reset Breakpoint state, which is moronically kept | |
1279 | # in a class |
|
1265 | # in a class | |
1280 | bdb.Breakpoint.next = 1 |
|
1266 | bdb.Breakpoint.next = 1 | |
1281 | bdb.Breakpoint.bplist = {} |
|
1267 | bdb.Breakpoint.bplist = {} | |
1282 | bdb.Breakpoint.bpbynumber = [None] |
|
1268 | bdb.Breakpoint.bpbynumber = [None] | |
1283 | # Set an initial breakpoint to stop execution |
|
1269 | # Set an initial breakpoint to stop execution | |
1284 | maxtries = 10 |
|
1270 | maxtries = 10 | |
1285 | bp = int(opts.get('b',[1])[0]) |
|
1271 | bp = int(opts.get('b',[1])[0]) | |
1286 | checkline = deb.checkline(filename,bp) |
|
1272 | checkline = deb.checkline(filename,bp) | |
1287 | if not checkline: |
|
1273 | if not checkline: | |
1288 | for bp in range(bp+1,bp+maxtries+1): |
|
1274 | for bp in range(bp+1,bp+maxtries+1): | |
1289 | if deb.checkline(filename,bp): |
|
1275 | if deb.checkline(filename,bp): | |
1290 | break |
|
1276 | break | |
1291 | else: |
|
1277 | else: | |
1292 | msg = ("\nI failed to find a valid line to set " |
|
1278 | msg = ("\nI failed to find a valid line to set " | |
1293 | "a breakpoint\n" |
|
1279 | "a breakpoint\n" | |
1294 | "after trying up to line: %s.\n" |
|
1280 | "after trying up to line: %s.\n" | |
1295 | "Please set a valid breakpoint manually " |
|
1281 | "Please set a valid breakpoint manually " | |
1296 | "with the -b option." % bp) |
|
1282 | "with the -b option." % bp) | |
1297 | error(msg) |
|
1283 | error(msg) | |
1298 | return |
|
1284 | return | |
1299 | # if we find a good linenumber, set the breakpoint |
|
1285 | # if we find a good linenumber, set the breakpoint | |
1300 | deb.do_break('%s:%s' % (filename,bp)) |
|
1286 | deb.do_break('%s:%s' % (filename,bp)) | |
1301 | # Start file run |
|
1287 | # Start file run | |
1302 | print "NOTE: Enter 'c' at the", |
|
1288 | print "NOTE: Enter 'c' at the", | |
1303 | print "(Pdb) prompt to start your script." |
|
1289 | print "(Pdb) prompt to start your script." | |
1304 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1290 | deb.run('execfile("%s")' % filename,prog_ns) | |
1305 | else: |
|
1291 | else: | |
1306 | if runner is None: |
|
1292 | if runner is None: | |
1307 | runner = self.shell.safe_execfile |
|
1293 | runner = self.shell.safe_execfile | |
1308 | if opts.has_key('t'): |
|
1294 | if opts.has_key('t'): | |
1309 | try: |
|
1295 | try: | |
1310 | nruns = int(opts['N'][0]) |
|
1296 | nruns = int(opts['N'][0]) | |
1311 | if nruns < 1: |
|
1297 | if nruns < 1: | |
1312 | error('Number of runs must be >=1') |
|
1298 | error('Number of runs must be >=1') | |
1313 | return |
|
1299 | return | |
1314 | except (KeyError): |
|
1300 | except (KeyError): | |
1315 | nruns = 1 |
|
1301 | nruns = 1 | |
1316 | if nruns == 1: |
|
1302 | if nruns == 1: | |
1317 | t0 = clock2() |
|
1303 | t0 = clock2() | |
1318 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1304 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1319 | t1 = clock2() |
|
1305 | t1 = clock2() | |
1320 | t_usr = t1[0]-t0[0] |
|
1306 | t_usr = t1[0]-t0[0] | |
1321 | t_sys = t1[1]-t1[1] |
|
1307 | t_sys = t1[1]-t1[1] | |
1322 | print "\nIPython CPU timings (estimated):" |
|
1308 | print "\nIPython CPU timings (estimated):" | |
1323 | print " User : %10s s." % t_usr |
|
1309 | print " User : %10s s." % t_usr | |
1324 | print " System: %10s s." % t_sys |
|
1310 | print " System: %10s s." % t_sys | |
1325 | else: |
|
1311 | else: | |
1326 | runs = range(nruns) |
|
1312 | runs = range(nruns) | |
1327 | t0 = clock2() |
|
1313 | t0 = clock2() | |
1328 | for nr in runs: |
|
1314 | for nr in runs: | |
1329 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1315 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1330 | t1 = clock2() |
|
1316 | t1 = clock2() | |
1331 | t_usr = t1[0]-t0[0] |
|
1317 | t_usr = t1[0]-t0[0] | |
1332 | t_sys = t1[1]-t1[1] |
|
1318 | t_sys = t1[1]-t1[1] | |
1333 | print "\nIPython CPU timings (estimated):" |
|
1319 | print "\nIPython CPU timings (estimated):" | |
1334 | print "Total runs performed:",nruns |
|
1320 | print "Total runs performed:",nruns | |
1335 | print " Times : %10s %10s" % ('Total','Per run') |
|
1321 | print " Times : %10s %10s" % ('Total','Per run') | |
1336 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1322 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1337 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1323 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1338 |
|
1324 | |||
1339 | else: |
|
1325 | else: | |
1340 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1326 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1341 | if opts.has_key('i'): |
|
1327 | if opts.has_key('i'): | |
1342 | self.shell.user_ns['__name__'] = __name__save |
|
1328 | self.shell.user_ns['__name__'] = __name__save | |
1343 | else: |
|
1329 | else: | |
1344 | # update IPython interactive namespace |
|
1330 | # update IPython interactive namespace | |
1345 | del prog_ns['__name__'] |
|
1331 | del prog_ns['__name__'] | |
1346 | self.shell.user_ns.update(prog_ns) |
|
1332 | self.shell.user_ns.update(prog_ns) | |
1347 | finally: |
|
1333 | finally: | |
1348 | sys.argv = save_argv |
|
1334 | sys.argv = save_argv | |
1349 | return stats |
|
1335 | return stats | |
1350 |
|
1336 | |||
1351 | def magic_runlog(self, parameter_s =''): |
|
1337 | def magic_runlog(self, parameter_s =''): | |
1352 | """Run files as logs. |
|
1338 | """Run files as logs. | |
1353 |
|
1339 | |||
1354 | Usage:\\ |
|
1340 | Usage:\\ | |
1355 | %runlog file1 file2 ... |
|
1341 | %runlog file1 file2 ... | |
1356 |
|
1342 | |||
1357 | Run the named files (treating them as log files) in sequence inside |
|
1343 | Run the named files (treating them as log files) in sequence inside | |
1358 | the interpreter, and return to the prompt. This is much slower than |
|
1344 | the interpreter, and return to the prompt. This is much slower than | |
1359 | %run because each line is executed in a try/except block, but it |
|
1345 | %run because each line is executed in a try/except block, but it | |
1360 | allows running files with syntax errors in them. |
|
1346 | allows running files with syntax errors in them. | |
1361 |
|
1347 | |||
1362 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1348 | Normally IPython will guess when a file is one of its own logfiles, so | |
1363 | you can typically use %run even for logs. This shorthand allows you to |
|
1349 | you can typically use %run even for logs. This shorthand allows you to | |
1364 | force any file to be treated as a log file.""" |
|
1350 | force any file to be treated as a log file.""" | |
1365 |
|
1351 | |||
1366 | for f in parameter_s.split(): |
|
1352 | for f in parameter_s.split(): | |
1367 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1353 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1368 | self.shell.user_ns,islog=1) |
|
1354 | self.shell.user_ns,islog=1) | |
1369 |
|
1355 | |||
1370 | def magic_time(self,parameter_s = ''): |
|
1356 | def magic_time(self,parameter_s = ''): | |
1371 | """Time execution of a Python statement or expression. |
|
1357 | """Time execution of a Python statement or expression. | |
1372 |
|
1358 | |||
1373 | The CPU and wall clock times are printed, and the value of the |
|
1359 | The CPU and wall clock times are printed, and the value of the | |
1374 | expression (if any) is returned. Note that under Win32, system time |
|
1360 | expression (if any) is returned. Note that under Win32, system time | |
1375 | is always reported as 0, since it can not be measured. |
|
1361 | is always reported as 0, since it can not be measured. | |
1376 |
|
1362 | |||
1377 | This function provides very basic timing functionality. In Python |
|
1363 | This function provides very basic timing functionality. In Python | |
1378 | 2.3, the timeit module offers more control and sophistication, but for |
|
1364 | 2.3, the timeit module offers more control and sophistication, but for | |
1379 | now IPython supports Python 2.2, so we can not rely on timeit being |
|
1365 | now IPython supports Python 2.2, so we can not rely on timeit being | |
1380 | present. |
|
1366 | present. | |
1381 |
|
1367 | |||
1382 | Some examples: |
|
1368 | Some examples: | |
1383 |
|
1369 | |||
1384 | In [1]: time 2**128 |
|
1370 | In [1]: time 2**128 | |
1385 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1371 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1386 | Wall time: 0.00 |
|
1372 | Wall time: 0.00 | |
1387 | Out[1]: 340282366920938463463374607431768211456L |
|
1373 | Out[1]: 340282366920938463463374607431768211456L | |
1388 |
|
1374 | |||
1389 | In [2]: n = 1000000 |
|
1375 | In [2]: n = 1000000 | |
1390 |
|
1376 | |||
1391 | In [3]: time sum(range(n)) |
|
1377 | In [3]: time sum(range(n)) | |
1392 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1378 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1393 | Wall time: 1.37 |
|
1379 | Wall time: 1.37 | |
1394 | Out[3]: 499999500000L |
|
1380 | Out[3]: 499999500000L | |
1395 |
|
1381 | |||
1396 | In [4]: time print 'hello world' |
|
1382 | In [4]: time print 'hello world' | |
1397 | hello world |
|
1383 | hello world | |
1398 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1384 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1399 | Wall time: 0.00 |
|
1385 | Wall time: 0.00 | |
1400 | """ |
|
1386 | """ | |
1401 |
|
1387 | |||
1402 | # fail immediately if the given expression can't be compiled |
|
1388 | # fail immediately if the given expression can't be compiled | |
1403 | try: |
|
1389 | try: | |
1404 | mode = 'eval' |
|
1390 | mode = 'eval' | |
1405 | code = compile(parameter_s,'<timed eval>',mode) |
|
1391 | code = compile(parameter_s,'<timed eval>',mode) | |
1406 | except SyntaxError: |
|
1392 | except SyntaxError: | |
1407 | mode = 'exec' |
|
1393 | mode = 'exec' | |
1408 | code = compile(parameter_s,'<timed exec>',mode) |
|
1394 | code = compile(parameter_s,'<timed exec>',mode) | |
1409 | # skew measurement as little as possible |
|
1395 | # skew measurement as little as possible | |
1410 | glob = self.shell.user_ns |
|
1396 | glob = self.shell.user_ns | |
1411 | clk = clock2 |
|
1397 | clk = clock2 | |
1412 | wtime = time.time |
|
1398 | wtime = time.time | |
1413 | # time execution |
|
1399 | # time execution | |
1414 | wall_st = wtime() |
|
1400 | wall_st = wtime() | |
1415 | if mode=='eval': |
|
1401 | if mode=='eval': | |
1416 | st = clk() |
|
1402 | st = clk() | |
1417 | out = eval(code,glob) |
|
1403 | out = eval(code,glob) | |
1418 | end = clk() |
|
1404 | end = clk() | |
1419 | else: |
|
1405 | else: | |
1420 | st = clk() |
|
1406 | st = clk() | |
1421 | exec code in glob |
|
1407 | exec code in glob | |
1422 | end = clk() |
|
1408 | end = clk() | |
1423 | out = None |
|
1409 | out = None | |
1424 | wall_end = wtime() |
|
1410 | wall_end = wtime() | |
1425 | # Compute actual times and report |
|
1411 | # Compute actual times and report | |
1426 | wall_time = wall_end-wall_st |
|
1412 | wall_time = wall_end-wall_st | |
1427 | cpu_user = end[0]-st[0] |
|
1413 | cpu_user = end[0]-st[0] | |
1428 | cpu_sys = end[1]-st[1] |
|
1414 | cpu_sys = end[1]-st[1] | |
1429 | cpu_tot = cpu_user+cpu_sys |
|
1415 | cpu_tot = cpu_user+cpu_sys | |
1430 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1416 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1431 | (cpu_user,cpu_sys,cpu_tot) |
|
1417 | (cpu_user,cpu_sys,cpu_tot) | |
1432 | print "Wall time: %.2f" % wall_time |
|
1418 | print "Wall time: %.2f" % wall_time | |
1433 | return out |
|
1419 | return out | |
1434 |
|
1420 | |||
1435 | def magic_macro(self,parameter_s = ''): |
|
1421 | def magic_macro(self,parameter_s = ''): | |
1436 | """Define a set of input lines as a macro for future re-execution. |
|
1422 | """Define a set of input lines as a macro for future re-execution. | |
1437 |
|
1423 | |||
1438 | Usage:\\ |
|
1424 | Usage:\\ | |
1439 | %macro name n1:n2 n3:n4 ... n5 .. n6 ... |
|
1425 | %macro name n1:n2 n3:n4 ... n5 .. n6 ... | |
1440 |
|
1426 | |||
1441 | This will define a global variable called `name` which is a string |
|
1427 | This will define a global variable called `name` which is a string | |
1442 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1428 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1443 | above) from your input history into a single string. This variable |
|
1429 | above) from your input history into a single string. This variable | |
1444 | acts like an automatic function which re-executes those lines as if |
|
1430 | acts like an automatic function which re-executes those lines as if | |
1445 | you had typed them. You just type 'name' at the prompt and the code |
|
1431 | you had typed them. You just type 'name' at the prompt and the code | |
1446 | executes. |
|
1432 | executes. | |
1447 |
|
1433 | |||
1448 | Note that the slices use the standard Python slicing notation (5:8 |
|
1434 | Note that the slices use the standard Python slicing notation (5:8 | |
1449 | means include lines numbered 5,6,7). |
|
1435 | means include lines numbered 5,6,7). | |
1450 |
|
1436 | |||
1451 | For example, if your history contains (%hist prints it): |
|
1437 | For example, if your history contains (%hist prints it): | |
1452 |
|
1438 | |||
1453 | 44: x=1\\ |
|
1439 | 44: x=1\\ | |
1454 | 45: y=3\\ |
|
1440 | 45: y=3\\ | |
1455 | 46: z=x+y\\ |
|
1441 | 46: z=x+y\\ | |
1456 | 47: print x\\ |
|
1442 | 47: print x\\ | |
1457 | 48: a=5\\ |
|
1443 | 48: a=5\\ | |
1458 | 49: print 'x',x,'y',y\\ |
|
1444 | 49: print 'x',x,'y',y\\ | |
1459 |
|
1445 | |||
1460 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1446 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1461 | called my_macro with: |
|
1447 | called my_macro with: | |
1462 |
|
1448 | |||
1463 | In [51]: %macro my_macro 44:48 49 |
|
1449 | In [51]: %macro my_macro 44:48 49 | |
1464 |
|
1450 | |||
1465 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1451 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1466 | in one pass. |
|
1452 | in one pass. | |
1467 |
|
1453 | |||
1468 | You don't need to give the line-numbers in order, and any given line |
|
1454 | You don't need to give the line-numbers in order, and any given line | |
1469 | number can appear multiple times. You can assemble macros with any |
|
1455 | number can appear multiple times. You can assemble macros with any | |
1470 | lines from your input history in any order. |
|
1456 | lines from your input history in any order. | |
1471 |
|
1457 | |||
1472 | The macro is a simple object which holds its value in an attribute, |
|
1458 | The macro is a simple object which holds its value in an attribute, | |
1473 | but IPython's display system checks for macros and executes them as |
|
1459 | but IPython's display system checks for macros and executes them as | |
1474 | code instead of printing them when you type their name. |
|
1460 | code instead of printing them when you type their name. | |
1475 |
|
1461 | |||
1476 | You can view a macro's contents by explicitly printing it with: |
|
1462 | You can view a macro's contents by explicitly printing it with: | |
1477 |
|
1463 | |||
1478 | 'print macro_name'. |
|
1464 | 'print macro_name'. | |
1479 |
|
1465 | |||
1480 | For one-off cases which DON'T contain magic function calls in them you |
|
1466 | For one-off cases which DON'T contain magic function calls in them you | |
1481 | can obtain similar results by explicitly executing slices from your |
|
1467 | can obtain similar results by explicitly executing slices from your | |
1482 | input history with: |
|
1468 | input history with: | |
1483 |
|
1469 | |||
1484 | In [60]: exec In[44:48]+In[49]""" |
|
1470 | In [60]: exec In[44:48]+In[49]""" | |
1485 |
|
1471 | |||
1486 | args = parameter_s.split() |
|
1472 | args = parameter_s.split() | |
1487 | name,ranges = args[0], args[1:] |
|
1473 | name,ranges = args[0], args[1:] | |
1488 | #print 'rng',ranges # dbg |
|
1474 | #print 'rng',ranges # dbg | |
1489 | cmds = self.extract_input_slices(ranges) |
|
1475 | cmds = self.extract_input_slices(ranges) | |
1490 | macro = Macro(cmds) |
|
1476 | macro = Macro(cmds) | |
1491 | self.shell.user_ns.update({name:macro}) |
|
1477 | self.shell.user_ns.update({name:macro}) | |
1492 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1478 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1493 | print 'Macro contents:' |
|
1479 | print 'Macro contents:' | |
1494 | print str(macro).rstrip(), |
|
1480 | print str(macro).rstrip(), | |
1495 |
|
1481 | |||
1496 | def magic_save(self,parameter_s = ''): |
|
1482 | def magic_save(self,parameter_s = ''): | |
1497 | """Save a set of lines to a given filename. |
|
1483 | """Save a set of lines to a given filename. | |
1498 |
|
1484 | |||
1499 | Usage:\\ |
|
1485 | Usage:\\ | |
1500 | %save filename n1:n2 n3:n4 ... n5 .. n6 ... |
|
1486 | %save filename n1:n2 n3:n4 ... n5 .. n6 ... | |
1501 |
|
1487 | |||
1502 | This function uses the same syntax as %macro for line extraction, but |
|
1488 | This function uses the same syntax as %macro for line extraction, but | |
1503 | instead of creating a macro it saves the resulting string to the |
|
1489 | instead of creating a macro it saves the resulting string to the | |
1504 | filename you specify. |
|
1490 | filename you specify. | |
1505 |
|
1491 | |||
1506 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1492 | It adds a '.py' extension to the file if you don't do so yourself, and | |
1507 | it asks for confirmation before overwriting existing files.""" |
|
1493 | it asks for confirmation before overwriting existing files.""" | |
1508 |
|
1494 | |||
1509 | args = parameter_s.split() |
|
1495 | args = parameter_s.split() | |
1510 | fname,ranges = args[0], args[1:] |
|
1496 | fname,ranges = args[0], args[1:] | |
1511 | if not fname.endswith('.py'): |
|
1497 | if not fname.endswith('.py'): | |
1512 | fname += '.py' |
|
1498 | fname += '.py' | |
1513 | if os.path.isfile(fname): |
|
1499 | if os.path.isfile(fname): | |
1514 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1500 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
1515 | if ans.lower() not in ['y','yes']: |
|
1501 | if ans.lower() not in ['y','yes']: | |
1516 | print 'Operation cancelled.' |
|
1502 | print 'Operation cancelled.' | |
1517 | return |
|
1503 | return | |
1518 | cmds = ''.join(self.extract_input_slices(ranges)) |
|
1504 | cmds = ''.join(self.extract_input_slices(ranges)) | |
1519 | f = file(fname,'w') |
|
1505 | f = file(fname,'w') | |
1520 | f.write(cmds) |
|
1506 | f.write(cmds) | |
1521 | f.close() |
|
1507 | f.close() | |
1522 | print 'The following commands were written to file `%s`:' % fname |
|
1508 | print 'The following commands were written to file `%s`:' % fname | |
1523 | print cmds |
|
1509 | print cmds | |
1524 |
|
1510 | |||
1525 | def magic_ed(self,parameter_s = ''): |
|
1511 | def magic_ed(self,parameter_s = ''): | |
1526 | """Alias to %edit.""" |
|
1512 | """Alias to %edit.""" | |
1527 | return self.magic_edit(parameter_s) |
|
1513 | return self.magic_edit(parameter_s) | |
1528 |
|
1514 | |||
1529 | def magic_edit(self,parameter_s = '',last_call=['','']): |
|
1515 | def magic_edit(self,parameter_s = '',last_call=['','']): | |
1530 | """Bring up an editor and execute the resulting code. |
|
1516 | """Bring up an editor and execute the resulting code. | |
1531 |
|
1517 | |||
1532 | Usage: |
|
1518 | Usage: | |
1533 | %edit [options] [args] |
|
1519 | %edit [options] [args] | |
1534 |
|
1520 | |||
1535 | %edit runs IPython's editor hook. The default version of this hook is |
|
1521 | %edit runs IPython's editor hook. The default version of this hook is | |
1536 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1522 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
1537 | environment variable $EDITOR. If this isn't found, it will default to |
|
1523 | environment variable $EDITOR. If this isn't found, it will default to | |
1538 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1524 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
1539 | docstring for how to change the editor hook. |
|
1525 | docstring for how to change the editor hook. | |
1540 |
|
1526 | |||
1541 | You can also set the value of this editor via the command line option |
|
1527 | You can also set the value of this editor via the command line option | |
1542 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
1528 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
1543 | specifically for IPython an editor different from your typical default |
|
1529 | specifically for IPython an editor different from your typical default | |
1544 | (and for Windows users who typically don't set environment variables). |
|
1530 | (and for Windows users who typically don't set environment variables). | |
1545 |
|
1531 | |||
1546 | This command allows you to conveniently edit multi-line code right in |
|
1532 | This command allows you to conveniently edit multi-line code right in | |
1547 | your IPython session. |
|
1533 | your IPython session. | |
1548 |
|
1534 | |||
1549 | If called without arguments, %edit opens up an empty editor with a |
|
1535 | If called without arguments, %edit opens up an empty editor with a | |
1550 | temporary file and will execute the contents of this file when you |
|
1536 | temporary file and will execute the contents of this file when you | |
1551 | close it (don't forget to save it!). |
|
1537 | close it (don't forget to save it!). | |
1552 |
|
1538 | |||
1553 | Options: |
|
1539 | Options: | |
1554 |
|
1540 | |||
1555 | -p: this will call the editor with the same data as the previous time |
|
1541 | -p: this will call the editor with the same data as the previous time | |
1556 | it was used, regardless of how long ago (in your current session) it |
|
1542 | it was used, regardless of how long ago (in your current session) it | |
1557 | was. |
|
1543 | was. | |
1558 |
|
1544 | |||
1559 | -x: do not execute the edited code immediately upon exit. This is |
|
1545 | -x: do not execute the edited code immediately upon exit. This is | |
1560 | mainly useful if you are editing programs which need to be called with |
|
1546 | mainly useful if you are editing programs which need to be called with | |
1561 | command line arguments, which you can then do using %run. |
|
1547 | command line arguments, which you can then do using %run. | |
1562 |
|
1548 | |||
1563 | Arguments: |
|
1549 | Arguments: | |
1564 |
|
1550 | |||
1565 | If arguments are given, the following possibilites exist: |
|
1551 | If arguments are given, the following possibilites exist: | |
1566 |
|
1552 | |||
1567 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
1553 | - The arguments are numbers or pairs of colon-separated numbers (like | |
1568 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
1554 | 1 4:8 9). These are interpreted as lines of previous input to be | |
1569 | loaded into the editor. The syntax is the same of the %macro command. |
|
1555 | loaded into the editor. The syntax is the same of the %macro command. | |
1570 |
|
1556 | |||
1571 | - If the argument doesn't start with a number, it is evaluated as a |
|
1557 | - If the argument doesn't start with a number, it is evaluated as a | |
1572 | variable and its contents loaded into the editor. You can thus edit |
|
1558 | variable and its contents loaded into the editor. You can thus edit | |
1573 | any string which contains python code (including the result of |
|
1559 | any string which contains python code (including the result of | |
1574 | previous edits). |
|
1560 | previous edits). | |
1575 |
|
1561 | |||
1576 | - If the argument is the name of an object (other than a string), |
|
1562 | - If the argument is the name of an object (other than a string), | |
1577 | IPython will try to locate the file where it was defined and open the |
|
1563 | IPython will try to locate the file where it was defined and open the | |
1578 | editor at the point where it is defined. You can use `%edit function` |
|
1564 | editor at the point where it is defined. You can use `%edit function` | |
1579 | to load an editor exactly at the point where 'function' is defined, |
|
1565 | to load an editor exactly at the point where 'function' is defined, | |
1580 | edit it and have the file be executed automatically. |
|
1566 | edit it and have the file be executed automatically. | |
1581 |
|
1567 | |||
1582 | Note: opening at an exact line is only supported under Unix, and some |
|
1568 | Note: opening at an exact line is only supported under Unix, and some | |
1583 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
1569 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
1584 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
1570 | '+NUMBER' parameter necessary for this feature. Good editors like | |
1585 | (X)Emacs, vi, jed, pico and joe all do. |
|
1571 | (X)Emacs, vi, jed, pico and joe all do. | |
1586 |
|
1572 | |||
1587 | - If the argument is not found as a variable, IPython will look for a |
|
1573 | - If the argument is not found as a variable, IPython will look for a | |
1588 | file with that name (adding .py if necessary) and load it into the |
|
1574 | file with that name (adding .py if necessary) and load it into the | |
1589 | editor. It will execute its contents with execfile() when you exit, |
|
1575 | editor. It will execute its contents with execfile() when you exit, | |
1590 | loading any code in the file into your interactive namespace. |
|
1576 | loading any code in the file into your interactive namespace. | |
1591 |
|
1577 | |||
1592 | After executing your code, %edit will return as output the code you |
|
1578 | After executing your code, %edit will return as output the code you | |
1593 | typed in the editor (except when it was an existing file). This way |
|
1579 | typed in the editor (except when it was an existing file). This way | |
1594 | you can reload the code in further invocations of %edit as a variable, |
|
1580 | you can reload the code in further invocations of %edit as a variable, | |
1595 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
1581 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
1596 | the output. |
|
1582 | the output. | |
1597 |
|
1583 | |||
1598 | Note that %edit is also available through the alias %ed. |
|
1584 | Note that %edit is also available through the alias %ed. | |
1599 |
|
1585 | |||
1600 | This is an example of creating a simple function inside the editor and |
|
1586 | This is an example of creating a simple function inside the editor and | |
1601 | then modifying it. First, start up the editor: |
|
1587 | then modifying it. First, start up the editor: | |
1602 |
|
1588 | |||
1603 | In [1]: ed\\ |
|
1589 | In [1]: ed\\ | |
1604 | Editing... done. Executing edited code...\\ |
|
1590 | Editing... done. Executing edited code...\\ | |
1605 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
1591 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' | |
1606 |
|
1592 | |||
1607 | We can then call the function foo(): |
|
1593 | We can then call the function foo(): | |
1608 |
|
1594 | |||
1609 | In [2]: foo()\\ |
|
1595 | In [2]: foo()\\ | |
1610 | foo() was defined in an editing session |
|
1596 | foo() was defined in an editing session | |
1611 |
|
1597 | |||
1612 | Now we edit foo. IPython automatically loads the editor with the |
|
1598 | Now we edit foo. IPython automatically loads the editor with the | |
1613 | (temporary) file where foo() was previously defined: |
|
1599 | (temporary) file where foo() was previously defined: | |
1614 |
|
1600 | |||
1615 | In [3]: ed foo\\ |
|
1601 | In [3]: ed foo\\ | |
1616 | Editing... done. Executing edited code... |
|
1602 | Editing... done. Executing edited code... | |
1617 |
|
1603 | |||
1618 | And if we call foo() again we get the modified version: |
|
1604 | And if we call foo() again we get the modified version: | |
1619 |
|
1605 | |||
1620 | In [4]: foo()\\ |
|
1606 | In [4]: foo()\\ | |
1621 | foo() has now been changed! |
|
1607 | foo() has now been changed! | |
1622 |
|
1608 | |||
1623 | Here is an example of how to edit a code snippet successive |
|
1609 | Here is an example of how to edit a code snippet successive | |
1624 | times. First we call the editor: |
|
1610 | times. First we call the editor: | |
1625 |
|
1611 | |||
1626 | In [8]: ed\\ |
|
1612 | In [8]: ed\\ | |
1627 | Editing... done. Executing edited code...\\ |
|
1613 | Editing... done. Executing edited code...\\ | |
1628 | hello\\ |
|
1614 | hello\\ | |
1629 | Out[8]: "print 'hello'\\n" |
|
1615 | Out[8]: "print 'hello'\\n" | |
1630 |
|
1616 | |||
1631 | Now we call it again with the previous output (stored in _): |
|
1617 | Now we call it again with the previous output (stored in _): | |
1632 |
|
1618 | |||
1633 | In [9]: ed _\\ |
|
1619 | In [9]: ed _\\ | |
1634 | Editing... done. Executing edited code...\\ |
|
1620 | Editing... done. Executing edited code...\\ | |
1635 | hello world\\ |
|
1621 | hello world\\ | |
1636 | Out[9]: "print 'hello world'\\n" |
|
1622 | Out[9]: "print 'hello world'\\n" | |
1637 |
|
1623 | |||
1638 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
1624 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
1639 |
|
1625 | |||
1640 | In [10]: ed _8\\ |
|
1626 | In [10]: ed _8\\ | |
1641 | Editing... done. Executing edited code...\\ |
|
1627 | Editing... done. Executing edited code...\\ | |
1642 | hello again\\ |
|
1628 | hello again\\ | |
1643 | Out[10]: "print 'hello again'\\n" |
|
1629 | Out[10]: "print 'hello again'\\n" | |
1644 |
|
1630 | |||
1645 |
|
1631 | |||
1646 | Changing the default editor hook: |
|
1632 | Changing the default editor hook: | |
1647 |
|
1633 | |||
1648 | If you wish to write your own editor hook, you can put it in a |
|
1634 | If you wish to write your own editor hook, you can put it in a | |
1649 | configuration file which you load at startup time. The default hook |
|
1635 | configuration file which you load at startup time. The default hook | |
1650 | is defined in the IPython.hooks module, and you can use that as a |
|
1636 | is defined in the IPython.hooks module, and you can use that as a | |
1651 | starting example for further modifications. That file also has |
|
1637 | starting example for further modifications. That file also has | |
1652 | general instructions on how to set a new hook for use once you've |
|
1638 | general instructions on how to set a new hook for use once you've | |
1653 | defined it.""" |
|
1639 | defined it.""" | |
1654 |
|
1640 | |||
1655 | # FIXME: This function has become a convoluted mess. It needs a |
|
1641 | # FIXME: This function has become a convoluted mess. It needs a | |
1656 | # ground-up rewrite with clean, simple logic. |
|
1642 | # ground-up rewrite with clean, simple logic. | |
1657 |
|
1643 | |||
1658 | def make_filename(arg): |
|
1644 | def make_filename(arg): | |
1659 | "Make a filename from the given args" |
|
1645 | "Make a filename from the given args" | |
1660 | try: |
|
1646 | try: | |
1661 | filename = get_py_filename(arg) |
|
1647 | filename = get_py_filename(arg) | |
1662 | except IOError: |
|
1648 | except IOError: | |
1663 | if args.endswith('.py'): |
|
1649 | if args.endswith('.py'): | |
1664 | filename = arg |
|
1650 | filename = arg | |
1665 | else: |
|
1651 | else: | |
1666 | filename = None |
|
1652 | filename = None | |
1667 | return filename |
|
1653 | return filename | |
1668 |
|
1654 | |||
1669 | # custom exceptions |
|
1655 | # custom exceptions | |
1670 | class DataIsObject(Exception): pass |
|
1656 | class DataIsObject(Exception): pass | |
1671 |
|
1657 | |||
1672 | opts,args = self.parse_options(parameter_s,'px') |
|
1658 | opts,args = self.parse_options(parameter_s,'px') | |
1673 |
|
1659 | |||
1674 | # Default line number value |
|
1660 | # Default line number value | |
1675 | lineno = None |
|
1661 | lineno = None | |
1676 | if opts.has_key('p'): |
|
1662 | if opts.has_key('p'): | |
1677 | args = '_%s' % last_call[0] |
|
1663 | args = '_%s' % last_call[0] | |
1678 | if not self.shell.user_ns.has_key(args): |
|
1664 | if not self.shell.user_ns.has_key(args): | |
1679 | args = last_call[1] |
|
1665 | args = last_call[1] | |
1680 |
|
1666 | |||
1681 | # use last_call to remember the state of the previous call, but don't |
|
1667 | # use last_call to remember the state of the previous call, but don't | |
1682 | # let it be clobbered by successive '-p' calls. |
|
1668 | # let it be clobbered by successive '-p' calls. | |
1683 | try: |
|
1669 | try: | |
1684 | last_call[0] = self.shell.outputcache.prompt_count |
|
1670 | last_call[0] = self.shell.outputcache.prompt_count | |
1685 | if not opts.has_key('p'): |
|
1671 | if not opts.has_key('p'): | |
1686 | last_call[1] = parameter_s |
|
1672 | last_call[1] = parameter_s | |
1687 | except: |
|
1673 | except: | |
1688 | pass |
|
1674 | pass | |
1689 |
|
1675 | |||
1690 | # by default this is done with temp files, except when the given |
|
1676 | # by default this is done with temp files, except when the given | |
1691 | # arg is a filename |
|
1677 | # arg is a filename | |
1692 | use_temp = 1 |
|
1678 | use_temp = 1 | |
1693 |
|
1679 | |||
1694 | if re.match(r'\d',args): |
|
1680 | if re.match(r'\d',args): | |
1695 | # Mode where user specifies ranges of lines, like in %macro. |
|
1681 | # Mode where user specifies ranges of lines, like in %macro. | |
1696 | # This means that you can't edit files whose names begin with |
|
1682 | # This means that you can't edit files whose names begin with | |
1697 | # numbers this way. Tough. |
|
1683 | # numbers this way. Tough. | |
1698 | ranges = args.split() |
|
1684 | ranges = args.split() | |
1699 | data = ''.join(self.extract_input_slices(ranges)) |
|
1685 | data = ''.join(self.extract_input_slices(ranges)) | |
1700 | elif args.endswith('.py'): |
|
1686 | elif args.endswith('.py'): | |
1701 | filename = make_filename(args) |
|
1687 | filename = make_filename(args) | |
1702 | data = '' |
|
1688 | data = '' | |
1703 | use_temp = 0 |
|
1689 | use_temp = 0 | |
1704 | elif args: |
|
1690 | elif args: | |
1705 | try: |
|
1691 | try: | |
1706 | # Load the parameter given as a variable. If not a string, |
|
1692 | # Load the parameter given as a variable. If not a string, | |
1707 | # process it as an object instead (below) |
|
1693 | # process it as an object instead (below) | |
1708 |
|
1694 | |||
1709 | #print '*** args',args,'type',type(args) # dbg |
|
1695 | #print '*** args',args,'type',type(args) # dbg | |
1710 | data = eval(args,self.shell.user_ns) |
|
1696 | data = eval(args,self.shell.user_ns) | |
1711 | if not type(data) in StringTypes: |
|
1697 | if not type(data) in StringTypes: | |
1712 | raise DataIsObject |
|
1698 | raise DataIsObject | |
1713 | except (NameError,SyntaxError): |
|
1699 | except (NameError,SyntaxError): | |
1714 | # given argument is not a variable, try as a filename |
|
1700 | # given argument is not a variable, try as a filename | |
1715 | filename = make_filename(args) |
|
1701 | filename = make_filename(args) | |
1716 | if filename is None: |
|
1702 | if filename is None: | |
1717 | warn("Argument given (%s) can't be found as a variable " |
|
1703 | warn("Argument given (%s) can't be found as a variable " | |
1718 | "or as a filename." % args) |
|
1704 | "or as a filename." % args) | |
1719 | return |
|
1705 | return | |
1720 | data = '' |
|
1706 | data = '' | |
1721 | use_temp = 0 |
|
1707 | use_temp = 0 | |
1722 | except DataIsObject: |
|
1708 | except DataIsObject: | |
1723 | # For objects, try to edit the file where they are defined |
|
1709 | # For objects, try to edit the file where they are defined | |
1724 | try: |
|
1710 | try: | |
1725 | filename = inspect.getabsfile(data) |
|
1711 | filename = inspect.getabsfile(data) | |
1726 | datafile = 1 |
|
1712 | datafile = 1 | |
1727 | except TypeError: |
|
1713 | except TypeError: | |
1728 | filename = make_filename(args) |
|
1714 | filename = make_filename(args) | |
1729 | datafile = 1 |
|
1715 | datafile = 1 | |
1730 | warn('Could not find file where `%s` is defined.\n' |
|
1716 | warn('Could not find file where `%s` is defined.\n' | |
1731 | 'Opening a file named `%s`' % (args,filename)) |
|
1717 | 'Opening a file named `%s`' % (args,filename)) | |
1732 | # Now, make sure we can actually read the source (if it was in |
|
1718 | # Now, make sure we can actually read the source (if it was in | |
1733 | # a temp file it's gone by now). |
|
1719 | # a temp file it's gone by now). | |
1734 | if datafile: |
|
1720 | if datafile: | |
1735 | try: |
|
1721 | try: | |
1736 | lineno = inspect.getsourcelines(data)[1] |
|
1722 | lineno = inspect.getsourcelines(data)[1] | |
1737 | except IOError: |
|
1723 | except IOError: | |
1738 | filename = make_filename(args) |
|
1724 | filename = make_filename(args) | |
1739 | if filename is None: |
|
1725 | if filename is None: | |
1740 | warn('The file `%s` where `%s` was defined cannot ' |
|
1726 | warn('The file `%s` where `%s` was defined cannot ' | |
1741 | 'be read.' % (filename,data)) |
|
1727 | 'be read.' % (filename,data)) | |
1742 | return |
|
1728 | return | |
1743 | use_temp = 0 |
|
1729 | use_temp = 0 | |
1744 | else: |
|
1730 | else: | |
1745 | data = '' |
|
1731 | data = '' | |
1746 |
|
1732 | |||
1747 | if use_temp: |
|
1733 | if use_temp: | |
1748 | filename = tempfile.mktemp('.py') |
|
1734 | filename = tempfile.mktemp('.py') | |
1749 | self.shell.tempfiles.append(filename) |
|
1735 | self.shell.tempfiles.append(filename) | |
1750 |
|
1736 | |||
1751 | if data and use_temp: |
|
1737 | if data and use_temp: | |
1752 | tmp_file = open(filename,'w') |
|
1738 | tmp_file = open(filename,'w') | |
1753 | tmp_file.write(data) |
|
1739 | tmp_file.write(data) | |
1754 | tmp_file.close() |
|
1740 | tmp_file.close() | |
1755 |
|
1741 | |||
1756 | # do actual editing here |
|
1742 | # do actual editing here | |
1757 | print 'Editing...', |
|
1743 | print 'Editing...', | |
1758 | sys.stdout.flush() |
|
1744 | sys.stdout.flush() | |
1759 | self.shell.hooks.editor(filename,lineno) |
|
1745 | self.shell.hooks.editor(filename,lineno) | |
1760 | if opts.has_key('x'): # -x prevents actual execution |
|
1746 | if opts.has_key('x'): # -x prevents actual execution | |
1761 |
|
1747 | |||
1762 | else: |
|
1748 | else: | |
1763 | print 'done. Executing edited code...' |
|
1749 | print 'done. Executing edited code...' | |
1764 | try: |
|
1750 | try: | |
1765 | execfile(filename,self.shell.user_ns) |
|
1751 | execfile(filename,self.shell.user_ns) | |
1766 | except IOError,msg: |
|
1752 | except IOError,msg: | |
1767 | if msg.filename == filename: |
|
1753 | if msg.filename == filename: | |
1768 | warn('File not found. Did you forget to save?') |
|
1754 | warn('File not found. Did you forget to save?') | |
1769 | return |
|
1755 | return | |
1770 | else: |
|
1756 | else: | |
1771 | self.shell.showtraceback() |
|
1757 | self.shell.showtraceback() | |
1772 | except: |
|
1758 | except: | |
1773 | self.shell.showtraceback() |
|
1759 | self.shell.showtraceback() | |
1774 | if use_temp: |
|
1760 | if use_temp: | |
1775 | contents = open(filename).read() |
|
1761 | contents = open(filename).read() | |
1776 | return contents |
|
1762 | return contents | |
1777 |
|
1763 | |||
1778 | def magic_xmode(self,parameter_s = ''): |
|
1764 | def magic_xmode(self,parameter_s = ''): | |
1779 | """Switch modes for the exception handlers. |
|
1765 | """Switch modes for the exception handlers. | |
1780 |
|
1766 | |||
1781 | Valid modes: Plain, Context and Verbose. |
|
1767 | Valid modes: Plain, Context and Verbose. | |
1782 |
|
1768 | |||
1783 | If called without arguments, acts as a toggle.""" |
|
1769 | If called without arguments, acts as a toggle.""" | |
1784 |
|
1770 | |||
1785 | new_mode = parameter_s.strip().capitalize() |
|
1771 | new_mode = parameter_s.strip().capitalize() | |
1786 | try: |
|
1772 | try: | |
1787 | self.InteractiveTB.set_mode(mode = new_mode) |
|
1773 | self.InteractiveTB.set_mode(mode = new_mode) | |
1788 | print 'Exception reporting mode:',self.InteractiveTB.mode |
|
1774 | print 'Exception reporting mode:',self.InteractiveTB.mode | |
1789 | except: |
|
1775 | except: | |
1790 | warn('Error changing exception modes.\n' + str(sys.exc_info()[1])) |
|
1776 | warn('Error changing exception modes.\n' + str(sys.exc_info()[1])) | |
1791 |
|
1777 | |||
1792 | def magic_colors(self,parameter_s = ''): |
|
1778 | def magic_colors(self,parameter_s = ''): | |
1793 | """Switch color scheme for prompts, info system and exception handlers. |
|
1779 | """Switch color scheme for prompts, info system and exception handlers. | |
1794 |
|
1780 | |||
1795 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
1781 | Currently implemented schemes: NoColor, Linux, LightBG. | |
1796 |
|
1782 | |||
1797 | Color scheme names are not case-sensitive.""" |
|
1783 | Color scheme names are not case-sensitive.""" | |
1798 |
|
1784 | |||
1799 | new_scheme = parameter_s.strip() |
|
1785 | new_scheme = parameter_s.strip() | |
1800 | if not new_scheme: |
|
1786 | if not new_scheme: | |
1801 | print 'You must specify a color scheme.' |
|
1787 | print 'You must specify a color scheme.' | |
1802 | return |
|
1788 | return | |
1803 | # Under Windows, check for Gary Bishop's readline, which is necessary |
|
1789 | # Under Windows, check for Gary Bishop's readline, which is necessary | |
1804 | # for ANSI coloring |
|
1790 | # for ANSI coloring | |
1805 | if os.name in ['nt','dos']: |
|
1791 | if os.name in ['nt','dos']: | |
1806 | try: |
|
1792 | try: | |
1807 | import readline |
|
1793 | import readline | |
1808 | except ImportError: |
|
1794 | except ImportError: | |
1809 | has_readline = 0 |
|
1795 | has_readline = 0 | |
1810 | else: |
|
1796 | else: | |
1811 | try: |
|
1797 | try: | |
1812 | readline.GetOutputFile() |
|
1798 | readline.GetOutputFile() | |
1813 | except AttributeError: |
|
1799 | except AttributeError: | |
1814 | has_readline = 0 |
|
1800 | has_readline = 0 | |
1815 | else: |
|
1801 | else: | |
1816 | has_readline = 1 |
|
1802 | has_readline = 1 | |
1817 | if not has_readline: |
|
1803 | if not has_readline: | |
1818 | msg = """\ |
|
1804 | msg = """\ | |
1819 | Proper color support under MS Windows requires Gary Bishop's readline library. |
|
1805 | Proper color support under MS Windows requires Gary Bishop's readline library. | |
1820 | You can find it at: |
|
1806 | You can find it at: | |
1821 | http://sourceforge.net/projects/uncpythontools |
|
1807 | http://sourceforge.net/projects/uncpythontools | |
1822 | Gary's readline needs the ctypes module, from: |
|
1808 | Gary's readline needs the ctypes module, from: | |
1823 | http://starship.python.net/crew/theller/ctypes |
|
1809 | http://starship.python.net/crew/theller/ctypes | |
1824 |
|
1810 | |||
1825 | Defaulting color scheme to 'NoColor'""" |
|
1811 | Defaulting color scheme to 'NoColor'""" | |
1826 | new_scheme = 'NoColor' |
|
1812 | new_scheme = 'NoColor' | |
1827 | warn(msg) |
|
1813 | warn(msg) | |
1828 |
|
1814 | |||
1829 | # Set prompt colors |
|
1815 | # Set prompt colors | |
1830 | try: |
|
1816 | try: | |
1831 | self.shell.outputcache.set_colors(new_scheme) |
|
1817 | self.shell.outputcache.set_colors(new_scheme) | |
1832 | except: |
|
1818 | except: | |
1833 | warn('Error changing prompt color schemes.\n' |
|
1819 | warn('Error changing prompt color schemes.\n' | |
1834 | + str(sys.exc_info()[1])) |
|
1820 | + str(sys.exc_info()[1])) | |
1835 | else: |
|
1821 | else: | |
1836 | self.shell.rc.colors = \ |
|
1822 | self.shell.rc.colors = \ | |
1837 | self.shell.outputcache.color_table.active_scheme_name |
|
1823 | self.shell.outputcache.color_table.active_scheme_name | |
1838 | # Set exception colors |
|
1824 | # Set exception colors | |
1839 | try: |
|
1825 | try: | |
1840 | self.shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
1826 | self.shell.InteractiveTB.set_colors(scheme = new_scheme) | |
1841 | self.shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
1827 | self.shell.SyntaxTB.set_colors(scheme = new_scheme) | |
1842 | except: |
|
1828 | except: | |
1843 | warn('Error changing exception color schemes.\n' |
|
1829 | warn('Error changing exception color schemes.\n' | |
1844 | + str(sys.exc_info()[1])) |
|
1830 | + str(sys.exc_info()[1])) | |
1845 | # Set info (for 'object?') colors |
|
1831 | # Set info (for 'object?') colors | |
1846 | if self.shell.rc.color_info: |
|
1832 | if self.shell.rc.color_info: | |
1847 | try: |
|
1833 | try: | |
1848 | self.shell.inspector.set_active_scheme(new_scheme) |
|
1834 | self.shell.inspector.set_active_scheme(new_scheme) | |
1849 | except: |
|
1835 | except: | |
1850 | warn('Error changing object inspector color schemes.\n' |
|
1836 | warn('Error changing object inspector color schemes.\n' | |
1851 | + str(sys.exc_info()[1])) |
|
1837 | + str(sys.exc_info()[1])) | |
1852 | else: |
|
1838 | else: | |
1853 | self.shell.inspector.set_active_scheme('NoColor') |
|
1839 | self.shell.inspector.set_active_scheme('NoColor') | |
1854 |
|
1840 | |||
1855 | def magic_color_info(self,parameter_s = ''): |
|
1841 | def magic_color_info(self,parameter_s = ''): | |
1856 | """Toggle color_info. |
|
1842 | """Toggle color_info. | |
1857 |
|
1843 | |||
1858 | The color_info configuration parameter controls whether colors are |
|
1844 | The color_info configuration parameter controls whether colors are | |
1859 | used for displaying object details (by things like %psource, %pfile or |
|
1845 | used for displaying object details (by things like %psource, %pfile or | |
1860 | the '?' system). This function toggles this value with each call. |
|
1846 | the '?' system). This function toggles this value with each call. | |
1861 |
|
1847 | |||
1862 | Note that unless you have a fairly recent pager (less works better |
|
1848 | Note that unless you have a fairly recent pager (less works better | |
1863 | than more) in your system, using colored object information displays |
|
1849 | than more) in your system, using colored object information displays | |
1864 | will not work properly. Test it and see.""" |
|
1850 | will not work properly. Test it and see.""" | |
1865 |
|
1851 | |||
1866 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
1852 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
1867 | self.magic_colors(self.shell.rc.colors) |
|
1853 | self.magic_colors(self.shell.rc.colors) | |
1868 | print 'Object introspection functions have now coloring:', |
|
1854 | print 'Object introspection functions have now coloring:', | |
1869 | print ['OFF','ON'][self.shell.rc.color_info] |
|
1855 | print ['OFF','ON'][self.shell.rc.color_info] | |
1870 |
|
1856 | |||
1871 | def magic_Pprint(self, parameter_s=''): |
|
1857 | def magic_Pprint(self, parameter_s=''): | |
1872 | """Toggle pretty printing on/off.""" |
|
1858 | """Toggle pretty printing on/off.""" | |
1873 |
|
1859 | |||
1874 | self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint |
|
1860 | self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint | |
1875 | print 'Pretty printing has been turned', \ |
|
1861 | print 'Pretty printing has been turned', \ | |
1876 | ['OFF','ON'][self.shell.outputcache.Pprint] |
|
1862 | ['OFF','ON'][self.shell.outputcache.Pprint] | |
1877 |
|
1863 | |||
1878 | def magic_Exit(self, parameter_s=''): |
|
1864 | def magic_Exit(self, parameter_s=''): | |
1879 | """Exit IPython without confirmation.""" |
|
1865 | """Exit IPython without confirmation.""" | |
1880 |
|
1866 | |||
1881 | self.shell.exit_now = True |
|
1867 | self.shell.exit_now = True | |
1882 |
|
1868 | |||
1883 | def magic_Quit(self, parameter_s=''): |
|
1869 | def magic_Quit(self, parameter_s=''): | |
1884 | """Exit IPython without confirmation (like %Exit).""" |
|
1870 | """Exit IPython without confirmation (like %Exit).""" | |
1885 |
|
1871 | |||
1886 | self.shell.exit_now = True |
|
1872 | self.shell.exit_now = True | |
1887 |
|
1873 | |||
1888 | #...................................................................... |
|
1874 | #...................................................................... | |
1889 | # Functions to implement unix shell-type things |
|
1875 | # Functions to implement unix shell-type things | |
1890 |
|
1876 | |||
1891 | def magic_alias(self, parameter_s = ''): |
|
1877 | def magic_alias(self, parameter_s = ''): | |
1892 | """Define an alias for a system command. |
|
1878 | """Define an alias for a system command. | |
1893 |
|
1879 | |||
1894 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
1880 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
1895 |
|
1881 | |||
1896 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
1882 | Then, typing 'alias_name params' will execute the system command 'cmd | |
1897 | params' (from your underlying operating system). |
|
1883 | params' (from your underlying operating system). | |
1898 |
|
1884 | |||
1899 | Aliases have lower precedence than magic functions and Python normal |
|
1885 | Aliases have lower precedence than magic functions and Python normal | |
1900 | variables, so if 'foo' is both a Python variable and an alias, the |
|
1886 | variables, so if 'foo' is both a Python variable and an alias, the | |
1901 | alias can not be executed until 'del foo' removes the Python variable. |
|
1887 | alias can not be executed until 'del foo' removes the Python variable. | |
1902 |
|
1888 | |||
1903 | You can use the %l specifier in an alias definition to represent the |
|
1889 | You can use the %l specifier in an alias definition to represent the | |
1904 | whole line when the alias is called. For example: |
|
1890 | whole line when the alias is called. For example: | |
1905 |
|
1891 | |||
1906 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
1892 | In [2]: alias all echo "Input in brackets: <%l>"\\ | |
1907 | In [3]: all hello world\\ |
|
1893 | In [3]: all hello world\\ | |
1908 | Input in brackets: <hello world> |
|
1894 | Input in brackets: <hello world> | |
1909 |
|
1895 | |||
1910 | You can also define aliases with parameters using %s specifiers (one |
|
1896 | You can also define aliases with parameters using %s specifiers (one | |
1911 | per parameter): |
|
1897 | per parameter): | |
1912 |
|
1898 | |||
1913 | In [1]: alias parts echo first %s second %s\\ |
|
1899 | In [1]: alias parts echo first %s second %s\\ | |
1914 | In [2]: %parts A B\\ |
|
1900 | In [2]: %parts A B\\ | |
1915 | first A second B\\ |
|
1901 | first A second B\\ | |
1916 | In [3]: %parts A\\ |
|
1902 | In [3]: %parts A\\ | |
1917 | Incorrect number of arguments: 2 expected.\\ |
|
1903 | Incorrect number of arguments: 2 expected.\\ | |
1918 | parts is an alias to: 'echo first %s second %s' |
|
1904 | parts is an alias to: 'echo first %s second %s' | |
1919 |
|
1905 | |||
1920 | Note that %l and %s are mutually exclusive. You can only use one or |
|
1906 | Note that %l and %s are mutually exclusive. You can only use one or | |
1921 | the other in your aliases. |
|
1907 | the other in your aliases. | |
1922 |
|
1908 | |||
1923 | Aliases expand Python variables just like system calls using ! or !! |
|
1909 | Aliases expand Python variables just like system calls using ! or !! | |
1924 | do: all expressions prefixed with '$' get expanded. For details of |
|
1910 | do: all expressions prefixed with '$' get expanded. For details of | |
1925 | the semantic rules, see PEP-215: |
|
1911 | the semantic rules, see PEP-215: | |
1926 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
1912 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
1927 | IPython for variable expansion. If you want to access a true shell |
|
1913 | IPython for variable expansion. If you want to access a true shell | |
1928 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
1914 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
1929 |
|
1915 | |||
1930 | In [6]: alias show echo\\ |
|
1916 | In [6]: alias show echo\\ | |
1931 | In [7]: PATH='A Python string'\\ |
|
1917 | In [7]: PATH='A Python string'\\ | |
1932 | In [8]: show $PATH\\ |
|
1918 | In [8]: show $PATH\\ | |
1933 | A Python string\\ |
|
1919 | A Python string\\ | |
1934 | In [9]: show $$PATH\\ |
|
1920 | In [9]: show $$PATH\\ | |
1935 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
1921 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
1936 |
|
1922 | |||
1937 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
1923 | You can use the alias facility to acess all of $PATH. See the %rehash | |
1938 | and %rehashx functions, which automatically create aliases for the |
|
1924 | and %rehashx functions, which automatically create aliases for the | |
1939 | contents of your $PATH. |
|
1925 | contents of your $PATH. | |
1940 |
|
1926 | |||
1941 | If called with no parameters, %alias prints the current alias table.""" |
|
1927 | If called with no parameters, %alias prints the current alias table.""" | |
1942 |
|
1928 | |||
1943 | par = parameter_s.strip() |
|
1929 | par = parameter_s.strip() | |
1944 | if not par: |
|
1930 | if not par: | |
1945 | if self.shell.rc.automagic: |
|
1931 | if self.shell.rc.automagic: | |
1946 | prechar = '' |
|
1932 | prechar = '' | |
1947 | else: |
|
1933 | else: | |
1948 | prechar = self.shell.ESC_MAGIC |
|
1934 | prechar = self.shell.ESC_MAGIC | |
1949 | print 'Alias\t\tSystem Command\n'+'-'*30 |
|
1935 | print 'Alias\t\tSystem Command\n'+'-'*30 | |
1950 | atab = self.shell.alias_table |
|
1936 | atab = self.shell.alias_table | |
1951 | aliases = atab.keys() |
|
1937 | aliases = atab.keys() | |
1952 | aliases.sort() |
|
1938 | aliases.sort() | |
1953 | for alias in aliases: |
|
1939 | for alias in aliases: | |
1954 | print prechar+alias+'\t\t'+atab[alias][1] |
|
1940 | print prechar+alias+'\t\t'+atab[alias][1] | |
1955 | print '-'*30+'\nTotal number of aliases:',len(aliases) |
|
1941 | print '-'*30+'\nTotal number of aliases:',len(aliases) | |
1956 | return |
|
1942 | return | |
1957 | try: |
|
1943 | try: | |
1958 | alias,cmd = par.split(None,1) |
|
1944 | alias,cmd = par.split(None,1) | |
1959 | except: |
|
1945 | except: | |
1960 | print OInspect.getdoc(self.magic_alias) |
|
1946 | print OInspect.getdoc(self.magic_alias) | |
1961 | else: |
|
1947 | else: | |
1962 | nargs = cmd.count('%s') |
|
1948 | nargs = cmd.count('%s') | |
1963 | if nargs>0 and cmd.find('%l')>=0: |
|
1949 | if nargs>0 and cmd.find('%l')>=0: | |
1964 | error('The %s and %l specifiers are mutually exclusive ' |
|
1950 | error('The %s and %l specifiers are mutually exclusive ' | |
1965 | 'in alias definitions.') |
|
1951 | 'in alias definitions.') | |
1966 | else: # all looks OK |
|
1952 | else: # all looks OK | |
1967 | self.shell.alias_table[alias] = (nargs,cmd) |
|
1953 | self.shell.alias_table[alias] = (nargs,cmd) | |
1968 | self.shell.alias_table_validate(verbose=1) |
|
1954 | self.shell.alias_table_validate(verbose=1) | |
1969 | # end magic_alias |
|
1955 | # end magic_alias | |
1970 |
|
1956 | |||
1971 | def magic_unalias(self, parameter_s = ''): |
|
1957 | def magic_unalias(self, parameter_s = ''): | |
1972 | """Remove an alias""" |
|
1958 | """Remove an alias""" | |
1973 |
|
1959 | |||
1974 | aname = parameter_s.strip() |
|
1960 | aname = parameter_s.strip() | |
1975 | if aname in self.shell.alias_table: |
|
1961 | if aname in self.shell.alias_table: | |
1976 | del self.shell.alias_table[aname] |
|
1962 | del self.shell.alias_table[aname] | |
1977 |
|
1963 | |||
1978 | def magic_rehash(self, parameter_s = ''): |
|
1964 | def magic_rehash(self, parameter_s = ''): | |
1979 | """Update the alias table with all entries in $PATH. |
|
1965 | """Update the alias table with all entries in $PATH. | |
1980 |
|
1966 | |||
1981 | This version does no checks on execute permissions or whether the |
|
1967 | This version does no checks on execute permissions or whether the | |
1982 | contents of $PATH are truly files (instead of directories or something |
|
1968 | contents of $PATH are truly files (instead of directories or something | |
1983 | else). For such a safer (but slower) version, use %rehashx.""" |
|
1969 | else). For such a safer (but slower) version, use %rehashx.""" | |
1984 |
|
1970 | |||
1985 | # This function (and rehashx) manipulate the alias_table directly |
|
1971 | # This function (and rehashx) manipulate the alias_table directly | |
1986 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
1972 | # rather than calling magic_alias, for speed reasons. A rehash on a | |
1987 | # typical Linux box involves several thousand entries, so efficiency |
|
1973 | # typical Linux box involves several thousand entries, so efficiency | |
1988 | # here is a top concern. |
|
1974 | # here is a top concern. | |
1989 |
|
1975 | |||
1990 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
1976 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) | |
1991 | alias_table = self.shell.alias_table |
|
1977 | alias_table = self.shell.alias_table | |
1992 | for pdir in path: |
|
1978 | for pdir in path: | |
1993 | for ff in os.listdir(pdir): |
|
1979 | for ff in os.listdir(pdir): | |
1994 | # each entry in the alias table must be (N,name), where |
|
1980 | # each entry in the alias table must be (N,name), where | |
1995 | # N is the number of positional arguments of the alias. |
|
1981 | # N is the number of positional arguments of the alias. | |
1996 | alias_table[ff] = (0,ff) |
|
1982 | alias_table[ff] = (0,ff) | |
1997 | # Make sure the alias table doesn't contain keywords or builtins |
|
1983 | # Make sure the alias table doesn't contain keywords or builtins | |
1998 | self.shell.alias_table_validate() |
|
1984 | self.shell.alias_table_validate() | |
1999 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
1985 | # Call again init_auto_alias() so we get 'rm -i' and other modified | |
2000 | # aliases since %rehash will probably clobber them |
|
1986 | # aliases since %rehash will probably clobber them | |
2001 | self.shell.init_auto_alias() |
|
1987 | self.shell.init_auto_alias() | |
2002 |
|
1988 | |||
2003 | def magic_rehashx(self, parameter_s = ''): |
|
1989 | def magic_rehashx(self, parameter_s = ''): | |
2004 | """Update the alias table with all executable files in $PATH. |
|
1990 | """Update the alias table with all executable files in $PATH. | |
2005 |
|
1991 | |||
2006 | This version explicitly checks that every entry in $PATH is a file |
|
1992 | This version explicitly checks that every entry in $PATH is a file | |
2007 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
1993 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2008 |
|
1994 | |||
2009 | Under Windows, it checks executability as a match agains a |
|
1995 | Under Windows, it checks executability as a match agains a | |
2010 | '|'-separated string of extensions, stored in the IPython config |
|
1996 | '|'-separated string of extensions, stored in the IPython config | |
2011 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ |
|
1997 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ | |
2012 |
|
1998 | |||
2013 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
1999 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) | |
2014 | alias_table = self.shell.alias_table |
|
2000 | alias_table = self.shell.alias_table | |
2015 |
|
2001 | |||
2016 | if os.name == 'posix': |
|
2002 | if os.name == 'posix': | |
2017 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2003 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2018 | os.access(fname,os.X_OK) |
|
2004 | os.access(fname,os.X_OK) | |
2019 | else: |
|
2005 | else: | |
2020 |
|
2006 | |||
2021 | try: |
|
2007 | try: | |
2022 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2008 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2023 | except KeyError: |
|
2009 | except KeyError: | |
2024 | winext = 'exe|com|bat' |
|
2010 | winext = 'exe|com|bat' | |
2025 |
|
2011 | |||
2026 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2012 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2027 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2013 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2028 | savedir = os.getcwd() |
|
2014 | savedir = os.getcwd() | |
2029 | try: |
|
2015 | try: | |
2030 | # write the whole loop for posix/Windows so we don't have an if in |
|
2016 | # write the whole loop for posix/Windows so we don't have an if in | |
2031 | # the innermost part |
|
2017 | # the innermost part | |
2032 | if os.name == 'posix': |
|
2018 | if os.name == 'posix': | |
2033 | for pdir in path: |
|
2019 | for pdir in path: | |
2034 | os.chdir(pdir) |
|
2020 | os.chdir(pdir) | |
2035 | for ff in os.listdir(pdir): |
|
2021 | for ff in os.listdir(pdir): | |
2036 | if isexec(ff): |
|
2022 | if isexec(ff): | |
2037 | # each entry in the alias table must be (N,name), |
|
2023 | # each entry in the alias table must be (N,name), | |
2038 | # where N is the number of positional arguments of the |
|
2024 | # where N is the number of positional arguments of the | |
2039 | # alias. |
|
2025 | # alias. | |
2040 | alias_table[ff] = (0,ff) |
|
2026 | alias_table[ff] = (0,ff) | |
2041 | else: |
|
2027 | else: | |
2042 | for pdir in path: |
|
2028 | for pdir in path: | |
2043 | os.chdir(pdir) |
|
2029 | os.chdir(pdir) | |
2044 | for ff in os.listdir(pdir): |
|
2030 | for ff in os.listdir(pdir): | |
2045 | if isexec(ff): |
|
2031 | if isexec(ff): | |
2046 | alias_table[execre.sub(r'\1',ff)] = (0,ff) |
|
2032 | alias_table[execre.sub(r'\1',ff)] = (0,ff) | |
2047 | # Make sure the alias table doesn't contain keywords or builtins |
|
2033 | # Make sure the alias table doesn't contain keywords or builtins | |
2048 | self.shell.alias_table_validate() |
|
2034 | self.shell.alias_table_validate() | |
2049 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2035 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2050 | # modified aliases since %rehashx will probably clobber them |
|
2036 | # modified aliases since %rehashx will probably clobber them | |
2051 | self.shell.init_auto_alias() |
|
2037 | self.shell.init_auto_alias() | |
2052 | finally: |
|
2038 | finally: | |
2053 | os.chdir(savedir) |
|
2039 | os.chdir(savedir) | |
2054 |
|
2040 | |||
2055 | def magic_pwd(self, parameter_s = ''): |
|
2041 | def magic_pwd(self, parameter_s = ''): | |
2056 | """Return the current working directory path.""" |
|
2042 | """Return the current working directory path.""" | |
2057 | return os.getcwd() |
|
2043 | return os.getcwd() | |
2058 |
|
2044 | |||
2059 | def magic_cd(self, parameter_s=''): |
|
2045 | def magic_cd(self, parameter_s=''): | |
2060 | """Change the current working directory. |
|
2046 | """Change the current working directory. | |
2061 |
|
2047 | |||
2062 | This command automatically maintains an internal list of directories |
|
2048 | This command automatically maintains an internal list of directories | |
2063 | you visit during your IPython session, in the variable _dh. The |
|
2049 | you visit during your IPython session, in the variable _dh. The | |
2064 | command %dhist shows this history nicely formatted. |
|
2050 | command %dhist shows this history nicely formatted. | |
2065 |
|
2051 | |||
2066 | Usage: |
|
2052 | Usage: | |
2067 |
|
2053 | |||
2068 | cd 'dir': changes to directory 'dir'. |
|
2054 | cd 'dir': changes to directory 'dir'. | |
2069 |
|
2055 | |||
2070 | cd -: changes to the last visited directory. |
|
2056 | cd -: changes to the last visited directory. | |
2071 |
|
2057 | |||
2072 | cd -<n>: changes to the n-th directory in the directory history. |
|
2058 | cd -<n>: changes to the n-th directory in the directory history. | |
2073 |
|
2059 | |||
2074 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2060 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2075 | (note: cd <bookmark_name> is enough if there is no |
|
2061 | (note: cd <bookmark_name> is enough if there is no | |
2076 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2062 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2077 |
|
2063 | |||
2078 | Options: |
|
2064 | Options: | |
2079 |
|
2065 | |||
2080 | -q: quiet. Do not print the working directory after the cd command is |
|
2066 | -q: quiet. Do not print the working directory after the cd command is | |
2081 | executed. By default IPython's cd command does print this directory, |
|
2067 | executed. By default IPython's cd command does print this directory, | |
2082 | since the default prompts do not display path information. |
|
2068 | since the default prompts do not display path information. | |
2083 |
|
2069 | |||
2084 | Note that !cd doesn't work for this purpose because the shell where |
|
2070 | Note that !cd doesn't work for this purpose because the shell where | |
2085 | !command runs is immediately discarded after executing 'command'.""" |
|
2071 | !command runs is immediately discarded after executing 'command'.""" | |
2086 |
|
2072 | |||
2087 | parameter_s = parameter_s.strip() |
|
2073 | parameter_s = parameter_s.strip() | |
2088 | bkms = self.shell.persist.get("bookmarks",{}) |
|
2074 | bkms = self.shell.persist.get("bookmarks",{}) | |
2089 |
|
2075 | |||
2090 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2076 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2091 | # jump in directory history by number |
|
2077 | # jump in directory history by number | |
2092 | if numcd: |
|
2078 | if numcd: | |
2093 | nn = int(numcd.group(2)) |
|
2079 | nn = int(numcd.group(2)) | |
2094 | try: |
|
2080 | try: | |
2095 | ps = self.shell.user_ns['_dh'][nn] |
|
2081 | ps = self.shell.user_ns['_dh'][nn] | |
2096 | except IndexError: |
|
2082 | except IndexError: | |
2097 | print 'The requested directory does not exist in history.' |
|
2083 | print 'The requested directory does not exist in history.' | |
2098 | return |
|
2084 | return | |
2099 | else: |
|
2085 | else: | |
2100 | opts = {} |
|
2086 | opts = {} | |
2101 | else: |
|
2087 | else: | |
2102 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2088 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2103 | # jump to previous |
|
2089 | # jump to previous | |
2104 | if ps == '-': |
|
2090 | if ps == '-': | |
2105 | try: |
|
2091 | try: | |
2106 | ps = self.shell.user_ns['_dh'][-2] |
|
2092 | ps = self.shell.user_ns['_dh'][-2] | |
2107 | except IndexError: |
|
2093 | except IndexError: | |
2108 | print 'No previous directory to change to.' |
|
2094 | print 'No previous directory to change to.' | |
2109 | return |
|
2095 | return | |
2110 | # jump to bookmark |
|
2096 | # jump to bookmark | |
2111 | elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)): |
|
2097 | elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)): | |
2112 | if bkms.has_key(ps): |
|
2098 | if bkms.has_key(ps): | |
2113 | target = bkms[ps] |
|
2099 | target = bkms[ps] | |
2114 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2100 | print '(bookmark:%s) -> %s' % (ps,target) | |
2115 | ps = target |
|
2101 | ps = target | |
2116 | else: |
|
2102 | else: | |
2117 | if bkms: |
|
2103 | if bkms: | |
2118 | error("Bookmark '%s' not found. " |
|
2104 | error("Bookmark '%s' not found. " | |
2119 | "Use '%bookmark -l' to see your bookmarks." % ps) |
|
2105 | "Use '%bookmark -l' to see your bookmarks." % ps) | |
2120 | else: |
|
2106 | else: | |
2121 | print "Bookmarks not set - use %bookmark <bookmarkname>" |
|
2107 | print "Bookmarks not set - use %bookmark <bookmarkname>" | |
2122 | return |
|
2108 | return | |
2123 |
|
2109 | |||
2124 | # at this point ps should point to the target dir |
|
2110 | # at this point ps should point to the target dir | |
2125 | if ps: |
|
2111 | if ps: | |
2126 | try: |
|
2112 | try: | |
2127 | os.chdir(os.path.expanduser(ps)) |
|
2113 | os.chdir(os.path.expanduser(ps)) | |
2128 | except OSError: |
|
2114 | except OSError: | |
2129 | print sys.exc_info()[1] |
|
2115 | print sys.exc_info()[1] | |
2130 | else: |
|
2116 | else: | |
2131 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2117 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2132 | else: |
|
2118 | else: | |
2133 | os.chdir(self.home_dir) |
|
2119 | os.chdir(self.home_dir) | |
2134 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2120 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2135 | if not 'q' in opts: |
|
2121 | if not 'q' in opts: | |
2136 | print self.shell.user_ns['_dh'][-1] |
|
2122 | print self.shell.user_ns['_dh'][-1] | |
2137 |
|
2123 | |||
2138 | def magic_dhist(self, parameter_s=''): |
|
2124 | def magic_dhist(self, parameter_s=''): | |
2139 | """Print your history of visited directories. |
|
2125 | """Print your history of visited directories. | |
2140 |
|
2126 | |||
2141 | %dhist -> print full history\\ |
|
2127 | %dhist -> print full history\\ | |
2142 | %dhist n -> print last n entries only\\ |
|
2128 | %dhist n -> print last n entries only\\ | |
2143 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2129 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2144 |
|
2130 | |||
2145 | This history is automatically maintained by the %cd command, and |
|
2131 | This history is automatically maintained by the %cd command, and | |
2146 | always available as the global list variable _dh. You can use %cd -<n> |
|
2132 | always available as the global list variable _dh. You can use %cd -<n> | |
2147 | to go to directory number <n>.""" |
|
2133 | to go to directory number <n>.""" | |
2148 |
|
2134 | |||
2149 | dh = self.shell.user_ns['_dh'] |
|
2135 | dh = self.shell.user_ns['_dh'] | |
2150 | if parameter_s: |
|
2136 | if parameter_s: | |
2151 | try: |
|
2137 | try: | |
2152 | args = map(int,parameter_s.split()) |
|
2138 | args = map(int,parameter_s.split()) | |
2153 | except: |
|
2139 | except: | |
2154 | self.arg_err(Magic.magic_dhist) |
|
2140 | self.arg_err(Magic.magic_dhist) | |
2155 | return |
|
2141 | return | |
2156 | if len(args) == 1: |
|
2142 | if len(args) == 1: | |
2157 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2143 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2158 | elif len(args) == 2: |
|
2144 | elif len(args) == 2: | |
2159 | ini,fin = args |
|
2145 | ini,fin = args | |
2160 | else: |
|
2146 | else: | |
2161 | self.arg_err(Magic.magic_dhist) |
|
2147 | self.arg_err(Magic.magic_dhist) | |
2162 | return |
|
2148 | return | |
2163 | else: |
|
2149 | else: | |
2164 | ini,fin = 0,len(dh) |
|
2150 | ini,fin = 0,len(dh) | |
2165 | nlprint(dh, |
|
2151 | nlprint(dh, | |
2166 | header = 'Directory history (kept in _dh)', |
|
2152 | header = 'Directory history (kept in _dh)', | |
2167 | start=ini,stop=fin) |
|
2153 | start=ini,stop=fin) | |
2168 |
|
2154 | |||
2169 | def magic_env(self, parameter_s=''): |
|
2155 | def magic_env(self, parameter_s=''): | |
2170 | """List environment variables.""" |
|
2156 | """List environment variables.""" | |
2171 |
|
2157 | |||
2172 | # environ is an instance of UserDict |
|
2158 | # environ is an instance of UserDict | |
2173 | return os.environ.data |
|
2159 | return os.environ.data | |
2174 |
|
2160 | |||
2175 | def magic_pushd(self, parameter_s=''): |
|
2161 | def magic_pushd(self, parameter_s=''): | |
2176 | """Place the current dir on stack and change directory. |
|
2162 | """Place the current dir on stack and change directory. | |
2177 |
|
2163 | |||
2178 | Usage:\\ |
|
2164 | Usage:\\ | |
2179 | %pushd ['dirname'] |
|
2165 | %pushd ['dirname'] | |
2180 |
|
2166 | |||
2181 | %pushd with no arguments does a %pushd to your home directory. |
|
2167 | %pushd with no arguments does a %pushd to your home directory. | |
2182 | """ |
|
2168 | """ | |
2183 | if parameter_s == '': parameter_s = '~' |
|
2169 | if parameter_s == '': parameter_s = '~' | |
2184 | if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \ |
|
2170 | if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \ | |
2185 | os.path.expanduser(self.dir_stack[0]): |
|
2171 | os.path.expanduser(self.dir_stack[0]): | |
2186 | try: |
|
2172 | try: | |
2187 | self.magic_cd(parameter_s) |
|
2173 | self.magic_cd(parameter_s) | |
2188 | self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2174 | self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~')) | |
2189 | self.magic_dirs() |
|
2175 | self.magic_dirs() | |
2190 | except: |
|
2176 | except: | |
2191 | print 'Invalid directory' |
|
2177 | print 'Invalid directory' | |
2192 | else: |
|
2178 | else: | |
2193 | print 'You are already there!' |
|
2179 | print 'You are already there!' | |
2194 |
|
2180 | |||
2195 | def magic_popd(self, parameter_s=''): |
|
2181 | def magic_popd(self, parameter_s=''): | |
2196 | """Change to directory popped off the top of the stack. |
|
2182 | """Change to directory popped off the top of the stack. | |
2197 | """ |
|
2183 | """ | |
2198 | if len (self.dir_stack) > 1: |
|
2184 | if len (self.dir_stack) > 1: | |
2199 | self.dir_stack.pop(0) |
|
2185 | self.dir_stack.pop(0) | |
2200 | self.magic_cd(self.dir_stack[0]) |
|
2186 | self.magic_cd(self.dir_stack[0]) | |
2201 | print self.dir_stack[0] |
|
2187 | print self.dir_stack[0] | |
2202 | else: |
|
2188 | else: | |
2203 | print "You can't remove the starting directory from the stack:",\ |
|
2189 | print "You can't remove the starting directory from the stack:",\ | |
2204 | self.dir_stack |
|
2190 | self.dir_stack | |
2205 |
|
2191 | |||
2206 | def magic_dirs(self, parameter_s=''): |
|
2192 | def magic_dirs(self, parameter_s=''): | |
2207 | """Return the current directory stack.""" |
|
2193 | """Return the current directory stack.""" | |
2208 |
|
2194 | |||
2209 | return self.dir_stack[:] |
|
2195 | return self.dir_stack[:] | |
2210 |
|
2196 | |||
2211 | def magic_sc(self, parameter_s=''): |
|
2197 | def magic_sc(self, parameter_s=''): | |
2212 | """Shell capture - execute a shell command and capture its output. |
|
2198 | """Shell capture - execute a shell command and capture its output. | |
2213 |
|
2199 | |||
2214 | %sc [options] varname=command |
|
2200 | %sc [options] varname=command | |
2215 |
|
2201 | |||
2216 | IPython will run the given command using commands.getoutput(), and |
|
2202 | IPython will run the given command using commands.getoutput(), and | |
2217 | will then update the user's interactive namespace with a variable |
|
2203 | will then update the user's interactive namespace with a variable | |
2218 | called varname, containing the value of the call. Your command can |
|
2204 | called varname, containing the value of the call. Your command can | |
2219 | contain shell wildcards, pipes, etc. |
|
2205 | contain shell wildcards, pipes, etc. | |
2220 |
|
2206 | |||
2221 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2207 | The '=' sign in the syntax is mandatory, and the variable name you | |
2222 | supply must follow Python's standard conventions for valid names. |
|
2208 | supply must follow Python's standard conventions for valid names. | |
2223 |
|
2209 | |||
2224 | Options: |
|
2210 | Options: | |
2225 |
|
2211 | |||
2226 | -l: list output. Split the output on newlines into a list before |
|
2212 | -l: list output. Split the output on newlines into a list before | |
2227 | assigning it to the given variable. By default the output is stored |
|
2213 | assigning it to the given variable. By default the output is stored | |
2228 | as a single string. |
|
2214 | as a single string. | |
2229 |
|
2215 | |||
2230 | -v: verbose. Print the contents of the variable. |
|
2216 | -v: verbose. Print the contents of the variable. | |
2231 |
|
2217 | |||
2232 | In most cases you should not need to split as a list, because the |
|
2218 | In most cases you should not need to split as a list, because the | |
2233 | returned value is a special type of string which can automatically |
|
2219 | returned value is a special type of string which can automatically | |
2234 | provide its contents either as a list (split on newlines) or as a |
|
2220 | provide its contents either as a list (split on newlines) or as a | |
2235 | space-separated string. These are convenient, respectively, either |
|
2221 | space-separated string. These are convenient, respectively, either | |
2236 | for sequential processing or to be passed to a shell command. |
|
2222 | for sequential processing or to be passed to a shell command. | |
2237 |
|
2223 | |||
2238 | For example: |
|
2224 | For example: | |
2239 |
|
2225 | |||
2240 | # Capture into variable a |
|
2226 | # Capture into variable a | |
2241 | In [9]: sc a=ls *py |
|
2227 | In [9]: sc a=ls *py | |
2242 |
|
2228 | |||
2243 | # a is a string with embedded newlines |
|
2229 | # a is a string with embedded newlines | |
2244 | In [10]: a |
|
2230 | In [10]: a | |
2245 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2231 | Out[10]: 'setup.py\nwin32_manual_post_install.py' | |
2246 |
|
2232 | |||
2247 | # which can be seen as a list: |
|
2233 | # which can be seen as a list: | |
2248 | In [11]: a.l |
|
2234 | In [11]: a.l | |
2249 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2235 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] | |
2250 |
|
2236 | |||
2251 | # or as a whitespace-separated string: |
|
2237 | # or as a whitespace-separated string: | |
2252 | In [12]: a.s |
|
2238 | In [12]: a.s | |
2253 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2239 | Out[12]: 'setup.py win32_manual_post_install.py' | |
2254 |
|
2240 | |||
2255 | # a.s is useful to pass as a single command line: |
|
2241 | # a.s is useful to pass as a single command line: | |
2256 | In [13]: !wc -l $a.s |
|
2242 | In [13]: !wc -l $a.s | |
2257 | 146 setup.py |
|
2243 | 146 setup.py | |
2258 | 130 win32_manual_post_install.py |
|
2244 | 130 win32_manual_post_install.py | |
2259 | 276 total |
|
2245 | 276 total | |
2260 |
|
2246 | |||
2261 | # while the list form is useful to loop over: |
|
2247 | # while the list form is useful to loop over: | |
2262 | In [14]: for f in a.l: |
|
2248 | In [14]: for f in a.l: | |
2263 | ....: !wc -l $f |
|
2249 | ....: !wc -l $f | |
2264 | ....: |
|
2250 | ....: | |
2265 | 146 setup.py |
|
2251 | 146 setup.py | |
2266 | 130 win32_manual_post_install.py |
|
2252 | 130 win32_manual_post_install.py | |
2267 |
|
2253 | |||
2268 | Similiarly, the lists returned by the -l option are also special, in |
|
2254 | Similiarly, the lists returned by the -l option are also special, in | |
2269 | the sense that you can equally invoke the .s attribute on them to |
|
2255 | the sense that you can equally invoke the .s attribute on them to | |
2270 | automatically get a whitespace-separated string from their contents: |
|
2256 | automatically get a whitespace-separated string from their contents: | |
2271 |
|
2257 | |||
2272 | In [1]: sc -l b=ls *py |
|
2258 | In [1]: sc -l b=ls *py | |
2273 |
|
2259 | |||
2274 | In [2]: b |
|
2260 | In [2]: b | |
2275 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2261 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] | |
2276 |
|
2262 | |||
2277 | In [3]: b.s |
|
2263 | In [3]: b.s | |
2278 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2264 | Out[3]: 'setup.py win32_manual_post_install.py' | |
2279 |
|
2265 | |||
2280 | In summary, both the lists and strings used for ouptut capture have |
|
2266 | In summary, both the lists and strings used for ouptut capture have | |
2281 | the following special attributes: |
|
2267 | the following special attributes: | |
2282 |
|
2268 | |||
2283 | .l (or .list) : value as list. |
|
2269 | .l (or .list) : value as list. | |
2284 | .n (or .nlstr): value as newline-separated string. |
|
2270 | .n (or .nlstr): value as newline-separated string. | |
2285 | .s (or .spstr): value as space-separated string. |
|
2271 | .s (or .spstr): value as space-separated string. | |
2286 | """ |
|
2272 | """ | |
2287 |
|
2273 | |||
2288 | opts,args = self.parse_options(parameter_s,'lv') |
|
2274 | opts,args = self.parse_options(parameter_s,'lv') | |
2289 | # Try to get a variable name and command to run |
|
2275 | # Try to get a variable name and command to run | |
2290 | try: |
|
2276 | try: | |
2291 | # the variable name must be obtained from the parse_options |
|
2277 | # the variable name must be obtained from the parse_options | |
2292 | # output, which uses shlex.split to strip options out. |
|
2278 | # output, which uses shlex.split to strip options out. | |
2293 | var,_ = args.split('=',1) |
|
2279 | var,_ = args.split('=',1) | |
2294 | var = var.strip() |
|
2280 | var = var.strip() | |
2295 | # But the the command has to be extracted from the original input |
|
2281 | # But the the command has to be extracted from the original input | |
2296 | # parameter_s, not on what parse_options returns, to avoid the |
|
2282 | # parameter_s, not on what parse_options returns, to avoid the | |
2297 | # quote stripping which shlex.split performs on it. |
|
2283 | # quote stripping which shlex.split performs on it. | |
2298 | _,cmd = parameter_s.split('=',1) |
|
2284 | _,cmd = parameter_s.split('=',1) | |
2299 | except ValueError: |
|
2285 | except ValueError: | |
2300 | var,cmd = '','' |
|
2286 | var,cmd = '','' | |
2301 | if not var: |
|
2287 | if not var: | |
2302 | error('you must specify a variable to assign the command to.') |
|
2288 | error('you must specify a variable to assign the command to.') | |
2303 | return |
|
2289 | return | |
2304 | # If all looks ok, proceed |
|
2290 | # If all looks ok, proceed | |
2305 | out,err = self.shell.getoutputerror(cmd) |
|
2291 | out,err = self.shell.getoutputerror(cmd) | |
2306 | if err: |
|
2292 | if err: | |
2307 | print >> Term.cerr,err |
|
2293 | print >> Term.cerr,err | |
2308 | if opts.has_key('l'): |
|
2294 | if opts.has_key('l'): | |
2309 | out = SList(out.split('\n')) |
|
2295 | out = SList(out.split('\n')) | |
2310 | else: |
|
2296 | else: | |
2311 | out = LSString(out) |
|
2297 | out = LSString(out) | |
2312 | if opts.has_key('v'): |
|
2298 | if opts.has_key('v'): | |
2313 | print '%s ==\n%s' % (var,pformat(out)) |
|
2299 | print '%s ==\n%s' % (var,pformat(out)) | |
2314 | self.shell.user_ns.update({var:out}) |
|
2300 | self.shell.user_ns.update({var:out}) | |
2315 |
|
2301 | |||
2316 | def magic_sx(self, parameter_s=''): |
|
2302 | def magic_sx(self, parameter_s=''): | |
2317 | """Shell execute - run a shell command and capture its output. |
|
2303 | """Shell execute - run a shell command and capture its output. | |
2318 |
|
2304 | |||
2319 | %sx command |
|
2305 | %sx command | |
2320 |
|
2306 | |||
2321 | IPython will run the given command using commands.getoutput(), and |
|
2307 | IPython will run the given command using commands.getoutput(), and | |
2322 | return the result formatted as a list (split on '\\n'). Since the |
|
2308 | return the result formatted as a list (split on '\\n'). Since the | |
2323 | output is _returned_, it will be stored in ipython's regular output |
|
2309 | output is _returned_, it will be stored in ipython's regular output | |
2324 | cache Out[N] and in the '_N' automatic variables. |
|
2310 | cache Out[N] and in the '_N' automatic variables. | |
2325 |
|
2311 | |||
2326 | Notes: |
|
2312 | Notes: | |
2327 |
|
2313 | |||
2328 | 1) If an input line begins with '!!', then %sx is automatically |
|
2314 | 1) If an input line begins with '!!', then %sx is automatically | |
2329 | invoked. That is, while: |
|
2315 | invoked. That is, while: | |
2330 | !ls |
|
2316 | !ls | |
2331 | causes ipython to simply issue system('ls'), typing |
|
2317 | causes ipython to simply issue system('ls'), typing | |
2332 | !!ls |
|
2318 | !!ls | |
2333 | is a shorthand equivalent to: |
|
2319 | is a shorthand equivalent to: | |
2334 | %sx ls |
|
2320 | %sx ls | |
2335 |
|
2321 | |||
2336 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2322 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2337 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2323 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2338 | to process line-oriented shell output via further python commands. |
|
2324 | to process line-oriented shell output via further python commands. | |
2339 | %sc is meant to provide much finer control, but requires more |
|
2325 | %sc is meant to provide much finer control, but requires more | |
2340 | typing. |
|
2326 | typing. | |
2341 |
|
2327 | |||
2342 | 3) Just like %sc -l, this is a list with special attributes: |
|
2328 | 3) Just like %sc -l, this is a list with special attributes: | |
2343 |
|
2329 | |||
2344 | .l (or .list) : value as list. |
|
2330 | .l (or .list) : value as list. | |
2345 | .n (or .nlstr): value as newline-separated string. |
|
2331 | .n (or .nlstr): value as newline-separated string. | |
2346 | .s (or .spstr): value as whitespace-separated string. |
|
2332 | .s (or .spstr): value as whitespace-separated string. | |
2347 |
|
2333 | |||
2348 | This is very useful when trying to use such lists as arguments to |
|
2334 | This is very useful when trying to use such lists as arguments to | |
2349 | system commands.""" |
|
2335 | system commands.""" | |
2350 |
|
2336 | |||
2351 | if parameter_s: |
|
2337 | if parameter_s: | |
2352 | out,err = self.shell.getoutputerror(parameter_s) |
|
2338 | out,err = self.shell.getoutputerror(parameter_s) | |
2353 | if err: |
|
2339 | if err: | |
2354 | print >> Term.cerr,err |
|
2340 | print >> Term.cerr,err | |
2355 | return SList(out.split('\n')) |
|
2341 | return SList(out.split('\n')) | |
2356 |
|
2342 | |||
2357 | def magic_bg(self, parameter_s=''): |
|
2343 | def magic_bg(self, parameter_s=''): | |
2358 | """Run a job in the background, in a separate thread. |
|
2344 | """Run a job in the background, in a separate thread. | |
2359 |
|
2345 | |||
2360 | For example, |
|
2346 | For example, | |
2361 |
|
2347 | |||
2362 | %bg myfunc(x,y,z=1) |
|
2348 | %bg myfunc(x,y,z=1) | |
2363 |
|
2349 | |||
2364 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2350 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
2365 | execution starts, a message will be printed indicating the job |
|
2351 | execution starts, a message will be printed indicating the job | |
2366 | number. If your job number is 5, you can use |
|
2352 | number. If your job number is 5, you can use | |
2367 |
|
2353 | |||
2368 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2354 | myvar = jobs.result(5) or myvar = jobs[5].result | |
2369 |
|
2355 | |||
2370 | to assign this result to variable 'myvar'. |
|
2356 | to assign this result to variable 'myvar'. | |
2371 |
|
2357 | |||
2372 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2358 | IPython has a job manager, accessible via the 'jobs' object. You can | |
2373 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2359 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
2374 | its attributes. All attributes not starting with an underscore are |
|
2360 | its attributes. All attributes not starting with an underscore are | |
2375 | meant for public use. |
|
2361 | meant for public use. | |
2376 |
|
2362 | |||
2377 | In particular, look at the jobs.new() method, which is used to create |
|
2363 | In particular, look at the jobs.new() method, which is used to create | |
2378 | new jobs. This magic %bg function is just a convenience wrapper |
|
2364 | new jobs. This magic %bg function is just a convenience wrapper | |
2379 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2365 | around jobs.new(), for expression-based jobs. If you want to create a | |
2380 | new job with an explicit function object and arguments, you must call |
|
2366 | new job with an explicit function object and arguments, you must call | |
2381 | jobs.new() directly. |
|
2367 | jobs.new() directly. | |
2382 |
|
2368 | |||
2383 | The jobs.new docstring also describes in detail several important |
|
2369 | The jobs.new docstring also describes in detail several important | |
2384 | caveats associated with a thread-based model for background job |
|
2370 | caveats associated with a thread-based model for background job | |
2385 | execution. Type jobs.new? for details. |
|
2371 | execution. Type jobs.new? for details. | |
2386 |
|
2372 | |||
2387 | You can check the status of all jobs with jobs.status(). |
|
2373 | You can check the status of all jobs with jobs.status(). | |
2388 |
|
2374 | |||
2389 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2375 | The jobs variable is set by IPython into the Python builtin namespace. | |
2390 | If you ever declare a variable named 'jobs', you will shadow this |
|
2376 | If you ever declare a variable named 'jobs', you will shadow this | |
2391 | name. You can either delete your global jobs variable to regain |
|
2377 | name. You can either delete your global jobs variable to regain | |
2392 | access to the job manager, or make a new name and assign it manually |
|
2378 | access to the job manager, or make a new name and assign it manually | |
2393 | to the manager (stored in IPython's namespace). For example, to |
|
2379 | to the manager (stored in IPython's namespace). For example, to | |
2394 | assign the job manager to the Jobs name, use: |
|
2380 | assign the job manager to the Jobs name, use: | |
2395 |
|
2381 | |||
2396 | Jobs = __builtins__.jobs""" |
|
2382 | Jobs = __builtins__.jobs""" | |
2397 |
|
2383 | |||
2398 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2384 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
2399 |
|
2385 | |||
2400 | def magic_bookmark(self, parameter_s=''): |
|
2386 | def magic_bookmark(self, parameter_s=''): | |
2401 | """Manage IPython's bookmark system. |
|
2387 | """Manage IPython's bookmark system. | |
2402 |
|
2388 | |||
2403 | %bookmark <name> - set bookmark to current dir |
|
2389 | %bookmark <name> - set bookmark to current dir | |
2404 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2390 | %bookmark <name> <dir> - set bookmark to <dir> | |
2405 | %bookmark -l - list all bookmarks |
|
2391 | %bookmark -l - list all bookmarks | |
2406 | %bookmark -d <name> - remove bookmark |
|
2392 | %bookmark -d <name> - remove bookmark | |
2407 | %bookmark -r - remove all bookmarks |
|
2393 | %bookmark -r - remove all bookmarks | |
2408 |
|
2394 | |||
2409 | You can later on access a bookmarked folder with: |
|
2395 | You can later on access a bookmarked folder with: | |
2410 | %cd -b <name> |
|
2396 | %cd -b <name> | |
2411 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2397 | or simply '%cd <name>' if there is no directory called <name> AND | |
2412 | there is such a bookmark defined. |
|
2398 | there is such a bookmark defined. | |
2413 |
|
2399 | |||
2414 | Your bookmarks persist through IPython sessions, but they are |
|
2400 | Your bookmarks persist through IPython sessions, but they are | |
2415 | associated with each profile.""" |
|
2401 | associated with each profile.""" | |
2416 |
|
2402 | |||
2417 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2403 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
2418 | if len(args) > 2: |
|
2404 | if len(args) > 2: | |
2419 | error('You can only give at most two arguments') |
|
2405 | error('You can only give at most two arguments') | |
2420 | return |
|
2406 | return | |
2421 |
|
2407 | |||
2422 | bkms = self.shell.persist.get('bookmarks',{}) |
|
2408 | bkms = self.shell.persist.get('bookmarks',{}) | |
2423 |
|
2409 | |||
2424 | if opts.has_key('d'): |
|
2410 | if opts.has_key('d'): | |
2425 | try: |
|
2411 | try: | |
2426 | todel = args[0] |
|
2412 | todel = args[0] | |
2427 | except IndexError: |
|
2413 | except IndexError: | |
2428 | error('You must provide a bookmark to delete') |
|
2414 | error('You must provide a bookmark to delete') | |
2429 | else: |
|
2415 | else: | |
2430 | try: |
|
2416 | try: | |
2431 | del bkms[todel] |
|
2417 | del bkms[todel] | |
2432 | except: |
|
2418 | except: | |
2433 | error("Can't delete bookmark '%s'" % todel) |
|
2419 | error("Can't delete bookmark '%s'" % todel) | |
2434 | elif opts.has_key('r'): |
|
2420 | elif opts.has_key('r'): | |
2435 | bkms = {} |
|
2421 | bkms = {} | |
2436 | elif opts.has_key('l'): |
|
2422 | elif opts.has_key('l'): | |
2437 | bks = bkms.keys() |
|
2423 | bks = bkms.keys() | |
2438 | bks.sort() |
|
2424 | bks.sort() | |
2439 | if bks: |
|
2425 | if bks: | |
2440 | size = max(map(len,bks)) |
|
2426 | size = max(map(len,bks)) | |
2441 | else: |
|
2427 | else: | |
2442 | size = 0 |
|
2428 | size = 0 | |
2443 | fmt = '%-'+str(size)+'s -> %s' |
|
2429 | fmt = '%-'+str(size)+'s -> %s' | |
2444 | print 'Current bookmarks:' |
|
2430 | print 'Current bookmarks:' | |
2445 | for bk in bks: |
|
2431 | for bk in bks: | |
2446 | print fmt % (bk,bkms[bk]) |
|
2432 | print fmt % (bk,bkms[bk]) | |
2447 | else: |
|
2433 | else: | |
2448 | if not args: |
|
2434 | if not args: | |
2449 | error("You must specify the bookmark name") |
|
2435 | error("You must specify the bookmark name") | |
2450 | elif len(args)==1: |
|
2436 | elif len(args)==1: | |
2451 | bkms[args[0]] = os.getcwd() |
|
2437 | bkms[args[0]] = os.getcwd() | |
2452 | elif len(args)==2: |
|
2438 | elif len(args)==2: | |
2453 | bkms[args[0]] = args[1] |
|
2439 | bkms[args[0]] = args[1] | |
2454 | self.persist['bookmarks'] = bkms |
|
2440 | self.persist['bookmarks'] = bkms | |
2455 |
|
2441 | |||
2456 | def magic_pycat(self, parameter_s=''): |
|
2442 | def magic_pycat(self, parameter_s=''): | |
2457 | """Show a syntax-highlighted file through a pager. |
|
2443 | """Show a syntax-highlighted file through a pager. | |
2458 |
|
2444 | |||
2459 | This magic is similar to the cat utility, but it will assume the file |
|
2445 | This magic is similar to the cat utility, but it will assume the file | |
2460 | to be Python source and will show it with syntax highlighting. """ |
|
2446 | to be Python source and will show it with syntax highlighting. """ | |
2461 |
|
2447 | |||
2462 | try: |
|
2448 | filename = get_py_filename(parameter_s) | |
2463 | filename = get_py_filename(parameter_s) |
|
2449 | page(self.shell.colorize(file_read(filename)), | |
2464 | except IndexError: |
|
2450 | screen_lines=self.shell.rc.screen_length) | |
2465 | warn('you must provide at least a filename.') |
|
|||
2466 | return |
|
|||
2467 | fobj=open(filename,'r') |
|
|||
2468 | source = fobj.read() |
|
|||
2469 | fobj.close() |
|
|||
2470 | colorize = Parser().format |
|
|||
2471 | colorized_src = colorize(source,'str',self.shell.rc['colors']) |
|
|||
2472 | page(colorized_src,screen_lines=self.shell.rc.screen_length) |
|
|||
2473 |
|
2451 | |||
2474 | # end Magic |
|
2452 | # end Magic |
@@ -1,201 +1,309 b'' | |||||
1 | """Module for interactive demos using IPython. |
|
1 | """Module for interactive demos using IPython. | |
2 |
|
2 | |||
3 | Sorry, but this uses Python 2.3 features, so it won't work in 2.2 environments. |
|
3 | This module implements a single class, Demo, for running Python scripts | |
|
4 | interactively in IPython for demonstrations. With very simple markup (a few | |||
|
5 | tags in comments), you can control points where the script stops executing and | |||
|
6 | returns control to IPython. | |||
|
7 | ||||
|
8 | The file is run in its own empty namespace (though you can pass it a string of | |||
|
9 | arguments as if in a command line environment, and it will see those as | |||
|
10 | sys.argv). But at each stop, the global IPython namespace is updated with the | |||
|
11 | current internal demo namespace, so you can work interactively with the data | |||
|
12 | accumulated so far. | |||
|
13 | ||||
|
14 | By default, each block of code is printed (with syntax highlighting) before | |||
|
15 | executing it and you have to confirm execution. This is intended to show the | |||
|
16 | code to an audience first so you can discuss it, and only proceed with | |||
|
17 | execution once you agree. There are a few tags which allow you to modify this | |||
|
18 | behavior. | |||
|
19 | ||||
|
20 | The supported tags are: | |||
|
21 | ||||
|
22 | # <demo> --- stop --- | |||
|
23 | ||||
|
24 | Defines block boundaries, the points where IPython stops execution of the | |||
|
25 | file and returns to the interactive prompt. | |||
|
26 | ||||
|
27 | # <demo> silent | |||
|
28 | ||||
|
29 | Make a block execute silently (and hence automatically). Typically used in | |||
|
30 | cases where you have some boilerplate or initialization code which you need | |||
|
31 | executed but do not want to be seen in the demo. | |||
|
32 | ||||
|
33 | # <demo> auto | |||
|
34 | ||||
|
35 | Make a block execute automatically, but still being printed. Useful for | |||
|
36 | simple code which does not warrant discussion, since it avoids the extra | |||
|
37 | manual confirmation. | |||
|
38 | ||||
|
39 | # <demo> auto_all | |||
|
40 | ||||
|
41 | This tag can _only_ be in the first block, and if given it overrides the | |||
|
42 | individual auto tags to make the whole demo fully automatic (no block asks | |||
|
43 | for confirmation). It can also be given at creation time (or the attribute | |||
|
44 | set later) to override what's in the file. | |||
|
45 | ||||
|
46 | While _any_ python file can be run as a Demo instance, if there are no stop | |||
|
47 | tags the whole file will run in a single block (no different that calling | |||
|
48 | first %pycat and then %run). The minimal markup to make this useful is to | |||
|
49 | place a set of stop tags; the other tags are only there to let you fine-tune | |||
|
50 | the execution. | |||
|
51 | ||||
|
52 | This is probably best explained with the simple example file below. You can | |||
|
53 | copy this into a file named ex_demo.py, and try running it via: | |||
|
54 | ||||
|
55 | from IPython.demo import Demo | |||
|
56 | d = Demo('ex_demo.py') | |||
|
57 | d() <--- Call the d object (omit the parens if you have autocall on). | |||
|
58 | ||||
|
59 | Each time you call the demo object, it runs the next block. The demo object | |||
|
60 | has a few useful methods for navigation, like again(), jump(), seek() and | |||
|
61 | back(). It can be reset for a new run via reset() or reloaded from disk (in | |||
|
62 | case you've edited the source) via reload(). See their docstrings below. | |||
|
63 | ||||
|
64 | #################### EXAMPLE DEMO <ex_demo.py> ############################### | |||
|
65 | '''A simple interactive demo to illustrate the use of IPython's Demo class.''' | |||
|
66 | ||||
|
67 | print 'Hello, welcome to an interactive IPython demo.' | |||
|
68 | ||||
|
69 | # The mark below defines a block boundary, which is a point where IPython will | |||
|
70 | # stop execution and return to the interactive prompt. | |||
|
71 | # Note that in actual interactive execution, | |||
|
72 | # <demo> --- stop --- | |||
|
73 | ||||
|
74 | x = 1 | |||
|
75 | y = 2 | |||
|
76 | ||||
|
77 | # <demo> --- stop --- | |||
|
78 | ||||
|
79 | # the mark below makes this block as silent | |||
|
80 | # <demo> silent | |||
|
81 | ||||
|
82 | print 'This is a silent block, which gets executed but not printed.' | |||
|
83 | ||||
|
84 | # <demo> --- stop --- | |||
|
85 | # <demo> auto | |||
|
86 | print 'This is an automatic block.' | |||
|
87 | print 'It is executed without asking for confirmation, but printed.' | |||
|
88 | z = x+y | |||
|
89 | ||||
|
90 | print 'z=',x | |||
|
91 | ||||
|
92 | # <demo> --- stop --- | |||
|
93 | # This is just another normal block. | |||
|
94 | print 'z is now:', z | |||
|
95 | ||||
|
96 | print 'bye!' | |||
|
97 | ################### END EXAMPLE DEMO <ex_demo.py> ############################ | |||
|
98 | ||||
|
99 | WARNING: this module uses Python 2.3 features, so it won't work in 2.2 | |||
|
100 | environments. | |||
4 | """ |
|
101 | """ | |
5 | #***************************************************************************** |
|
102 | #***************************************************************************** | |
6 | # Copyright (C) 2005 Fernando Perez. <Fernando.Perez@colorado.edu> |
|
103 | # Copyright (C) 2005 Fernando Perez. <Fernando.Perez@colorado.edu> | |
7 | # |
|
104 | # | |
8 | # Distributed under the terms of the BSD License. The full license is in |
|
105 | # Distributed under the terms of the BSD License. The full license is in | |
9 | # the file COPYING, distributed as part of this software. |
|
106 | # the file COPYING, distributed as part of this software. | |
10 | # |
|
107 | # | |
11 | #***************************************************************************** |
|
108 | #***************************************************************************** | |
12 |
|
109 | |||
13 | import sys |
|
110 | import sys | |
14 | import exceptions |
|
111 | import exceptions | |
15 | import re |
|
112 | import re | |
16 |
|
113 | |||
17 | from IPython.PyColorize import Parser |
|
114 | from IPython.PyColorize import Parser | |
18 | from IPython.genutils import marquee, shlex_split |
|
115 | from IPython.genutils import marquee, shlex_split, file_read | |
|
116 | ||||
|
117 | __all__ = ['Demo','DemoError'] | |||
19 |
|
118 | |||
20 | class DemoError(exceptions.Exception): pass |
|
119 | class DemoError(exceptions.Exception): pass | |
21 |
|
120 | |||
|
121 | def re_mark(mark): | |||
|
122 | return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE) | |||
|
123 | ||||
22 | class Demo: |
|
124 | class Demo: | |
23 | def __init__(self,fname,arg_str='',mark_pause='# pause', |
|
125 | ||
24 | mark_silent='# silent',mark_auto='# auto',auto=False): |
|
126 | re_stop = re_mark('---\s?stop\s?---') | |
|
127 | re_silent = re_mark('silent') | |||
|
128 | re_auto = re_mark('auto') | |||
|
129 | re_auto_all = re_mark('auto_all') | |||
|
130 | ||||
|
131 | def __init__(self,fname,arg_str='',auto_all=None): | |||
25 | """Make a new demo object. To run the demo, simply call the object. |
|
132 | """Make a new demo object. To run the demo, simply call the object. | |
26 |
|
133 | |||
|
134 | See the module docstring for full details and an example (you can use | |||
|
135 | IPython.Demo? in IPython to see it). | |||
|
136 | ||||
27 | Inputs: |
|
137 | Inputs: | |
28 |
|
138 | |||
29 | - fname = filename. |
|
139 | - fname = filename. | |
30 |
|
140 | |||
31 | Optional inputs: |
|
141 | Optional inputs: | |
32 |
|
142 | |||
33 | - arg_str(''): a string of arguments, internally converted to a list |
|
143 | - arg_str(''): a string of arguments, internally converted to a list | |
34 | just like sys.argv, so the demo script can see a similar |
|
144 | just like sys.argv, so the demo script can see a similar | |
35 | environment. |
|
145 | environment. | |
36 |
|
146 | |||
37 | - mark_pause ('# pause'): marks for pausing (block boundaries). The |
|
147 | - auto_all(None): global flag to run all blocks automatically without | |
38 | marks are turned into regexps which match them as standalone in a |
|
|||
39 | line, with all leading/trailing whitespace ignored. |
|
|||
40 |
|
||||
41 | - mark_silent('# silent'): mark blocks as silent, which means that |
|
|||
42 | they are executed without printing their content to screen. Silent |
|
|||
43 | blocks are always automatically executed. |
|
|||
44 |
|
||||
45 | - mark_auto ('# auto'): mark individual blocks as automatically |
|
|||
46 | executed (without asking for confirmation). |
|
|||
47 |
|
||||
48 | - auto(False): global flag to run all blocks automatically without |
|
|||
49 | confirmation. This attribute overrides the block-level tags and |
|
148 | confirmation. This attribute overrides the block-level tags and | |
50 | applies to the whole demo. It is an attribute of the object, and |
|
149 | applies to the whole demo. It is an attribute of the object, and | |
51 | can be changed at runtime simply by reassigning it to a boolean |
|
150 | can be changed at runtime simply by reassigning it to a boolean | |
52 | value. |
|
151 | value. | |
53 | """ |
|
152 | """ | |
54 |
|
153 | |||
55 |
self.fname |
|
154 | self.fname = fname | |
56 |
self.sys_argv |
|
155 | self.sys_argv = [fname] + shlex_split(arg_str) | |
57 | self.mark_pause = mark_pause |
|
156 | self.auto_all = auto_all | |
58 | self.mark_silent = mark_silent |
|
157 | ||
59 | self.re_pause = re.compile(r'^\s*%s\s*$' % mark_pause,re.MULTILINE) |
|
|||
60 | self.re_silent = re.compile(r'^\s*%s\s*$' % mark_silent,re.MULTILINE) |
|
|||
61 | self.re_auto = re.compile(r'^\s*%s\s*$' % mark_auto,re.MULTILINE) |
|
|||
62 | self.auto = auto |
|
|||
63 |
|
||||
64 | # get a few things from ipython. While it's a bit ugly design-wise, |
|
158 | # get a few things from ipython. While it's a bit ugly design-wise, | |
65 | # it ensures that things like color scheme and the like are always in |
|
159 | # it ensures that things like color scheme and the like are always in | |
66 | # sync with the ipython mode being used. This class is only meant to |
|
160 | # sync with the ipython mode being used. This class is only meant to | |
67 | # be used inside ipython anyways, so it's OK. |
|
161 | # be used inside ipython anyways, so it's OK. | |
68 | self.ip_showtb = __IPYTHON__.showtraceback |
|
162 | self.ip_showtb = __IPYTHON__.showtraceback | |
69 | self.ip_ns = __IPYTHON__.user_ns |
|
163 | self.ip_ns = __IPYTHON__.user_ns | |
70 |
self.ip_color |
|
164 | self.ip_colorize = __IPYTHON__.pycolorize | |
71 | self.colorize = Parser().format |
|
|||
72 |
|
165 | |||
73 | # load user data and initialize data structures |
|
166 | # load user data and initialize data structures | |
74 | self.reload() |
|
167 | self.reload() | |
75 |
|
168 | |||
76 | def reload(self): |
|
169 | def reload(self): | |
77 | """Reload source from disk and initialize state.""" |
|
170 | """Reload source from disk and initialize state.""" | |
78 | # read data and parse into blocks |
|
171 | # read data and parse into blocks | |
79 |
|
|
172 | self.src = file_read(self.fname) | |
80 | self.src = fobj.read() |
|
173 | src_b = [b.strip() for b in self.re_stop.split(self.src) if b] | |
81 | fobj.close() |
|
174 | self._silent = [bool(self.re_silent.findall(b)) for b in src_b] | |
82 | src_blocks = [b.strip() for b in self.re_pause.split(self.src) if b] |
|
175 | self._auto = [bool(self.re_auto.findall(b)) for b in src_b] | |
83 | self._silent = [bool(self.re_silent.findall(b)) for b in src_blocks] |
|
176 | ||
84 | self._auto = [bool(self.re_auto.findall(b)) for b in src_blocks] |
|
177 | # if auto_all is not given (def. None), we read it from the file | |
85 | # strip out the 'auto' markers |
|
178 | if self.auto_all is None: | |
86 | src_b = [] |
|
179 | self.auto_all = bool(self.re_auto_all.findall(src_b[0])) | |
|
180 | else: | |||
|
181 | self.auto_all = bool(self.auto_all) | |||
|
182 | ||||
|
183 | # Clean the sources from all markup so it doesn't get displayed when | |||
|
184 | # running the demo | |||
|
185 | src_blocks = [] | |||
87 | auto_strip = lambda s: self.re_auto.sub('',s) |
|
186 | auto_strip = lambda s: self.re_auto.sub('',s) | |
88 |
for i,b in enumerate(src_b |
|
187 | for i,b in enumerate(src_b): | |
89 | if self._auto[i]: |
|
188 | if self._auto[i]: | |
90 | src_b.append(auto_strip(b)) |
|
189 | src_blocks.append(auto_strip(b)) | |
91 | else: |
|
190 | else: | |
92 | src_b.append(b) |
|
191 | src_blocks.append(b) | |
93 | self.nblocks = len(src_b) |
|
192 | # remove the auto_all marker | |
94 | self.src_blocks = src_b |
|
193 | src_blocks[0] = self.re_auto_all.sub('',src_blocks[0]) | |
95 |
|
194 | |||
96 | # try to colorize blocks |
|
195 | self.nblocks = len(src_blocks) | |
97 | col_scheme = self.ip_colors |
|
196 | self.src_blocks = src_blocks | |
98 | self.src_blocks_colored = [self.colorize(s_blk,'str',col_scheme) |
|
197 | ||
99 | for s_blk in self.src_blocks] |
|
198 | # also build syntax-highlighted source | |
|
199 | self.src_blocks_colored = map(self.ip_colorize,self.src_blocks) | |||
|
200 | ||||
100 | # ensure clean namespace and seek offset |
|
201 | # ensure clean namespace and seek offset | |
101 | self.reset() |
|
202 | self.reset() | |
102 |
|
203 | |||
103 | def reset(self): |
|
204 | def reset(self): | |
104 | """Reset the namespace and seek pointer to restart the demo""" |
|
205 | """Reset the namespace and seek pointer to restart the demo""" | |
105 | self.user_ns = {} |
|
206 | self.user_ns = {} | |
106 | self.finished = False |
|
207 | self.finished = False | |
107 | self.block_index = 0 |
|
208 | self.block_index = 0 | |
108 |
|
209 | |||
109 | def again(self): |
|
|||
110 | """Repeat the last block""" |
|
|||
111 | self.block_index -= 1 |
|
|||
112 | self.finished = False |
|
|||
113 | self() |
|
|||
114 |
|
||||
115 | def _validate_index(self,index): |
|
210 | def _validate_index(self,index): | |
116 | if index<0 or index>=self.nblocks: |
|
211 | if index<0 or index>=self.nblocks: | |
117 | raise ValueError('invalid block index %s' % index) |
|
212 | raise ValueError('invalid block index %s' % index) | |
118 |
|
213 | |||
119 | def seek(self,index): |
|
214 | def seek(self,index): | |
120 | """Move the current seek pointer to the given block""" |
|
215 | """Move the current seek pointer to the given block""" | |
121 | self._validate_index(index) |
|
216 | self._validate_index(index) | |
122 | self.block_index = index |
|
217 | self.block_index = index | |
123 | self.finished = False |
|
218 | self.finished = False | |
124 |
|
219 | |||
|
220 | def back(self,num=1): | |||
|
221 | """Move the seek pointer back num blocks (default is 1).""" | |||
|
222 | self.seek(self.block_index-num) | |||
|
223 | ||||
|
224 | def jump(self,num): | |||
|
225 | """Jump a given number of blocks relative to the current one.""" | |||
|
226 | self.seek(self.block_index+num) | |||
|
227 | ||||
|
228 | def again(self): | |||
|
229 | """Move the seek pointer back one block and re-execute.""" | |||
|
230 | self.back(1) | |||
|
231 | self() | |||
|
232 | ||||
125 | def show(self,index=None): |
|
233 | def show(self,index=None): | |
126 | """Show a single block on screen""" |
|
234 | """Show a single block on screen""" | |
127 | if index is None: |
|
235 | if index is None: | |
128 | if self.finished: |
|
236 | if self.finished: | |
129 | print 'Demo finished. Use reset() if you want to rerun it.' |
|
237 | print 'Demo finished. Use reset() if you want to rerun it.' | |
130 | return |
|
238 | return | |
131 | index = self.block_index |
|
239 | index = self.block_index | |
132 | else: |
|
240 | else: | |
133 | self._validate_index(index) |
|
241 | self._validate_index(index) | |
134 | print marquee('<%s> block # %s (%s remaining)' % |
|
242 | print marquee('<%s> block # %s (%s remaining)' % | |
135 | (self.fname,index,self.nblocks-index-1)) |
|
243 | (self.fname,index,self.nblocks-index-1)) | |
136 | print self.src_blocks_colored[index], |
|
244 | print self.src_blocks_colored[index], | |
137 |
|
245 | |||
138 | def show_all(self): |
|
246 | def show_all(self): | |
139 | """Show entire demo on screen, block by block""" |
|
247 | """Show entire demo on screen, block by block""" | |
140 |
|
248 | |||
141 | fname = self.fname |
|
249 | fname = self.fname | |
142 | nblocks = self.nblocks |
|
250 | nblocks = self.nblocks | |
143 | silent = self._silent |
|
251 | silent = self._silent | |
144 | for index,block in enumerate(self.src_blocks_colored): |
|
252 | for index,block in enumerate(self.src_blocks_colored): | |
145 | if silent[index]: |
|
253 | if silent[index]: | |
146 | print marquee('<%s> SILENT block # %s (%s remaining)' % |
|
254 | print marquee('<%s> SILENT block # %s (%s remaining)' % | |
147 | (fname,index,nblocks-index-1)) |
|
255 | (fname,index,nblocks-index-1)) | |
148 | else: |
|
256 | else: | |
149 | print marquee('<%s> block # %s (%s remaining)' % |
|
257 | print marquee('<%s> block # %s (%s remaining)' % | |
150 | (fname,index,nblocks-index-1)) |
|
258 | (fname,index,nblocks-index-1)) | |
151 | print block, |
|
259 | print block, | |
152 |
|
260 | |||
153 | def __call__(self,index=None): |
|
261 | def __call__(self,index=None): | |
154 | """run a block of the demo. |
|
262 | """run a block of the demo. | |
155 |
|
263 | |||
156 | If index is given, it should be an integer >=1 and <= nblocks. This |
|
264 | If index is given, it should be an integer >=1 and <= nblocks. This | |
157 | means that the calling convention is one off from typical Python |
|
265 | means that the calling convention is one off from typical Python | |
158 | lists. The reason for the inconsistency is that the demo always |
|
266 | lists. The reason for the inconsistency is that the demo always | |
159 | prints 'Block n/N, and N is the total, so it would be very odd to use |
|
267 | prints 'Block n/N, and N is the total, so it would be very odd to use | |
160 | zero-indexing here.""" |
|
268 | zero-indexing here.""" | |
161 |
|
269 | |||
162 | if index is None and self.finished: |
|
270 | if index is None and self.finished: | |
163 | print 'Demo finished. Use reset() if you want to rerun it.' |
|
271 | print 'Demo finished. Use reset() if you want to rerun it.' | |
164 | return |
|
272 | return | |
165 | if index is None: |
|
273 | if index is None: | |
166 | index = self.block_index |
|
274 | index = self.block_index | |
167 | self._validate_index(index) |
|
275 | self._validate_index(index) | |
168 | try: |
|
276 | try: | |
169 | next_block = self.src_blocks[index] |
|
277 | next_block = self.src_blocks[index] | |
170 | self.block_index += 1 |
|
278 | self.block_index += 1 | |
171 | if self._silent[index]: |
|
279 | if self._silent[index]: | |
172 | print marquee('Executing silent block # %s (%s remaining)' % |
|
280 | print marquee('Executing silent block # %s (%s remaining)' % | |
173 | (index,self.nblocks-index-1)) |
|
281 | (index,self.nblocks-index-1)) | |
174 | else: |
|
282 | else: | |
175 | self.show(index) |
|
283 | self.show(index) | |
176 | if self.auto or self._auto[index]: |
|
284 | if self.auto_all or self._auto[index]: | |
177 | print marquee('output') |
|
285 | print marquee('output') | |
178 | else: |
|
286 | else: | |
179 | print marquee('Press <q> to quit, <Enter> to execute...'), |
|
287 | print marquee('Press <q> to quit, <Enter> to execute...'), | |
180 | ans = raw_input().strip() |
|
288 | ans = raw_input().strip() | |
181 | if ans: |
|
289 | if ans: | |
182 | print marquee('Block NOT executed') |
|
290 | print marquee('Block NOT executed') | |
183 | return |
|
291 | return | |
184 | try: |
|
292 | try: | |
185 | save_argv = sys.argv |
|
293 | save_argv = sys.argv | |
186 | sys.argv = self.sys_argv |
|
294 | sys.argv = self.sys_argv | |
187 | exec next_block in self.user_ns |
|
295 | exec next_block in self.user_ns | |
188 | finally: |
|
296 | finally: | |
189 | sys.argv = save_argv |
|
297 | sys.argv = save_argv | |
190 |
|
298 | |||
191 | except: |
|
299 | except: | |
192 | self.ip_showtb(filename=self.fname) |
|
300 | self.ip_showtb(filename=self.fname) | |
193 | else: |
|
301 | else: | |
194 | self.ip_ns.update(self.user_ns) |
|
302 | self.ip_ns.update(self.user_ns) | |
195 |
|
303 | |||
196 | if self.block_index == self.nblocks: |
|
304 | if self.block_index == self.nblocks: | |
197 |
|
305 | |||
198 | print marquee(' END OF DEMO ') |
|
306 | print marquee(' END OF DEMO ') | |
199 | print marquee('Use reset() if you want to rerun it.') |
|
307 | print marquee('Use reset() if you want to rerun it.') | |
200 | self.finished = True |
|
308 | self.finished = True | |
201 |
|
309 |
@@ -1,1578 +1,1601 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 |
|
8 | $Id: genutils.py 908 2005-09-26 16:05:48Z fperez $""" | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> |
|
11 | # Copyright (C) 2001-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 | from __future__ import generators # 2.2 compatibility |
|
17 | from __future__ import generators # 2.2 compatibility | |
18 |
|
18 | |||
19 | from IPython import Release |
|
19 | from IPython import Release | |
20 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
20 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
21 | __license__ = Release.license |
|
21 | __license__ = Release.license | |
22 |
|
22 | |||
23 | #**************************************************************************** |
|
23 | #**************************************************************************** | |
24 | # required modules |
|
24 | # required modules | |
25 | import __main__ |
|
25 | import __main__ | |
26 | import types,commands,time,sys,os,re,shutil |
|
26 | import types,commands,time,sys,os,re,shutil | |
27 | import shlex |
|
27 | import shlex | |
28 | import tempfile |
|
28 | import tempfile | |
29 | from IPython.Itpl import Itpl,itpl,printpl |
|
29 | from IPython.Itpl import Itpl,itpl,printpl | |
30 | from IPython import DPyGetOpt |
|
30 | from IPython import DPyGetOpt | |
31 |
|
31 | |||
32 | # Build objects which appeared in Python 2.3 for 2.2, to make ipython |
|
32 | # Build objects which appeared in Python 2.3 for 2.2, to make ipython | |
33 | # 2.2-friendly |
|
33 | # 2.2-friendly | |
34 | try: |
|
34 | try: | |
35 | basestring |
|
35 | basestring | |
36 | except NameError: |
|
36 | except NameError: | |
37 | import types |
|
37 | import types | |
38 | basestring = (types.StringType, types.UnicodeType) |
|
38 | basestring = (types.StringType, types.UnicodeType) | |
39 | True = 1==1 |
|
39 | True = 1==1 | |
40 | False = 1==0 |
|
40 | False = 1==0 | |
41 |
|
41 | |||
42 | def enumerate(obj): |
|
42 | def enumerate(obj): | |
43 | i = -1 |
|
43 | i = -1 | |
44 | for item in obj: |
|
44 | for item in obj: | |
45 | i += 1 |
|
45 | i += 1 | |
46 | yield i, item |
|
46 | yield i, item | |
47 |
|
47 | |||
48 | # add these to the builtin namespace, so that all modules find them |
|
48 | # add these to the builtin namespace, so that all modules find them | |
49 | import __builtin__ |
|
49 | import __builtin__ | |
50 | __builtin__.basestring = basestring |
|
50 | __builtin__.basestring = basestring | |
51 | __builtin__.True = True |
|
51 | __builtin__.True = True | |
52 | __builtin__.False = False |
|
52 | __builtin__.False = False | |
53 | __builtin__.enumerate = enumerate |
|
53 | __builtin__.enumerate = enumerate | |
54 |
|
54 | |||
55 | # Try to use shlex.split for converting an input string into a sys.argv-type |
|
55 | # Try to use shlex.split for converting an input string into a sys.argv-type | |
56 | # list. This appeared in Python 2.3, so here's a quick backport for 2.2. |
|
56 | # list. This appeared in Python 2.3, so here's a quick backport for 2.2. | |
57 | try: |
|
57 | try: | |
58 | shlex_split = shlex.split |
|
58 | shlex_split = shlex.split | |
59 | except AttributeError: |
|
59 | except AttributeError: | |
60 | _quotesre = re.compile(r'[\'"](.*)[\'"]') |
|
60 | _quotesre = re.compile(r'[\'"](.*)[\'"]') | |
61 | _wordchars = ('abcdfeghijklmnopqrstuvwxyz' |
|
61 | _wordchars = ('abcdfeghijklmnopqrstuvwxyz' | |
62 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?' |
|
62 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?' | |
63 | 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' |
|
63 | 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' | |
64 | 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s' |
|
64 | 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s' | |
65 | % os.sep) |
|
65 | % os.sep) | |
66 |
|
66 | |||
67 | def shlex_split(s): |
|
67 | def shlex_split(s): | |
68 | """Simplified backport to Python 2.2 of shlex.split(). |
|
68 | """Simplified backport to Python 2.2 of shlex.split(). | |
69 |
|
69 | |||
70 | This is a quick and dirty hack, since the shlex module under 2.2 lacks |
|
70 | This is a quick and dirty hack, since the shlex module under 2.2 lacks | |
71 | several of the features needed to really match the functionality of |
|
71 | several of the features needed to really match the functionality of | |
72 | shlex.split() in 2.3.""" |
|
72 | shlex.split() in 2.3.""" | |
73 |
|
73 | |||
74 | lex = shlex.shlex(StringIO(s)) |
|
74 | lex = shlex.shlex(StringIO(s)) | |
75 | # Try to get options, extensions and path separators as characters |
|
75 | # Try to get options, extensions and path separators as characters | |
76 | lex.wordchars = _wordchars |
|
76 | lex.wordchars = _wordchars | |
77 | lex.commenters = '' |
|
77 | lex.commenters = '' | |
78 | # Make a list out of the lexer by hand, since in 2.2 it's not an |
|
78 | # Make a list out of the lexer by hand, since in 2.2 it's not an | |
79 | # iterator. |
|
79 | # iterator. | |
80 | lout = [] |
|
80 | lout = [] | |
81 | while 1: |
|
81 | while 1: | |
82 | token = lex.get_token() |
|
82 | token = lex.get_token() | |
83 | if token == '': |
|
83 | if token == '': | |
84 | break |
|
84 | break | |
85 | # Try to handle quoted tokens correctly |
|
85 | # Try to handle quoted tokens correctly | |
86 | quotes = _quotesre.match(token) |
|
86 | quotes = _quotesre.match(token) | |
87 | if quotes: |
|
87 | if quotes: | |
88 | token = quotes.group(1) |
|
88 | token = quotes.group(1) | |
89 | lout.append(token) |
|
89 | lout.append(token) | |
90 | return lout |
|
90 | return lout | |
91 |
|
91 | |||
92 | #**************************************************************************** |
|
92 | #**************************************************************************** | |
93 | # Exceptions |
|
93 | # Exceptions | |
94 | class Error(Exception): |
|
94 | class Error(Exception): | |
95 | """Base class for exceptions in this module.""" |
|
95 | """Base class for exceptions in this module.""" | |
96 | pass |
|
96 | pass | |
97 |
|
97 | |||
98 | #---------------------------------------------------------------------------- |
|
98 | #---------------------------------------------------------------------------- | |
99 | class IOStream: |
|
99 | class IOStream: | |
100 | def __init__(self,stream,fallback): |
|
100 | def __init__(self,stream,fallback): | |
101 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
101 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): | |
102 | stream = fallback |
|
102 | stream = fallback | |
103 | self.stream = stream |
|
103 | self.stream = stream | |
104 | self._swrite = stream.write |
|
104 | self._swrite = stream.write | |
105 | self.flush = stream.flush |
|
105 | self.flush = stream.flush | |
106 |
|
106 | |||
107 | def write(self,data): |
|
107 | def write(self,data): | |
108 | try: |
|
108 | try: | |
109 | self._swrite(data) |
|
109 | self._swrite(data) | |
110 | except: |
|
110 | except: | |
111 | try: |
|
111 | try: | |
112 | # print handles some unicode issues which may trip a plain |
|
112 | # print handles some unicode issues which may trip a plain | |
113 | # write() call. Attempt to emulate write() by using a |
|
113 | # write() call. Attempt to emulate write() by using a | |
114 | # trailing comma |
|
114 | # trailing comma | |
115 | print >> self.stream, data, |
|
115 | print >> self.stream, data, | |
116 | except: |
|
116 | except: | |
117 | # if we get here, something is seriously broken. |
|
117 | # if we get here, something is seriously broken. | |
118 | print >> sys.stderr, \ |
|
118 | print >> sys.stderr, \ | |
119 | 'ERROR - failed to write data to stream:', stream |
|
119 | 'ERROR - failed to write data to stream:', stream | |
120 |
|
120 | |||
121 | class IOTerm: |
|
121 | class IOTerm: | |
122 | """ Term holds the file or file-like objects for handling I/O operations. |
|
122 | """ Term holds the file or file-like objects for handling I/O operations. | |
123 |
|
123 | |||
124 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
124 | These are normally just sys.stdin, sys.stdout and sys.stderr but for | |
125 | Windows they can can replaced to allow editing the strings before they are |
|
125 | Windows they can can replaced to allow editing the strings before they are | |
126 | displayed.""" |
|
126 | displayed.""" | |
127 |
|
127 | |||
128 | # In the future, having IPython channel all its I/O operations through |
|
128 | # In the future, having IPython channel all its I/O operations through | |
129 | # this class will make it easier to embed it into other environments which |
|
129 | # this class will make it easier to embed it into other environments which | |
130 | # are not a normal terminal (such as a GUI-based shell) |
|
130 | # are not a normal terminal (such as a GUI-based shell) | |
131 | def __init__(self,cin=None,cout=None,cerr=None): |
|
131 | def __init__(self,cin=None,cout=None,cerr=None): | |
132 | self.cin = IOStream(cin,sys.stdin) |
|
132 | self.cin = IOStream(cin,sys.stdin) | |
133 | self.cout = IOStream(cout,sys.stdout) |
|
133 | self.cout = IOStream(cout,sys.stdout) | |
134 | self.cerr = IOStream(cerr,sys.stderr) |
|
134 | self.cerr = IOStream(cerr,sys.stderr) | |
135 |
|
135 | |||
136 | # Global variable to be used for all I/O |
|
136 | # Global variable to be used for all I/O | |
137 | Term = IOTerm() |
|
137 | Term = IOTerm() | |
138 |
|
138 | |||
139 | # Windows-specific code to load Gary Bishop's readline and configure it |
|
139 | # Windows-specific code to load Gary Bishop's readline and configure it | |
140 | # automatically for the users |
|
140 | # automatically for the users | |
141 | # Note: os.name on cygwin returns posix, so this should only pick up 'native' |
|
141 | # Note: os.name on cygwin returns posix, so this should only pick up 'native' | |
142 | # windows. Cygwin returns 'cygwin' for sys.platform. |
|
142 | # windows. Cygwin returns 'cygwin' for sys.platform. | |
143 | if os.name == 'nt': |
|
143 | if os.name == 'nt': | |
144 | try: |
|
144 | try: | |
145 | import readline |
|
145 | import readline | |
146 | except ImportError: |
|
146 | except ImportError: | |
147 | pass |
|
147 | pass | |
148 | else: |
|
148 | else: | |
149 | try: |
|
149 | try: | |
150 | _out = readline.GetOutputFile() |
|
150 | _out = readline.GetOutputFile() | |
151 | except AttributeError: |
|
151 | except AttributeError: | |
152 | pass |
|
152 | pass | |
153 | else: |
|
153 | else: | |
154 | # Remake Term to use the readline i/o facilities |
|
154 | # Remake Term to use the readline i/o facilities | |
155 | Term = IOTerm(cout=_out,cerr=_out) |
|
155 | Term = IOTerm(cout=_out,cerr=_out) | |
156 | del _out |
|
156 | del _out | |
157 |
|
157 | |||
158 | #**************************************************************************** |
|
158 | #**************************************************************************** | |
159 | # Generic warning/error printer, used by everything else |
|
159 | # Generic warning/error printer, used by everything else | |
160 | def warn(msg,level=2,exit_val=1): |
|
160 | def warn(msg,level=2,exit_val=1): | |
161 | """Standard warning printer. Gives formatting consistency. |
|
161 | """Standard warning printer. Gives formatting consistency. | |
162 |
|
162 | |||
163 | Output is sent to Term.cerr (sys.stderr by default). |
|
163 | Output is sent to Term.cerr (sys.stderr by default). | |
164 |
|
164 | |||
165 | Options: |
|
165 | Options: | |
166 |
|
166 | |||
167 | -level(2): allows finer control: |
|
167 | -level(2): allows finer control: | |
168 | 0 -> Do nothing, dummy function. |
|
168 | 0 -> Do nothing, dummy function. | |
169 | 1 -> Print message. |
|
169 | 1 -> Print message. | |
170 | 2 -> Print 'WARNING:' + message. (Default level). |
|
170 | 2 -> Print 'WARNING:' + message. (Default level). | |
171 | 3 -> Print 'ERROR:' + message. |
|
171 | 3 -> Print 'ERROR:' + message. | |
172 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
172 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). | |
173 |
|
173 | |||
174 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
174 | -exit_val (1): exit value returned by sys.exit() for a level 4 | |
175 | warning. Ignored for all other levels.""" |
|
175 | warning. Ignored for all other levels.""" | |
176 |
|
176 | |||
177 | if level>0: |
|
177 | if level>0: | |
178 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
178 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] | |
179 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
179 | print >> Term.cerr, '%s%s' % (header[level],msg) | |
180 | if level == 4: |
|
180 | if level == 4: | |
181 | print >> Term.cerr,'Exiting.\n' |
|
181 | print >> Term.cerr,'Exiting.\n' | |
182 | sys.exit(exit_val) |
|
182 | sys.exit(exit_val) | |
183 |
|
183 | |||
184 | def info(msg): |
|
184 | def info(msg): | |
185 | """Equivalent to warn(msg,level=1).""" |
|
185 | """Equivalent to warn(msg,level=1).""" | |
186 |
|
186 | |||
187 | warn(msg,level=1) |
|
187 | warn(msg,level=1) | |
188 |
|
188 | |||
189 | def error(msg): |
|
189 | def error(msg): | |
190 | """Equivalent to warn(msg,level=3).""" |
|
190 | """Equivalent to warn(msg,level=3).""" | |
191 |
|
191 | |||
192 | warn(msg,level=3) |
|
192 | warn(msg,level=3) | |
193 |
|
193 | |||
194 | def fatal(msg,exit_val=1): |
|
194 | def fatal(msg,exit_val=1): | |
195 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
195 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" | |
196 |
|
196 | |||
197 | warn(msg,exit_val=exit_val,level=4) |
|
197 | warn(msg,exit_val=exit_val,level=4) | |
198 |
|
198 | |||
199 | #---------------------------------------------------------------------------- |
|
199 | #---------------------------------------------------------------------------- | |
200 | StringTypes = types.StringTypes |
|
200 | StringTypes = types.StringTypes | |
201 |
|
201 | |||
202 | # Basic timing functionality |
|
202 | # Basic timing functionality | |
203 |
|
203 | |||
204 | # If possible (Unix), use the resource module instead of time.clock() |
|
204 | # If possible (Unix), use the resource module instead of time.clock() | |
205 | try: |
|
205 | try: | |
206 | import resource |
|
206 | import resource | |
207 | def clock(): |
|
207 | def clock(): | |
208 | """clock() -> floating point number |
|
208 | """clock() -> floating point number | |
209 |
|
209 | |||
210 | Return the CPU time in seconds (user time only, system time is |
|
210 | Return the CPU time in seconds (user time only, system time is | |
211 | ignored) since the start of the process. This is done via a call to |
|
211 | ignored) since the start of the process. This is done via a call to | |
212 | resource.getrusage, so it avoids the wraparound problems in |
|
212 | resource.getrusage, so it avoids the wraparound problems in | |
213 | time.clock().""" |
|
213 | time.clock().""" | |
214 |
|
214 | |||
215 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
215 | return resource.getrusage(resource.RUSAGE_SELF)[0] | |
216 |
|
216 | |||
217 | def clock2(): |
|
217 | def clock2(): | |
218 | """clock2() -> (t_user,t_system) |
|
218 | """clock2() -> (t_user,t_system) | |
219 |
|
219 | |||
220 | Similar to clock(), but return a tuple of user/system times.""" |
|
220 | Similar to clock(), but return a tuple of user/system times.""" | |
221 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
221 | return resource.getrusage(resource.RUSAGE_SELF)[:2] | |
222 |
|
222 | |||
223 | except ImportError: |
|
223 | except ImportError: | |
224 | clock = time.clock |
|
224 | clock = time.clock | |
225 | def clock2(): |
|
225 | def clock2(): | |
226 | """Under windows, system CPU time can't be measured. |
|
226 | """Under windows, system CPU time can't be measured. | |
227 |
|
227 | |||
228 | This just returns clock() and zero.""" |
|
228 | This just returns clock() and zero.""" | |
229 | return time.clock(),0.0 |
|
229 | return time.clock(),0.0 | |
230 |
|
230 | |||
231 | def timings_out(reps,func,*args,**kw): |
|
231 | def timings_out(reps,func,*args,**kw): | |
232 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
232 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) | |
233 |
|
233 | |||
234 | Execute a function reps times, return a tuple with the elapsed total |
|
234 | Execute a function reps times, return a tuple with the elapsed total | |
235 | CPU time in seconds, the time per call and the function's output. |
|
235 | CPU time in seconds, the time per call and the function's output. | |
236 |
|
236 | |||
237 | Under Unix, the return value is the sum of user+system time consumed by |
|
237 | Under Unix, the return value is the sum of user+system time consumed by | |
238 | the process, computed via the resource module. This prevents problems |
|
238 | the process, computed via the resource module. This prevents problems | |
239 | related to the wraparound effect which the time.clock() function has. |
|
239 | related to the wraparound effect which the time.clock() function has. | |
240 |
|
240 | |||
241 | Under Windows the return value is in wall clock seconds. See the |
|
241 | Under Windows the return value is in wall clock seconds. See the | |
242 | documentation for the time module for more details.""" |
|
242 | documentation for the time module for more details.""" | |
243 |
|
243 | |||
244 | reps = int(reps) |
|
244 | reps = int(reps) | |
245 | assert reps >=1, 'reps must be >= 1' |
|
245 | assert reps >=1, 'reps must be >= 1' | |
246 | if reps==1: |
|
246 | if reps==1: | |
247 | start = clock() |
|
247 | start = clock() | |
248 | out = func(*args,**kw) |
|
248 | out = func(*args,**kw) | |
249 | tot_time = clock()-start |
|
249 | tot_time = clock()-start | |
250 | else: |
|
250 | else: | |
251 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
251 | rng = xrange(reps-1) # the last time is executed separately to store output | |
252 | start = clock() |
|
252 | start = clock() | |
253 | for dummy in rng: func(*args,**kw) |
|
253 | for dummy in rng: func(*args,**kw) | |
254 | out = func(*args,**kw) # one last time |
|
254 | out = func(*args,**kw) # one last time | |
255 | tot_time = clock()-start |
|
255 | tot_time = clock()-start | |
256 | av_time = tot_time / reps |
|
256 | av_time = tot_time / reps | |
257 | return tot_time,av_time,out |
|
257 | return tot_time,av_time,out | |
258 |
|
258 | |||
259 | def timings(reps,func,*args,**kw): |
|
259 | def timings(reps,func,*args,**kw): | |
260 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
260 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) | |
261 |
|
261 | |||
262 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
262 | Execute a function reps times, return a tuple with the elapsed total CPU | |
263 | time in seconds and the time per call. These are just the first two values |
|
263 | time in seconds and the time per call. These are just the first two values | |
264 | in timings_out().""" |
|
264 | in timings_out().""" | |
265 |
|
265 | |||
266 | return timings_out(reps,func,*args,**kw)[0:2] |
|
266 | return timings_out(reps,func,*args,**kw)[0:2] | |
267 |
|
267 | |||
268 | def timing(func,*args,**kw): |
|
268 | def timing(func,*args,**kw): | |
269 | """timing(func,*args,**kw) -> t_total |
|
269 | """timing(func,*args,**kw) -> t_total | |
270 |
|
270 | |||
271 | Execute a function once, return the elapsed total CPU time in |
|
271 | Execute a function once, return the elapsed total CPU time in | |
272 | seconds. This is just the first value in timings_out().""" |
|
272 | seconds. This is just the first value in timings_out().""" | |
273 |
|
273 | |||
274 | return timings_out(1,func,*args,**kw)[0] |
|
274 | return timings_out(1,func,*args,**kw)[0] | |
275 |
|
275 | |||
276 | #**************************************************************************** |
|
276 | #**************************************************************************** | |
277 | # file and system |
|
277 | # file and system | |
278 |
|
278 | |||
279 | def system(cmd,verbose=0,debug=0,header=''): |
|
279 | def system(cmd,verbose=0,debug=0,header=''): | |
280 | """Execute a system command, return its exit status. |
|
280 | """Execute a system command, return its exit status. | |
281 |
|
281 | |||
282 | Options: |
|
282 | Options: | |
283 |
|
283 | |||
284 | - verbose (0): print the command to be executed. |
|
284 | - verbose (0): print the command to be executed. | |
285 |
|
285 | |||
286 | - debug (0): only print, do not actually execute. |
|
286 | - debug (0): only print, do not actually execute. | |
287 |
|
287 | |||
288 | - header (''): Header to print on screen prior to the executed command (it |
|
288 | - header (''): Header to print on screen prior to the executed command (it | |
289 | is only prepended to the command, no newlines are added). |
|
289 | is only prepended to the command, no newlines are added). | |
290 |
|
290 | |||
291 | Note: a stateful version of this function is available through the |
|
291 | Note: a stateful version of this function is available through the | |
292 | SystemExec class.""" |
|
292 | SystemExec class.""" | |
293 |
|
293 | |||
294 | stat = 0 |
|
294 | stat = 0 | |
295 | if verbose or debug: print header+cmd |
|
295 | if verbose or debug: print header+cmd | |
296 | sys.stdout.flush() |
|
296 | sys.stdout.flush() | |
297 | if not debug: stat = os.system(cmd) |
|
297 | if not debug: stat = os.system(cmd) | |
298 | return stat |
|
298 | return stat | |
299 |
|
299 | |||
300 | def shell(cmd,verbose=0,debug=0,header=''): |
|
300 | def shell(cmd,verbose=0,debug=0,header=''): | |
301 | """Execute a command in the system shell, always return None. |
|
301 | """Execute a command in the system shell, always return None. | |
302 |
|
302 | |||
303 | Options: |
|
303 | Options: | |
304 |
|
304 | |||
305 | - verbose (0): print the command to be executed. |
|
305 | - verbose (0): print the command to be executed. | |
306 |
|
306 | |||
307 | - debug (0): only print, do not actually execute. |
|
307 | - debug (0): only print, do not actually execute. | |
308 |
|
308 | |||
309 | - header (''): Header to print on screen prior to the executed command (it |
|
309 | - header (''): Header to print on screen prior to the executed command (it | |
310 | is only prepended to the command, no newlines are added). |
|
310 | is only prepended to the command, no newlines are added). | |
311 |
|
311 | |||
312 | Note: this is similar to genutils.system(), but it returns None so it can |
|
312 | Note: this is similar to genutils.system(), but it returns None so it can | |
313 | be conveniently used in interactive loops without getting the return value |
|
313 | be conveniently used in interactive loops without getting the return value | |
314 | (typically 0) printed many times.""" |
|
314 | (typically 0) printed many times.""" | |
315 |
|
315 | |||
316 | stat = 0 |
|
316 | stat = 0 | |
317 | if verbose or debug: print header+cmd |
|
317 | if verbose or debug: print header+cmd | |
318 | # flush stdout so we don't mangle python's buffering |
|
318 | # flush stdout so we don't mangle python's buffering | |
319 | sys.stdout.flush() |
|
319 | sys.stdout.flush() | |
320 | if not debug: |
|
320 | if not debug: | |
321 | os.system(cmd) |
|
321 | os.system(cmd) | |
322 |
|
322 | |||
323 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
323 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): | |
324 | """Dummy substitute for perl's backquotes. |
|
324 | """Dummy substitute for perl's backquotes. | |
325 |
|
325 | |||
326 | Executes a command and returns the output. |
|
326 | Executes a command and returns the output. | |
327 |
|
327 | |||
328 | Accepts the same arguments as system(), plus: |
|
328 | Accepts the same arguments as system(), plus: | |
329 |
|
329 | |||
330 | - split(0): if true, the output is returned as a list split on newlines. |
|
330 | - split(0): if true, the output is returned as a list split on newlines. | |
331 |
|
331 | |||
332 | Note: a stateful version of this function is available through the |
|
332 | Note: a stateful version of this function is available through the | |
333 | SystemExec class.""" |
|
333 | SystemExec class.""" | |
334 |
|
334 | |||
335 | if verbose or debug: print header+cmd |
|
335 | if verbose or debug: print header+cmd | |
336 | if not debug: |
|
336 | if not debug: | |
337 | output = commands.getoutput(cmd) |
|
337 | output = commands.getoutput(cmd) | |
338 | if split: |
|
338 | if split: | |
339 | return output.split('\n') |
|
339 | return output.split('\n') | |
340 | else: |
|
340 | else: | |
341 | return output |
|
341 | return output | |
342 |
|
342 | |||
343 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
343 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): | |
344 | """Return (standard output,standard error) of executing cmd in a shell. |
|
344 | """Return (standard output,standard error) of executing cmd in a shell. | |
345 |
|
345 | |||
346 | Accepts the same arguments as system(), plus: |
|
346 | Accepts the same arguments as system(), plus: | |
347 |
|
347 | |||
348 | - split(0): if true, each of stdout/err is returned as a list split on |
|
348 | - split(0): if true, each of stdout/err is returned as a list split on | |
349 | newlines. |
|
349 | newlines. | |
350 |
|
350 | |||
351 | Note: a stateful version of this function is available through the |
|
351 | Note: a stateful version of this function is available through the | |
352 | SystemExec class.""" |
|
352 | SystemExec class.""" | |
353 |
|
353 | |||
354 | if verbose or debug: print header+cmd |
|
354 | if verbose or debug: print header+cmd | |
355 | if not cmd: |
|
355 | if not cmd: | |
356 | if split: |
|
356 | if split: | |
357 | return [],[] |
|
357 | return [],[] | |
358 | else: |
|
358 | else: | |
359 | return '','' |
|
359 | return '','' | |
360 | if not debug: |
|
360 | if not debug: | |
361 | pin,pout,perr = os.popen3(cmd) |
|
361 | pin,pout,perr = os.popen3(cmd) | |
362 | tout = pout.read().rstrip() |
|
362 | tout = pout.read().rstrip() | |
363 | terr = perr.read().rstrip() |
|
363 | terr = perr.read().rstrip() | |
364 | pin.close() |
|
364 | pin.close() | |
365 | pout.close() |
|
365 | pout.close() | |
366 | perr.close() |
|
366 | perr.close() | |
367 | if split: |
|
367 | if split: | |
368 | return tout.split('\n'),terr.split('\n') |
|
368 | return tout.split('\n'),terr.split('\n') | |
369 | else: |
|
369 | else: | |
370 | return tout,terr |
|
370 | return tout,terr | |
371 |
|
371 | |||
372 | # for compatibility with older naming conventions |
|
372 | # for compatibility with older naming conventions | |
373 | xsys = system |
|
373 | xsys = system | |
374 | bq = getoutput |
|
374 | bq = getoutput | |
375 |
|
375 | |||
376 | class SystemExec: |
|
376 | class SystemExec: | |
377 | """Access the system and getoutput functions through a stateful interface. |
|
377 | """Access the system and getoutput functions through a stateful interface. | |
378 |
|
378 | |||
379 | Note: here we refer to the system and getoutput functions from this |
|
379 | Note: here we refer to the system and getoutput functions from this | |
380 | library, not the ones from the standard python library. |
|
380 | library, not the ones from the standard python library. | |
381 |
|
381 | |||
382 | This class offers the system and getoutput functions as methods, but the |
|
382 | This class offers the system and getoutput functions as methods, but the | |
383 | verbose, debug and header parameters can be set for the instance (at |
|
383 | verbose, debug and header parameters can be set for the instance (at | |
384 | creation time or later) so that they don't need to be specified on each |
|
384 | creation time or later) so that they don't need to be specified on each | |
385 | call. |
|
385 | call. | |
386 |
|
386 | |||
387 | For efficiency reasons, there's no way to override the parameters on a |
|
387 | For efficiency reasons, there's no way to override the parameters on a | |
388 | per-call basis other than by setting instance attributes. If you need |
|
388 | per-call basis other than by setting instance attributes. If you need | |
389 | local overrides, it's best to directly call system() or getoutput(). |
|
389 | local overrides, it's best to directly call system() or getoutput(). | |
390 |
|
390 | |||
391 | The following names are provided as alternate options: |
|
391 | The following names are provided as alternate options: | |
392 | - xsys: alias to system |
|
392 | - xsys: alias to system | |
393 | - bq: alias to getoutput |
|
393 | - bq: alias to getoutput | |
394 |
|
394 | |||
395 | An instance can then be created as: |
|
395 | An instance can then be created as: | |
396 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
396 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') | |
397 |
|
397 | |||
398 | And used as: |
|
398 | And used as: | |
399 | >>> sysexec.xsys('pwd') |
|
399 | >>> sysexec.xsys('pwd') | |
400 | >>> dirlist = sysexec.bq('ls -l') |
|
400 | >>> dirlist = sysexec.bq('ls -l') | |
401 | """ |
|
401 | """ | |
402 |
|
402 | |||
403 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
403 | def __init__(self,verbose=0,debug=0,header='',split=0): | |
404 | """Specify the instance's values for verbose, debug and header.""" |
|
404 | """Specify the instance's values for verbose, debug and header.""" | |
405 | setattr_list(self,'verbose debug header split') |
|
405 | setattr_list(self,'verbose debug header split') | |
406 |
|
406 | |||
407 | def system(self,cmd): |
|
407 | def system(self,cmd): | |
408 | """Stateful interface to system(), with the same keyword parameters.""" |
|
408 | """Stateful interface to system(), with the same keyword parameters.""" | |
409 |
|
409 | |||
410 | system(cmd,self.verbose,self.debug,self.header) |
|
410 | system(cmd,self.verbose,self.debug,self.header) | |
411 |
|
411 | |||
412 | def shell(self,cmd): |
|
412 | def shell(self,cmd): | |
413 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
413 | """Stateful interface to shell(), with the same keyword parameters.""" | |
414 |
|
414 | |||
415 | shell(cmd,self.verbose,self.debug,self.header) |
|
415 | shell(cmd,self.verbose,self.debug,self.header) | |
416 |
|
416 | |||
417 | xsys = system # alias |
|
417 | xsys = system # alias | |
418 |
|
418 | |||
419 | def getoutput(self,cmd): |
|
419 | def getoutput(self,cmd): | |
420 | """Stateful interface to getoutput().""" |
|
420 | """Stateful interface to getoutput().""" | |
421 |
|
421 | |||
422 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
422 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) | |
423 |
|
423 | |||
424 | def getoutputerror(self,cmd): |
|
424 | def getoutputerror(self,cmd): | |
425 | """Stateful interface to getoutputerror().""" |
|
425 | """Stateful interface to getoutputerror().""" | |
426 |
|
426 | |||
427 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
427 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) | |
428 |
|
428 | |||
429 | bq = getoutput # alias |
|
429 | bq = getoutput # alias | |
430 |
|
430 | |||
431 | #----------------------------------------------------------------------------- |
|
431 | #----------------------------------------------------------------------------- | |
432 | def mutex_opts(dict,ex_op): |
|
432 | def mutex_opts(dict,ex_op): | |
433 | """Check for presence of mutually exclusive keys in a dict. |
|
433 | """Check for presence of mutually exclusive keys in a dict. | |
434 |
|
434 | |||
435 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
435 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" | |
436 | for op1,op2 in ex_op: |
|
436 | for op1,op2 in ex_op: | |
437 | if op1 in dict and op2 in dict: |
|
437 | if op1 in dict and op2 in dict: | |
438 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
438 | raise ValueError,'\n*** ERROR in Arguments *** '\ | |
439 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
439 | 'Options '+op1+' and '+op2+' are mutually exclusive.' | |
440 |
|
440 | |||
441 | #----------------------------------------------------------------------------- |
|
441 | #----------------------------------------------------------------------------- | |
|
442 | def get_py_filename(name): | |||
|
443 | """Return a valid python filename in the current directory. | |||
|
444 | ||||
|
445 | If the given name is not a file, it adds '.py' and searches again. | |||
|
446 | Raises IOError with an informative message if the file isn't found.""" | |||
|
447 | ||||
|
448 | name = os.path.expanduser(name) | |||
|
449 | if not os.path.isfile(name) and not name.endswith('.py'): | |||
|
450 | name += '.py' | |||
|
451 | if os.path.isfile(name): | |||
|
452 | return name | |||
|
453 | else: | |||
|
454 | raise IOError,'File `%s` not found.' % name | |||
|
455 | ||||
|
456 | #----------------------------------------------------------------------------- | |||
442 | def filefind(fname,alt_dirs = None): |
|
457 | def filefind(fname,alt_dirs = None): | |
443 | """Return the given filename either in the current directory, if it |
|
458 | """Return the given filename either in the current directory, if it | |
444 | exists, or in a specified list of directories. |
|
459 | exists, or in a specified list of directories. | |
445 |
|
460 | |||
446 | ~ expansion is done on all file and directory names. |
|
461 | ~ expansion is done on all file and directory names. | |
447 |
|
462 | |||
448 | Upon an unsuccessful search, raise an IOError exception.""" |
|
463 | Upon an unsuccessful search, raise an IOError exception.""" | |
449 |
|
464 | |||
450 | if alt_dirs is None: |
|
465 | if alt_dirs is None: | |
451 | try: |
|
466 | try: | |
452 | alt_dirs = get_home_dir() |
|
467 | alt_dirs = get_home_dir() | |
453 | except HomeDirError: |
|
468 | except HomeDirError: | |
454 | alt_dirs = os.getcwd() |
|
469 | alt_dirs = os.getcwd() | |
455 | search = [fname] + list_strings(alt_dirs) |
|
470 | search = [fname] + list_strings(alt_dirs) | |
456 | search = map(os.path.expanduser,search) |
|
471 | search = map(os.path.expanduser,search) | |
457 | #print 'search list for',fname,'list:',search # dbg |
|
472 | #print 'search list for',fname,'list:',search # dbg | |
458 | fname = search[0] |
|
473 | fname = search[0] | |
459 | if os.path.isfile(fname): |
|
474 | if os.path.isfile(fname): | |
460 | return fname |
|
475 | return fname | |
461 | for direc in search[1:]: |
|
476 | for direc in search[1:]: | |
462 | testname = os.path.join(direc,fname) |
|
477 | testname = os.path.join(direc,fname) | |
463 | #print 'testname',testname # dbg |
|
478 | #print 'testname',testname # dbg | |
464 | if os.path.isfile(testname): |
|
479 | if os.path.isfile(testname): | |
465 | return testname |
|
480 | return testname | |
466 | raise IOError,'File' + `fname` + \ |
|
481 | raise IOError,'File' + `fname` + \ | |
467 | ' not found in current or supplied directories:' + `alt_dirs` |
|
482 | ' not found in current or supplied directories:' + `alt_dirs` | |
468 |
|
483 | |||
469 | #---------------------------------------------------------------------------- |
|
484 | #---------------------------------------------------------------------------- | |
|
485 | def file_read(filename): | |||
|
486 | """Read a file and close it. Returns the file source.""" | |||
|
487 | fobj=open(filename,'r'); | |||
|
488 | source = fobj.read(); | |||
|
489 | fobj.close() | |||
|
490 | return source | |||
|
491 | ||||
|
492 | #---------------------------------------------------------------------------- | |||
470 | def target_outdated(target,deps): |
|
493 | def target_outdated(target,deps): | |
471 | """Determine whether a target is out of date. |
|
494 | """Determine whether a target is out of date. | |
472 |
|
495 | |||
473 | target_outdated(target,deps) -> 1/0 |
|
496 | target_outdated(target,deps) -> 1/0 | |
474 |
|
497 | |||
475 | deps: list of filenames which MUST exist. |
|
498 | deps: list of filenames which MUST exist. | |
476 | target: single filename which may or may not exist. |
|
499 | target: single filename which may or may not exist. | |
477 |
|
500 | |||
478 | If target doesn't exist or is older than any file listed in deps, return |
|
501 | If target doesn't exist or is older than any file listed in deps, return | |
479 | true, otherwise return false. |
|
502 | true, otherwise return false. | |
480 | """ |
|
503 | """ | |
481 | try: |
|
504 | try: | |
482 | target_time = os.path.getmtime(target) |
|
505 | target_time = os.path.getmtime(target) | |
483 | except os.error: |
|
506 | except os.error: | |
484 | return 1 |
|
507 | return 1 | |
485 | for dep in deps: |
|
508 | for dep in deps: | |
486 | dep_time = os.path.getmtime(dep) |
|
509 | dep_time = os.path.getmtime(dep) | |
487 | if dep_time > target_time: |
|
510 | if dep_time > target_time: | |
488 | #print "For target",target,"Dep failed:",dep # dbg |
|
511 | #print "For target",target,"Dep failed:",dep # dbg | |
489 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
512 | #print "times (dep,tar):",dep_time,target_time # dbg | |
490 | return 1 |
|
513 | return 1 | |
491 | return 0 |
|
514 | return 0 | |
492 |
|
515 | |||
493 | #----------------------------------------------------------------------------- |
|
516 | #----------------------------------------------------------------------------- | |
494 | def target_update(target,deps,cmd): |
|
517 | def target_update(target,deps,cmd): | |
495 | """Update a target with a given command given a list of dependencies. |
|
518 | """Update a target with a given command given a list of dependencies. | |
496 |
|
519 | |||
497 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
520 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
498 |
|
521 | |||
499 | This is just a wrapper around target_outdated() which calls the given |
|
522 | This is just a wrapper around target_outdated() which calls the given | |
500 | command if target is outdated.""" |
|
523 | command if target is outdated.""" | |
501 |
|
524 | |||
502 | if target_outdated(target,deps): |
|
525 | if target_outdated(target,deps): | |
503 | xsys(cmd) |
|
526 | xsys(cmd) | |
504 |
|
527 | |||
505 | #---------------------------------------------------------------------------- |
|
528 | #---------------------------------------------------------------------------- | |
506 | def unquote_ends(istr): |
|
529 | def unquote_ends(istr): | |
507 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
530 | """Remove a single pair of quotes from the endpoints of a string.""" | |
508 |
|
531 | |||
509 | if not istr: |
|
532 | if not istr: | |
510 | return istr |
|
533 | return istr | |
511 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
534 | if (istr[0]=="'" and istr[-1]=="'") or \ | |
512 | (istr[0]=='"' and istr[-1]=='"'): |
|
535 | (istr[0]=='"' and istr[-1]=='"'): | |
513 | return istr[1:-1] |
|
536 | return istr[1:-1] | |
514 | else: |
|
537 | else: | |
515 | return istr |
|
538 | return istr | |
516 |
|
539 | |||
517 | #---------------------------------------------------------------------------- |
|
540 | #---------------------------------------------------------------------------- | |
518 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
541 | def process_cmdline(argv,names=[],defaults={},usage=''): | |
519 | """ Process command-line options and arguments. |
|
542 | """ Process command-line options and arguments. | |
520 |
|
543 | |||
521 | Arguments: |
|
544 | Arguments: | |
522 |
|
545 | |||
523 | - argv: list of arguments, typically sys.argv. |
|
546 | - argv: list of arguments, typically sys.argv. | |
524 |
|
547 | |||
525 | - names: list of option names. See DPyGetOpt docs for details on options |
|
548 | - names: list of option names. See DPyGetOpt docs for details on options | |
526 | syntax. |
|
549 | syntax. | |
527 |
|
550 | |||
528 | - defaults: dict of default values. |
|
551 | - defaults: dict of default values. | |
529 |
|
552 | |||
530 | - usage: optional usage notice to print if a wrong argument is passed. |
|
553 | - usage: optional usage notice to print if a wrong argument is passed. | |
531 |
|
554 | |||
532 | Return a dict of options and a list of free arguments.""" |
|
555 | Return a dict of options and a list of free arguments.""" | |
533 |
|
556 | |||
534 | getopt = DPyGetOpt.DPyGetOpt() |
|
557 | getopt = DPyGetOpt.DPyGetOpt() | |
535 | getopt.setIgnoreCase(0) |
|
558 | getopt.setIgnoreCase(0) | |
536 | getopt.parseConfiguration(names) |
|
559 | getopt.parseConfiguration(names) | |
537 |
|
560 | |||
538 | try: |
|
561 | try: | |
539 | getopt.processArguments(argv) |
|
562 | getopt.processArguments(argv) | |
540 | except: |
|
563 | except: | |
541 | print usage |
|
564 | print usage | |
542 | warn(`sys.exc_value`,level=4) |
|
565 | warn(`sys.exc_value`,level=4) | |
543 |
|
566 | |||
544 | defaults.update(getopt.optionValues) |
|
567 | defaults.update(getopt.optionValues) | |
545 | args = getopt.freeValues |
|
568 | args = getopt.freeValues | |
546 |
|
569 | |||
547 | return defaults,args |
|
570 | return defaults,args | |
548 |
|
571 | |||
549 | #---------------------------------------------------------------------------- |
|
572 | #---------------------------------------------------------------------------- | |
550 | def optstr2types(ostr): |
|
573 | def optstr2types(ostr): | |
551 | """Convert a string of option names to a dict of type mappings. |
|
574 | """Convert a string of option names to a dict of type mappings. | |
552 |
|
575 | |||
553 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
576 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} | |
554 |
|
577 | |||
555 | This is used to get the types of all the options in a string formatted |
|
578 | This is used to get the types of all the options in a string formatted | |
556 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
579 | with the conventions of DPyGetOpt. The 'type' None is used for options | |
557 | which are strings (they need no further conversion). This function's main |
|
580 | which are strings (they need no further conversion). This function's main | |
558 | use is to get a typemap for use with read_dict(). |
|
581 | use is to get a typemap for use with read_dict(). | |
559 | """ |
|
582 | """ | |
560 |
|
583 | |||
561 | typeconv = {None:'',int:'',float:''} |
|
584 | typeconv = {None:'',int:'',float:''} | |
562 | typemap = {'s':None,'i':int,'f':float} |
|
585 | typemap = {'s':None,'i':int,'f':float} | |
563 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
586 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') | |
564 |
|
587 | |||
565 | for w in ostr.split(): |
|
588 | for w in ostr.split(): | |
566 | oname,alias,otype = opt_re.match(w).groups() |
|
589 | oname,alias,otype = opt_re.match(w).groups() | |
567 | if otype == '' or alias == '!': # simple switches are integers too |
|
590 | if otype == '' or alias == '!': # simple switches are integers too | |
568 | otype = 'i' |
|
591 | otype = 'i' | |
569 | typeconv[typemap[otype]] += oname + ' ' |
|
592 | typeconv[typemap[otype]] += oname + ' ' | |
570 | return typeconv |
|
593 | return typeconv | |
571 |
|
594 | |||
572 | #---------------------------------------------------------------------------- |
|
595 | #---------------------------------------------------------------------------- | |
573 | def read_dict(filename,type_conv=None,**opt): |
|
596 | def read_dict(filename,type_conv=None,**opt): | |
574 |
|
597 | |||
575 | """Read a dictionary of key=value pairs from an input file, optionally |
|
598 | """Read a dictionary of key=value pairs from an input file, optionally | |
576 | performing conversions on the resulting values. |
|
599 | performing conversions on the resulting values. | |
577 |
|
600 | |||
578 | read_dict(filename,type_conv,**opt) -> dict |
|
601 | read_dict(filename,type_conv,**opt) -> dict | |
579 |
|
602 | |||
580 | Only one value per line is accepted, the format should be |
|
603 | Only one value per line is accepted, the format should be | |
581 | # optional comments are ignored |
|
604 | # optional comments are ignored | |
582 | key value\n |
|
605 | key value\n | |
583 |
|
606 | |||
584 | Args: |
|
607 | Args: | |
585 |
|
608 | |||
586 | - type_conv: A dictionary specifying which keys need to be converted to |
|
609 | - type_conv: A dictionary specifying which keys need to be converted to | |
587 | which types. By default all keys are read as strings. This dictionary |
|
610 | which types. By default all keys are read as strings. This dictionary | |
588 | should have as its keys valid conversion functions for strings |
|
611 | should have as its keys valid conversion functions for strings | |
589 | (int,long,float,complex, or your own). The value for each key |
|
612 | (int,long,float,complex, or your own). The value for each key | |
590 | (converter) should be a whitespace separated string containing the names |
|
613 | (converter) should be a whitespace separated string containing the names | |
591 | of all the entries in the file to be converted using that function. For |
|
614 | of all the entries in the file to be converted using that function. For | |
592 | keys to be left alone, use None as the conversion function (only needed |
|
615 | keys to be left alone, use None as the conversion function (only needed | |
593 | with purge=1, see below). |
|
616 | with purge=1, see below). | |
594 |
|
617 | |||
595 | - opt: dictionary with extra options as below (default in parens) |
|
618 | - opt: dictionary with extra options as below (default in parens) | |
596 |
|
619 | |||
597 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
620 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out | |
598 | of the dictionary to be returned. If purge is going to be used, the |
|
621 | of the dictionary to be returned. If purge is going to be used, the | |
599 | set of keys to be left as strings also has to be explicitly specified |
|
622 | set of keys to be left as strings also has to be explicitly specified | |
600 | using the (non-existent) conversion function None. |
|
623 | using the (non-existent) conversion function None. | |
601 |
|
624 | |||
602 | fs(None): field separator. This is the key/value separator to be used |
|
625 | fs(None): field separator. This is the key/value separator to be used | |
603 | when parsing the file. The None default means any whitespace [behavior |
|
626 | when parsing the file. The None default means any whitespace [behavior | |
604 | of string.split()]. |
|
627 | of string.split()]. | |
605 |
|
628 | |||
606 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
629 | strip(0): if 1, strip string values of leading/trailinig whitespace. | |
607 |
|
630 | |||
608 | warn(1): warning level if requested keys are not found in file. |
|
631 | warn(1): warning level if requested keys are not found in file. | |
609 | - 0: silently ignore. |
|
632 | - 0: silently ignore. | |
610 | - 1: inform but proceed. |
|
633 | - 1: inform but proceed. | |
611 | - 2: raise KeyError exception. |
|
634 | - 2: raise KeyError exception. | |
612 |
|
635 | |||
613 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
636 | no_empty(0): if 1, remove keys with whitespace strings as a value. | |
614 |
|
637 | |||
615 | unique([]): list of keys (or space separated string) which can't be |
|
638 | unique([]): list of keys (or space separated string) which can't be | |
616 | repeated. If one such key is found in the file, each new instance |
|
639 | repeated. If one such key is found in the file, each new instance | |
617 | overwrites the previous one. For keys not listed here, the behavior is |
|
640 | overwrites the previous one. For keys not listed here, the behavior is | |
618 | to make a list of all appearances. |
|
641 | to make a list of all appearances. | |
619 |
|
642 | |||
620 | Example: |
|
643 | Example: | |
621 | If the input file test.ini has: |
|
644 | If the input file test.ini has: | |
622 | i 3 |
|
645 | i 3 | |
623 | x 4.5 |
|
646 | x 4.5 | |
624 | y 5.5 |
|
647 | y 5.5 | |
625 | s hi ho |
|
648 | s hi ho | |
626 | Then: |
|
649 | Then: | |
627 |
|
650 | |||
628 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
651 | >>> type_conv={int:'i',float:'x',None:'s'} | |
629 | >>> read_dict('test.ini') |
|
652 | >>> read_dict('test.ini') | |
630 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} |
|
653 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} | |
631 | >>> read_dict('test.ini',type_conv) |
|
654 | >>> read_dict('test.ini',type_conv) | |
632 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} |
|
655 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} | |
633 | >>> read_dict('test.ini',type_conv,purge=1) |
|
656 | >>> read_dict('test.ini',type_conv,purge=1) | |
634 | {'i': 3, 's': 'hi ho', 'x': 4.5} |
|
657 | {'i': 3, 's': 'hi ho', 'x': 4.5} | |
635 | """ |
|
658 | """ | |
636 |
|
659 | |||
637 | # starting config |
|
660 | # starting config | |
638 | opt.setdefault('purge',0) |
|
661 | opt.setdefault('purge',0) | |
639 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
662 | opt.setdefault('fs',None) # field sep defaults to any whitespace | |
640 | opt.setdefault('strip',0) |
|
663 | opt.setdefault('strip',0) | |
641 | opt.setdefault('warn',1) |
|
664 | opt.setdefault('warn',1) | |
642 | opt.setdefault('no_empty',0) |
|
665 | opt.setdefault('no_empty',0) | |
643 | opt.setdefault('unique','') |
|
666 | opt.setdefault('unique','') | |
644 | if type(opt['unique']) in StringTypes: |
|
667 | if type(opt['unique']) in StringTypes: | |
645 | unique_keys = qw(opt['unique']) |
|
668 | unique_keys = qw(opt['unique']) | |
646 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
669 | elif type(opt['unique']) in (types.TupleType,types.ListType): | |
647 | unique_keys = opt['unique'] |
|
670 | unique_keys = opt['unique'] | |
648 | else: |
|
671 | else: | |
649 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
672 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' | |
650 |
|
673 | |||
651 | dict = {} |
|
674 | dict = {} | |
652 | # first read in table of values as strings |
|
675 | # first read in table of values as strings | |
653 | file = open(filename,'r') |
|
676 | file = open(filename,'r') | |
654 | for line in file.readlines(): |
|
677 | for line in file.readlines(): | |
655 | line = line.strip() |
|
678 | line = line.strip() | |
656 | if len(line) and line[0]=='#': continue |
|
679 | if len(line) and line[0]=='#': continue | |
657 | if len(line)>0: |
|
680 | if len(line)>0: | |
658 | lsplit = line.split(opt['fs'],1) |
|
681 | lsplit = line.split(opt['fs'],1) | |
659 | try: |
|
682 | try: | |
660 | key,val = lsplit |
|
683 | key,val = lsplit | |
661 | except ValueError: |
|
684 | except ValueError: | |
662 | key,val = lsplit[0],'' |
|
685 | key,val = lsplit[0],'' | |
663 | key = key.strip() |
|
686 | key = key.strip() | |
664 | if opt['strip']: val = val.strip() |
|
687 | if opt['strip']: val = val.strip() | |
665 | if val == "''" or val == '""': val = '' |
|
688 | if val == "''" or val == '""': val = '' | |
666 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
689 | if opt['no_empty'] and (val=='' or val.isspace()): | |
667 | continue |
|
690 | continue | |
668 | # if a key is found more than once in the file, build a list |
|
691 | # if a key is found more than once in the file, build a list | |
669 | # unless it's in the 'unique' list. In that case, last found in file |
|
692 | # unless it's in the 'unique' list. In that case, last found in file | |
670 | # takes precedence. User beware. |
|
693 | # takes precedence. User beware. | |
671 | try: |
|
694 | try: | |
672 | if dict[key] and key in unique_keys: |
|
695 | if dict[key] and key in unique_keys: | |
673 | dict[key] = val |
|
696 | dict[key] = val | |
674 | elif type(dict[key]) is types.ListType: |
|
697 | elif type(dict[key]) is types.ListType: | |
675 | dict[key].append(val) |
|
698 | dict[key].append(val) | |
676 | else: |
|
699 | else: | |
677 | dict[key] = [dict[key],val] |
|
700 | dict[key] = [dict[key],val] | |
678 | except KeyError: |
|
701 | except KeyError: | |
679 | dict[key] = val |
|
702 | dict[key] = val | |
680 | # purge if requested |
|
703 | # purge if requested | |
681 | if opt['purge']: |
|
704 | if opt['purge']: | |
682 | accepted_keys = qwflat(type_conv.values()) |
|
705 | accepted_keys = qwflat(type_conv.values()) | |
683 | for key in dict.keys(): |
|
706 | for key in dict.keys(): | |
684 | if key in accepted_keys: continue |
|
707 | if key in accepted_keys: continue | |
685 | del(dict[key]) |
|
708 | del(dict[key]) | |
686 | # now convert if requested |
|
709 | # now convert if requested | |
687 | if type_conv==None: return dict |
|
710 | if type_conv==None: return dict | |
688 | conversions = type_conv.keys() |
|
711 | conversions = type_conv.keys() | |
689 | try: conversions.remove(None) |
|
712 | try: conversions.remove(None) | |
690 | except: pass |
|
713 | except: pass | |
691 | for convert in conversions: |
|
714 | for convert in conversions: | |
692 | for val in qw(type_conv[convert]): |
|
715 | for val in qw(type_conv[convert]): | |
693 | try: |
|
716 | try: | |
694 | dict[val] = convert(dict[val]) |
|
717 | dict[val] = convert(dict[val]) | |
695 | except KeyError,e: |
|
718 | except KeyError,e: | |
696 | if opt['warn'] == 0: |
|
719 | if opt['warn'] == 0: | |
697 | pass |
|
720 | pass | |
698 | elif opt['warn'] == 1: |
|
721 | elif opt['warn'] == 1: | |
699 | print >>sys.stderr, 'Warning: key',val,\ |
|
722 | print >>sys.stderr, 'Warning: key',val,\ | |
700 | 'not found in file',filename |
|
723 | 'not found in file',filename | |
701 | elif opt['warn'] == 2: |
|
724 | elif opt['warn'] == 2: | |
702 | raise KeyError,e |
|
725 | raise KeyError,e | |
703 | else: |
|
726 | else: | |
704 | raise ValueError,'Warning level must be 0,1 or 2' |
|
727 | raise ValueError,'Warning level must be 0,1 or 2' | |
705 |
|
728 | |||
706 | return dict |
|
729 | return dict | |
707 |
|
730 | |||
708 | #---------------------------------------------------------------------------- |
|
731 | #---------------------------------------------------------------------------- | |
709 | def flag_calls(func): |
|
732 | def flag_calls(func): | |
710 | """Wrap a function to detect and flag when it gets called. |
|
733 | """Wrap a function to detect and flag when it gets called. | |
711 |
|
734 | |||
712 | This is a decorator which takes a function and wraps it in a function with |
|
735 | This is a decorator which takes a function and wraps it in a function with | |
713 | a 'called' attribute. wrapper.called is initialized to False. |
|
736 | a 'called' attribute. wrapper.called is initialized to False. | |
714 |
|
737 | |||
715 | The wrapper.called attribute is set to False right before each call to the |
|
738 | The wrapper.called attribute is set to False right before each call to the | |
716 | wrapped function, so if the call fails it remains False. After the call |
|
739 | wrapped function, so if the call fails it remains False. After the call | |
717 | completes, wrapper.called is set to True and the output is returned. |
|
740 | completes, wrapper.called is set to True and the output is returned. | |
718 |
|
741 | |||
719 | Testing for truth in wrapper.called allows you to determine if a call to |
|
742 | Testing for truth in wrapper.called allows you to determine if a call to | |
720 | func() was attempted and succeeded.""" |
|
743 | func() was attempted and succeeded.""" | |
721 |
|
744 | |||
722 | def wrapper(*args,**kw): |
|
745 | def wrapper(*args,**kw): | |
723 | wrapper.called = False |
|
746 | wrapper.called = False | |
724 | out = func(*args,**kw) |
|
747 | out = func(*args,**kw) | |
725 | wrapper.called = True |
|
748 | wrapper.called = True | |
726 | return out |
|
749 | return out | |
727 |
|
750 | |||
728 | wrapper.called = False |
|
751 | wrapper.called = False | |
729 | wrapper.__doc__ = func.__doc__ |
|
752 | wrapper.__doc__ = func.__doc__ | |
730 | return wrapper |
|
753 | return wrapper | |
731 |
|
754 | |||
732 | #---------------------------------------------------------------------------- |
|
755 | #---------------------------------------------------------------------------- | |
733 | class HomeDirError(Error): |
|
756 | class HomeDirError(Error): | |
734 | pass |
|
757 | pass | |
735 |
|
758 | |||
736 | def get_home_dir(): |
|
759 | def get_home_dir(): | |
737 | """Return the closest possible equivalent to a 'home' directory. |
|
760 | """Return the closest possible equivalent to a 'home' directory. | |
738 |
|
761 | |||
739 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
762 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. | |
740 |
|
763 | |||
741 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
764 | Currently only Posix and NT are implemented, a HomeDirError exception is | |
742 | raised for all other OSes. """ |
|
765 | raised for all other OSes. """ | |
743 |
|
766 | |||
744 | isdir = os.path.isdir |
|
767 | isdir = os.path.isdir | |
745 | env = os.environ |
|
768 | env = os.environ | |
746 | try: |
|
769 | try: | |
747 | homedir = env['HOME'] |
|
770 | homedir = env['HOME'] | |
748 | if not isdir(homedir): |
|
771 | if not isdir(homedir): | |
749 | # in case a user stuck some string which does NOT resolve to a |
|
772 | # in case a user stuck some string which does NOT resolve to a | |
750 | # valid path, it's as good as if we hadn't foud it |
|
773 | # valid path, it's as good as if we hadn't foud it | |
751 | raise KeyError |
|
774 | raise KeyError | |
752 | return homedir |
|
775 | return homedir | |
753 | except KeyError: |
|
776 | except KeyError: | |
754 | if os.name == 'posix': |
|
777 | if os.name == 'posix': | |
755 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
778 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' | |
756 | elif os.name == 'nt': |
|
779 | elif os.name == 'nt': | |
757 | # For some strange reason, win9x returns 'nt' for os.name. |
|
780 | # For some strange reason, win9x returns 'nt' for os.name. | |
758 | try: |
|
781 | try: | |
759 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
782 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) | |
760 | if not isdir(homedir): |
|
783 | if not isdir(homedir): | |
761 | homedir = os.path.join(env['USERPROFILE']) |
|
784 | homedir = os.path.join(env['USERPROFILE']) | |
762 | if not isdir(homedir): |
|
785 | if not isdir(homedir): | |
763 | raise HomeDirError |
|
786 | raise HomeDirError | |
764 | return homedir |
|
787 | return homedir | |
765 | except: |
|
788 | except: | |
766 | try: |
|
789 | try: | |
767 | # Use the registry to get the 'My Documents' folder. |
|
790 | # Use the registry to get the 'My Documents' folder. | |
768 | import _winreg as wreg |
|
791 | import _winreg as wreg | |
769 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
792 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, | |
770 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
793 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") | |
771 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
794 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
772 | key.Close() |
|
795 | key.Close() | |
773 | if not isdir(homedir): |
|
796 | if not isdir(homedir): | |
774 | e = ('Invalid "Personal" folder registry key ' |
|
797 | e = ('Invalid "Personal" folder registry key ' | |
775 | 'typically "My Documents".\n' |
|
798 | 'typically "My Documents".\n' | |
776 | 'Value: %s\n' |
|
799 | 'Value: %s\n' | |
777 | 'This is not a valid directory on your system.' % |
|
800 | 'This is not a valid directory on your system.' % | |
778 | homedir) |
|
801 | homedir) | |
779 | raise HomeDirError(e) |
|
802 | raise HomeDirError(e) | |
780 | return homedir |
|
803 | return homedir | |
781 | except HomeDirError: |
|
804 | except HomeDirError: | |
782 | raise |
|
805 | raise | |
783 | except: |
|
806 | except: | |
784 | return 'C:\\' |
|
807 | return 'C:\\' | |
785 | elif os.name == 'dos': |
|
808 | elif os.name == 'dos': | |
786 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
809 | # Desperate, may do absurd things in classic MacOS. May work under DOS. | |
787 | return 'C:\\' |
|
810 | return 'C:\\' | |
788 | else: |
|
811 | else: | |
789 | raise HomeDirError,'support for your operating system not implemented.' |
|
812 | raise HomeDirError,'support for your operating system not implemented.' | |
790 |
|
813 | |||
791 | #**************************************************************************** |
|
814 | #**************************************************************************** | |
792 | # strings and text |
|
815 | # strings and text | |
793 |
|
816 | |||
794 | class LSString(str): |
|
817 | class LSString(str): | |
795 | """String derivative with a special access attributes. |
|
818 | """String derivative with a special access attributes. | |
796 |
|
819 | |||
797 | These are normal strings, but with the special attributes: |
|
820 | These are normal strings, but with the special attributes: | |
798 |
|
821 | |||
799 | .l (or .list) : value as list (split on newlines). |
|
822 | .l (or .list) : value as list (split on newlines). | |
800 | .n (or .nlstr): original value (the string itself). |
|
823 | .n (or .nlstr): original value (the string itself). | |
801 | .s (or .spstr): value as whitespace-separated string. |
|
824 | .s (or .spstr): value as whitespace-separated string. | |
802 |
|
825 | |||
803 | Any values which require transformations are computed only once and |
|
826 | Any values which require transformations are computed only once and | |
804 | cached. |
|
827 | cached. | |
805 |
|
828 | |||
806 | Such strings are very useful to efficiently interact with the shell, which |
|
829 | Such strings are very useful to efficiently interact with the shell, which | |
807 | typically only understands whitespace-separated options for commands.""" |
|
830 | typically only understands whitespace-separated options for commands.""" | |
808 |
|
831 | |||
809 | def get_list(self): |
|
832 | def get_list(self): | |
810 | try: |
|
833 | try: | |
811 | return self.__list |
|
834 | return self.__list | |
812 | except AttributeError: |
|
835 | except AttributeError: | |
813 | self.__list = self.split('\n') |
|
836 | self.__list = self.split('\n') | |
814 | return self.__list |
|
837 | return self.__list | |
815 |
|
838 | |||
816 | l = list = property(get_list) |
|
839 | l = list = property(get_list) | |
817 |
|
840 | |||
818 | def get_spstr(self): |
|
841 | def get_spstr(self): | |
819 | try: |
|
842 | try: | |
820 | return self.__spstr |
|
843 | return self.__spstr | |
821 | except AttributeError: |
|
844 | except AttributeError: | |
822 | self.__spstr = self.replace('\n',' ') |
|
845 | self.__spstr = self.replace('\n',' ') | |
823 | return self.__spstr |
|
846 | return self.__spstr | |
824 |
|
847 | |||
825 | s = spstr = property(get_spstr) |
|
848 | s = spstr = property(get_spstr) | |
826 |
|
849 | |||
827 | def get_nlstr(self): |
|
850 | def get_nlstr(self): | |
828 | return self |
|
851 | return self | |
829 |
|
852 | |||
830 | n = nlstr = property(get_nlstr) |
|
853 | n = nlstr = property(get_nlstr) | |
831 |
|
854 | |||
832 | class SList(list): |
|
855 | class SList(list): | |
833 | """List derivative with a special access attributes. |
|
856 | """List derivative with a special access attributes. | |
834 |
|
857 | |||
835 | These are normal lists, but with the special attributes: |
|
858 | These are normal lists, but with the special attributes: | |
836 |
|
859 | |||
837 | .l (or .list) : value as list (the list itself). |
|
860 | .l (or .list) : value as list (the list itself). | |
838 | .n (or .nlstr): value as a string, joined on newlines. |
|
861 | .n (or .nlstr): value as a string, joined on newlines. | |
839 | .s (or .spstr): value as a string, joined on spaces. |
|
862 | .s (or .spstr): value as a string, joined on spaces. | |
840 |
|
863 | |||
841 | Any values which require transformations are computed only once and |
|
864 | Any values which require transformations are computed only once and | |
842 | cached.""" |
|
865 | cached.""" | |
843 |
|
866 | |||
844 | def get_list(self): |
|
867 | def get_list(self): | |
845 | return self |
|
868 | return self | |
846 |
|
869 | |||
847 | l = list = property(get_list) |
|
870 | l = list = property(get_list) | |
848 |
|
871 | |||
849 | def get_spstr(self): |
|
872 | def get_spstr(self): | |
850 | try: |
|
873 | try: | |
851 | return self.__spstr |
|
874 | return self.__spstr | |
852 | except AttributeError: |
|
875 | except AttributeError: | |
853 | self.__spstr = ' '.join(self) |
|
876 | self.__spstr = ' '.join(self) | |
854 | return self.__spstr |
|
877 | return self.__spstr | |
855 |
|
878 | |||
856 | s = spstr = property(get_spstr) |
|
879 | s = spstr = property(get_spstr) | |
857 |
|
880 | |||
858 | def get_nlstr(self): |
|
881 | def get_nlstr(self): | |
859 | try: |
|
882 | try: | |
860 | return self.__nlstr |
|
883 | return self.__nlstr | |
861 | except AttributeError: |
|
884 | except AttributeError: | |
862 | self.__nlstr = '\n'.join(self) |
|
885 | self.__nlstr = '\n'.join(self) | |
863 | return self.__nlstr |
|
886 | return self.__nlstr | |
864 |
|
887 | |||
865 | n = nlstr = property(get_nlstr) |
|
888 | n = nlstr = property(get_nlstr) | |
866 |
|
889 | |||
867 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
890 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): | |
868 | """Take multiple lines of input. |
|
891 | """Take multiple lines of input. | |
869 |
|
892 | |||
870 | A list with each line of input as a separate element is returned when a |
|
893 | A list with each line of input as a separate element is returned when a | |
871 | termination string is entered (defaults to a single '.'). Input can also |
|
894 | termination string is entered (defaults to a single '.'). Input can also | |
872 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
895 | terminate via EOF (^D in Unix, ^Z-RET in Windows). | |
873 |
|
896 | |||
874 | Lines of input which end in \\ are joined into single entries (and a |
|
897 | Lines of input which end in \\ are joined into single entries (and a | |
875 | secondary continuation prompt is issued as long as the user terminates |
|
898 | secondary continuation prompt is issued as long as the user terminates | |
876 | lines with \\). This allows entering very long strings which are still |
|
899 | lines with \\). This allows entering very long strings which are still | |
877 | meant to be treated as single entities. |
|
900 | meant to be treated as single entities. | |
878 | """ |
|
901 | """ | |
879 |
|
902 | |||
880 | try: |
|
903 | try: | |
881 | if header: |
|
904 | if header: | |
882 | header += '\n' |
|
905 | header += '\n' | |
883 | lines = [raw_input(header + ps1)] |
|
906 | lines = [raw_input(header + ps1)] | |
884 | except EOFError: |
|
907 | except EOFError: | |
885 | return [] |
|
908 | return [] | |
886 | terminate = [terminate_str] |
|
909 | terminate = [terminate_str] | |
887 | try: |
|
910 | try: | |
888 | while lines[-1:] != terminate: |
|
911 | while lines[-1:] != terminate: | |
889 | new_line = raw_input(ps1) |
|
912 | new_line = raw_input(ps1) | |
890 | while new_line.endswith('\\'): |
|
913 | while new_line.endswith('\\'): | |
891 | new_line = new_line[:-1] + raw_input(ps2) |
|
914 | new_line = new_line[:-1] + raw_input(ps2) | |
892 | lines.append(new_line) |
|
915 | lines.append(new_line) | |
893 |
|
916 | |||
894 | return lines[:-1] # don't return the termination command |
|
917 | return lines[:-1] # don't return the termination command | |
895 | except EOFError: |
|
918 | except EOFError: | |
896 |
|
919 | |||
897 | return lines |
|
920 | return lines | |
898 |
|
921 | |||
899 | #---------------------------------------------------------------------------- |
|
922 | #---------------------------------------------------------------------------- | |
900 | def raw_input_ext(prompt='', ps2='... '): |
|
923 | def raw_input_ext(prompt='', ps2='... '): | |
901 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
924 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" | |
902 |
|
925 | |||
903 | line = raw_input(prompt) |
|
926 | line = raw_input(prompt) | |
904 | while line.endswith('\\'): |
|
927 | while line.endswith('\\'): | |
905 | line = line[:-1] + raw_input(ps2) |
|
928 | line = line[:-1] + raw_input(ps2) | |
906 | return line |
|
929 | return line | |
907 |
|
930 | |||
908 | #---------------------------------------------------------------------------- |
|
931 | #---------------------------------------------------------------------------- | |
909 | def ask_yes_no(prompt,default=None): |
|
932 | def ask_yes_no(prompt,default=None): | |
910 | """Asks a question and returns an integer 1/0 (y/n) answer. |
|
933 | """Asks a question and returns an integer 1/0 (y/n) answer. | |
911 |
|
934 | |||
912 | If default is given (one of 'y','n'), it is used if the user input is |
|
935 | If default is given (one of 'y','n'), it is used if the user input is | |
913 | empty. Otherwise the question is repeated until an answer is given. |
|
936 | empty. Otherwise the question is repeated until an answer is given. | |
914 | If EOF occurs 20 times consecutively, the default answer is assumed, |
|
937 | If EOF occurs 20 times consecutively, the default answer is assumed, | |
915 | or if there is no default, an exception is raised to prevent infinite |
|
938 | or if there is no default, an exception is raised to prevent infinite | |
916 | loops. |
|
939 | loops. | |
917 |
|
940 | |||
918 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
941 | Valid answers are: y/yes/n/no (match is not case sensitive).""" | |
919 |
|
942 | |||
920 | answers = {'y':1,'n':0,'yes':1,'no':0} |
|
943 | answers = {'y':1,'n':0,'yes':1,'no':0} | |
921 | ans = None |
|
944 | ans = None | |
922 | eofs, max_eofs = 0, 20 |
|
945 | eofs, max_eofs = 0, 20 | |
923 | while ans not in answers.keys(): |
|
946 | while ans not in answers.keys(): | |
924 | try: |
|
947 | try: | |
925 | ans = raw_input(prompt+' ').lower() |
|
948 | ans = raw_input(prompt+' ').lower() | |
926 | if not ans: # response was an empty string |
|
949 | if not ans: # response was an empty string | |
927 | ans = default |
|
950 | ans = default | |
928 | eofs = 0 |
|
951 | eofs = 0 | |
929 | except (EOFError,KeyboardInterrupt): |
|
952 | except (EOFError,KeyboardInterrupt): | |
930 | eofs = eofs + 1 |
|
953 | eofs = eofs + 1 | |
931 | if eofs >= max_eofs: |
|
954 | if eofs >= max_eofs: | |
932 | if default in answers.keys(): |
|
955 | if default in answers.keys(): | |
933 | ans = default |
|
956 | ans = default | |
934 | else: |
|
957 | else: | |
935 | raise |
|
958 | raise | |
936 |
|
959 | |||
937 | return answers[ans] |
|
960 | return answers[ans] | |
938 |
|
961 | |||
939 | #---------------------------------------------------------------------------- |
|
962 | #---------------------------------------------------------------------------- | |
940 |
def marquee(txt='',width=8 |
|
963 | def marquee(txt='',width=78,mark='*'): | |
941 | """Return the input string centered in a 'marquee'.""" |
|
964 | """Return the input string centered in a 'marquee'.""" | |
942 | if not txt: |
|
965 | if not txt: | |
943 | return (mark*width)[:width] |
|
966 | return (mark*width)[:width] | |
944 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
967 | nmark = (width-len(txt)-2)/len(mark)/2 | |
945 | if nmark < 0: nmark =0 |
|
968 | if nmark < 0: nmark =0 | |
946 | marks = mark*nmark |
|
969 | marks = mark*nmark | |
947 | return '%s %s %s' % (marks,txt,marks) |
|
970 | return '%s %s %s' % (marks,txt,marks) | |
948 |
|
971 | |||
949 | #---------------------------------------------------------------------------- |
|
972 | #---------------------------------------------------------------------------- | |
950 | class EvalDict: |
|
973 | class EvalDict: | |
951 | """ |
|
974 | """ | |
952 | Emulate a dict which evaluates its contents in the caller's frame. |
|
975 | Emulate a dict which evaluates its contents in the caller's frame. | |
953 |
|
976 | |||
954 | Usage: |
|
977 | Usage: | |
955 | >>>number = 19 |
|
978 | >>>number = 19 | |
956 | >>>text = "python" |
|
979 | >>>text = "python" | |
957 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
980 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() | |
958 | """ |
|
981 | """ | |
959 |
|
982 | |||
960 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
983 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a | |
961 | # modified (shorter) version of: |
|
984 | # modified (shorter) version of: | |
962 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
985 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by | |
963 | # Skip Montanaro (skip@pobox.com). |
|
986 | # Skip Montanaro (skip@pobox.com). | |
964 |
|
987 | |||
965 | def __getitem__(self, name): |
|
988 | def __getitem__(self, name): | |
966 | frame = sys._getframe(1) |
|
989 | frame = sys._getframe(1) | |
967 | return eval(name, frame.f_globals, frame.f_locals) |
|
990 | return eval(name, frame.f_globals, frame.f_locals) | |
968 |
|
991 | |||
969 | EvalString = EvalDict # for backwards compatibility |
|
992 | EvalString = EvalDict # for backwards compatibility | |
970 | #---------------------------------------------------------------------------- |
|
993 | #---------------------------------------------------------------------------- | |
971 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
994 | def qw(words,flat=0,sep=None,maxsplit=-1): | |
972 | """Similar to Perl's qw() operator, but with some more options. |
|
995 | """Similar to Perl's qw() operator, but with some more options. | |
973 |
|
996 | |||
974 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
997 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) | |
975 |
|
998 | |||
976 | words can also be a list itself, and with flat=1, the output will be |
|
999 | words can also be a list itself, and with flat=1, the output will be | |
977 | recursively flattened. Examples: |
|
1000 | recursively flattened. Examples: | |
978 |
|
1001 | |||
979 | >>> qw('1 2') |
|
1002 | >>> qw('1 2') | |
980 | ['1', '2'] |
|
1003 | ['1', '2'] | |
981 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1004 | >>> qw(['a b','1 2',['m n','p q']]) | |
982 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1005 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] | |
983 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1006 | >>> qw(['a b','1 2',['m n','p q']],flat=1) | |
984 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ |
|
1007 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ | |
985 |
|
1008 | |||
986 | if type(words) in StringTypes: |
|
1009 | if type(words) in StringTypes: | |
987 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1010 | return [word.strip() for word in words.split(sep,maxsplit) | |
988 | if word and not word.isspace() ] |
|
1011 | if word and not word.isspace() ] | |
989 | if flat: |
|
1012 | if flat: | |
990 | return flatten(map(qw,words,[1]*len(words))) |
|
1013 | return flatten(map(qw,words,[1]*len(words))) | |
991 | return map(qw,words) |
|
1014 | return map(qw,words) | |
992 |
|
1015 | |||
993 | #---------------------------------------------------------------------------- |
|
1016 | #---------------------------------------------------------------------------- | |
994 | def qwflat(words,sep=None,maxsplit=-1): |
|
1017 | def qwflat(words,sep=None,maxsplit=-1): | |
995 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1018 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" | |
996 | return qw(words,1,sep,maxsplit) |
|
1019 | return qw(words,1,sep,maxsplit) | |
997 |
|
1020 | |||
998 | #----------------------------------------------------------------------------- |
|
1021 | #----------------------------------------------------------------------------- | |
999 | def list_strings(arg): |
|
1022 | def list_strings(arg): | |
1000 | """Always return a list of strings, given a string or list of strings |
|
1023 | """Always return a list of strings, given a string or list of strings | |
1001 | as input.""" |
|
1024 | as input.""" | |
1002 |
|
1025 | |||
1003 | if type(arg) in StringTypes: return [arg] |
|
1026 | if type(arg) in StringTypes: return [arg] | |
1004 | else: return arg |
|
1027 | else: return arg | |
1005 |
|
1028 | |||
1006 | #---------------------------------------------------------------------------- |
|
1029 | #---------------------------------------------------------------------------- | |
1007 | def grep(pat,list,case=1): |
|
1030 | def grep(pat,list,case=1): | |
1008 | """Simple minded grep-like function. |
|
1031 | """Simple minded grep-like function. | |
1009 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1032 | grep(pat,list) returns occurrences of pat in list, None on failure. | |
1010 |
|
1033 | |||
1011 | It only does simple string matching, with no support for regexps. Use the |
|
1034 | It only does simple string matching, with no support for regexps. Use the | |
1012 | option case=0 for case-insensitive matching.""" |
|
1035 | option case=0 for case-insensitive matching.""" | |
1013 |
|
1036 | |||
1014 | # This is pretty crude. At least it should implement copying only references |
|
1037 | # This is pretty crude. At least it should implement copying only references | |
1015 | # to the original data in case it's big. Now it copies the data for output. |
|
1038 | # to the original data in case it's big. Now it copies the data for output. | |
1016 | out=[] |
|
1039 | out=[] | |
1017 | if case: |
|
1040 | if case: | |
1018 | for term in list: |
|
1041 | for term in list: | |
1019 | if term.find(pat)>-1: out.append(term) |
|
1042 | if term.find(pat)>-1: out.append(term) | |
1020 | else: |
|
1043 | else: | |
1021 | lpat=pat.lower() |
|
1044 | lpat=pat.lower() | |
1022 | for term in list: |
|
1045 | for term in list: | |
1023 | if term.lower().find(lpat)>-1: out.append(term) |
|
1046 | if term.lower().find(lpat)>-1: out.append(term) | |
1024 |
|
1047 | |||
1025 | if len(out): return out |
|
1048 | if len(out): return out | |
1026 | else: return None |
|
1049 | else: return None | |
1027 |
|
1050 | |||
1028 | #---------------------------------------------------------------------------- |
|
1051 | #---------------------------------------------------------------------------- | |
1029 | def dgrep(pat,*opts): |
|
1052 | def dgrep(pat,*opts): | |
1030 | """Return grep() on dir()+dir(__builtins__). |
|
1053 | """Return grep() on dir()+dir(__builtins__). | |
1031 |
|
1054 | |||
1032 | A very common use of grep() when working interactively.""" |
|
1055 | A very common use of grep() when working interactively.""" | |
1033 |
|
1056 | |||
1034 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1057 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) | |
1035 |
|
1058 | |||
1036 | #---------------------------------------------------------------------------- |
|
1059 | #---------------------------------------------------------------------------- | |
1037 | def idgrep(pat): |
|
1060 | def idgrep(pat): | |
1038 | """Case-insensitive dgrep()""" |
|
1061 | """Case-insensitive dgrep()""" | |
1039 |
|
1062 | |||
1040 | return dgrep(pat,0) |
|
1063 | return dgrep(pat,0) | |
1041 |
|
1064 | |||
1042 | #---------------------------------------------------------------------------- |
|
1065 | #---------------------------------------------------------------------------- | |
1043 | def igrep(pat,list): |
|
1066 | def igrep(pat,list): | |
1044 | """Synonym for case-insensitive grep.""" |
|
1067 | """Synonym for case-insensitive grep.""" | |
1045 |
|
1068 | |||
1046 | return grep(pat,list,case=0) |
|
1069 | return grep(pat,list,case=0) | |
1047 |
|
1070 | |||
1048 | #---------------------------------------------------------------------------- |
|
1071 | #---------------------------------------------------------------------------- | |
1049 | def indent(str,nspaces=4,ntabs=0): |
|
1072 | def indent(str,nspaces=4,ntabs=0): | |
1050 | """Indent a string a given number of spaces or tabstops. |
|
1073 | """Indent a string a given number of spaces or tabstops. | |
1051 |
|
1074 | |||
1052 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1075 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. | |
1053 | """ |
|
1076 | """ | |
1054 | if str is None: |
|
1077 | if str is None: | |
1055 | return |
|
1078 | return | |
1056 | ind = '\t'*ntabs+' '*nspaces |
|
1079 | ind = '\t'*ntabs+' '*nspaces | |
1057 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1080 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) | |
1058 | if outstr.endswith(os.linesep+ind): |
|
1081 | if outstr.endswith(os.linesep+ind): | |
1059 | return outstr[:-len(ind)] |
|
1082 | return outstr[:-len(ind)] | |
1060 | else: |
|
1083 | else: | |
1061 | return outstr |
|
1084 | return outstr | |
1062 |
|
1085 | |||
1063 | #----------------------------------------------------------------------------- |
|
1086 | #----------------------------------------------------------------------------- | |
1064 | def native_line_ends(filename,backup=1): |
|
1087 | def native_line_ends(filename,backup=1): | |
1065 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1088 | """Convert (in-place) a file to line-ends native to the current OS. | |
1066 |
|
1089 | |||
1067 | If the optional backup argument is given as false, no backup of the |
|
1090 | If the optional backup argument is given as false, no backup of the | |
1068 | original file is left. """ |
|
1091 | original file is left. """ | |
1069 |
|
1092 | |||
1070 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1093 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} | |
1071 |
|
1094 | |||
1072 | bak_filename = filename + backup_suffixes[os.name] |
|
1095 | bak_filename = filename + backup_suffixes[os.name] | |
1073 |
|
1096 | |||
1074 | original = open(filename).read() |
|
1097 | original = open(filename).read() | |
1075 | shutil.copy2(filename,bak_filename) |
|
1098 | shutil.copy2(filename,bak_filename) | |
1076 | try: |
|
1099 | try: | |
1077 | new = open(filename,'wb') |
|
1100 | new = open(filename,'wb') | |
1078 | new.write(os.linesep.join(original.splitlines())) |
|
1101 | new.write(os.linesep.join(original.splitlines())) | |
1079 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1102 | new.write(os.linesep) # ALWAYS put an eol at the end of the file | |
1080 | new.close() |
|
1103 | new.close() | |
1081 | except: |
|
1104 | except: | |
1082 | os.rename(bak_filename,filename) |
|
1105 | os.rename(bak_filename,filename) | |
1083 | if not backup: |
|
1106 | if not backup: | |
1084 | try: |
|
1107 | try: | |
1085 | os.remove(bak_filename) |
|
1108 | os.remove(bak_filename) | |
1086 | except: |
|
1109 | except: | |
1087 | pass |
|
1110 | pass | |
1088 |
|
1111 | |||
1089 | #---------------------------------------------------------------------------- |
|
1112 | #---------------------------------------------------------------------------- | |
1090 | def get_pager_cmd(pager_cmd = None): |
|
1113 | def get_pager_cmd(pager_cmd = None): | |
1091 | """Return a pager command. |
|
1114 | """Return a pager command. | |
1092 |
|
1115 | |||
1093 | Makes some attempts at finding an OS-correct one.""" |
|
1116 | Makes some attempts at finding an OS-correct one.""" | |
1094 |
|
1117 | |||
1095 | if os.name == 'posix': |
|
1118 | if os.name == 'posix': | |
1096 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1119 | default_pager_cmd = 'less -r' # -r for color control sequences | |
1097 | elif os.name in ['nt','dos']: |
|
1120 | elif os.name in ['nt','dos']: | |
1098 | default_pager_cmd = 'type' |
|
1121 | default_pager_cmd = 'type' | |
1099 |
|
1122 | |||
1100 | if pager_cmd is None: |
|
1123 | if pager_cmd is None: | |
1101 | try: |
|
1124 | try: | |
1102 | pager_cmd = os.environ['PAGER'] |
|
1125 | pager_cmd = os.environ['PAGER'] | |
1103 | except: |
|
1126 | except: | |
1104 | pager_cmd = default_pager_cmd |
|
1127 | pager_cmd = default_pager_cmd | |
1105 | return pager_cmd |
|
1128 | return pager_cmd | |
1106 |
|
1129 | |||
1107 | #----------------------------------------------------------------------------- |
|
1130 | #----------------------------------------------------------------------------- | |
1108 | def get_pager_start(pager,start): |
|
1131 | def get_pager_start(pager,start): | |
1109 | """Return the string for paging files with an offset. |
|
1132 | """Return the string for paging files with an offset. | |
1110 |
|
1133 | |||
1111 | This is the '+N' argument which less and more (under Unix) accept. |
|
1134 | This is the '+N' argument which less and more (under Unix) accept. | |
1112 | """ |
|
1135 | """ | |
1113 |
|
1136 | |||
1114 | if pager in ['less','more']: |
|
1137 | if pager in ['less','more']: | |
1115 | if start: |
|
1138 | if start: | |
1116 | start_string = '+' + str(start) |
|
1139 | start_string = '+' + str(start) | |
1117 | else: |
|
1140 | else: | |
1118 | start_string = '' |
|
1141 | start_string = '' | |
1119 | else: |
|
1142 | else: | |
1120 | start_string = '' |
|
1143 | start_string = '' | |
1121 | return start_string |
|
1144 | return start_string | |
1122 |
|
1145 | |||
1123 | #---------------------------------------------------------------------------- |
|
1146 | #---------------------------------------------------------------------------- | |
1124 | def page_dumb(strng,start=0,screen_lines=25): |
|
1147 | def page_dumb(strng,start=0,screen_lines=25): | |
1125 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1148 | """Very dumb 'pager' in Python, for when nothing else works. | |
1126 |
|
1149 | |||
1127 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1150 | Only moves forward, same interface as page(), except for pager_cmd and | |
1128 | mode.""" |
|
1151 | mode.""" | |
1129 |
|
1152 | |||
1130 | out_ln = strng.splitlines()[start:] |
|
1153 | out_ln = strng.splitlines()[start:] | |
1131 | screens = chop(out_ln,screen_lines-1) |
|
1154 | screens = chop(out_ln,screen_lines-1) | |
1132 | if len(screens) == 1: |
|
1155 | if len(screens) == 1: | |
1133 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1156 | print >>Term.cout, os.linesep.join(screens[0]) | |
1134 | else: |
|
1157 | else: | |
1135 | for scr in screens[0:-1]: |
|
1158 | for scr in screens[0:-1]: | |
1136 | print >>Term.cout, os.linesep.join(scr) |
|
1159 | print >>Term.cout, os.linesep.join(scr) | |
1137 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1160 | ans = raw_input('---Return to continue, q to quit--- ') | |
1138 | if ans.lower().startswith('q'): |
|
1161 | if ans.lower().startswith('q'): | |
1139 | return |
|
1162 | return | |
1140 | print >>Term.cout, os.linesep.join(screens[-1]) |
|
1163 | print >>Term.cout, os.linesep.join(screens[-1]) | |
1141 |
|
1164 | |||
1142 | #---------------------------------------------------------------------------- |
|
1165 | #---------------------------------------------------------------------------- | |
1143 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1166 | def page(strng,start=0,screen_lines=0,pager_cmd = None): | |
1144 | """Print a string, piping through a pager after a certain length. |
|
1167 | """Print a string, piping through a pager after a certain length. | |
1145 |
|
1168 | |||
1146 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1169 | The screen_lines parameter specifies the number of *usable* lines of your | |
1147 | terminal screen (total lines minus lines you need to reserve to show other |
|
1170 | terminal screen (total lines minus lines you need to reserve to show other | |
1148 | information). |
|
1171 | information). | |
1149 |
|
1172 | |||
1150 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1173 | If you set screen_lines to a number <=0, page() will try to auto-determine | |
1151 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1174 | your screen size and will only use up to (screen_size+screen_lines) for | |
1152 | printing, paging after that. That is, if you want auto-detection but need |
|
1175 | printing, paging after that. That is, if you want auto-detection but need | |
1153 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1176 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for | |
1154 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1177 | auto-detection without any lines reserved simply use screen_lines = 0. | |
1155 |
|
1178 | |||
1156 | If a string won't fit in the allowed lines, it is sent through the |
|
1179 | If a string won't fit in the allowed lines, it is sent through the | |
1157 | specified pager command. If none given, look for PAGER in the environment, |
|
1180 | specified pager command. If none given, look for PAGER in the environment, | |
1158 | and ultimately default to less. |
|
1181 | and ultimately default to less. | |
1159 |
|
1182 | |||
1160 | If no system pager works, the string is sent through a 'dumb pager' |
|
1183 | If no system pager works, the string is sent through a 'dumb pager' | |
1161 | written in python, very simplistic. |
|
1184 | written in python, very simplistic. | |
1162 | """ |
|
1185 | """ | |
1163 |
|
1186 | |||
1164 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1187 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs | |
1165 | TERM = os.environ.get('TERM','dumb') |
|
1188 | TERM = os.environ.get('TERM','dumb') | |
1166 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1189 | if TERM in ['dumb','emacs'] and os.name != 'nt': | |
1167 | print strng |
|
1190 | print strng | |
1168 | return |
|
1191 | return | |
1169 | # chop off the topmost part of the string we don't want to see |
|
1192 | # chop off the topmost part of the string we don't want to see | |
1170 | str_lines = strng.split(os.linesep)[start:] |
|
1193 | str_lines = strng.split(os.linesep)[start:] | |
1171 | str_toprint = os.linesep.join(str_lines) |
|
1194 | str_toprint = os.linesep.join(str_lines) | |
1172 | num_newlines = len(str_lines) |
|
1195 | num_newlines = len(str_lines) | |
1173 | len_str = len(str_toprint) |
|
1196 | len_str = len(str_toprint) | |
1174 |
|
1197 | |||
1175 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1198 | # Dumb heuristics to guesstimate number of on-screen lines the string | |
1176 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1199 | # takes. Very basic, but good enough for docstrings in reasonable | |
1177 | # terminals. If someone later feels like refining it, it's not hard. |
|
1200 | # terminals. If someone later feels like refining it, it's not hard. | |
1178 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1201 | numlines = max(num_newlines,int(len_str/80)+1) | |
1179 |
|
1202 | |||
1180 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1203 | screen_lines_def = 25 # default value if we can't auto-determine | |
1181 |
|
1204 | |||
1182 | # auto-determine screen size |
|
1205 | # auto-determine screen size | |
1183 | if screen_lines <= 0: |
|
1206 | if screen_lines <= 0: | |
1184 | if TERM=='xterm': |
|
1207 | if TERM=='xterm': | |
1185 | try: |
|
1208 | try: | |
1186 | import curses |
|
1209 | import curses | |
1187 | if hasattr(curses,'initscr'): |
|
1210 | if hasattr(curses,'initscr'): | |
1188 | use_curses = 1 |
|
1211 | use_curses = 1 | |
1189 | else: |
|
1212 | else: | |
1190 | use_curses = 0 |
|
1213 | use_curses = 0 | |
1191 | except ImportError: |
|
1214 | except ImportError: | |
1192 | use_curses = 0 |
|
1215 | use_curses = 0 | |
1193 | else: |
|
1216 | else: | |
1194 | # curses causes problems on many terminals other than xterm. |
|
1217 | # curses causes problems on many terminals other than xterm. | |
1195 | use_curses = 0 |
|
1218 | use_curses = 0 | |
1196 | if use_curses: |
|
1219 | if use_curses: | |
1197 | scr = curses.initscr() |
|
1220 | scr = curses.initscr() | |
1198 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1221 | screen_lines_real,screen_cols = scr.getmaxyx() | |
1199 | curses.endwin() |
|
1222 | curses.endwin() | |
1200 | screen_lines += screen_lines_real |
|
1223 | screen_lines += screen_lines_real | |
1201 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1224 | #print '***Screen size:',screen_lines_real,'lines x',\ | |
1202 | #screen_cols,'columns.' # dbg |
|
1225 | #screen_cols,'columns.' # dbg | |
1203 | else: |
|
1226 | else: | |
1204 | screen_lines += screen_lines_def |
|
1227 | screen_lines += screen_lines_def | |
1205 |
|
1228 | |||
1206 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1229 | #print 'numlines',numlines,'screenlines',screen_lines # dbg | |
1207 | if numlines <= screen_lines : |
|
1230 | if numlines <= screen_lines : | |
1208 | #print '*** normal print' # dbg |
|
1231 | #print '*** normal print' # dbg | |
1209 | print >>Term.cout, str_toprint |
|
1232 | print >>Term.cout, str_toprint | |
1210 | else: |
|
1233 | else: | |
1211 | # Try to open pager and default to internal one if that fails. |
|
1234 | # Try to open pager and default to internal one if that fails. | |
1212 | # All failure modes are tagged as 'retval=1', to match the return |
|
1235 | # All failure modes are tagged as 'retval=1', to match the return | |
1213 | # value of a failed system command. If any intermediate attempt |
|
1236 | # value of a failed system command. If any intermediate attempt | |
1214 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1237 | # sets retval to 1, at the end we resort to our own page_dumb() pager. | |
1215 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1238 | pager_cmd = get_pager_cmd(pager_cmd) | |
1216 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1239 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1217 | if os.name == 'nt': |
|
1240 | if os.name == 'nt': | |
1218 | if pager_cmd.startswith('type'): |
|
1241 | if pager_cmd.startswith('type'): | |
1219 | # The default WinXP 'type' command is failing on complex strings. |
|
1242 | # The default WinXP 'type' command is failing on complex strings. | |
1220 | retval = 1 |
|
1243 | retval = 1 | |
1221 | else: |
|
1244 | else: | |
1222 | tmpname = tempfile.mktemp('.txt') |
|
1245 | tmpname = tempfile.mktemp('.txt') | |
1223 | tmpfile = file(tmpname,'wt') |
|
1246 | tmpfile = file(tmpname,'wt') | |
1224 | tmpfile.write(strng) |
|
1247 | tmpfile.write(strng) | |
1225 | tmpfile.close() |
|
1248 | tmpfile.close() | |
1226 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1249 | cmd = "%s < %s" % (pager_cmd,tmpname) | |
1227 | if os.system(cmd): |
|
1250 | if os.system(cmd): | |
1228 | retval = 1 |
|
1251 | retval = 1 | |
1229 | else: |
|
1252 | else: | |
1230 | retval = None |
|
1253 | retval = None | |
1231 | os.remove(tmpname) |
|
1254 | os.remove(tmpname) | |
1232 | else: |
|
1255 | else: | |
1233 | try: |
|
1256 | try: | |
1234 | retval = None |
|
1257 | retval = None | |
1235 | # if I use popen4, things hang. No idea why. |
|
1258 | # if I use popen4, things hang. No idea why. | |
1236 | #pager,shell_out = os.popen4(pager_cmd) |
|
1259 | #pager,shell_out = os.popen4(pager_cmd) | |
1237 | pager = os.popen(pager_cmd,'w') |
|
1260 | pager = os.popen(pager_cmd,'w') | |
1238 | pager.write(strng) |
|
1261 | pager.write(strng) | |
1239 | pager.close() |
|
1262 | pager.close() | |
1240 | retval = pager.close() # success returns None |
|
1263 | retval = pager.close() # success returns None | |
1241 | except IOError,msg: # broken pipe when user quits |
|
1264 | except IOError,msg: # broken pipe when user quits | |
1242 | if msg.args == (32,'Broken pipe'): |
|
1265 | if msg.args == (32,'Broken pipe'): | |
1243 | retval = None |
|
1266 | retval = None | |
1244 | else: |
|
1267 | else: | |
1245 | retval = 1 |
|
1268 | retval = 1 | |
1246 | except OSError: |
|
1269 | except OSError: | |
1247 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1270 | # Other strange problems, sometimes seen in Win2k/cygwin | |
1248 | retval = 1 |
|
1271 | retval = 1 | |
1249 | if retval is not None: |
|
1272 | if retval is not None: | |
1250 | page_dumb(strng,screen_lines=screen_lines) |
|
1273 | page_dumb(strng,screen_lines=screen_lines) | |
1251 |
|
1274 | |||
1252 | #---------------------------------------------------------------------------- |
|
1275 | #---------------------------------------------------------------------------- | |
1253 | def page_file(fname,start = 0, pager_cmd = None): |
|
1276 | def page_file(fname,start = 0, pager_cmd = None): | |
1254 | """Page a file, using an optional pager command and starting line. |
|
1277 | """Page a file, using an optional pager command and starting line. | |
1255 | """ |
|
1278 | """ | |
1256 |
|
1279 | |||
1257 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1280 | pager_cmd = get_pager_cmd(pager_cmd) | |
1258 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1281 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1259 |
|
1282 | |||
1260 | try: |
|
1283 | try: | |
1261 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1284 | if os.environ['TERM'] in ['emacs','dumb']: | |
1262 | raise EnvironmentError |
|
1285 | raise EnvironmentError | |
1263 | xsys(pager_cmd + ' ' + fname) |
|
1286 | xsys(pager_cmd + ' ' + fname) | |
1264 | except: |
|
1287 | except: | |
1265 | try: |
|
1288 | try: | |
1266 | if start > 0: |
|
1289 | if start > 0: | |
1267 | start -= 1 |
|
1290 | start -= 1 | |
1268 | page(open(fname).read(),start) |
|
1291 | page(open(fname).read(),start) | |
1269 | except: |
|
1292 | except: | |
1270 | print 'Unable to show file',`fname` |
|
1293 | print 'Unable to show file',`fname` | |
1271 |
|
1294 | |||
1272 | #---------------------------------------------------------------------------- |
|
1295 | #---------------------------------------------------------------------------- | |
1273 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1296 | def snip_print(str,width = 75,print_full = 0,header = ''): | |
1274 | """Print a string snipping the midsection to fit in width. |
|
1297 | """Print a string snipping the midsection to fit in width. | |
1275 |
|
1298 | |||
1276 | print_full: mode control: |
|
1299 | print_full: mode control: | |
1277 | - 0: only snip long strings |
|
1300 | - 0: only snip long strings | |
1278 | - 1: send to page() directly. |
|
1301 | - 1: send to page() directly. | |
1279 | - 2: snip long strings and ask for full length viewing with page() |
|
1302 | - 2: snip long strings and ask for full length viewing with page() | |
1280 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1303 | Return 1 if snipping was necessary, 0 otherwise.""" | |
1281 |
|
1304 | |||
1282 | if print_full == 1: |
|
1305 | if print_full == 1: | |
1283 | page(header+str) |
|
1306 | page(header+str) | |
1284 | return 0 |
|
1307 | return 0 | |
1285 |
|
1308 | |||
1286 | print header, |
|
1309 | print header, | |
1287 | if len(str) < width: |
|
1310 | if len(str) < width: | |
1288 | print str |
|
1311 | print str | |
1289 | snip = 0 |
|
1312 | snip = 0 | |
1290 | else: |
|
1313 | else: | |
1291 | whalf = int((width -5)/2) |
|
1314 | whalf = int((width -5)/2) | |
1292 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1315 | print str[:whalf] + ' <...> ' + str[-whalf:] | |
1293 | snip = 1 |
|
1316 | snip = 1 | |
1294 | if snip and print_full == 2: |
|
1317 | if snip and print_full == 2: | |
1295 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1318 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': | |
1296 | page(str) |
|
1319 | page(str) | |
1297 | return snip |
|
1320 | return snip | |
1298 |
|
1321 | |||
1299 | #**************************************************************************** |
|
1322 | #**************************************************************************** | |
1300 | # lists, dicts and structures |
|
1323 | # lists, dicts and structures | |
1301 |
|
1324 | |||
1302 | def belong(candidates,checklist): |
|
1325 | def belong(candidates,checklist): | |
1303 | """Check whether a list of items appear in a given list of options. |
|
1326 | """Check whether a list of items appear in a given list of options. | |
1304 |
|
1327 | |||
1305 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1328 | Returns a list of 1 and 0, one for each candidate given.""" | |
1306 |
|
1329 | |||
1307 | return [x in checklist for x in candidates] |
|
1330 | return [x in checklist for x in candidates] | |
1308 |
|
1331 | |||
1309 | #---------------------------------------------------------------------------- |
|
1332 | #---------------------------------------------------------------------------- | |
1310 | def uniq_stable(elems): |
|
1333 | def uniq_stable(elems): | |
1311 | """uniq_stable(elems) -> list |
|
1334 | """uniq_stable(elems) -> list | |
1312 |
|
1335 | |||
1313 | Return from an iterable, a list of all the unique elements in the input, |
|
1336 | Return from an iterable, a list of all the unique elements in the input, | |
1314 | but maintaining the order in which they first appear. |
|
1337 | but maintaining the order in which they first appear. | |
1315 |
|
1338 | |||
1316 | A naive solution to this problem which just makes a dictionary with the |
|
1339 | A naive solution to this problem which just makes a dictionary with the | |
1317 | elements as keys fails to respect the stability condition, since |
|
1340 | elements as keys fails to respect the stability condition, since | |
1318 | dictionaries are unsorted by nature. |
|
1341 | dictionaries are unsorted by nature. | |
1319 |
|
1342 | |||
1320 | Note: All elements in the input must be valid dictionary keys for this |
|
1343 | Note: All elements in the input must be valid dictionary keys for this | |
1321 | routine to work, as it internally uses a dictionary for efficiency |
|
1344 | routine to work, as it internally uses a dictionary for efficiency | |
1322 | reasons.""" |
|
1345 | reasons.""" | |
1323 |
|
1346 | |||
1324 | unique = [] |
|
1347 | unique = [] | |
1325 | unique_dict = {} |
|
1348 | unique_dict = {} | |
1326 | for nn in elems: |
|
1349 | for nn in elems: | |
1327 | if nn not in unique_dict: |
|
1350 | if nn not in unique_dict: | |
1328 | unique.append(nn) |
|
1351 | unique.append(nn) | |
1329 | unique_dict[nn] = None |
|
1352 | unique_dict[nn] = None | |
1330 | return unique |
|
1353 | return unique | |
1331 |
|
1354 | |||
1332 | #---------------------------------------------------------------------------- |
|
1355 | #---------------------------------------------------------------------------- | |
1333 | class NLprinter: |
|
1356 | class NLprinter: | |
1334 | """Print an arbitrarily nested list, indicating index numbers. |
|
1357 | """Print an arbitrarily nested list, indicating index numbers. | |
1335 |
|
1358 | |||
1336 | An instance of this class called nlprint is available and callable as a |
|
1359 | An instance of this class called nlprint is available and callable as a | |
1337 | function. |
|
1360 | function. | |
1338 |
|
1361 | |||
1339 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1362 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' | |
1340 | and using 'sep' to separate the index from the value. """ |
|
1363 | and using 'sep' to separate the index from the value. """ | |
1341 |
|
1364 | |||
1342 | def __init__(self): |
|
1365 | def __init__(self): | |
1343 | self.depth = 0 |
|
1366 | self.depth = 0 | |
1344 |
|
1367 | |||
1345 | def __call__(self,lst,pos='',**kw): |
|
1368 | def __call__(self,lst,pos='',**kw): | |
1346 | """Prints the nested list numbering levels.""" |
|
1369 | """Prints the nested list numbering levels.""" | |
1347 | kw.setdefault('indent',' ') |
|
1370 | kw.setdefault('indent',' ') | |
1348 | kw.setdefault('sep',': ') |
|
1371 | kw.setdefault('sep',': ') | |
1349 | kw.setdefault('start',0) |
|
1372 | kw.setdefault('start',0) | |
1350 | kw.setdefault('stop',len(lst)) |
|
1373 | kw.setdefault('stop',len(lst)) | |
1351 | # we need to remove start and stop from kw so they don't propagate |
|
1374 | # we need to remove start and stop from kw so they don't propagate | |
1352 | # into a recursive call for a nested list. |
|
1375 | # into a recursive call for a nested list. | |
1353 | start = kw['start']; del kw['start'] |
|
1376 | start = kw['start']; del kw['start'] | |
1354 | stop = kw['stop']; del kw['stop'] |
|
1377 | stop = kw['stop']; del kw['stop'] | |
1355 | if self.depth == 0 and 'header' in kw.keys(): |
|
1378 | if self.depth == 0 and 'header' in kw.keys(): | |
1356 | print kw['header'] |
|
1379 | print kw['header'] | |
1357 |
|
1380 | |||
1358 | for idx in range(start,stop): |
|
1381 | for idx in range(start,stop): | |
1359 | elem = lst[idx] |
|
1382 | elem = lst[idx] | |
1360 | if type(elem)==type([]): |
|
1383 | if type(elem)==type([]): | |
1361 | self.depth += 1 |
|
1384 | self.depth += 1 | |
1362 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1385 | self.__call__(elem,itpl('$pos$idx,'),**kw) | |
1363 | self.depth -= 1 |
|
1386 | self.depth -= 1 | |
1364 | else: |
|
1387 | else: | |
1365 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1388 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') | |
1366 |
|
1389 | |||
1367 | nlprint = NLprinter() |
|
1390 | nlprint = NLprinter() | |
1368 | #---------------------------------------------------------------------------- |
|
1391 | #---------------------------------------------------------------------------- | |
1369 | def all_belong(candidates,checklist): |
|
1392 | def all_belong(candidates,checklist): | |
1370 | """Check whether a list of items ALL appear in a given list of options. |
|
1393 | """Check whether a list of items ALL appear in a given list of options. | |
1371 |
|
1394 | |||
1372 | Returns a single 1 or 0 value.""" |
|
1395 | Returns a single 1 or 0 value.""" | |
1373 |
|
1396 | |||
1374 | return 1-(0 in [x in checklist for x in candidates]) |
|
1397 | return 1-(0 in [x in checklist for x in candidates]) | |
1375 |
|
1398 | |||
1376 | #---------------------------------------------------------------------------- |
|
1399 | #---------------------------------------------------------------------------- | |
1377 | def sort_compare(lst1,lst2,inplace = 1): |
|
1400 | def sort_compare(lst1,lst2,inplace = 1): | |
1378 | """Sort and compare two lists. |
|
1401 | """Sort and compare two lists. | |
1379 |
|
1402 | |||
1380 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1403 | By default it does it in place, thus modifying the lists. Use inplace = 0 | |
1381 | to avoid that (at the cost of temporary copy creation).""" |
|
1404 | to avoid that (at the cost of temporary copy creation).""" | |
1382 | if not inplace: |
|
1405 | if not inplace: | |
1383 | lst1 = lst1[:] |
|
1406 | lst1 = lst1[:] | |
1384 | lst2 = lst2[:] |
|
1407 | lst2 = lst2[:] | |
1385 | lst1.sort(); lst2.sort() |
|
1408 | lst1.sort(); lst2.sort() | |
1386 | return lst1 == lst2 |
|
1409 | return lst1 == lst2 | |
1387 |
|
1410 | |||
1388 | #---------------------------------------------------------------------------- |
|
1411 | #---------------------------------------------------------------------------- | |
1389 | def mkdict(**kwargs): |
|
1412 | def mkdict(**kwargs): | |
1390 | """Return a dict from a keyword list. |
|
1413 | """Return a dict from a keyword list. | |
1391 |
|
1414 | |||
1392 | It's just syntactic sugar for making ditcionary creation more convenient: |
|
1415 | It's just syntactic sugar for making ditcionary creation more convenient: | |
1393 | # the standard way |
|
1416 | # the standard way | |
1394 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } |
|
1417 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } | |
1395 | # a cleaner way |
|
1418 | # a cleaner way | |
1396 | >>>data = dict(red=1, green=2, blue=3) |
|
1419 | >>>data = dict(red=1, green=2, blue=3) | |
1397 |
|
1420 | |||
1398 | If you need more than this, look at the Struct() class.""" |
|
1421 | If you need more than this, look at the Struct() class.""" | |
1399 |
|
1422 | |||
1400 | return kwargs |
|
1423 | return kwargs | |
1401 |
|
1424 | |||
1402 | #---------------------------------------------------------------------------- |
|
1425 | #---------------------------------------------------------------------------- | |
1403 | def list2dict(lst): |
|
1426 | def list2dict(lst): | |
1404 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1427 | """Takes a list of (key,value) pairs and turns it into a dict.""" | |
1405 |
|
1428 | |||
1406 | dic = {} |
|
1429 | dic = {} | |
1407 | for k,v in lst: dic[k] = v |
|
1430 | for k,v in lst: dic[k] = v | |
1408 | return dic |
|
1431 | return dic | |
1409 |
|
1432 | |||
1410 | #---------------------------------------------------------------------------- |
|
1433 | #---------------------------------------------------------------------------- | |
1411 | def list2dict2(lst,default=''): |
|
1434 | def list2dict2(lst,default=''): | |
1412 | """Takes a list and turns it into a dict. |
|
1435 | """Takes a list and turns it into a dict. | |
1413 | Much slower than list2dict, but more versatile. This version can take |
|
1436 | Much slower than list2dict, but more versatile. This version can take | |
1414 | lists with sublists of arbitrary length (including sclars).""" |
|
1437 | lists with sublists of arbitrary length (including sclars).""" | |
1415 |
|
1438 | |||
1416 | dic = {} |
|
1439 | dic = {} | |
1417 | for elem in lst: |
|
1440 | for elem in lst: | |
1418 | if type(elem) in (types.ListType,types.TupleType): |
|
1441 | if type(elem) in (types.ListType,types.TupleType): | |
1419 | size = len(elem) |
|
1442 | size = len(elem) | |
1420 | if size == 0: |
|
1443 | if size == 0: | |
1421 | pass |
|
1444 | pass | |
1422 | elif size == 1: |
|
1445 | elif size == 1: | |
1423 | dic[elem] = default |
|
1446 | dic[elem] = default | |
1424 | else: |
|
1447 | else: | |
1425 | k,v = elem[0], elem[1:] |
|
1448 | k,v = elem[0], elem[1:] | |
1426 | if len(v) == 1: v = v[0] |
|
1449 | if len(v) == 1: v = v[0] | |
1427 | dic[k] = v |
|
1450 | dic[k] = v | |
1428 | else: |
|
1451 | else: | |
1429 | dic[elem] = default |
|
1452 | dic[elem] = default | |
1430 | return dic |
|
1453 | return dic | |
1431 |
|
1454 | |||
1432 | #---------------------------------------------------------------------------- |
|
1455 | #---------------------------------------------------------------------------- | |
1433 | def flatten(seq): |
|
1456 | def flatten(seq): | |
1434 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1457 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" | |
1435 |
|
1458 | |||
1436 | # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in). |
|
1459 | # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in). | |
1437 |
|
1460 | |||
1438 | # if the x=0 isn't made, a *global* variable x is left over after calling |
|
1461 | # if the x=0 isn't made, a *global* variable x is left over after calling | |
1439 | # this function, with the value of the last element in the return |
|
1462 | # this function, with the value of the last element in the return | |
1440 | # list. This does seem like a bug big time to me. |
|
1463 | # list. This does seem like a bug big time to me. | |
1441 |
|
1464 | |||
1442 | # the problem is fixed with the x=0, which seems to force the creation of |
|
1465 | # the problem is fixed with the x=0, which seems to force the creation of | |
1443 | # a local name |
|
1466 | # a local name | |
1444 |
|
1467 | |||
1445 | x = 0 |
|
1468 | x = 0 | |
1446 | return [x for subseq in seq for x in subseq] |
|
1469 | return [x for subseq in seq for x in subseq] | |
1447 |
|
1470 | |||
1448 | #---------------------------------------------------------------------------- |
|
1471 | #---------------------------------------------------------------------------- | |
1449 | def get_slice(seq,start=0,stop=None,step=1): |
|
1472 | def get_slice(seq,start=0,stop=None,step=1): | |
1450 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1473 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" | |
1451 | if stop == None: |
|
1474 | if stop == None: | |
1452 | stop = len(seq) |
|
1475 | stop = len(seq) | |
1453 | item = lambda i: seq[i] |
|
1476 | item = lambda i: seq[i] | |
1454 | return map(item,xrange(start,stop,step)) |
|
1477 | return map(item,xrange(start,stop,step)) | |
1455 |
|
1478 | |||
1456 | #---------------------------------------------------------------------------- |
|
1479 | #---------------------------------------------------------------------------- | |
1457 | def chop(seq,size): |
|
1480 | def chop(seq,size): | |
1458 | """Chop a sequence into chunks of the given size.""" |
|
1481 | """Chop a sequence into chunks of the given size.""" | |
1459 | chunk = lambda i: seq[i:i+size] |
|
1482 | chunk = lambda i: seq[i:i+size] | |
1460 | return map(chunk,xrange(0,len(seq),size)) |
|
1483 | return map(chunk,xrange(0,len(seq),size)) | |
1461 |
|
1484 | |||
1462 | #---------------------------------------------------------------------------- |
|
1485 | #---------------------------------------------------------------------------- | |
1463 | def with(object, **args): |
|
1486 | def with(object, **args): | |
1464 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1487 | """Set multiple attributes for an object, similar to Pascal's with. | |
1465 |
|
1488 | |||
1466 | Example: |
|
1489 | Example: | |
1467 | with(jim, |
|
1490 | with(jim, | |
1468 | born = 1960, |
|
1491 | born = 1960, | |
1469 | haircolour = 'Brown', |
|
1492 | haircolour = 'Brown', | |
1470 | eyecolour = 'Green') |
|
1493 | eyecolour = 'Green') | |
1471 |
|
1494 | |||
1472 | Credit: Greg Ewing, in |
|
1495 | Credit: Greg Ewing, in | |
1473 | http://mail.python.org/pipermail/python-list/2001-May/040703.html""" |
|
1496 | http://mail.python.org/pipermail/python-list/2001-May/040703.html""" | |
1474 |
|
1497 | |||
1475 | object.__dict__.update(args) |
|
1498 | object.__dict__.update(args) | |
1476 |
|
1499 | |||
1477 | #---------------------------------------------------------------------------- |
|
1500 | #---------------------------------------------------------------------------- | |
1478 | def setattr_list(obj,alist,nspace = None): |
|
1501 | def setattr_list(obj,alist,nspace = None): | |
1479 | """Set a list of attributes for an object taken from a namespace. |
|
1502 | """Set a list of attributes for an object taken from a namespace. | |
1480 |
|
1503 | |||
1481 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1504 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in | |
1482 | alist with their values taken from nspace, which must be a dict (something |
|
1505 | alist with their values taken from nspace, which must be a dict (something | |
1483 | like locals() will often do) If nspace isn't given, locals() of the |
|
1506 | like locals() will often do) If nspace isn't given, locals() of the | |
1484 | *caller* is used, so in most cases you can omit it. |
|
1507 | *caller* is used, so in most cases you can omit it. | |
1485 |
|
1508 | |||
1486 | Note that alist can be given as a string, which will be automatically |
|
1509 | Note that alist can be given as a string, which will be automatically | |
1487 | split into a list on whitespace. If given as a list, it must be a list of |
|
1510 | split into a list on whitespace. If given as a list, it must be a list of | |
1488 | *strings* (the variable names themselves), not of variables.""" |
|
1511 | *strings* (the variable names themselves), not of variables.""" | |
1489 |
|
1512 | |||
1490 | # this grabs the local variables from the *previous* call frame -- that is |
|
1513 | # this grabs the local variables from the *previous* call frame -- that is | |
1491 | # the locals from the function that called setattr_list(). |
|
1514 | # the locals from the function that called setattr_list(). | |
1492 | # - snipped from weave.inline() |
|
1515 | # - snipped from weave.inline() | |
1493 | if nspace is None: |
|
1516 | if nspace is None: | |
1494 | call_frame = sys._getframe().f_back |
|
1517 | call_frame = sys._getframe().f_back | |
1495 | nspace = call_frame.f_locals |
|
1518 | nspace = call_frame.f_locals | |
1496 |
|
1519 | |||
1497 | if type(alist) in StringTypes: |
|
1520 | if type(alist) in StringTypes: | |
1498 | alist = alist.split() |
|
1521 | alist = alist.split() | |
1499 | for attr in alist: |
|
1522 | for attr in alist: | |
1500 | val = eval(attr,nspace) |
|
1523 | val = eval(attr,nspace) | |
1501 | setattr(obj,attr,val) |
|
1524 | setattr(obj,attr,val) | |
1502 |
|
1525 | |||
1503 | #---------------------------------------------------------------------------- |
|
1526 | #---------------------------------------------------------------------------- | |
1504 | def getattr_list(obj,alist,*args): |
|
1527 | def getattr_list(obj,alist,*args): | |
1505 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1528 | """getattr_list(obj,alist[, default]) -> attribute list. | |
1506 |
|
1529 | |||
1507 | Get a list of named attributes for an object. When a default argument is |
|
1530 | Get a list of named attributes for an object. When a default argument is | |
1508 | given, it is returned when the attribute doesn't exist; without it, an |
|
1531 | given, it is returned when the attribute doesn't exist; without it, an | |
1509 | exception is raised in that case. |
|
1532 | exception is raised in that case. | |
1510 |
|
1533 | |||
1511 | Note that alist can be given as a string, which will be automatically |
|
1534 | Note that alist can be given as a string, which will be automatically | |
1512 | split into a list on whitespace. If given as a list, it must be a list of |
|
1535 | split into a list on whitespace. If given as a list, it must be a list of | |
1513 | *strings* (the variable names themselves), not of variables.""" |
|
1536 | *strings* (the variable names themselves), not of variables.""" | |
1514 |
|
1537 | |||
1515 | if type(alist) in StringTypes: |
|
1538 | if type(alist) in StringTypes: | |
1516 | alist = alist.split() |
|
1539 | alist = alist.split() | |
1517 | if args: |
|
1540 | if args: | |
1518 | if len(args)==1: |
|
1541 | if len(args)==1: | |
1519 | default = args[0] |
|
1542 | default = args[0] | |
1520 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1543 | return map(lambda attr: getattr(obj,attr,default),alist) | |
1521 | else: |
|
1544 | else: | |
1522 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1545 | raise ValueError,'getattr_list() takes only one optional argument' | |
1523 | else: |
|
1546 | else: | |
1524 | return map(lambda attr: getattr(obj,attr),alist) |
|
1547 | return map(lambda attr: getattr(obj,attr),alist) | |
1525 |
|
1548 | |||
1526 | #---------------------------------------------------------------------------- |
|
1549 | #---------------------------------------------------------------------------- | |
1527 | def map_method(method,object_list,*argseq,**kw): |
|
1550 | def map_method(method,object_list,*argseq,**kw): | |
1528 | """map_method(method,object_list,*args,**kw) -> list |
|
1551 | """map_method(method,object_list,*args,**kw) -> list | |
1529 |
|
1552 | |||
1530 | Return a list of the results of applying the methods to the items of the |
|
1553 | Return a list of the results of applying the methods to the items of the | |
1531 | argument sequence(s). If more than one sequence is given, the method is |
|
1554 | argument sequence(s). If more than one sequence is given, the method is | |
1532 | called with an argument list consisting of the corresponding item of each |
|
1555 | called with an argument list consisting of the corresponding item of each | |
1533 | sequence. All sequences must be of the same length. |
|
1556 | sequence. All sequences must be of the same length. | |
1534 |
|
1557 | |||
1535 | Keyword arguments are passed verbatim to all objects called. |
|
1558 | Keyword arguments are passed verbatim to all objects called. | |
1536 |
|
1559 | |||
1537 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1560 | This is Python code, so it's not nearly as fast as the builtin map().""" | |
1538 |
|
1561 | |||
1539 | out_list = [] |
|
1562 | out_list = [] | |
1540 | idx = 0 |
|
1563 | idx = 0 | |
1541 | for object in object_list: |
|
1564 | for object in object_list: | |
1542 | try: |
|
1565 | try: | |
1543 | handler = getattr(object, method) |
|
1566 | handler = getattr(object, method) | |
1544 | except AttributeError: |
|
1567 | except AttributeError: | |
1545 | out_list.append(None) |
|
1568 | out_list.append(None) | |
1546 | else: |
|
1569 | else: | |
1547 | if argseq: |
|
1570 | if argseq: | |
1548 | args = map(lambda lst:lst[idx],argseq) |
|
1571 | args = map(lambda lst:lst[idx],argseq) | |
1549 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1572 | #print 'ob',object,'hand',handler,'ar',args # dbg | |
1550 | out_list.append(handler(args,**kw)) |
|
1573 | out_list.append(handler(args,**kw)) | |
1551 | else: |
|
1574 | else: | |
1552 | out_list.append(handler(**kw)) |
|
1575 | out_list.append(handler(**kw)) | |
1553 | idx += 1 |
|
1576 | idx += 1 | |
1554 | return out_list |
|
1577 | return out_list | |
1555 |
|
1578 | |||
1556 | #---------------------------------------------------------------------------- |
|
1579 | #---------------------------------------------------------------------------- | |
1557 | # Proposed popitem() extension, written as a method |
|
1580 | # Proposed popitem() extension, written as a method | |
1558 |
|
1581 | |||
1559 | class NotGiven: pass |
|
1582 | class NotGiven: pass | |
1560 |
|
1583 | |||
1561 | def popkey(dct,key,default=NotGiven): |
|
1584 | def popkey(dct,key,default=NotGiven): | |
1562 | """Return dct[key] and delete dct[key]. |
|
1585 | """Return dct[key] and delete dct[key]. | |
1563 |
|
1586 | |||
1564 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
1587 | If default is given, return it if dct[key] doesn't exist, otherwise raise | |
1565 | KeyError. """ |
|
1588 | KeyError. """ | |
1566 |
|
1589 | |||
1567 | try: |
|
1590 | try: | |
1568 | val = dct[key] |
|
1591 | val = dct[key] | |
1569 | except KeyError: |
|
1592 | except KeyError: | |
1570 | if default is NotGiven: |
|
1593 | if default is NotGiven: | |
1571 | raise |
|
1594 | raise | |
1572 | else: |
|
1595 | else: | |
1573 | return default |
|
1596 | return default | |
1574 | else: |
|
1597 | else: | |
1575 | del dct[key] |
|
1598 | del dct[key] | |
1576 | return val |
|
1599 | return val | |
1577 | #*************************** end of file <genutils.py> ********************** |
|
1600 | #*************************** end of file <genutils.py> ********************** | |
1578 |
|
1601 |
@@ -1,2047 +1,2052 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.1 or newer. |
|
5 | Requires Python 2.1 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 |
|
9 | $Id: iplib.py 908 2005-09-26 16:05:48Z 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-2004 Fernando Perez. <fperez@colorado.edu> |
|
14 | # Copyright (C) 2001-2004 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, much of that class has been copied |
|
20 | # Python standard library. Over time, much 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. The Python License (sec. 2) allows for this, but it's always |
|
22 | # subclassing. The Python License (sec. 2) allows for this, but it's always | |
23 | # nice to acknowledge credit where credit is due. |
|
23 | # nice to acknowledge credit where credit is due. | |
24 | #***************************************************************************** |
|
24 | #***************************************************************************** | |
25 |
|
25 | |||
26 | #**************************************************************************** |
|
26 | #**************************************************************************** | |
27 | # Modules and globals |
|
27 | # Modules and globals | |
28 |
|
28 | |||
29 | from __future__ import generators # for 2.2 backwards-compatibility |
|
29 | from __future__ import generators # for 2.2 backwards-compatibility | |
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 exceptions |
|
40 | import exceptions | |
41 | import keyword |
|
41 | import keyword | |
42 | import new |
|
42 | import new | |
43 | import os, sys, shutil |
|
43 | import os, sys, shutil | |
44 | import code, glob, types, re |
|
44 | import code, glob, types, re | |
45 | import string, StringIO |
|
45 | import string, StringIO | |
46 | import inspect, pydoc |
|
46 | import inspect, pydoc | |
47 | import bdb, pdb |
|
47 | import bdb, pdb | |
48 | import UserList # don't subclass list so this works with Python2.1 |
|
48 | import UserList # don't subclass list so this works with Python2.1 | |
49 | from pprint import pprint, pformat |
|
49 | from pprint import pprint, pformat | |
50 | import cPickle as pickle |
|
50 | import cPickle as pickle | |
51 | import traceback |
|
51 | import traceback | |
52 |
|
52 | |||
53 | # IPython's own modules |
|
53 | # IPython's own modules | |
54 | import IPython |
|
54 | import IPython | |
55 | from IPython import OInspect,PyColorize,ultraTB |
|
55 | from IPython import OInspect,PyColorize,ultraTB | |
56 | from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names |
|
56 | from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names | |
57 | from IPython.Logger import Logger |
|
57 | from IPython.Logger import Logger | |
58 | from IPython.Magic import Magic,magic2python,shlex_split |
|
58 | from IPython.Magic import Magic,magic2python,shlex_split | |
59 | from IPython.usage import cmd_line_usage,interactive_usage |
|
59 | from IPython.usage import cmd_line_usage,interactive_usage | |
60 | from IPython.Struct import Struct |
|
60 | from IPython.Struct import Struct | |
61 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
61 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
62 | from IPython.FakeModule import FakeModule |
|
62 | from IPython.FakeModule import FakeModule | |
63 | from IPython.background_jobs import BackgroundJobManager |
|
63 | from IPython.background_jobs import BackgroundJobManager | |
|
64 | from IPython.PyColorize import Parser | |||
64 | from IPython.genutils import * |
|
65 | from IPython.genutils import * | |
65 |
|
66 | |||
66 | # Global pointer to the running |
|
67 | # Global pointer to the running | |
67 |
|
68 | |||
68 | # store the builtin raw_input globally, and use this always, in case user code |
|
69 | # store the builtin raw_input globally, and use this always, in case user code | |
69 | # overwrites it (like wx.py.PyShell does) |
|
70 | # overwrites it (like wx.py.PyShell does) | |
70 | raw_input_original = raw_input |
|
71 | raw_input_original = raw_input | |
71 |
|
72 | |||
72 | #**************************************************************************** |
|
73 | #**************************************************************************** | |
73 | # Some utility function definitions |
|
74 | # Some utility function definitions | |
74 |
|
75 | |||
75 | class Bunch: pass |
|
76 | class Bunch: pass | |
76 |
|
77 | |||
77 | def esc_quotes(strng): |
|
78 | def esc_quotes(strng): | |
78 | """Return the input string with single and double quotes escaped out""" |
|
79 | """Return the input string with single and double quotes escaped out""" | |
79 |
|
80 | |||
80 | return strng.replace('"','\\"').replace("'","\\'") |
|
81 | return strng.replace('"','\\"').replace("'","\\'") | |
81 |
|
82 | |||
82 | def import_fail_info(mod_name,fns=None): |
|
83 | def import_fail_info(mod_name,fns=None): | |
83 | """Inform load failure for a module.""" |
|
84 | """Inform load failure for a module.""" | |
84 |
|
85 | |||
85 | if fns == None: |
|
86 | if fns == None: | |
86 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
87 | warn("Loading of %s failed.\n" % (mod_name,)) | |
87 | else: |
|
88 | else: | |
88 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
89 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) | |
89 |
|
90 | |||
90 | def qw_lol(indata): |
|
91 | def qw_lol(indata): | |
91 | """qw_lol('a b') -> [['a','b']], |
|
92 | """qw_lol('a b') -> [['a','b']], | |
92 | otherwise it's just a call to qw(). |
|
93 | otherwise it's just a call to qw(). | |
93 |
|
94 | |||
94 | We need this to make sure the modules_some keys *always* end up as a |
|
95 | We need this to make sure the modules_some keys *always* end up as a | |
95 | list of lists.""" |
|
96 | list of lists.""" | |
96 |
|
97 | |||
97 | if type(indata) in StringTypes: |
|
98 | if type(indata) in StringTypes: | |
98 | return [qw(indata)] |
|
99 | return [qw(indata)] | |
99 | else: |
|
100 | else: | |
100 | return qw(indata) |
|
101 | return qw(indata) | |
101 |
|
102 | |||
102 | def ipmagic(arg_s): |
|
103 | def ipmagic(arg_s): | |
103 | """Call a magic function by name. |
|
104 | """Call a magic function by name. | |
104 |
|
105 | |||
105 | Input: a string containing the name of the magic function to call and any |
|
106 | Input: a string containing the name of the magic function to call and any | |
106 | additional arguments to be passed to the magic. |
|
107 | additional arguments to be passed to the magic. | |
107 |
|
108 | |||
108 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
109 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
109 | prompt: |
|
110 | prompt: | |
110 |
|
111 | |||
111 | In[1]: %name -opt foo bar |
|
112 | In[1]: %name -opt foo bar | |
112 |
|
113 | |||
113 | To call a magic without arguments, simply use ipmagic('name'). |
|
114 | To call a magic without arguments, simply use ipmagic('name'). | |
114 |
|
115 | |||
115 | This provides a proper Python function to call IPython's magics in any |
|
116 | This provides a proper Python function to call IPython's magics in any | |
116 | valid Python code you can type at the interpreter, including loops and |
|
117 | valid Python code you can type at the interpreter, including loops and | |
117 | compound statements. It is added by IPython to the Python builtin |
|
118 | compound statements. It is added by IPython to the Python builtin | |
118 | namespace upon initialization.""" |
|
119 | namespace upon initialization.""" | |
119 |
|
120 | |||
120 | args = arg_s.split(' ',1) |
|
121 | args = arg_s.split(' ',1) | |
121 | magic_name = args[0] |
|
122 | magic_name = args[0] | |
122 | if magic_name.startswith(__IPYTHON__.ESC_MAGIC): |
|
123 | if magic_name.startswith(__IPYTHON__.ESC_MAGIC): | |
123 | magic_name = magic_name[1:] |
|
124 | magic_name = magic_name[1:] | |
124 | try: |
|
125 | try: | |
125 | magic_args = args[1] |
|
126 | magic_args = args[1] | |
126 | except IndexError: |
|
127 | except IndexError: | |
127 | magic_args = '' |
|
128 | magic_args = '' | |
128 | fn = getattr(__IPYTHON__,'magic_'+magic_name,None) |
|
129 | fn = getattr(__IPYTHON__,'magic_'+magic_name,None) | |
129 | if fn is None: |
|
130 | if fn is None: | |
130 | error("Magic function `%s` not found." % magic_name) |
|
131 | error("Magic function `%s` not found." % magic_name) | |
131 | else: |
|
132 | else: | |
132 | magic_args = __IPYTHON__.var_expand(magic_args) |
|
133 | magic_args = __IPYTHON__.var_expand(magic_args) | |
133 | return fn(magic_args) |
|
134 | return fn(magic_args) | |
134 |
|
135 | |||
135 | def ipalias(arg_s): |
|
136 | def ipalias(arg_s): | |
136 | """Call an alias by name. |
|
137 | """Call an alias by name. | |
137 |
|
138 | |||
138 | Input: a string containing the name of the alias to call and any |
|
139 | Input: a string containing the name of the alias to call and any | |
139 | additional arguments to be passed to the magic. |
|
140 | additional arguments to be passed to the magic. | |
140 |
|
141 | |||
141 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
142 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
142 | prompt: |
|
143 | prompt: | |
143 |
|
144 | |||
144 | In[1]: name -opt foo bar |
|
145 | In[1]: name -opt foo bar | |
145 |
|
146 | |||
146 | To call an alias without arguments, simply use ipalias('name'). |
|
147 | To call an alias without arguments, simply use ipalias('name'). | |
147 |
|
148 | |||
148 | This provides a proper Python function to call IPython's aliases in any |
|
149 | This provides a proper Python function to call IPython's aliases in any | |
149 | valid Python code you can type at the interpreter, including loops and |
|
150 | valid Python code you can type at the interpreter, including loops and | |
150 | compound statements. It is added by IPython to the Python builtin |
|
151 | compound statements. It is added by IPython to the Python builtin | |
151 | namespace upon initialization.""" |
|
152 | namespace upon initialization.""" | |
152 |
|
153 | |||
153 | args = arg_s.split(' ',1) |
|
154 | args = arg_s.split(' ',1) | |
154 | alias_name = args[0] |
|
155 | alias_name = args[0] | |
155 | try: |
|
156 | try: | |
156 | alias_args = args[1] |
|
157 | alias_args = args[1] | |
157 | except IndexError: |
|
158 | except IndexError: | |
158 | alias_args = '' |
|
159 | alias_args = '' | |
159 | if alias_name in __IPYTHON__.alias_table: |
|
160 | if alias_name in __IPYTHON__.alias_table: | |
160 | __IPYTHON__.call_alias(alias_name,alias_args) |
|
161 | __IPYTHON__.call_alias(alias_name,alias_args) | |
161 | else: |
|
162 | else: | |
162 | error("Alias `%s` not found." % alias_name) |
|
163 | error("Alias `%s` not found." % alias_name) | |
163 |
|
164 | |||
164 | #----------------------------------------------------------------------------- |
|
165 | #----------------------------------------------------------------------------- | |
165 | # Local use classes |
|
166 | # Local use classes | |
166 | try: |
|
167 | try: | |
167 | from IPython import FlexCompleter |
|
168 | from IPython import FlexCompleter | |
168 |
|
169 | |||
169 | class MagicCompleter(FlexCompleter.Completer): |
|
170 | class MagicCompleter(FlexCompleter.Completer): | |
170 | """Extension of the completer class to work on %-prefixed lines.""" |
|
171 | """Extension of the completer class to work on %-prefixed lines.""" | |
171 |
|
172 | |||
172 | def __init__(self,shell,namespace=None,omit__names=0,alias_table=None): |
|
173 | def __init__(self,shell,namespace=None,omit__names=0,alias_table=None): | |
173 | """MagicCompleter() -> completer |
|
174 | """MagicCompleter() -> completer | |
174 |
|
175 | |||
175 | Return a completer object suitable for use by the readline library |
|
176 | Return a completer object suitable for use by the readline library | |
176 | via readline.set_completer(). |
|
177 | via readline.set_completer(). | |
177 |
|
178 | |||
178 | Inputs: |
|
179 | Inputs: | |
179 |
|
180 | |||
180 | - shell: a pointer to the ipython shell itself. This is needed |
|
181 | - shell: a pointer to the ipython shell itself. This is needed | |
181 | because this completer knows about magic functions, and those can |
|
182 | because this completer knows about magic functions, and those can | |
182 | only be accessed via the ipython instance. |
|
183 | only be accessed via the ipython instance. | |
183 |
|
184 | |||
184 | - namespace: an optional dict where completions are performed. |
|
185 | - namespace: an optional dict where completions are performed. | |
185 |
|
186 | |||
186 | - The optional omit__names parameter sets the completer to omit the |
|
187 | - The optional omit__names parameter sets the completer to omit the | |
187 | 'magic' names (__magicname__) for python objects unless the text |
|
188 | 'magic' names (__magicname__) for python objects unless the text | |
188 | to be completed explicitly starts with one or more underscores. |
|
189 | to be completed explicitly starts with one or more underscores. | |
189 |
|
190 | |||
190 | - If alias_table is supplied, it should be a dictionary of aliases |
|
191 | - If alias_table is supplied, it should be a dictionary of aliases | |
191 | to complete. """ |
|
192 | to complete. """ | |
192 |
|
193 | |||
193 | FlexCompleter.Completer.__init__(self,namespace) |
|
194 | FlexCompleter.Completer.__init__(self,namespace) | |
194 | self.magic_prefix = shell.name+'.magic_' |
|
195 | self.magic_prefix = shell.name+'.magic_' | |
195 | self.magic_escape = shell.ESC_MAGIC |
|
196 | self.magic_escape = shell.ESC_MAGIC | |
196 | self.readline = FlexCompleter.readline |
|
197 | self.readline = FlexCompleter.readline | |
197 | delims = self.readline.get_completer_delims() |
|
198 | delims = self.readline.get_completer_delims() | |
198 | delims = delims.replace(self.magic_escape,'') |
|
199 | delims = delims.replace(self.magic_escape,'') | |
199 | self.readline.set_completer_delims(delims) |
|
200 | self.readline.set_completer_delims(delims) | |
200 | self.get_line_buffer = self.readline.get_line_buffer |
|
201 | self.get_line_buffer = self.readline.get_line_buffer | |
201 | self.omit__names = omit__names |
|
202 | self.omit__names = omit__names | |
202 | self.merge_completions = shell.rc.readline_merge_completions |
|
203 | self.merge_completions = shell.rc.readline_merge_completions | |
203 |
|
204 | |||
204 | if alias_table is None: |
|
205 | if alias_table is None: | |
205 | alias_table = {} |
|
206 | alias_table = {} | |
206 | self.alias_table = alias_table |
|
207 | self.alias_table = alias_table | |
207 | # Regexp to split filenames with spaces in them |
|
208 | # Regexp to split filenames with spaces in them | |
208 | self.space_name_re = re.compile(r'([^\\] )') |
|
209 | self.space_name_re = re.compile(r'([^\\] )') | |
209 | # Hold a local ref. to glob.glob for speed |
|
210 | # Hold a local ref. to glob.glob for speed | |
210 | self.glob = glob.glob |
|
211 | self.glob = glob.glob | |
211 | # Special handling of backslashes needed in win32 platforms |
|
212 | # Special handling of backslashes needed in win32 platforms | |
212 | if sys.platform == "win32": |
|
213 | if sys.platform == "win32": | |
213 | self.clean_glob = self._clean_glob_win32 |
|
214 | self.clean_glob = self._clean_glob_win32 | |
214 | else: |
|
215 | else: | |
215 | self.clean_glob = self._clean_glob |
|
216 | self.clean_glob = self._clean_glob | |
216 | self.matchers = [self.python_matches, |
|
217 | self.matchers = [self.python_matches, | |
217 | self.file_matches, |
|
218 | self.file_matches, | |
218 | self.alias_matches, |
|
219 | self.alias_matches, | |
219 | self.python_func_kw_matches] |
|
220 | self.python_func_kw_matches] | |
220 |
|
221 | |||
221 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
222 | # Code contributed by Alex Schmolck, for ipython/emacs integration | |
222 | def all_completions(self, text): |
|
223 | def all_completions(self, text): | |
223 | """Return all possible completions for the benefit of emacs.""" |
|
224 | """Return all possible completions for the benefit of emacs.""" | |
224 |
|
225 | |||
225 | completions = [] |
|
226 | completions = [] | |
226 | try: |
|
227 | try: | |
227 | for i in xrange(sys.maxint): |
|
228 | for i in xrange(sys.maxint): | |
228 | res = self.complete(text, i) |
|
229 | res = self.complete(text, i) | |
229 |
|
230 | |||
230 | if not res: break |
|
231 | if not res: break | |
231 |
|
232 | |||
232 | completions.append(res) |
|
233 | completions.append(res) | |
233 | #XXX workaround for ``notDefined.<tab>`` |
|
234 | #XXX workaround for ``notDefined.<tab>`` | |
234 | except NameError: |
|
235 | except NameError: | |
235 | pass |
|
236 | pass | |
236 | return completions |
|
237 | return completions | |
237 | # /end Alex Schmolck code. |
|
238 | # /end Alex Schmolck code. | |
238 |
|
239 | |||
239 | def _clean_glob(self,text): |
|
240 | def _clean_glob(self,text): | |
240 | return self.glob("%s*" % text) |
|
241 | return self.glob("%s*" % text) | |
241 |
|
242 | |||
242 | def _clean_glob_win32(self,text): |
|
243 | def _clean_glob_win32(self,text): | |
243 | return [f.replace("\\","/") |
|
244 | return [f.replace("\\","/") | |
244 | for f in self.glob("%s*" % text)] |
|
245 | for f in self.glob("%s*" % text)] | |
245 |
|
246 | |||
246 | def file_matches(self, text): |
|
247 | def file_matches(self, text): | |
247 | """Match filneames, expanding ~USER type strings. |
|
248 | """Match filneames, expanding ~USER type strings. | |
248 |
|
249 | |||
249 | Most of the seemingly convoluted logic in this completer is an |
|
250 | Most of the seemingly convoluted logic in this completer is an | |
250 | attempt to handle filenames with spaces in them. And yet it's not |
|
251 | attempt to handle filenames with spaces in them. And yet it's not | |
251 | quite perfect, because Python's readline doesn't expose all of the |
|
252 | quite perfect, because Python's readline doesn't expose all of the | |
252 | GNU readline details needed for this to be done correctly. |
|
253 | GNU readline details needed for this to be done correctly. | |
253 |
|
254 | |||
254 | For a filename with a space in it, the printed completions will be |
|
255 | For a filename with a space in it, the printed completions will be | |
255 | only the parts after what's already been typed (instead of the |
|
256 | only the parts after what's already been typed (instead of the | |
256 | full completions, as is normally done). I don't think with the |
|
257 | full completions, as is normally done). I don't think with the | |
257 | current (as of Python 2.3) Python readline it's possible to do |
|
258 | current (as of Python 2.3) Python readline it's possible to do | |
258 | better.""" |
|
259 | better.""" | |
259 |
|
260 | |||
260 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
261 | #print 'Completer->file_matches: <%s>' % text # dbg | |
261 |
|
262 | |||
262 | # chars that require escaping with backslash - i.e. chars |
|
263 | # chars that require escaping with backslash - i.e. chars | |
263 | # that readline treats incorrectly as delimiters, but we |
|
264 | # that readline treats incorrectly as delimiters, but we | |
264 | # don't want to treat as delimiters in filename matching |
|
265 | # don't want to treat as delimiters in filename matching | |
265 | # when escaped with backslash |
|
266 | # when escaped with backslash | |
266 |
|
267 | |||
267 | protectables = ' ()[]{}' |
|
268 | protectables = ' ()[]{}' | |
268 |
|
269 | |||
269 | def protect_filename(s): |
|
270 | def protect_filename(s): | |
270 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
271 | return "".join([(ch in protectables and '\\' + ch or ch) | |
271 | for ch in s]) |
|
272 | for ch in s]) | |
272 |
|
273 | |||
273 | lbuf = self.get_line_buffer()[:self.readline.get_endidx()] |
|
274 | lbuf = self.get_line_buffer()[:self.readline.get_endidx()] | |
274 | open_quotes = 0 # track strings with open quotes |
|
275 | open_quotes = 0 # track strings with open quotes | |
275 | try: |
|
276 | try: | |
276 | lsplit = shlex_split(lbuf)[-1] |
|
277 | lsplit = shlex_split(lbuf)[-1] | |
277 | except ValueError: |
|
278 | except ValueError: | |
278 | # typically an unmatched ", or backslash without escaped char. |
|
279 | # typically an unmatched ", or backslash without escaped char. | |
279 | if lbuf.count('"')==1: |
|
280 | if lbuf.count('"')==1: | |
280 | open_quotes = 1 |
|
281 | open_quotes = 1 | |
281 | lsplit = lbuf.split('"')[-1] |
|
282 | lsplit = lbuf.split('"')[-1] | |
282 | elif lbuf.count("'")==1: |
|
283 | elif lbuf.count("'")==1: | |
283 | open_quotes = 1 |
|
284 | open_quotes = 1 | |
284 | lsplit = lbuf.split("'")[-1] |
|
285 | lsplit = lbuf.split("'")[-1] | |
285 | else: |
|
286 | else: | |
286 | return None |
|
287 | return None | |
287 | except IndexError: |
|
288 | except IndexError: | |
288 | # tab pressed on empty line |
|
289 | # tab pressed on empty line | |
289 | lsplit = "" |
|
290 | lsplit = "" | |
290 |
|
291 | |||
291 | if lsplit != protect_filename(lsplit): |
|
292 | if lsplit != protect_filename(lsplit): | |
292 | # if protectables are found, do matching on the whole escaped |
|
293 | # if protectables are found, do matching on the whole escaped | |
293 | # name |
|
294 | # name | |
294 | has_protectables = 1 |
|
295 | has_protectables = 1 | |
295 | text0,text = text,lsplit |
|
296 | text0,text = text,lsplit | |
296 | else: |
|
297 | else: | |
297 | has_protectables = 0 |
|
298 | has_protectables = 0 | |
298 | text = os.path.expanduser(text) |
|
299 | text = os.path.expanduser(text) | |
299 |
|
300 | |||
300 | if text == "": |
|
301 | if text == "": | |
301 | return [protect_filename(f) for f in self.glob("*")] |
|
302 | return [protect_filename(f) for f in self.glob("*")] | |
302 |
|
303 | |||
303 | m0 = self.clean_glob(text.replace('\\','')) |
|
304 | m0 = self.clean_glob(text.replace('\\','')) | |
304 | if has_protectables: |
|
305 | if has_protectables: | |
305 | # If we had protectables, we need to revert our changes to the |
|
306 | # If we had protectables, we need to revert our changes to the | |
306 | # beginning of filename so that we don't double-write the part |
|
307 | # beginning of filename so that we don't double-write the part | |
307 | # of the filename we have so far |
|
308 | # of the filename we have so far | |
308 | len_lsplit = len(lsplit) |
|
309 | len_lsplit = len(lsplit) | |
309 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] |
|
310 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] | |
310 | else: |
|
311 | else: | |
311 | if open_quotes: |
|
312 | if open_quotes: | |
312 | # if we have a string with an open quote, we don't need to |
|
313 | # if we have a string with an open quote, we don't need to | |
313 | # protect the names at all (and we _shouldn't_, as it |
|
314 | # protect the names at all (and we _shouldn't_, as it | |
314 | # would cause bugs when the filesystem call is made). |
|
315 | # would cause bugs when the filesystem call is made). | |
315 | matches = m0 |
|
316 | matches = m0 | |
316 | else: |
|
317 | else: | |
317 | matches = [protect_filename(f) for f in m0] |
|
318 | matches = [protect_filename(f) for f in m0] | |
318 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
319 | if len(matches) == 1 and os.path.isdir(matches[0]): | |
319 | # Takes care of links to directories also. Use '/' |
|
320 | # Takes care of links to directories also. Use '/' | |
320 | # explicitly, even under Windows, so that name completions |
|
321 | # explicitly, even under Windows, so that name completions | |
321 | # don't end up escaped. |
|
322 | # don't end up escaped. | |
322 | matches[0] += '/' |
|
323 | matches[0] += '/' | |
323 | return matches |
|
324 | return matches | |
324 |
|
325 | |||
325 | def alias_matches(self, text): |
|
326 | def alias_matches(self, text): | |
326 | """Match internal system aliases""" |
|
327 | """Match internal system aliases""" | |
327 | #print 'Completer->alias_matches:',text # dbg |
|
328 | #print 'Completer->alias_matches:',text # dbg | |
328 | text = os.path.expanduser(text) |
|
329 | text = os.path.expanduser(text) | |
329 | aliases = self.alias_table.keys() |
|
330 | aliases = self.alias_table.keys() | |
330 | if text == "": |
|
331 | if text == "": | |
331 | return aliases |
|
332 | return aliases | |
332 | else: |
|
333 | else: | |
333 | return [alias for alias in aliases if alias.startswith(text)] |
|
334 | return [alias for alias in aliases if alias.startswith(text)] | |
334 |
|
335 | |||
335 | def python_matches(self,text): |
|
336 | def python_matches(self,text): | |
336 | """Match attributes or global python names""" |
|
337 | """Match attributes or global python names""" | |
337 | #print 'Completer->python_matches' # dbg |
|
338 | #print 'Completer->python_matches' # dbg | |
338 | if "." in text: |
|
339 | if "." in text: | |
339 | try: |
|
340 | try: | |
340 | matches = self.attr_matches(text) |
|
341 | matches = self.attr_matches(text) | |
341 | if text.endswith('.') and self.omit__names: |
|
342 | if text.endswith('.') and self.omit__names: | |
342 | if self.omit__names == 1: |
|
343 | if self.omit__names == 1: | |
343 | # true if txt is _not_ a __ name, false otherwise: |
|
344 | # true if txt is _not_ a __ name, false otherwise: | |
344 | no__name = (lambda txt: |
|
345 | no__name = (lambda txt: | |
345 | re.match(r'.*\.__.*?__',txt) is None) |
|
346 | re.match(r'.*\.__.*?__',txt) is None) | |
346 | else: |
|
347 | else: | |
347 | # true if txt is _not_ a _ name, false otherwise: |
|
348 | # true if txt is _not_ a _ name, false otherwise: | |
348 | no__name = (lambda txt: |
|
349 | no__name = (lambda txt: | |
349 | re.match(r'.*\._.*?',txt) is None) |
|
350 | re.match(r'.*\._.*?',txt) is None) | |
350 | matches = filter(no__name, matches) |
|
351 | matches = filter(no__name, matches) | |
351 | except NameError: |
|
352 | except NameError: | |
352 | # catches <undefined attributes>.<tab> |
|
353 | # catches <undefined attributes>.<tab> | |
353 | matches = [] |
|
354 | matches = [] | |
354 | else: |
|
355 | else: | |
355 | matches = self.global_matches(text) |
|
356 | matches = self.global_matches(text) | |
356 | # this is so completion finds magics when automagic is on: |
|
357 | # this is so completion finds magics when automagic is on: | |
357 | if matches == [] and not text.startswith(os.sep): |
|
358 | if matches == [] and not text.startswith(os.sep): | |
358 | matches = self.attr_matches(self.magic_prefix+text) |
|
359 | matches = self.attr_matches(self.magic_prefix+text) | |
359 | return matches |
|
360 | return matches | |
360 |
|
361 | |||
361 | def _default_arguments(self, obj): |
|
362 | def _default_arguments(self, obj): | |
362 | """Return the list of default arguments of obj if it is callable, |
|
363 | """Return the list of default arguments of obj if it is callable, | |
363 | or empty list otherwise.""" |
|
364 | or empty list otherwise.""" | |
364 |
|
365 | |||
365 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
366 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
366 | # for classes, check for __init__,__new__ |
|
367 | # for classes, check for __init__,__new__ | |
367 | if inspect.isclass(obj): |
|
368 | if inspect.isclass(obj): | |
368 | obj = (getattr(obj,'__init__',None) or |
|
369 | obj = (getattr(obj,'__init__',None) or | |
369 | getattr(obj,'__new__',None)) |
|
370 | getattr(obj,'__new__',None)) | |
370 | # for all others, check if they are __call__able |
|
371 | # for all others, check if they are __call__able | |
371 | elif hasattr(obj, '__call__'): |
|
372 | elif hasattr(obj, '__call__'): | |
372 | obj = obj.__call__ |
|
373 | obj = obj.__call__ | |
373 | # XXX: is there a way to handle the builtins ? |
|
374 | # XXX: is there a way to handle the builtins ? | |
374 | try: |
|
375 | try: | |
375 | args,_,_1,defaults = inspect.getargspec(obj) |
|
376 | args,_,_1,defaults = inspect.getargspec(obj) | |
376 | if defaults: |
|
377 | if defaults: | |
377 | return args[-len(defaults):] |
|
378 | return args[-len(defaults):] | |
378 | except TypeError: pass |
|
379 | except TypeError: pass | |
379 | return [] |
|
380 | return [] | |
380 |
|
381 | |||
381 | def python_func_kw_matches(self,text): |
|
382 | def python_func_kw_matches(self,text): | |
382 | """Match named parameters (kwargs) of the last open function""" |
|
383 | """Match named parameters (kwargs) of the last open function""" | |
383 |
|
384 | |||
384 | if "." in text: # a parameter cannot be dotted |
|
385 | if "." in text: # a parameter cannot be dotted | |
385 | return [] |
|
386 | return [] | |
386 | try: regexp = self.__funcParamsRegex |
|
387 | try: regexp = self.__funcParamsRegex | |
387 | except AttributeError: |
|
388 | except AttributeError: | |
388 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
389 | regexp = self.__funcParamsRegex = re.compile(r''' | |
389 | '.*?' | # single quoted strings or |
|
390 | '.*?' | # single quoted strings or | |
390 | ".*?" | # double quoted strings or |
|
391 | ".*?" | # double quoted strings or | |
391 | \w+ | # identifier |
|
392 | \w+ | # identifier | |
392 | \S # other characters |
|
393 | \S # other characters | |
393 | ''', re.VERBOSE | re.DOTALL) |
|
394 | ''', re.VERBOSE | re.DOTALL) | |
394 | # 1. find the nearest identifier that comes before an unclosed |
|
395 | # 1. find the nearest identifier that comes before an unclosed | |
395 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
396 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" | |
396 | tokens = regexp.findall(self.get_line_buffer()) |
|
397 | tokens = regexp.findall(self.get_line_buffer()) | |
397 | tokens.reverse() |
|
398 | tokens.reverse() | |
398 | iterTokens = iter(tokens); openPar = 0 |
|
399 | iterTokens = iter(tokens); openPar = 0 | |
399 | for token in iterTokens: |
|
400 | for token in iterTokens: | |
400 | if token == ')': |
|
401 | if token == ')': | |
401 | openPar -= 1 |
|
402 | openPar -= 1 | |
402 | elif token == '(': |
|
403 | elif token == '(': | |
403 | openPar += 1 |
|
404 | openPar += 1 | |
404 | if openPar > 0: |
|
405 | if openPar > 0: | |
405 | # found the last unclosed parenthesis |
|
406 | # found the last unclosed parenthesis | |
406 | break |
|
407 | break | |
407 | else: |
|
408 | else: | |
408 | return [] |
|
409 | return [] | |
409 | # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" ) |
|
410 | # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" ) | |
410 | ids = [] |
|
411 | ids = [] | |
411 | isId = re.compile(r'\w+$').match |
|
412 | isId = re.compile(r'\w+$').match | |
412 | while True: |
|
413 | while True: | |
413 | try: |
|
414 | try: | |
414 | ids.append(iterTokens.next()) |
|
415 | ids.append(iterTokens.next()) | |
415 | if not isId(ids[-1]): |
|
416 | if not isId(ids[-1]): | |
416 | ids.pop(); break |
|
417 | ids.pop(); break | |
417 | if not iterTokens.next() == '.': |
|
418 | if not iterTokens.next() == '.': | |
418 | break |
|
419 | break | |
419 | except StopIteration: |
|
420 | except StopIteration: | |
420 | break |
|
421 | break | |
421 | # lookup the candidate callable matches either using global_matches |
|
422 | # lookup the candidate callable matches either using global_matches | |
422 | # or attr_matches for dotted names |
|
423 | # or attr_matches for dotted names | |
423 | if len(ids) == 1: |
|
424 | if len(ids) == 1: | |
424 | callableMatches = self.global_matches(ids[0]) |
|
425 | callableMatches = self.global_matches(ids[0]) | |
425 | else: |
|
426 | else: | |
426 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
427 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
427 | argMatches = [] |
|
428 | argMatches = [] | |
428 | for callableMatch in callableMatches: |
|
429 | for callableMatch in callableMatches: | |
429 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
430 | try: namedArgs = self._default_arguments(eval(callableMatch, | |
430 | self.namespace)) |
|
431 | self.namespace)) | |
431 | except: continue |
|
432 | except: continue | |
432 | for namedArg in namedArgs: |
|
433 | for namedArg in namedArgs: | |
433 | if namedArg.startswith(text): |
|
434 | if namedArg.startswith(text): | |
434 | argMatches.append("%s=" %namedArg) |
|
435 | argMatches.append("%s=" %namedArg) | |
435 | return argMatches |
|
436 | return argMatches | |
436 |
|
437 | |||
437 | def complete(self, text, state): |
|
438 | def complete(self, text, state): | |
438 | """Return the next possible completion for 'text'. |
|
439 | """Return the next possible completion for 'text'. | |
439 |
|
440 | |||
440 | This is called successively with state == 0, 1, 2, ... until it |
|
441 | This is called successively with state == 0, 1, 2, ... until it | |
441 | returns None. The completion should begin with 'text'. """ |
|
442 | returns None. The completion should begin with 'text'. """ | |
442 |
|
443 | |||
443 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
444 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg | |
444 | magic_escape = self.magic_escape |
|
445 | magic_escape = self.magic_escape | |
445 | magic_prefix = self.magic_prefix |
|
446 | magic_prefix = self.magic_prefix | |
446 |
|
447 | |||
447 | try: |
|
448 | try: | |
448 | if text.startswith(magic_escape): |
|
449 | if text.startswith(magic_escape): | |
449 | text = text.replace(magic_escape,magic_prefix) |
|
450 | text = text.replace(magic_escape,magic_prefix) | |
450 | elif text.startswith('~'): |
|
451 | elif text.startswith('~'): | |
451 | text = os.path.expanduser(text) |
|
452 | text = os.path.expanduser(text) | |
452 | if state == 0: |
|
453 | if state == 0: | |
453 | # Extend the list of completions with the results of each |
|
454 | # Extend the list of completions with the results of each | |
454 | # matcher, so we return results to the user from all |
|
455 | # matcher, so we return results to the user from all | |
455 | # namespaces. |
|
456 | # namespaces. | |
456 | if self.merge_completions: |
|
457 | if self.merge_completions: | |
457 | self.matches = [] |
|
458 | self.matches = [] | |
458 | for matcher in self.matchers: |
|
459 | for matcher in self.matchers: | |
459 | self.matches.extend(matcher(text)) |
|
460 | self.matches.extend(matcher(text)) | |
460 | else: |
|
461 | else: | |
461 | for matcher in self.matchers: |
|
462 | for matcher in self.matchers: | |
462 | self.matches = matcher(text) |
|
463 | self.matches = matcher(text) | |
463 | if self.matches: |
|
464 | if self.matches: | |
464 | break |
|
465 | break | |
465 |
|
466 | |||
466 | try: |
|
467 | try: | |
467 | return self.matches[state].replace(magic_prefix,magic_escape) |
|
468 | return self.matches[state].replace(magic_prefix,magic_escape) | |
468 | except IndexError: |
|
469 | except IndexError: | |
469 | return None |
|
470 | return None | |
470 | except: |
|
471 | except: | |
471 | # If completion fails, don't annoy the user. |
|
472 | # If completion fails, don't annoy the user. | |
472 | pass |
|
473 | pass | |
473 |
|
474 | |||
474 | except ImportError: |
|
475 | except ImportError: | |
475 | pass # no readline support |
|
476 | pass # no readline support | |
476 |
|
477 | |||
477 | except KeyError: |
|
478 | except KeyError: | |
478 | pass # Windows doesn't set TERM, it doesn't matter |
|
479 | pass # Windows doesn't set TERM, it doesn't matter | |
479 |
|
480 | |||
480 |
|
481 | |||
481 | class InputList(UserList.UserList): |
|
482 | class InputList(UserList.UserList): | |
482 | """Class to store user input. |
|
483 | """Class to store user input. | |
483 |
|
484 | |||
484 | It's basically a list, but slices return a string instead of a list, thus |
|
485 | It's basically a list, but slices return a string instead of a list, thus | |
485 | allowing things like (assuming 'In' is an instance): |
|
486 | allowing things like (assuming 'In' is an instance): | |
486 |
|
487 | |||
487 | exec In[4:7] |
|
488 | exec In[4:7] | |
488 |
|
489 | |||
489 | or |
|
490 | or | |
490 |
|
491 | |||
491 | exec In[5:9] + In[14] + In[21:25]""" |
|
492 | exec In[5:9] + In[14] + In[21:25]""" | |
492 |
|
493 | |||
493 | def __getslice__(self,i,j): |
|
494 | def __getslice__(self,i,j): | |
494 | return ''.join(UserList.UserList.__getslice__(self,i,j)) |
|
495 | return ''.join(UserList.UserList.__getslice__(self,i,j)) | |
495 |
|
496 | |||
496 | #**************************************************************************** |
|
497 | #**************************************************************************** | |
497 | # Local use exceptions |
|
498 | # Local use exceptions | |
498 | class SpaceInInput(exceptions.Exception): |
|
499 | class SpaceInInput(exceptions.Exception): | |
499 | pass |
|
500 | pass | |
500 |
|
501 | |||
501 | #**************************************************************************** |
|
502 | #**************************************************************************** | |
502 | # Main IPython class |
|
503 | # Main IPython class | |
503 |
|
504 | |||
504 | class InteractiveShell(code.InteractiveConsole, Logger, Magic): |
|
505 | class InteractiveShell(code.InteractiveConsole, Logger, Magic): | |
505 | """An enhanced console for Python.""" |
|
506 | """An enhanced console for Python.""" | |
506 |
|
507 | |||
507 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
508 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
508 | user_ns = None,banner2='', |
|
509 | user_ns = None,banner2='', | |
509 | custom_exceptions=((),None)): |
|
510 | custom_exceptions=((),None)): | |
510 |
|
511 | |||
511 | # Put a reference to self in builtins so that any form of embedded or |
|
512 | # Put a reference to self in builtins so that any form of embedded or | |
512 | # imported code can test for being inside IPython. |
|
513 | # imported code can test for being inside IPython. | |
513 | __builtin__.__IPYTHON__ = self |
|
514 | __builtin__.__IPYTHON__ = self | |
514 |
|
515 | |||
515 | # And load into builtins ipmagic/ipalias as well |
|
516 | # And load into builtins ipmagic/ipalias as well | |
516 | __builtin__.ipmagic = ipmagic |
|
517 | __builtin__.ipmagic = ipmagic | |
517 | __builtin__.ipalias = ipalias |
|
518 | __builtin__.ipalias = ipalias | |
518 |
|
519 | |||
519 | # Add to __builtin__ other parts of IPython's public API |
|
520 | # Add to __builtin__ other parts of IPython's public API | |
520 | __builtin__.ip_set_hook = self.set_hook |
|
521 | __builtin__.ip_set_hook = self.set_hook | |
521 |
|
522 | |||
522 | # Keep in the builtins a flag for when IPython is active. We set it |
|
523 | # Keep in the builtins a flag for when IPython is active. We set it | |
523 | # with setdefault so that multiple nested IPythons don't clobber one |
|
524 | # with setdefault so that multiple nested IPythons don't clobber one | |
524 | # another. Each will increase its value by one upon being activated, |
|
525 | # another. Each will increase its value by one upon being activated, | |
525 | # which also gives us a way to determine the nesting level. |
|
526 | # which also gives us a way to determine the nesting level. | |
526 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
527 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
527 |
|
528 | |||
528 | # Inform the user of ipython's fast exit magics. |
|
529 | # Inform the user of ipython's fast exit magics. | |
529 | _exit = ' Use %Exit or %Quit to exit without confirmation.' |
|
530 | _exit = ' Use %Exit or %Quit to exit without confirmation.' | |
530 | __builtin__.exit += _exit |
|
531 | __builtin__.exit += _exit | |
531 | __builtin__.quit += _exit |
|
532 | __builtin__.quit += _exit | |
532 |
|
533 | |||
533 | # Create the namespace where the user will operate: |
|
534 | # Create the namespace where the user will operate: | |
534 |
|
535 | |||
535 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
536 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
536 | # level as a dict instead of a module. This is a manual fix, but I |
|
537 | # level as a dict instead of a module. This is a manual fix, but I | |
537 | # should really track down where the problem is coming from. Alex |
|
538 | # should really track down where the problem is coming from. Alex | |
538 | # Schmolck reported this problem first. |
|
539 | # Schmolck reported this problem first. | |
539 |
|
540 | |||
540 | # A useful post by Alex Martelli on this topic: |
|
541 | # A useful post by Alex Martelli on this topic: | |
541 | # Re: inconsistent value from __builtins__ |
|
542 | # Re: inconsistent value from __builtins__ | |
542 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
543 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
543 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
544 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
544 | # Gruppen: comp.lang.python |
|
545 | # Gruppen: comp.lang.python | |
545 | # Referenzen: 1 |
|
546 | # Referenzen: 1 | |
546 |
|
547 | |||
547 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
548 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
548 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
549 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
549 | # > <type 'dict'> |
|
550 | # > <type 'dict'> | |
550 | # > >>> print type(__builtins__) |
|
551 | # > >>> print type(__builtins__) | |
551 | # > <type 'module'> |
|
552 | # > <type 'module'> | |
552 | # > Is this difference in return value intentional? |
|
553 | # > Is this difference in return value intentional? | |
553 |
|
554 | |||
554 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
555 | # Well, it's documented that '__builtins__' can be either a dictionary | |
555 | # or a module, and it's been that way for a long time. Whether it's |
|
556 | # or a module, and it's been that way for a long time. Whether it's | |
556 | # intentional (or sensible), I don't know. In any case, the idea is that |
|
557 | # intentional (or sensible), I don't know. In any case, the idea is that | |
557 | # if you need to access the built-in namespace directly, you should start |
|
558 | # if you need to access the built-in namespace directly, you should start | |
558 | # with "import __builtin__" (note, no 's') which will definitely give you |
|
559 | # with "import __builtin__" (note, no 's') which will definitely give you | |
559 | # a module. Yeah, it's somewhat confusing:-(. |
|
560 | # a module. Yeah, it's somewhat confusing:-(. | |
560 |
|
561 | |||
561 | if user_ns is None: |
|
562 | if user_ns is None: | |
562 | # Set __name__ to __main__ to better match the behavior of the |
|
563 | # Set __name__ to __main__ to better match the behavior of the | |
563 | # normal interpreter. |
|
564 | # normal interpreter. | |
564 | self.user_ns = {'__name__' :'__main__', |
|
565 | self.user_ns = {'__name__' :'__main__', | |
565 | '__builtins__' : __builtin__, |
|
566 | '__builtins__' : __builtin__, | |
566 | } |
|
567 | } | |
567 | else: |
|
568 | else: | |
568 | self.user_ns = user_ns |
|
569 | self.user_ns = user_ns | |
569 |
|
570 | |||
570 | # The user namespace MUST have a pointer to the shell itself. |
|
571 | # The user namespace MUST have a pointer to the shell itself. | |
571 | self.user_ns[name] = self |
|
572 | self.user_ns[name] = self | |
572 |
|
573 | |||
573 | # We need to insert into sys.modules something that looks like a |
|
574 | # We need to insert into sys.modules something that looks like a | |
574 | # module but which accesses the IPython namespace, for shelve and |
|
575 | # module but which accesses the IPython namespace, for shelve and | |
575 | # pickle to work interactively. Normally they rely on getting |
|
576 | # pickle to work interactively. Normally they rely on getting | |
576 | # everything out of __main__, but for embedding purposes each IPython |
|
577 | # everything out of __main__, but for embedding purposes each IPython | |
577 | # instance has its own private namespace, so we can't go shoving |
|
578 | # instance has its own private namespace, so we can't go shoving | |
578 | # everything into __main__. |
|
579 | # everything into __main__. | |
579 |
|
580 | |||
580 | try: |
|
581 | try: | |
581 | main_name = self.user_ns['__name__'] |
|
582 | main_name = self.user_ns['__name__'] | |
582 | except KeyError: |
|
583 | except KeyError: | |
583 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
584 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
584 | else: |
|
585 | else: | |
585 | #print "pickle hack in place" # dbg |
|
586 | #print "pickle hack in place" # dbg | |
586 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
587 | sys.modules[main_name] = FakeModule(self.user_ns) | |
587 |
|
588 | |||
588 | # List of input with multi-line handling. |
|
589 | # List of input with multi-line handling. | |
589 | # Fill its zero entry, user counter starts at 1 |
|
590 | # Fill its zero entry, user counter starts at 1 | |
590 | self.input_hist = InputList(['\n']) |
|
591 | self.input_hist = InputList(['\n']) | |
591 |
|
592 | |||
592 | # list of visited directories |
|
593 | # list of visited directories | |
593 | try: |
|
594 | try: | |
594 | self.dir_hist = [os.getcwd()] |
|
595 | self.dir_hist = [os.getcwd()] | |
595 | except IOError, e: |
|
596 | except IOError, e: | |
596 | self.dir_hist = [] |
|
597 | self.dir_hist = [] | |
597 |
|
598 | |||
598 | # dict of output history |
|
599 | # dict of output history | |
599 | self.output_hist = {} |
|
600 | self.output_hist = {} | |
600 |
|
601 | |||
601 | # dict of names to be treated as system aliases. Each entry in the |
|
602 | # dict of names to be treated as system aliases. Each entry in the | |
602 | # alias table must be a 2-tuple of the form (N,name), where N is the |
|
603 | # alias table must be a 2-tuple of the form (N,name), where N is the | |
603 | # number of positional arguments of the alias. |
|
604 | # number of positional arguments of the alias. | |
604 | self.alias_table = {} |
|
605 | self.alias_table = {} | |
605 |
|
606 | |||
606 | # dict of things NOT to alias (keywords, builtins and some special magics) |
|
607 | # dict of things NOT to alias (keywords, builtins and some special magics) | |
607 | no_alias = {} |
|
608 | no_alias = {} | |
608 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
609 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
609 | for key in keyword.kwlist + no_alias_magics: |
|
610 | for key in keyword.kwlist + no_alias_magics: | |
610 | no_alias[key] = 1 |
|
611 | no_alias[key] = 1 | |
611 | no_alias.update(__builtin__.__dict__) |
|
612 | no_alias.update(__builtin__.__dict__) | |
612 | self.no_alias = no_alias |
|
613 | self.no_alias = no_alias | |
613 |
|
614 | |||
614 |
|
615 | |||
615 | # make global variables for user access to these |
|
616 | # make global variables for user access to these | |
616 | self.user_ns['_ih'] = self.input_hist |
|
617 | self.user_ns['_ih'] = self.input_hist | |
617 | self.user_ns['_oh'] = self.output_hist |
|
618 | self.user_ns['_oh'] = self.output_hist | |
618 | self.user_ns['_dh'] = self.dir_hist |
|
619 | self.user_ns['_dh'] = self.dir_hist | |
619 |
|
620 | |||
620 | # user aliases to input and output histories |
|
621 | # user aliases to input and output histories | |
621 | self.user_ns['In'] = self.input_hist |
|
622 | self.user_ns['In'] = self.input_hist | |
622 | self.user_ns['Out'] = self.output_hist |
|
623 | self.user_ns['Out'] = self.output_hist | |
623 |
|
624 | |||
624 | # Store the actual shell's name |
|
625 | # Store the actual shell's name | |
625 | self.name = name |
|
626 | self.name = name | |
626 |
|
627 | |||
627 | # Object variable to store code object waiting execution. This is |
|
628 | # Object variable to store code object waiting execution. This is | |
628 | # used mainly by the multithreaded shells, but it can come in handy in |
|
629 | # used mainly by the multithreaded shells, but it can come in handy in | |
629 | # other situations. No need to use a Queue here, since it's a single |
|
630 | # other situations. No need to use a Queue here, since it's a single | |
630 | # item which gets cleared once run. |
|
631 | # item which gets cleared once run. | |
631 | self.code_to_run = None |
|
632 | self.code_to_run = None | |
632 |
|
633 | |||
633 | # Job manager (for jobs run as background threads) |
|
634 | # Job manager (for jobs run as background threads) | |
634 | self.jobs = BackgroundJobManager() |
|
635 | self.jobs = BackgroundJobManager() | |
635 | # Put the job manager into builtins so it's always there. |
|
636 | # Put the job manager into builtins so it's always there. | |
636 | __builtin__.jobs = self.jobs |
|
637 | __builtin__.jobs = self.jobs | |
637 |
|
638 | |||
638 | # escapes for automatic behavior on the command line |
|
639 | # escapes for automatic behavior on the command line | |
639 | self.ESC_SHELL = '!' |
|
640 | self.ESC_SHELL = '!' | |
640 | self.ESC_HELP = '?' |
|
641 | self.ESC_HELP = '?' | |
641 | self.ESC_MAGIC = '%' |
|
642 | self.ESC_MAGIC = '%' | |
642 | self.ESC_QUOTE = ',' |
|
643 | self.ESC_QUOTE = ',' | |
643 | self.ESC_QUOTE2 = ';' |
|
644 | self.ESC_QUOTE2 = ';' | |
644 | self.ESC_PAREN = '/' |
|
645 | self.ESC_PAREN = '/' | |
645 |
|
646 | |||
646 | # And their associated handlers |
|
647 | # And their associated handlers | |
647 | self.esc_handlers = {self.ESC_PAREN:self.handle_auto, |
|
648 | self.esc_handlers = {self.ESC_PAREN:self.handle_auto, | |
648 | self.ESC_QUOTE:self.handle_auto, |
|
649 | self.ESC_QUOTE:self.handle_auto, | |
649 | self.ESC_QUOTE2:self.handle_auto, |
|
650 | self.ESC_QUOTE2:self.handle_auto, | |
650 | self.ESC_MAGIC:self.handle_magic, |
|
651 | self.ESC_MAGIC:self.handle_magic, | |
651 | self.ESC_HELP:self.handle_help, |
|
652 | self.ESC_HELP:self.handle_help, | |
652 | self.ESC_SHELL:self.handle_shell_escape, |
|
653 | self.ESC_SHELL:self.handle_shell_escape, | |
653 | } |
|
654 | } | |
654 |
|
655 | |||
655 | # class initializations |
|
656 | # class initializations | |
656 | code.InteractiveConsole.__init__(self,locals = self.user_ns) |
|
657 | code.InteractiveConsole.__init__(self,locals = self.user_ns) | |
657 | Logger.__init__(self,log_ns = self.user_ns) |
|
658 | Logger.__init__(self,log_ns = self.user_ns) | |
658 | Magic.__init__(self,self) |
|
659 | Magic.__init__(self,self) | |
659 |
|
660 | |||
660 | # an ugly hack to get a pointer to the shell, so I can start writing |
|
661 | # an ugly hack to get a pointer to the shell, so I can start writing | |
661 | # magic code via this pointer instead of the current mixin salad. |
|
662 | # magic code via this pointer instead of the current mixin salad. | |
662 | Magic.set_shell(self,self) |
|
663 | Magic.set_shell(self,self) | |
663 |
|
664 | |||
|
665 | # Python source parser/formatter for syntax highlighting | |||
|
666 | pyformat = Parser().format | |||
|
667 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |||
|
668 | ||||
664 | # hooks holds pointers used for user-side customizations |
|
669 | # hooks holds pointers used for user-side customizations | |
665 | self.hooks = Struct() |
|
670 | self.hooks = Struct() | |
666 |
|
671 | |||
667 | # Set all default hooks, defined in the IPython.hooks module. |
|
672 | # Set all default hooks, defined in the IPython.hooks module. | |
668 | hooks = IPython.hooks |
|
673 | hooks = IPython.hooks | |
669 | for hook_name in hooks.__all__: |
|
674 | for hook_name in hooks.__all__: | |
670 | self.set_hook(hook_name,getattr(hooks,hook_name)) |
|
675 | self.set_hook(hook_name,getattr(hooks,hook_name)) | |
671 |
|
676 | |||
672 | # Flag to mark unconditional exit |
|
677 | # Flag to mark unconditional exit | |
673 | self.exit_now = False |
|
678 | self.exit_now = False | |
674 |
|
679 | |||
675 | self.usage_min = """\ |
|
680 | self.usage_min = """\ | |
676 | An enhanced console for Python. |
|
681 | An enhanced console for Python. | |
677 | Some of its features are: |
|
682 | Some of its features are: | |
678 | - Readline support if the readline library is present. |
|
683 | - Readline support if the readline library is present. | |
679 | - Tab completion in the local namespace. |
|
684 | - Tab completion in the local namespace. | |
680 | - Logging of input, see command-line options. |
|
685 | - Logging of input, see command-line options. | |
681 | - System shell escape via ! , eg !ls. |
|
686 | - System shell escape via ! , eg !ls. | |
682 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
687 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
683 | - Keeps track of locally defined variables via %who, %whos. |
|
688 | - Keeps track of locally defined variables via %who, %whos. | |
684 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
689 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
685 | """ |
|
690 | """ | |
686 | if usage: self.usage = usage |
|
691 | if usage: self.usage = usage | |
687 | else: self.usage = self.usage_min |
|
692 | else: self.usage = self.usage_min | |
688 |
|
693 | |||
689 | # Storage |
|
694 | # Storage | |
690 | self.rc = rc # This will hold all configuration information |
|
695 | self.rc = rc # This will hold all configuration information | |
691 | self.inputcache = [] |
|
696 | self.inputcache = [] | |
692 | self._boundcache = [] |
|
697 | self._boundcache = [] | |
693 | self.pager = 'less' |
|
698 | self.pager = 'less' | |
694 | # temporary files used for various purposes. Deleted at exit. |
|
699 | # temporary files used for various purposes. Deleted at exit. | |
695 | self.tempfiles = [] |
|
700 | self.tempfiles = [] | |
696 |
|
701 | |||
697 | # Keep track of readline usage (later set by init_readline) |
|
702 | # Keep track of readline usage (later set by init_readline) | |
698 | self.has_readline = 0 |
|
703 | self.has_readline = 0 | |
699 |
|
704 | |||
700 | # for pushd/popd management |
|
705 | # for pushd/popd management | |
701 | try: |
|
706 | try: | |
702 | self.home_dir = get_home_dir() |
|
707 | self.home_dir = get_home_dir() | |
703 | except HomeDirError,msg: |
|
708 | except HomeDirError,msg: | |
704 | fatal(msg) |
|
709 | fatal(msg) | |
705 |
|
710 | |||
706 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] |
|
711 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] | |
707 |
|
712 | |||
708 | # Functions to call the underlying shell. |
|
713 | # Functions to call the underlying shell. | |
709 |
|
714 | |||
710 | # utility to expand user variables via Itpl |
|
715 | # utility to expand user variables via Itpl | |
711 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), |
|
716 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), | |
712 | self.user_ns)) |
|
717 | self.user_ns)) | |
713 | # The first is similar to os.system, but it doesn't return a value, |
|
718 | # The first is similar to os.system, but it doesn't return a value, | |
714 | # and it allows interpolation of variables in the user's namespace. |
|
719 | # and it allows interpolation of variables in the user's namespace. | |
715 | self.system = lambda cmd: shell(self.var_expand(cmd), |
|
720 | self.system = lambda cmd: shell(self.var_expand(cmd), | |
716 | header='IPython system call: ', |
|
721 | header='IPython system call: ', | |
717 | verbose=self.rc.system_verbose) |
|
722 | verbose=self.rc.system_verbose) | |
718 | # These are for getoutput and getoutputerror: |
|
723 | # These are for getoutput and getoutputerror: | |
719 | self.getoutput = lambda cmd: \ |
|
724 | self.getoutput = lambda cmd: \ | |
720 | getoutput(self.var_expand(cmd), |
|
725 | getoutput(self.var_expand(cmd), | |
721 | header='IPython system call: ', |
|
726 | header='IPython system call: ', | |
722 | verbose=self.rc.system_verbose) |
|
727 | verbose=self.rc.system_verbose) | |
723 | self.getoutputerror = lambda cmd: \ |
|
728 | self.getoutputerror = lambda cmd: \ | |
724 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), |
|
729 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), | |
725 | self.user_ns)), |
|
730 | self.user_ns)), | |
726 | header='IPython system call: ', |
|
731 | header='IPython system call: ', | |
727 | verbose=self.rc.system_verbose) |
|
732 | verbose=self.rc.system_verbose) | |
728 |
|
733 | |||
729 | # RegExp for splitting line contents into pre-char//first |
|
734 | # RegExp for splitting line contents into pre-char//first | |
730 | # word-method//rest. For clarity, each group in on one line. |
|
735 | # word-method//rest. For clarity, each group in on one line. | |
731 |
|
736 | |||
732 | # WARNING: update the regexp if the above escapes are changed, as they |
|
737 | # WARNING: update the regexp if the above escapes are changed, as they | |
733 | # are hardwired in. |
|
738 | # are hardwired in. | |
734 |
|
739 | |||
735 | # Don't get carried away with trying to make the autocalling catch too |
|
740 | # Don't get carried away with trying to make the autocalling catch too | |
736 | # much: it's better to be conservative rather than to trigger hidden |
|
741 | # much: it's better to be conservative rather than to trigger hidden | |
737 | # evals() somewhere and end up causing side effects. |
|
742 | # evals() somewhere and end up causing side effects. | |
738 |
|
743 | |||
739 | self.line_split = re.compile(r'^([\s*,;/])' |
|
744 | self.line_split = re.compile(r'^([\s*,;/])' | |
740 | r'([\?\w\.]+\w*\s*)' |
|
745 | r'([\?\w\.]+\w*\s*)' | |
741 | r'(\(?.*$)') |
|
746 | r'(\(?.*$)') | |
742 |
|
747 | |||
743 | # Original re, keep around for a while in case changes break something |
|
748 | # Original re, keep around for a while in case changes break something | |
744 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' |
|
749 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' | |
745 | # r'(\s*[\?\w\.]+\w*\s*)' |
|
750 | # r'(\s*[\?\w\.]+\w*\s*)' | |
746 | # r'(\(?.*$)') |
|
751 | # r'(\(?.*$)') | |
747 |
|
752 | |||
748 | # RegExp to identify potential function names |
|
753 | # RegExp to identify potential function names | |
749 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
754 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
750 | # RegExp to exclude strings with this start from autocalling |
|
755 | # RegExp to exclude strings with this start from autocalling | |
751 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') |
|
756 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') | |
752 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
757 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
753 | # (experimental). For this to work, the line_split regexp would need |
|
758 | # (experimental). For this to work, the line_split regexp would need | |
754 | # to be modified so it wouldn't break things at '['. That line is |
|
759 | # to be modified so it wouldn't break things at '['. That line is | |
755 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
760 | # nasty enough that I shouldn't change it until I can test it _well_. | |
756 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
761 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
757 |
|
762 | |||
758 | # keep track of where we started running (mainly for crash post-mortem) |
|
763 | # keep track of where we started running (mainly for crash post-mortem) | |
759 | self.starting_dir = os.getcwd() |
|
764 | self.starting_dir = os.getcwd() | |
760 |
|
765 | |||
761 | # Attributes for Logger mixin class, make defaults here |
|
766 | # Attributes for Logger mixin class, make defaults here | |
762 | self._dolog = 0 |
|
767 | self._dolog = 0 | |
763 | self.LOG = '' |
|
768 | self.LOG = '' | |
764 | self.LOGDEF = '.InteractiveShell.log' |
|
769 | self.LOGDEF = '.InteractiveShell.log' | |
765 | self.LOGMODE = 'over' |
|
770 | self.LOGMODE = 'over' | |
766 | self.LOGHEAD = Itpl( |
|
771 | self.LOGHEAD = Itpl( | |
767 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
772 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
768 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
773 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
769 | #log# opts = $self.rc.opts |
|
774 | #log# opts = $self.rc.opts | |
770 | #log# args = $self.rc.args |
|
775 | #log# args = $self.rc.args | |
771 | #log# It is safe to make manual edits below here. |
|
776 | #log# It is safe to make manual edits below here. | |
772 | #log#----------------------------------------------------------------------- |
|
777 | #log#----------------------------------------------------------------------- | |
773 | """) |
|
778 | """) | |
774 | # Various switches which can be set |
|
779 | # Various switches which can be set | |
775 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
780 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
776 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
781 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
777 | self.banner2 = banner2 |
|
782 | self.banner2 = banner2 | |
778 |
|
783 | |||
779 | # TraceBack handlers: |
|
784 | # TraceBack handlers: | |
780 | # Need two, one for syntax errors and one for other exceptions. |
|
785 | # Need two, one for syntax errors and one for other exceptions. | |
781 | self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor') |
|
786 | self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor') | |
782 | # This one is initialized with an offset, meaning we always want to |
|
787 | # This one is initialized with an offset, meaning we always want to | |
783 | # remove the topmost item in the traceback, which is our own internal |
|
788 | # remove the topmost item in the traceback, which is our own internal | |
784 | # code. Valid modes: ['Plain','Context','Verbose'] |
|
789 | # code. Valid modes: ['Plain','Context','Verbose'] | |
785 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
790 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
786 | color_scheme='NoColor', |
|
791 | color_scheme='NoColor', | |
787 | tb_offset = 1) |
|
792 | tb_offset = 1) | |
788 | # and add any custom exception handlers the user may have specified |
|
793 | # and add any custom exception handlers the user may have specified | |
789 | self.set_custom_exc(*custom_exceptions) |
|
794 | self.set_custom_exc(*custom_exceptions) | |
790 |
|
795 | |||
791 | # Object inspector |
|
796 | # Object inspector | |
792 | ins_colors = OInspect.InspectColors |
|
797 | ins_colors = OInspect.InspectColors | |
793 | code_colors = PyColorize.ANSICodeColors |
|
798 | code_colors = PyColorize.ANSICodeColors | |
794 | self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor') |
|
799 | self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor') | |
795 | self.autoindent = 0 |
|
800 | self.autoindent = 0 | |
796 |
|
801 | |||
797 | # Make some aliases automatically |
|
802 | # Make some aliases automatically | |
798 | # Prepare list of shell aliases to auto-define |
|
803 | # Prepare list of shell aliases to auto-define | |
799 | if os.name == 'posix': |
|
804 | if os.name == 'posix': | |
800 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
805 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
801 | 'mv mv -i','rm rm -i','cp cp -i', |
|
806 | 'mv mv -i','rm rm -i','cp cp -i', | |
802 | 'cat cat','less less','clear clear', |
|
807 | 'cat cat','less less','clear clear', | |
803 | # a better ls |
|
808 | # a better ls | |
804 | 'ls ls -F', |
|
809 | 'ls ls -F', | |
805 | # long ls |
|
810 | # long ls | |
806 | 'll ls -lF', |
|
811 | 'll ls -lF', | |
807 | # color ls |
|
812 | # color ls | |
808 | 'lc ls -F -o --color', |
|
813 | 'lc ls -F -o --color', | |
809 | # ls normal files only |
|
814 | # ls normal files only | |
810 | 'lf ls -F -o --color %l | grep ^-', |
|
815 | 'lf ls -F -o --color %l | grep ^-', | |
811 | # ls symbolic links |
|
816 | # ls symbolic links | |
812 | 'lk ls -F -o --color %l | grep ^l', |
|
817 | 'lk ls -F -o --color %l | grep ^l', | |
813 | # directories or links to directories, |
|
818 | # directories or links to directories, | |
814 | 'ldir ls -F -o --color %l | grep /$', |
|
819 | 'ldir ls -F -o --color %l | grep /$', | |
815 | # things which are executable |
|
820 | # things which are executable | |
816 | 'lx ls -F -o --color %l | grep ^-..x', |
|
821 | 'lx ls -F -o --color %l | grep ^-..x', | |
817 | ) |
|
822 | ) | |
818 | elif os.name in ['nt','dos']: |
|
823 | elif os.name in ['nt','dos']: | |
819 | auto_alias = ('dir dir /on', 'ls dir /on', |
|
824 | auto_alias = ('dir dir /on', 'ls dir /on', | |
820 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
825 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
821 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
826 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
822 | 'ren ren','cls cls','copy copy') |
|
827 | 'ren ren','cls cls','copy copy') | |
823 | else: |
|
828 | else: | |
824 | auto_alias = () |
|
829 | auto_alias = () | |
825 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) |
|
830 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) | |
826 | # Call the actual (public) initializer |
|
831 | # Call the actual (public) initializer | |
827 | self.init_auto_alias() |
|
832 | self.init_auto_alias() | |
828 | # end __init__ |
|
833 | # end __init__ | |
829 |
|
834 | |||
830 | def set_hook(self,name,hook): |
|
835 | def set_hook(self,name,hook): | |
831 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
836 | """set_hook(name,hook) -> sets an internal IPython hook. | |
832 |
|
837 | |||
833 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
838 | IPython exposes some of its internal API as user-modifiable hooks. By | |
834 | resetting one of these hooks, you can modify IPython's behavior to |
|
839 | resetting one of these hooks, you can modify IPython's behavior to | |
835 | call at runtime your own routines.""" |
|
840 | call at runtime your own routines.""" | |
836 |
|
841 | |||
837 | # At some point in the future, this should validate the hook before it |
|
842 | # At some point in the future, this should validate the hook before it | |
838 | # accepts it. Probably at least check that the hook takes the number |
|
843 | # accepts it. Probably at least check that the hook takes the number | |
839 | # of args it's supposed to. |
|
844 | # of args it's supposed to. | |
840 | setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
845 | setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
841 |
|
846 | |||
842 | def set_custom_exc(self,exc_tuple,handler): |
|
847 | def set_custom_exc(self,exc_tuple,handler): | |
843 | """set_custom_exc(exc_tuple,handler) |
|
848 | """set_custom_exc(exc_tuple,handler) | |
844 |
|
849 | |||
845 | Set a custom exception handler, which will be called if any of the |
|
850 | Set a custom exception handler, which will be called if any of the | |
846 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
851 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
847 | runcode() method. |
|
852 | runcode() method. | |
848 |
|
853 | |||
849 | Inputs: |
|
854 | Inputs: | |
850 |
|
855 | |||
851 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
856 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
852 | handler for. It is very important that you use a tuple, and NOT A |
|
857 | handler for. It is very important that you use a tuple, and NOT A | |
853 | LIST here, because of the way Python's except statement works. If |
|
858 | LIST here, because of the way Python's except statement works. If | |
854 | you only want to trap a single exception, use a singleton tuple: |
|
859 | you only want to trap a single exception, use a singleton tuple: | |
855 |
|
860 | |||
856 | exc_tuple == (MyCustomException,) |
|
861 | exc_tuple == (MyCustomException,) | |
857 |
|
862 | |||
858 | - handler: this must be defined as a function with the following |
|
863 | - handler: this must be defined as a function with the following | |
859 | basic interface: def my_handler(self,etype,value,tb). |
|
864 | basic interface: def my_handler(self,etype,value,tb). | |
860 |
|
865 | |||
861 | This will be made into an instance method (via new.instancemethod) |
|
866 | This will be made into an instance method (via new.instancemethod) | |
862 | of IPython itself, and it will be called if any of the exceptions |
|
867 | of IPython itself, and it will be called if any of the exceptions | |
863 | listed in the exc_tuple are caught. If the handler is None, an |
|
868 | listed in the exc_tuple are caught. If the handler is None, an | |
864 | internal basic one is used, which just prints basic info. |
|
869 | internal basic one is used, which just prints basic info. | |
865 |
|
870 | |||
866 | WARNING: by putting in your own exception handler into IPython's main |
|
871 | WARNING: by putting in your own exception handler into IPython's main | |
867 | execution loop, you run a very good chance of nasty crashes. This |
|
872 | execution loop, you run a very good chance of nasty crashes. This | |
868 | facility should only be used if you really know what you are doing.""" |
|
873 | facility should only be used if you really know what you are doing.""" | |
869 |
|
874 | |||
870 | assert type(exc_tuple)==type(()) , \ |
|
875 | assert type(exc_tuple)==type(()) , \ | |
871 | "The custom exceptions must be given AS A TUPLE." |
|
876 | "The custom exceptions must be given AS A TUPLE." | |
872 |
|
877 | |||
873 | def dummy_handler(self,etype,value,tb): |
|
878 | def dummy_handler(self,etype,value,tb): | |
874 | print '*** Simple custom exception handler ***' |
|
879 | print '*** Simple custom exception handler ***' | |
875 | print 'Exception type :',etype |
|
880 | print 'Exception type :',etype | |
876 | print 'Exception value:',value |
|
881 | print 'Exception value:',value | |
877 | print 'Traceback :',tb |
|
882 | print 'Traceback :',tb | |
878 | print 'Source code :','\n'.join(self.buffer) |
|
883 | print 'Source code :','\n'.join(self.buffer) | |
879 |
|
884 | |||
880 | if handler is None: handler = dummy_handler |
|
885 | if handler is None: handler = dummy_handler | |
881 |
|
886 | |||
882 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
887 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
883 | self.custom_exceptions = exc_tuple |
|
888 | self.custom_exceptions = exc_tuple | |
884 |
|
889 | |||
885 | def set_custom_completer(self,completer,pos=0): |
|
890 | def set_custom_completer(self,completer,pos=0): | |
886 | """set_custom_completer(completer,pos=0) |
|
891 | """set_custom_completer(completer,pos=0) | |
887 |
|
892 | |||
888 | Adds a new custom completer function. |
|
893 | Adds a new custom completer function. | |
889 |
|
894 | |||
890 | The position argument (defaults to 0) is the index in the completers |
|
895 | The position argument (defaults to 0) is the index in the completers | |
891 | list where you want the completer to be inserted.""" |
|
896 | list where you want the completer to be inserted.""" | |
892 |
|
897 | |||
893 | newcomp = new.instancemethod(completer,self.Completer, |
|
898 | newcomp = new.instancemethod(completer,self.Completer, | |
894 | self.Completer.__class__) |
|
899 | self.Completer.__class__) | |
895 | self.Completer.matchers.insert(pos,newcomp) |
|
900 | self.Completer.matchers.insert(pos,newcomp) | |
896 |
|
901 | |||
897 | def complete(self,text): |
|
902 | def complete(self,text): | |
898 | """Return a sorted list of all possible completions on text. |
|
903 | """Return a sorted list of all possible completions on text. | |
899 |
|
904 | |||
900 | Inputs: |
|
905 | Inputs: | |
901 |
|
906 | |||
902 | - text: a string of text to be completed on. |
|
907 | - text: a string of text to be completed on. | |
903 |
|
908 | |||
904 | This is a wrapper around the completion mechanism, similar to what |
|
909 | This is a wrapper around the completion mechanism, similar to what | |
905 | readline does at the command line when the TAB key is hit. By |
|
910 | readline does at the command line when the TAB key is hit. By | |
906 | exposing it as a method, it can be used by other non-readline |
|
911 | exposing it as a method, it can be used by other non-readline | |
907 | environments (such as GUIs) for text completion. |
|
912 | environments (such as GUIs) for text completion. | |
908 |
|
913 | |||
909 | Simple usage example: |
|
914 | Simple usage example: | |
910 |
|
915 | |||
911 | In [1]: x = 'hello' |
|
916 | In [1]: x = 'hello' | |
912 |
|
917 | |||
913 | In [2]: __IP.complete('x.l') |
|
918 | In [2]: __IP.complete('x.l') | |
914 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
919 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" | |
915 |
|
920 | |||
916 | complete = self.Completer.complete |
|
921 | complete = self.Completer.complete | |
917 | state = 0 |
|
922 | state = 0 | |
918 | # use a dict so we get unique keys, since ipyhton's multiple |
|
923 | # use a dict so we get unique keys, since ipyhton's multiple | |
919 | # completers can return duplicates. |
|
924 | # completers can return duplicates. | |
920 | comps = {} |
|
925 | comps = {} | |
921 | while True: |
|
926 | while True: | |
922 | newcomp = complete(text,state) |
|
927 | newcomp = complete(text,state) | |
923 | if newcomp is None: |
|
928 | if newcomp is None: | |
924 | break |
|
929 | break | |
925 | comps[newcomp] = 1 |
|
930 | comps[newcomp] = 1 | |
926 | state += 1 |
|
931 | state += 1 | |
927 | outcomps = comps.keys() |
|
932 | outcomps = comps.keys() | |
928 | outcomps.sort() |
|
933 | outcomps.sort() | |
929 | return outcomps |
|
934 | return outcomps | |
930 |
|
935 | |||
931 | def post_config_initialization(self): |
|
936 | def post_config_initialization(self): | |
932 | """Post configuration init method |
|
937 | """Post configuration init method | |
933 |
|
938 | |||
934 | This is called after the configuration files have been processed to |
|
939 | This is called after the configuration files have been processed to | |
935 | 'finalize' the initialization.""" |
|
940 | 'finalize' the initialization.""" | |
936 |
|
941 | |||
937 | # dynamic data that survives through sessions |
|
942 | # dynamic data that survives through sessions | |
938 | # XXX make the filename a config option? |
|
943 | # XXX make the filename a config option? | |
939 | persist_base = 'persist' |
|
944 | persist_base = 'persist' | |
940 | if self.rc.profile: |
|
945 | if self.rc.profile: | |
941 | persist_base += '_%s' % self.rc.profile |
|
946 | persist_base += '_%s' % self.rc.profile | |
942 | self.persist_fname = os.path.join(self.rc.ipythondir,persist_base) |
|
947 | self.persist_fname = os.path.join(self.rc.ipythondir,persist_base) | |
943 |
|
948 | |||
944 | try: |
|
949 | try: | |
945 | self.persist = pickle.load(file(self.persist_fname)) |
|
950 | self.persist = pickle.load(file(self.persist_fname)) | |
946 | except: |
|
951 | except: | |
947 | self.persist = {} |
|
952 | self.persist = {} | |
948 |
|
953 | |||
949 | def init_auto_alias(self): |
|
954 | def init_auto_alias(self): | |
950 | """Define some aliases automatically. |
|
955 | """Define some aliases automatically. | |
951 |
|
956 | |||
952 | These are ALL parameter-less aliases""" |
|
957 | These are ALL parameter-less aliases""" | |
953 | for alias,cmd in self.auto_alias: |
|
958 | for alias,cmd in self.auto_alias: | |
954 | self.alias_table[alias] = (0,cmd) |
|
959 | self.alias_table[alias] = (0,cmd) | |
955 |
|
960 | |||
956 | def alias_table_validate(self,verbose=0): |
|
961 | def alias_table_validate(self,verbose=0): | |
957 | """Update information about the alias table. |
|
962 | """Update information about the alias table. | |
958 |
|
963 | |||
959 | In particular, make sure no Python keywords/builtins are in it.""" |
|
964 | In particular, make sure no Python keywords/builtins are in it.""" | |
960 |
|
965 | |||
961 | no_alias = self.no_alias |
|
966 | no_alias = self.no_alias | |
962 | for k in self.alias_table.keys(): |
|
967 | for k in self.alias_table.keys(): | |
963 | if k in no_alias: |
|
968 | if k in no_alias: | |
964 | del self.alias_table[k] |
|
969 | del self.alias_table[k] | |
965 | if verbose: |
|
970 | if verbose: | |
966 | print ("Deleting alias <%s>, it's a Python " |
|
971 | print ("Deleting alias <%s>, it's a Python " | |
967 | "keyword or builtin." % k) |
|
972 | "keyword or builtin." % k) | |
968 |
|
973 | |||
969 | def set_autoindent(self,value=None): |
|
974 | def set_autoindent(self,value=None): | |
970 | """Set the autoindent flag, checking for readline support. |
|
975 | """Set the autoindent flag, checking for readline support. | |
971 |
|
976 | |||
972 | If called with no arguments, it acts as a toggle.""" |
|
977 | If called with no arguments, it acts as a toggle.""" | |
973 |
|
978 | |||
974 | if not self.has_readline: |
|
979 | if not self.has_readline: | |
975 | if os.name == 'posix': |
|
980 | if os.name == 'posix': | |
976 | warn("The auto-indent feature requires the readline library") |
|
981 | warn("The auto-indent feature requires the readline library") | |
977 | self.autoindent = 0 |
|
982 | self.autoindent = 0 | |
978 | return |
|
983 | return | |
979 | if value is None: |
|
984 | if value is None: | |
980 | self.autoindent = not self.autoindent |
|
985 | self.autoindent = not self.autoindent | |
981 | else: |
|
986 | else: | |
982 | self.autoindent = value |
|
987 | self.autoindent = value | |
983 |
|
988 | |||
984 | def rc_set_toggle(self,rc_field,value=None): |
|
989 | def rc_set_toggle(self,rc_field,value=None): | |
985 | """Set or toggle a field in IPython's rc config. structure. |
|
990 | """Set or toggle a field in IPython's rc config. structure. | |
986 |
|
991 | |||
987 | If called with no arguments, it acts as a toggle. |
|
992 | If called with no arguments, it acts as a toggle. | |
988 |
|
993 | |||
989 | If called with a non-existent field, the resulting AttributeError |
|
994 | If called with a non-existent field, the resulting AttributeError | |
990 | exception will propagate out.""" |
|
995 | exception will propagate out.""" | |
991 |
|
996 | |||
992 | rc_val = getattr(self.rc,rc_field) |
|
997 | rc_val = getattr(self.rc,rc_field) | |
993 | if value is None: |
|
998 | if value is None: | |
994 | value = not rc_val |
|
999 | value = not rc_val | |
995 | setattr(self.rc,rc_field,value) |
|
1000 | setattr(self.rc,rc_field,value) | |
996 |
|
1001 | |||
997 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1002 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
998 | """Install the user configuration directory. |
|
1003 | """Install the user configuration directory. | |
999 |
|
1004 | |||
1000 | Can be called when running for the first time or to upgrade the user's |
|
1005 | Can be called when running for the first time or to upgrade the user's | |
1001 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
1006 | .ipython/ directory with the mode parameter. Valid modes are 'install' | |
1002 | and 'upgrade'.""" |
|
1007 | and 'upgrade'.""" | |
1003 |
|
1008 | |||
1004 | def wait(): |
|
1009 | def wait(): | |
1005 | try: |
|
1010 | try: | |
1006 | raw_input("Please press <RETURN> to start IPython.") |
|
1011 | raw_input("Please press <RETURN> to start IPython.") | |
1007 | except EOFError: |
|
1012 | except EOFError: | |
1008 | print >> Term.cout |
|
1013 | print >> Term.cout | |
1009 | print '*'*70 |
|
1014 | print '*'*70 | |
1010 |
|
1015 | |||
1011 | cwd = os.getcwd() # remember where we started |
|
1016 | cwd = os.getcwd() # remember where we started | |
1012 | glb = glob.glob |
|
1017 | glb = glob.glob | |
1013 | print '*'*70 |
|
1018 | print '*'*70 | |
1014 | if mode == 'install': |
|
1019 | if mode == 'install': | |
1015 | print \ |
|
1020 | print \ | |
1016 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1021 | """Welcome to IPython. I will try to create a personal configuration directory | |
1017 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1022 | where you can customize many aspects of IPython's functionality in:\n""" | |
1018 | else: |
|
1023 | else: | |
1019 | print 'I am going to upgrade your configuration in:' |
|
1024 | print 'I am going to upgrade your configuration in:' | |
1020 |
|
1025 | |||
1021 | print ipythondir |
|
1026 | print ipythondir | |
1022 |
|
1027 | |||
1023 | rcdirend = os.path.join('IPython','UserConfig') |
|
1028 | rcdirend = os.path.join('IPython','UserConfig') | |
1024 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1029 | cfg = lambda d: os.path.join(d,rcdirend) | |
1025 | try: |
|
1030 | try: | |
1026 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1031 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
1027 | except IOError: |
|
1032 | except IOError: | |
1028 | warning = """ |
|
1033 | warning = """ | |
1029 | Installation error. IPython's directory was not found. |
|
1034 | Installation error. IPython's directory was not found. | |
1030 |
|
1035 | |||
1031 | Check the following: |
|
1036 | Check the following: | |
1032 |
|
1037 | |||
1033 | The ipython/IPython directory should be in a directory belonging to your |
|
1038 | The ipython/IPython directory should be in a directory belonging to your | |
1034 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1039 | PYTHONPATH environment variable (that is, it should be in a directory | |
1035 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1040 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
1036 |
|
1041 | |||
1037 | IPython will proceed with builtin defaults. |
|
1042 | IPython will proceed with builtin defaults. | |
1038 | """ |
|
1043 | """ | |
1039 | warn(warning) |
|
1044 | warn(warning) | |
1040 | wait() |
|
1045 | wait() | |
1041 | return |
|
1046 | return | |
1042 |
|
1047 | |||
1043 | if mode == 'install': |
|
1048 | if mode == 'install': | |
1044 | try: |
|
1049 | try: | |
1045 | shutil.copytree(rcdir,ipythondir) |
|
1050 | shutil.copytree(rcdir,ipythondir) | |
1046 | os.chdir(ipythondir) |
|
1051 | os.chdir(ipythondir) | |
1047 | rc_files = glb("ipythonrc*") |
|
1052 | rc_files = glb("ipythonrc*") | |
1048 | for rc_file in rc_files: |
|
1053 | for rc_file in rc_files: | |
1049 | os.rename(rc_file,rc_file+rc_suffix) |
|
1054 | os.rename(rc_file,rc_file+rc_suffix) | |
1050 | except: |
|
1055 | except: | |
1051 | warning = """ |
|
1056 | warning = """ | |
1052 |
|
1057 | |||
1053 | There was a problem with the installation: |
|
1058 | There was a problem with the installation: | |
1054 | %s |
|
1059 | %s | |
1055 | Try to correct it or contact the developers if you think it's a bug. |
|
1060 | Try to correct it or contact the developers if you think it's a bug. | |
1056 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1061 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
1057 | warn(warning) |
|
1062 | warn(warning) | |
1058 | wait() |
|
1063 | wait() | |
1059 | return |
|
1064 | return | |
1060 |
|
1065 | |||
1061 | elif mode == 'upgrade': |
|
1066 | elif mode == 'upgrade': | |
1062 | try: |
|
1067 | try: | |
1063 | os.chdir(ipythondir) |
|
1068 | os.chdir(ipythondir) | |
1064 | except: |
|
1069 | except: | |
1065 | print """ |
|
1070 | print """ | |
1066 | Can not upgrade: changing to directory %s failed. Details: |
|
1071 | Can not upgrade: changing to directory %s failed. Details: | |
1067 | %s |
|
1072 | %s | |
1068 | """ % (ipythondir,sys.exc_info()[1]) |
|
1073 | """ % (ipythondir,sys.exc_info()[1]) | |
1069 | wait() |
|
1074 | wait() | |
1070 | return |
|
1075 | return | |
1071 | else: |
|
1076 | else: | |
1072 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1077 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
1073 | for new_full_path in sources: |
|
1078 | for new_full_path in sources: | |
1074 | new_filename = os.path.basename(new_full_path) |
|
1079 | new_filename = os.path.basename(new_full_path) | |
1075 | if new_filename.startswith('ipythonrc'): |
|
1080 | if new_filename.startswith('ipythonrc'): | |
1076 | new_filename = new_filename + rc_suffix |
|
1081 | new_filename = new_filename + rc_suffix | |
1077 | # The config directory should only contain files, skip any |
|
1082 | # The config directory should only contain files, skip any | |
1078 | # directories which may be there (like CVS) |
|
1083 | # directories which may be there (like CVS) | |
1079 | if os.path.isdir(new_full_path): |
|
1084 | if os.path.isdir(new_full_path): | |
1080 | continue |
|
1085 | continue | |
1081 | if os.path.exists(new_filename): |
|
1086 | if os.path.exists(new_filename): | |
1082 | old_file = new_filename+'.old' |
|
1087 | old_file = new_filename+'.old' | |
1083 | if os.path.exists(old_file): |
|
1088 | if os.path.exists(old_file): | |
1084 | os.remove(old_file) |
|
1089 | os.remove(old_file) | |
1085 | os.rename(new_filename,old_file) |
|
1090 | os.rename(new_filename,old_file) | |
1086 | shutil.copy(new_full_path,new_filename) |
|
1091 | shutil.copy(new_full_path,new_filename) | |
1087 | else: |
|
1092 | else: | |
1088 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1093 | raise ValueError,'unrecognized mode for install:',`mode` | |
1089 |
|
1094 | |||
1090 | # Fix line-endings to those native to each platform in the config |
|
1095 | # Fix line-endings to those native to each platform in the config | |
1091 | # directory. |
|
1096 | # directory. | |
1092 | try: |
|
1097 | try: | |
1093 | os.chdir(ipythondir) |
|
1098 | os.chdir(ipythondir) | |
1094 | except: |
|
1099 | except: | |
1095 | print """ |
|
1100 | print """ | |
1096 | Problem: changing to directory %s failed. |
|
1101 | Problem: changing to directory %s failed. | |
1097 | Details: |
|
1102 | Details: | |
1098 | %s |
|
1103 | %s | |
1099 |
|
1104 | |||
1100 | Some configuration files may have incorrect line endings. This should not |
|
1105 | Some configuration files may have incorrect line endings. This should not | |
1101 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1106 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) | |
1102 | wait() |
|
1107 | wait() | |
1103 | else: |
|
1108 | else: | |
1104 | for fname in glb('ipythonrc*'): |
|
1109 | for fname in glb('ipythonrc*'): | |
1105 | try: |
|
1110 | try: | |
1106 | native_line_ends(fname,backup=0) |
|
1111 | native_line_ends(fname,backup=0) | |
1107 | except IOError: |
|
1112 | except IOError: | |
1108 | pass |
|
1113 | pass | |
1109 |
|
1114 | |||
1110 | if mode == 'install': |
|
1115 | if mode == 'install': | |
1111 | print """ |
|
1116 | print """ | |
1112 | Successful installation! |
|
1117 | Successful installation! | |
1113 |
|
1118 | |||
1114 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1119 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
1115 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1120 | IPython manual (there are both HTML and PDF versions supplied with the | |
1116 | distribution) to make sure that your system environment is properly configured |
|
1121 | distribution) to make sure that your system environment is properly configured | |
1117 | to take advantage of IPython's features.""" |
|
1122 | to take advantage of IPython's features.""" | |
1118 | else: |
|
1123 | else: | |
1119 | print """ |
|
1124 | print """ | |
1120 | Successful upgrade! |
|
1125 | Successful upgrade! | |
1121 |
|
1126 | |||
1122 | All files in your directory: |
|
1127 | All files in your directory: | |
1123 | %(ipythondir)s |
|
1128 | %(ipythondir)s | |
1124 | which would have been overwritten by the upgrade were backed up with a .old |
|
1129 | which would have been overwritten by the upgrade were backed up with a .old | |
1125 | extension. If you had made particular customizations in those files you may |
|
1130 | extension. If you had made particular customizations in those files you may | |
1126 | want to merge them back into the new files.""" % locals() |
|
1131 | want to merge them back into the new files.""" % locals() | |
1127 | wait() |
|
1132 | wait() | |
1128 | os.chdir(cwd) |
|
1133 | os.chdir(cwd) | |
1129 | # end user_setup() |
|
1134 | # end user_setup() | |
1130 |
|
1135 | |||
1131 | def atexit_operations(self): |
|
1136 | def atexit_operations(self): | |
1132 | """This will be executed at the time of exit. |
|
1137 | """This will be executed at the time of exit. | |
1133 |
|
1138 | |||
1134 | Saving of persistent data should be performed here. """ |
|
1139 | Saving of persistent data should be performed here. """ | |
1135 |
|
1140 | |||
1136 | # input history |
|
1141 | # input history | |
1137 | self.savehist() |
|
1142 | self.savehist() | |
1138 |
|
1143 | |||
1139 | # Cleanup all tempfiles left around |
|
1144 | # Cleanup all tempfiles left around | |
1140 | for tfile in self.tempfiles: |
|
1145 | for tfile in self.tempfiles: | |
1141 | try: |
|
1146 | try: | |
1142 | os.unlink(tfile) |
|
1147 | os.unlink(tfile) | |
1143 | except OSError: |
|
1148 | except OSError: | |
1144 | pass |
|
1149 | pass | |
1145 |
|
1150 | |||
1146 | # save the "persistent data" catch-all dictionary |
|
1151 | # save the "persistent data" catch-all dictionary | |
1147 | try: |
|
1152 | try: | |
1148 | pickle.dump(self.persist, open(self.persist_fname,"w")) |
|
1153 | pickle.dump(self.persist, open(self.persist_fname,"w")) | |
1149 | except: |
|
1154 | except: | |
1150 | print "*** ERROR *** persistent data saving failed." |
|
1155 | print "*** ERROR *** persistent data saving failed." | |
1151 |
|
1156 | |||
1152 | def savehist(self): |
|
1157 | def savehist(self): | |
1153 | """Save input history to a file (via readline library).""" |
|
1158 | """Save input history to a file (via readline library).""" | |
1154 | try: |
|
1159 | try: | |
1155 | self.readline.write_history_file(self.histfile) |
|
1160 | self.readline.write_history_file(self.histfile) | |
1156 | except: |
|
1161 | except: | |
1157 | print 'Unable to save IPython command history to file: ' + \ |
|
1162 | print 'Unable to save IPython command history to file: ' + \ | |
1158 | `self.histfile` |
|
1163 | `self.histfile` | |
1159 |
|
1164 | |||
1160 | def pre_readline(self): |
|
1165 | def pre_readline(self): | |
1161 | """readline hook to be used at the start of each line. |
|
1166 | """readline hook to be used at the start of each line. | |
1162 |
|
1167 | |||
1163 | Currently it handles auto-indent only.""" |
|
1168 | Currently it handles auto-indent only.""" | |
1164 |
|
1169 | |||
1165 | self.readline.insert_text(' '* self.readline_indent) |
|
1170 | self.readline.insert_text(' '* self.readline_indent) | |
1166 |
|
1171 | |||
1167 | def init_readline(self): |
|
1172 | def init_readline(self): | |
1168 | """Command history completion/saving/reloading.""" |
|
1173 | """Command history completion/saving/reloading.""" | |
1169 | try: |
|
1174 | try: | |
1170 | import readline |
|
1175 | import readline | |
1171 | self.Completer = MagicCompleter(self, |
|
1176 | self.Completer = MagicCompleter(self, | |
1172 | self.user_ns, |
|
1177 | self.user_ns, | |
1173 | self.rc.readline_omit__names, |
|
1178 | self.rc.readline_omit__names, | |
1174 | self.alias_table) |
|
1179 | self.alias_table) | |
1175 | except ImportError,NameError: |
|
1180 | except ImportError,NameError: | |
1176 | # If FlexCompleter failed to import, MagicCompleter won't be |
|
1181 | # If FlexCompleter failed to import, MagicCompleter won't be | |
1177 | # defined. This can happen because of a problem with readline |
|
1182 | # defined. This can happen because of a problem with readline | |
1178 | self.has_readline = 0 |
|
1183 | self.has_readline = 0 | |
1179 | # no point in bugging windows users with this every time: |
|
1184 | # no point in bugging windows users with this every time: | |
1180 | if os.name == 'posix': |
|
1185 | if os.name == 'posix': | |
1181 | warn('Readline services not available on this platform.') |
|
1186 | warn('Readline services not available on this platform.') | |
1182 | else: |
|
1187 | else: | |
1183 | import atexit |
|
1188 | import atexit | |
1184 |
|
1189 | |||
1185 | # Platform-specific configuration |
|
1190 | # Platform-specific configuration | |
1186 | if os.name == 'nt': |
|
1191 | if os.name == 'nt': | |
1187 | # readline under Windows modifies the default exit behavior |
|
1192 | # readline under Windows modifies the default exit behavior | |
1188 | # from being Ctrl-Z/Return to the Unix Ctrl-D one. |
|
1193 | # from being Ctrl-Z/Return to the Unix Ctrl-D one. | |
1189 | __builtin__.exit = __builtin__.quit = \ |
|
1194 | __builtin__.exit = __builtin__.quit = \ | |
1190 | ('Use Ctrl-D (i.e. EOF) to exit. ' |
|
1195 | ('Use Ctrl-D (i.e. EOF) to exit. ' | |
1191 | 'Use %Exit or %Quit to exit without confirmation.') |
|
1196 | 'Use %Exit or %Quit to exit without confirmation.') | |
1192 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1197 | self.readline_startup_hook = readline.set_pre_input_hook | |
1193 | else: |
|
1198 | else: | |
1194 | self.readline_startup_hook = readline.set_startup_hook |
|
1199 | self.readline_startup_hook = readline.set_startup_hook | |
1195 |
|
1200 | |||
1196 | # Load user's initrc file (readline config) |
|
1201 | # Load user's initrc file (readline config) | |
1197 | inputrc_name = os.environ.get('INPUTRC') |
|
1202 | inputrc_name = os.environ.get('INPUTRC') | |
1198 | if inputrc_name is None: |
|
1203 | if inputrc_name is None: | |
1199 | home_dir = get_home_dir() |
|
1204 | home_dir = get_home_dir() | |
1200 | if home_dir is not None: |
|
1205 | if home_dir is not None: | |
1201 | inputrc_name = os.path.join(home_dir,'.inputrc') |
|
1206 | inputrc_name = os.path.join(home_dir,'.inputrc') | |
1202 | if os.path.isfile(inputrc_name): |
|
1207 | if os.path.isfile(inputrc_name): | |
1203 | try: |
|
1208 | try: | |
1204 | readline.read_init_file(inputrc_name) |
|
1209 | readline.read_init_file(inputrc_name) | |
1205 | except: |
|
1210 | except: | |
1206 | warn('Problems reading readline initialization file <%s>' |
|
1211 | warn('Problems reading readline initialization file <%s>' | |
1207 | % inputrc_name) |
|
1212 | % inputrc_name) | |
1208 |
|
1213 | |||
1209 | self.has_readline = 1 |
|
1214 | self.has_readline = 1 | |
1210 | self.readline = readline |
|
1215 | self.readline = readline | |
1211 | self.readline_indent = 0 # for auto-indenting via readline |
|
1216 | self.readline_indent = 0 # for auto-indenting via readline | |
1212 | # save this in sys so embedded copies can restore it properly |
|
1217 | # save this in sys so embedded copies can restore it properly | |
1213 | sys.ipcompleter = self.Completer.complete |
|
1218 | sys.ipcompleter = self.Completer.complete | |
1214 | readline.set_completer(self.Completer.complete) |
|
1219 | readline.set_completer(self.Completer.complete) | |
1215 |
|
1220 | |||
1216 | # Configure readline according to user's prefs |
|
1221 | # Configure readline according to user's prefs | |
1217 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1222 | for rlcommand in self.rc.readline_parse_and_bind: | |
1218 | readline.parse_and_bind(rlcommand) |
|
1223 | readline.parse_and_bind(rlcommand) | |
1219 |
|
1224 | |||
1220 | # remove some chars from the delimiters list |
|
1225 | # remove some chars from the delimiters list | |
1221 | delims = readline.get_completer_delims() |
|
1226 | delims = readline.get_completer_delims() | |
1222 | delims = delims.translate(string._idmap, |
|
1227 | delims = delims.translate(string._idmap, | |
1223 | self.rc.readline_remove_delims) |
|
1228 | self.rc.readline_remove_delims) | |
1224 | readline.set_completer_delims(delims) |
|
1229 | readline.set_completer_delims(delims) | |
1225 | # otherwise we end up with a monster history after a while: |
|
1230 | # otherwise we end up with a monster history after a while: | |
1226 | readline.set_history_length(1000) |
|
1231 | readline.set_history_length(1000) | |
1227 | try: |
|
1232 | try: | |
1228 | #print '*** Reading readline history' # dbg |
|
1233 | #print '*** Reading readline history' # dbg | |
1229 | readline.read_history_file(self.histfile) |
|
1234 | readline.read_history_file(self.histfile) | |
1230 | except IOError: |
|
1235 | except IOError: | |
1231 | pass # It doesn't exist yet. |
|
1236 | pass # It doesn't exist yet. | |
1232 |
|
1237 | |||
1233 | atexit.register(self.atexit_operations) |
|
1238 | atexit.register(self.atexit_operations) | |
1234 | del atexit |
|
1239 | del atexit | |
1235 |
|
1240 | |||
1236 | # Configure auto-indent for all platforms |
|
1241 | # Configure auto-indent for all platforms | |
1237 | self.set_autoindent(self.rc.autoindent) |
|
1242 | self.set_autoindent(self.rc.autoindent) | |
1238 |
|
1243 | |||
1239 | def showsyntaxerror(self, filename=None): |
|
1244 | def showsyntaxerror(self, filename=None): | |
1240 | """Display the syntax error that just occurred. |
|
1245 | """Display the syntax error that just occurred. | |
1241 |
|
1246 | |||
1242 | This doesn't display a stack trace because there isn't one. |
|
1247 | This doesn't display a stack trace because there isn't one. | |
1243 |
|
1248 | |||
1244 | If a filename is given, it is stuffed in the exception instead |
|
1249 | If a filename is given, it is stuffed in the exception instead | |
1245 | of what was there before (because Python's parser always uses |
|
1250 | of what was there before (because Python's parser always uses | |
1246 | "<string>" when reading from a string). |
|
1251 | "<string>" when reading from a string). | |
1247 | """ |
|
1252 | """ | |
1248 | type, value, sys.last_traceback = sys.exc_info() |
|
1253 | type, value, sys.last_traceback = sys.exc_info() | |
1249 | sys.last_type = type |
|
1254 | sys.last_type = type | |
1250 | sys.last_value = value |
|
1255 | sys.last_value = value | |
1251 | if filename and type is SyntaxError: |
|
1256 | if filename and type is SyntaxError: | |
1252 | # Work hard to stuff the correct filename in the exception |
|
1257 | # Work hard to stuff the correct filename in the exception | |
1253 | try: |
|
1258 | try: | |
1254 | msg, (dummy_filename, lineno, offset, line) = value |
|
1259 | msg, (dummy_filename, lineno, offset, line) = value | |
1255 | except: |
|
1260 | except: | |
1256 | # Not the format we expect; leave it alone |
|
1261 | # Not the format we expect; leave it alone | |
1257 | pass |
|
1262 | pass | |
1258 | else: |
|
1263 | else: | |
1259 | # Stuff in the right filename |
|
1264 | # Stuff in the right filename | |
1260 | try: |
|
1265 | try: | |
1261 | # Assume SyntaxError is a class exception |
|
1266 | # Assume SyntaxError is a class exception | |
1262 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1267 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1263 | except: |
|
1268 | except: | |
1264 | # If that failed, assume SyntaxError is a string |
|
1269 | # If that failed, assume SyntaxError is a string | |
1265 | value = msg, (filename, lineno, offset, line) |
|
1270 | value = msg, (filename, lineno, offset, line) | |
1266 | self.SyntaxTB(type,value,[]) |
|
1271 | self.SyntaxTB(type,value,[]) | |
1267 |
|
1272 | |||
1268 | def debugger(self): |
|
1273 | def debugger(self): | |
1269 | """Call the pdb debugger.""" |
|
1274 | """Call the pdb debugger.""" | |
1270 |
|
1275 | |||
1271 | if not self.rc.pdb: |
|
1276 | if not self.rc.pdb: | |
1272 | return |
|
1277 | return | |
1273 | pdb.pm() |
|
1278 | pdb.pm() | |
1274 |
|
1279 | |||
1275 | def showtraceback(self,exc_tuple = None,filename=None): |
|
1280 | def showtraceback(self,exc_tuple = None,filename=None): | |
1276 | """Display the exception that just occurred.""" |
|
1281 | """Display the exception that just occurred.""" | |
1277 |
|
1282 | |||
1278 | # Though this won't be called by syntax errors in the input line, |
|
1283 | # Though this won't be called by syntax errors in the input line, | |
1279 | # there may be SyntaxError cases whith imported code. |
|
1284 | # there may be SyntaxError cases whith imported code. | |
1280 | if exc_tuple is None: |
|
1285 | if exc_tuple is None: | |
1281 | type, value, tb = sys.exc_info() |
|
1286 | type, value, tb = sys.exc_info() | |
1282 | else: |
|
1287 | else: | |
1283 | type, value, tb = exc_tuple |
|
1288 | type, value, tb = exc_tuple | |
1284 | if type is SyntaxError: |
|
1289 | if type is SyntaxError: | |
1285 | self.showsyntaxerror(filename) |
|
1290 | self.showsyntaxerror(filename) | |
1286 | else: |
|
1291 | else: | |
1287 | sys.last_type = type |
|
1292 | sys.last_type = type | |
1288 | sys.last_value = value |
|
1293 | sys.last_value = value | |
1289 | sys.last_traceback = tb |
|
1294 | sys.last_traceback = tb | |
1290 | self.InteractiveTB() |
|
1295 | self.InteractiveTB() | |
1291 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1296 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1292 | # pdb mucks up readline, fix it back |
|
1297 | # pdb mucks up readline, fix it back | |
1293 | self.readline.set_completer(self.Completer.complete) |
|
1298 | self.readline.set_completer(self.Completer.complete) | |
1294 |
|
1299 | |||
1295 | def update_cache(self, line): |
|
1300 | def update_cache(self, line): | |
1296 | """puts line into cache""" |
|
1301 | """puts line into cache""" | |
1297 | self.inputcache.insert(0, line) # This copies the cache every time ... :-( |
|
1302 | self.inputcache.insert(0, line) # This copies the cache every time ... :-( | |
1298 | if len(self.inputcache) >= self.CACHELENGTH: |
|
1303 | if len(self.inputcache) >= self.CACHELENGTH: | |
1299 | self.inputcache.pop() # This not :-) |
|
1304 | self.inputcache.pop() # This not :-) | |
1300 |
|
1305 | |||
1301 | def name_space_init(self): |
|
1306 | def name_space_init(self): | |
1302 | """Create local namespace.""" |
|
1307 | """Create local namespace.""" | |
1303 | # We want this to be a method to facilitate embedded initialization. |
|
1308 | # We want this to be a method to facilitate embedded initialization. | |
1304 | code.InteractiveConsole.__init__(self,self.user_ns) |
|
1309 | code.InteractiveConsole.__init__(self,self.user_ns) | |
1305 |
|
1310 | |||
1306 | def mainloop(self,banner=None): |
|
1311 | def mainloop(self,banner=None): | |
1307 | """Creates the local namespace and starts the mainloop. |
|
1312 | """Creates the local namespace and starts the mainloop. | |
1308 |
|
1313 | |||
1309 | If an optional banner argument is given, it will override the |
|
1314 | If an optional banner argument is given, it will override the | |
1310 | internally created default banner.""" |
|
1315 | internally created default banner.""" | |
1311 |
|
1316 | |||
1312 | self.name_space_init() |
|
1317 | self.name_space_init() | |
1313 | if self.rc.c: # Emulate Python's -c option |
|
1318 | if self.rc.c: # Emulate Python's -c option | |
1314 | self.exec_init_cmd() |
|
1319 | self.exec_init_cmd() | |
1315 | if banner is None: |
|
1320 | if banner is None: | |
1316 | if self.rc.banner: |
|
1321 | if self.rc.banner: | |
1317 | banner = self.BANNER+self.banner2 |
|
1322 | banner = self.BANNER+self.banner2 | |
1318 | else: |
|
1323 | else: | |
1319 | banner = '' |
|
1324 | banner = '' | |
1320 | self.interact(banner) |
|
1325 | self.interact(banner) | |
1321 |
|
1326 | |||
1322 | def exec_init_cmd(self): |
|
1327 | def exec_init_cmd(self): | |
1323 | """Execute a command given at the command line. |
|
1328 | """Execute a command given at the command line. | |
1324 |
|
1329 | |||
1325 | This emulates Python's -c option.""" |
|
1330 | This emulates Python's -c option.""" | |
1326 |
|
1331 | |||
1327 | sys.argv = ['-c'] |
|
1332 | sys.argv = ['-c'] | |
1328 | self.push(self.rc.c) |
|
1333 | self.push(self.rc.c) | |
1329 |
|
1334 | |||
1330 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1335 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1331 | """Embeds IPython into a running python program. |
|
1336 | """Embeds IPython into a running python program. | |
1332 |
|
1337 | |||
1333 | Input: |
|
1338 | Input: | |
1334 |
|
1339 | |||
1335 | - header: An optional header message can be specified. |
|
1340 | - header: An optional header message can be specified. | |
1336 |
|
1341 | |||
1337 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1342 | - local_ns, global_ns: working namespaces. If given as None, the | |
1338 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1343 | IPython-initialized one is updated with __main__.__dict__, so that | |
1339 | program variables become visible but user-specific configuration |
|
1344 | program variables become visible but user-specific configuration | |
1340 | remains possible. |
|
1345 | remains possible. | |
1341 |
|
1346 | |||
1342 | - stack_depth: specifies how many levels in the stack to go to |
|
1347 | - stack_depth: specifies how many levels in the stack to go to | |
1343 | looking for namespaces (when local_ns and global_ns are None). This |
|
1348 | looking for namespaces (when local_ns and global_ns are None). This | |
1344 | allows an intermediate caller to make sure that this function gets |
|
1349 | allows an intermediate caller to make sure that this function gets | |
1345 | the namespace from the intended level in the stack. By default (0) |
|
1350 | the namespace from the intended level in the stack. By default (0) | |
1346 | it will get its locals and globals from the immediate caller. |
|
1351 | it will get its locals and globals from the immediate caller. | |
1347 |
|
1352 | |||
1348 | Warning: it's possible to use this in a program which is being run by |
|
1353 | Warning: it's possible to use this in a program which is being run by | |
1349 | IPython itself (via %run), but some funny things will happen (a few |
|
1354 | IPython itself (via %run), but some funny things will happen (a few | |
1350 | globals get overwritten). In the future this will be cleaned up, as |
|
1355 | globals get overwritten). In the future this will be cleaned up, as | |
1351 | there is no fundamental reason why it can't work perfectly.""" |
|
1356 | there is no fundamental reason why it can't work perfectly.""" | |
1352 |
|
1357 | |||
1353 | # Patch for global embedding to make sure that things don't overwrite |
|
1358 | # Patch for global embedding to make sure that things don't overwrite | |
1354 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1359 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1355 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1360 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1356 | if local_ns is None and global_ns is None: |
|
1361 | if local_ns is None and global_ns is None: | |
1357 | self.user_ns.update(__main__.__dict__) |
|
1362 | self.user_ns.update(__main__.__dict__) | |
1358 |
|
1363 | |||
1359 | # Get locals and globals from caller |
|
1364 | # Get locals and globals from caller | |
1360 | if local_ns is None or global_ns is None: |
|
1365 | if local_ns is None or global_ns is None: | |
1361 | call_frame = sys._getframe(stack_depth).f_back |
|
1366 | call_frame = sys._getframe(stack_depth).f_back | |
1362 |
|
1367 | |||
1363 | if local_ns is None: |
|
1368 | if local_ns is None: | |
1364 | local_ns = call_frame.f_locals |
|
1369 | local_ns = call_frame.f_locals | |
1365 | if global_ns is None: |
|
1370 | if global_ns is None: | |
1366 | global_ns = call_frame.f_globals |
|
1371 | global_ns = call_frame.f_globals | |
1367 |
|
1372 | |||
1368 | # Update namespaces and fire up interpreter |
|
1373 | # Update namespaces and fire up interpreter | |
1369 | self.user_ns.update(local_ns) |
|
1374 | self.user_ns.update(local_ns) | |
1370 | self.interact(header) |
|
1375 | self.interact(header) | |
1371 |
|
1376 | |||
1372 | # Remove locals from namespace |
|
1377 | # Remove locals from namespace | |
1373 | for k in local_ns: |
|
1378 | for k in local_ns: | |
1374 | del self.user_ns[k] |
|
1379 | del self.user_ns[k] | |
1375 |
|
1380 | |||
1376 | def interact(self, banner=None): |
|
1381 | def interact(self, banner=None): | |
1377 | """Closely emulate the interactive Python console. |
|
1382 | """Closely emulate the interactive Python console. | |
1378 |
|
1383 | |||
1379 | The optional banner argument specify the banner to print |
|
1384 | The optional banner argument specify the banner to print | |
1380 | before the first interaction; by default it prints a banner |
|
1385 | before the first interaction; by default it prints a banner | |
1381 | similar to the one printed by the real Python interpreter, |
|
1386 | similar to the one printed by the real Python interpreter, | |
1382 | followed by the current class name in parentheses (so as not |
|
1387 | followed by the current class name in parentheses (so as not | |
1383 | to confuse this with the real interpreter -- since it's so |
|
1388 | to confuse this with the real interpreter -- since it's so | |
1384 | close!). |
|
1389 | close!). | |
1385 |
|
1390 | |||
1386 | """ |
|
1391 | """ | |
1387 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1392 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1388 | if banner is None: |
|
1393 | if banner is None: | |
1389 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1394 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1390 | (sys.version, sys.platform, cprt, |
|
1395 | (sys.version, sys.platform, cprt, | |
1391 | self.__class__.__name__)) |
|
1396 | self.__class__.__name__)) | |
1392 | else: |
|
1397 | else: | |
1393 | self.write(banner) |
|
1398 | self.write(banner) | |
1394 |
|
1399 | |||
1395 | more = 0 |
|
1400 | more = 0 | |
1396 |
|
1401 | |||
1397 | # Mark activity in the builtins |
|
1402 | # Mark activity in the builtins | |
1398 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1403 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1399 |
|
1404 | |||
1400 | # exit_now is set by a call to %Exit or %Quit |
|
1405 | # exit_now is set by a call to %Exit or %Quit | |
1401 | while not self.exit_now: |
|
1406 | while not self.exit_now: | |
1402 | try: |
|
1407 | try: | |
1403 | if more: |
|
1408 | if more: | |
1404 | prompt = self.outputcache.prompt2 |
|
1409 | prompt = self.outputcache.prompt2 | |
1405 | if self.autoindent: |
|
1410 | if self.autoindent: | |
1406 | self.readline_startup_hook(self.pre_readline) |
|
1411 | self.readline_startup_hook(self.pre_readline) | |
1407 | else: |
|
1412 | else: | |
1408 | prompt = self.outputcache.prompt1 |
|
1413 | prompt = self.outputcache.prompt1 | |
1409 | try: |
|
1414 | try: | |
1410 | line = self.raw_input(prompt) |
|
1415 | line = self.raw_input(prompt) | |
1411 | if self.autoindent: |
|
1416 | if self.autoindent: | |
1412 | self.readline_startup_hook(None) |
|
1417 | self.readline_startup_hook(None) | |
1413 | except EOFError: |
|
1418 | except EOFError: | |
1414 | if self.autoindent: |
|
1419 | if self.autoindent: | |
1415 | self.readline_startup_hook(None) |
|
1420 | self.readline_startup_hook(None) | |
1416 | self.write("\n") |
|
1421 | self.write("\n") | |
1417 | if self.rc.confirm_exit: |
|
1422 | if self.rc.confirm_exit: | |
1418 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
1423 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
1419 | break |
|
1424 | break | |
1420 | else: |
|
1425 | else: | |
1421 | break |
|
1426 | break | |
1422 | else: |
|
1427 | else: | |
1423 | more = self.push(line) |
|
1428 | more = self.push(line) | |
1424 | # Auto-indent management |
|
1429 | # Auto-indent management | |
1425 | if self.autoindent: |
|
1430 | if self.autoindent: | |
1426 | if line: |
|
1431 | if line: | |
1427 | ini_spaces = re.match('^(\s+)',line) |
|
1432 | ini_spaces = re.match('^(\s+)',line) | |
1428 | if ini_spaces: |
|
1433 | if ini_spaces: | |
1429 | nspaces = ini_spaces.end() |
|
1434 | nspaces = ini_spaces.end() | |
1430 | else: |
|
1435 | else: | |
1431 | nspaces = 0 |
|
1436 | nspaces = 0 | |
1432 | self.readline_indent = nspaces |
|
1437 | self.readline_indent = nspaces | |
1433 |
|
1438 | |||
1434 | if line[-1] == ':': |
|
1439 | if line[-1] == ':': | |
1435 | self.readline_indent += 4 |
|
1440 | self.readline_indent += 4 | |
1436 | elif re.match(r'^\s+raise|^\s+return',line): |
|
1441 | elif re.match(r'^\s+raise|^\s+return',line): | |
1437 | self.readline_indent -= 4 |
|
1442 | self.readline_indent -= 4 | |
1438 | else: |
|
1443 | else: | |
1439 | self.readline_indent = 0 |
|
1444 | self.readline_indent = 0 | |
1440 |
|
1445 | |||
1441 | except KeyboardInterrupt: |
|
1446 | except KeyboardInterrupt: | |
1442 | self.write("\nKeyboardInterrupt\n") |
|
1447 | self.write("\nKeyboardInterrupt\n") | |
1443 | self.resetbuffer() |
|
1448 | self.resetbuffer() | |
1444 | more = 0 |
|
1449 | more = 0 | |
1445 | # keep cache in sync with the prompt counter: |
|
1450 | # keep cache in sync with the prompt counter: | |
1446 | self.outputcache.prompt_count -= 1 |
|
1451 | self.outputcache.prompt_count -= 1 | |
1447 |
|
1452 | |||
1448 | if self.autoindent: |
|
1453 | if self.autoindent: | |
1449 | self.readline_indent = 0 |
|
1454 | self.readline_indent = 0 | |
1450 |
|
1455 | |||
1451 | except bdb.BdbQuit: |
|
1456 | except bdb.BdbQuit: | |
1452 | warn("The Python debugger has exited with a BdbQuit exception.\n" |
|
1457 | warn("The Python debugger has exited with a BdbQuit exception.\n" | |
1453 | "Because of how pdb handles the stack, it is impossible\n" |
|
1458 | "Because of how pdb handles the stack, it is impossible\n" | |
1454 | "for IPython to properly format this particular exception.\n" |
|
1459 | "for IPython to properly format this particular exception.\n" | |
1455 | "IPython will resume normal operation.") |
|
1460 | "IPython will resume normal operation.") | |
1456 |
|
1461 | |||
1457 | # We are off again... |
|
1462 | # We are off again... | |
1458 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1463 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1459 |
|
1464 | |||
1460 | def excepthook(self, type, value, tb): |
|
1465 | def excepthook(self, type, value, tb): | |
1461 | """One more defense for GUI apps that call sys.excepthook. |
|
1466 | """One more defense for GUI apps that call sys.excepthook. | |
1462 |
|
1467 | |||
1463 | GUI frameworks like wxPython trap exceptions and call |
|
1468 | GUI frameworks like wxPython trap exceptions and call | |
1464 | sys.excepthook themselves. I guess this is a feature that |
|
1469 | sys.excepthook themselves. I guess this is a feature that | |
1465 | enables them to keep running after exceptions that would |
|
1470 | enables them to keep running after exceptions that would | |
1466 | otherwise kill their mainloop. This is a bother for IPython |
|
1471 | otherwise kill their mainloop. This is a bother for IPython | |
1467 | which excepts to catch all of the program exceptions with a try: |
|
1472 | which excepts to catch all of the program exceptions with a try: | |
1468 | except: statement. |
|
1473 | except: statement. | |
1469 |
|
1474 | |||
1470 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1475 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1471 | any app directly invokes sys.excepthook, it will look to the user like |
|
1476 | any app directly invokes sys.excepthook, it will look to the user like | |
1472 | IPython crashed. In order to work around this, we can disable the |
|
1477 | IPython crashed. In order to work around this, we can disable the | |
1473 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1478 | CrashHandler and replace it with this excepthook instead, which prints a | |
1474 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1479 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1475 | call sys.excepthook will generate a regular-looking exception from |
|
1480 | call sys.excepthook will generate a regular-looking exception from | |
1476 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1481 | IPython, and the CrashHandler will only be triggered by real IPython | |
1477 | crashes. |
|
1482 | crashes. | |
1478 |
|
1483 | |||
1479 | This hook should be used sparingly, only in places which are not likely |
|
1484 | This hook should be used sparingly, only in places which are not likely | |
1480 | to be true IPython errors. |
|
1485 | to be true IPython errors. | |
1481 | """ |
|
1486 | """ | |
1482 |
|
1487 | |||
1483 | self.InteractiveTB(type, value, tb, tb_offset=0) |
|
1488 | self.InteractiveTB(type, value, tb, tb_offset=0) | |
1484 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1489 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1485 | self.readline.set_completer(self.Completer.complete) |
|
1490 | self.readline.set_completer(self.Completer.complete) | |
1486 |
|
1491 | |||
1487 | def call_alias(self,alias,rest=''): |
|
1492 | def call_alias(self,alias,rest=''): | |
1488 | """Call an alias given its name and the rest of the line. |
|
1493 | """Call an alias given its name and the rest of the line. | |
1489 |
|
1494 | |||
1490 | This function MUST be given a proper alias, because it doesn't make |
|
1495 | This function MUST be given a proper alias, because it doesn't make | |
1491 | any checks when looking up into the alias table. The caller is |
|
1496 | any checks when looking up into the alias table. The caller is | |
1492 | responsible for invoking it only with a valid alias.""" |
|
1497 | responsible for invoking it only with a valid alias.""" | |
1493 |
|
1498 | |||
1494 | #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg |
|
1499 | #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg | |
1495 | nargs,cmd = self.alias_table[alias] |
|
1500 | nargs,cmd = self.alias_table[alias] | |
1496 | # Expand the %l special to be the user's input line |
|
1501 | # Expand the %l special to be the user's input line | |
1497 | if cmd.find('%l') >= 0: |
|
1502 | if cmd.find('%l') >= 0: | |
1498 | cmd = cmd.replace('%l',rest) |
|
1503 | cmd = cmd.replace('%l',rest) | |
1499 | rest = '' |
|
1504 | rest = '' | |
1500 | if nargs==0: |
|
1505 | if nargs==0: | |
1501 | # Simple, argument-less aliases |
|
1506 | # Simple, argument-less aliases | |
1502 | cmd = '%s %s' % (cmd,rest) |
|
1507 | cmd = '%s %s' % (cmd,rest) | |
1503 | else: |
|
1508 | else: | |
1504 | # Handle aliases with positional arguments |
|
1509 | # Handle aliases with positional arguments | |
1505 | args = rest.split(None,nargs) |
|
1510 | args = rest.split(None,nargs) | |
1506 | if len(args)< nargs: |
|
1511 | if len(args)< nargs: | |
1507 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1512 | error('Alias <%s> requires %s arguments, %s given.' % | |
1508 | (alias,nargs,len(args))) |
|
1513 | (alias,nargs,len(args))) | |
1509 | return |
|
1514 | return | |
1510 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1515 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
1511 | # Now call the macro, evaluating in the user's namespace |
|
1516 | # Now call the macro, evaluating in the user's namespace | |
1512 | try: |
|
1517 | try: | |
1513 | self.system(cmd) |
|
1518 | self.system(cmd) | |
1514 | except: |
|
1519 | except: | |
1515 | self.showtraceback() |
|
1520 | self.showtraceback() | |
1516 |
|
1521 | |||
1517 | def runlines(self,lines): |
|
1522 | def runlines(self,lines): | |
1518 | """Run a string of one or more lines of source. |
|
1523 | """Run a string of one or more lines of source. | |
1519 |
|
1524 | |||
1520 | This method is capable of running a string containing multiple source |
|
1525 | This method is capable of running a string containing multiple source | |
1521 | lines, as if they had been entered at the IPython prompt. Since it |
|
1526 | lines, as if they had been entered at the IPython prompt. Since it | |
1522 | exposes IPython's processing machinery, the given strings can contain |
|
1527 | exposes IPython's processing machinery, the given strings can contain | |
1523 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1528 | magic calls (%magic), special shell access (!cmd), etc.""" | |
1524 |
|
1529 | |||
1525 | # We must start with a clean buffer, in case this is run from an |
|
1530 | # We must start with a clean buffer, in case this is run from an | |
1526 | # interactive IPython session (via a magic, for example). |
|
1531 | # interactive IPython session (via a magic, for example). | |
1527 | self.resetbuffer() |
|
1532 | self.resetbuffer() | |
1528 | lines = lines.split('\n') |
|
1533 | lines = lines.split('\n') | |
1529 | more = 0 |
|
1534 | more = 0 | |
1530 | for line in lines: |
|
1535 | for line in lines: | |
1531 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1536 | # skip blank lines so we don't mess up the prompt counter, but do | |
1532 | # NOT skip even a blank line if we are in a code block (more is |
|
1537 | # NOT skip even a blank line if we are in a code block (more is | |
1533 | # true) |
|
1538 | # true) | |
1534 | if line or more: |
|
1539 | if line or more: | |
1535 | more = self.push((self.prefilter(line,more))) |
|
1540 | more = self.push((self.prefilter(line,more))) | |
1536 | # IPython's runsource returns None if there was an error |
|
1541 | # IPython's runsource returns None if there was an error | |
1537 | # compiling the code. This allows us to stop processing right |
|
1542 | # compiling the code. This allows us to stop processing right | |
1538 | # away, so the user gets the error message at the right place. |
|
1543 | # away, so the user gets the error message at the right place. | |
1539 | if more is None: |
|
1544 | if more is None: | |
1540 | break |
|
1545 | break | |
1541 | # final newline in case the input didn't have it, so that the code |
|
1546 | # final newline in case the input didn't have it, so that the code | |
1542 | # actually does get executed |
|
1547 | # actually does get executed | |
1543 | if more: |
|
1548 | if more: | |
1544 | self.push('\n') |
|
1549 | self.push('\n') | |
1545 |
|
1550 | |||
1546 | def runsource(self, source, filename="<input>", symbol="single"): |
|
1551 | def runsource(self, source, filename="<input>", symbol="single"): | |
1547 | """Compile and run some source in the interpreter. |
|
1552 | """Compile and run some source in the interpreter. | |
1548 |
|
1553 | |||
1549 | Arguments are as for compile_command(). |
|
1554 | Arguments are as for compile_command(). | |
1550 |
|
1555 | |||
1551 | One several things can happen: |
|
1556 | One several things can happen: | |
1552 |
|
1557 | |||
1553 | 1) The input is incorrect; compile_command() raised an |
|
1558 | 1) The input is incorrect; compile_command() raised an | |
1554 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1559 | exception (SyntaxError or OverflowError). A syntax traceback | |
1555 | will be printed by calling the showsyntaxerror() method. |
|
1560 | will be printed by calling the showsyntaxerror() method. | |
1556 |
|
1561 | |||
1557 | 2) The input is incomplete, and more input is required; |
|
1562 | 2) The input is incomplete, and more input is required; | |
1558 | compile_command() returned None. Nothing happens. |
|
1563 | compile_command() returned None. Nothing happens. | |
1559 |
|
1564 | |||
1560 | 3) The input is complete; compile_command() returned a code |
|
1565 | 3) The input is complete; compile_command() returned a code | |
1561 | object. The code is executed by calling self.runcode() (which |
|
1566 | object. The code is executed by calling self.runcode() (which | |
1562 | also handles run-time exceptions, except for SystemExit). |
|
1567 | also handles run-time exceptions, except for SystemExit). | |
1563 |
|
1568 | |||
1564 | The return value is: |
|
1569 | The return value is: | |
1565 |
|
1570 | |||
1566 | - True in case 2 |
|
1571 | - True in case 2 | |
1567 |
|
1572 | |||
1568 | - False in the other cases, unless an exception is raised, where |
|
1573 | - False in the other cases, unless an exception is raised, where | |
1569 | None is returned instead. This can be used by external callers to |
|
1574 | None is returned instead. This can be used by external callers to | |
1570 | know whether to continue feeding input or not. |
|
1575 | know whether to continue feeding input or not. | |
1571 |
|
1576 | |||
1572 | The return value can be used to decide whether to use sys.ps1 or |
|
1577 | The return value can be used to decide whether to use sys.ps1 or | |
1573 | sys.ps2 to prompt the next line.""" |
|
1578 | sys.ps2 to prompt the next line.""" | |
1574 |
|
1579 | |||
1575 | try: |
|
1580 | try: | |
1576 | code = self.compile(source, filename, symbol) |
|
1581 | code = self.compile(source, filename, symbol) | |
1577 | except (OverflowError, SyntaxError, ValueError): |
|
1582 | except (OverflowError, SyntaxError, ValueError): | |
1578 | # Case 1 |
|
1583 | # Case 1 | |
1579 | self.showsyntaxerror(filename) |
|
1584 | self.showsyntaxerror(filename) | |
1580 | return None |
|
1585 | return None | |
1581 |
|
1586 | |||
1582 | if code is None: |
|
1587 | if code is None: | |
1583 | # Case 2 |
|
1588 | # Case 2 | |
1584 | return True |
|
1589 | return True | |
1585 |
|
1590 | |||
1586 | # Case 3 |
|
1591 | # Case 3 | |
1587 | # We store the code object so that threaded shells and |
|
1592 | # We store the code object so that threaded shells and | |
1588 | # custom exception handlers can access all this info if needed. |
|
1593 | # custom exception handlers can access all this info if needed. | |
1589 | # The source corresponding to this can be obtained from the |
|
1594 | # The source corresponding to this can be obtained from the | |
1590 | # buffer attribute as '\n'.join(self.buffer). |
|
1595 | # buffer attribute as '\n'.join(self.buffer). | |
1591 | self.code_to_run = code |
|
1596 | self.code_to_run = code | |
1592 | # now actually execute the code object |
|
1597 | # now actually execute the code object | |
1593 | if self.runcode(code) == 0: |
|
1598 | if self.runcode(code) == 0: | |
1594 | return False |
|
1599 | return False | |
1595 | else: |
|
1600 | else: | |
1596 | return None |
|
1601 | return None | |
1597 |
|
1602 | |||
1598 | def runcode(self,code_obj): |
|
1603 | def runcode(self,code_obj): | |
1599 | """Execute a code object. |
|
1604 | """Execute a code object. | |
1600 |
|
1605 | |||
1601 | When an exception occurs, self.showtraceback() is called to display a |
|
1606 | When an exception occurs, self.showtraceback() is called to display a | |
1602 | traceback. |
|
1607 | traceback. | |
1603 |
|
1608 | |||
1604 | Return value: a flag indicating whether the code to be run completed |
|
1609 | Return value: a flag indicating whether the code to be run completed | |
1605 | successfully: |
|
1610 | successfully: | |
1606 |
|
1611 | |||
1607 | - 0: successful execution. |
|
1612 | - 0: successful execution. | |
1608 | - 1: an error occurred. |
|
1613 | - 1: an error occurred. | |
1609 | """ |
|
1614 | """ | |
1610 |
|
1615 | |||
1611 | # Set our own excepthook in case the user code tries to call it |
|
1616 | # Set our own excepthook in case the user code tries to call it | |
1612 | # directly, so that the IPython crash handler doesn't get triggered |
|
1617 | # directly, so that the IPython crash handler doesn't get triggered | |
1613 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1618 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
1614 | outflag = 1 # happens in more places, so it's easier as default |
|
1619 | outflag = 1 # happens in more places, so it's easier as default | |
1615 | try: |
|
1620 | try: | |
1616 | try: |
|
1621 | try: | |
1617 | exec code_obj in self.locals |
|
1622 | exec code_obj in self.locals | |
1618 | finally: |
|
1623 | finally: | |
1619 | # Reset our crash handler in place |
|
1624 | # Reset our crash handler in place | |
1620 | sys.excepthook = old_excepthook |
|
1625 | sys.excepthook = old_excepthook | |
1621 | except SystemExit: |
|
1626 | except SystemExit: | |
1622 | self.resetbuffer() |
|
1627 | self.resetbuffer() | |
1623 | self.showtraceback() |
|
1628 | self.showtraceback() | |
1624 | warn( __builtin__.exit,level=1) |
|
1629 | warn( __builtin__.exit,level=1) | |
1625 | except self.custom_exceptions: |
|
1630 | except self.custom_exceptions: | |
1626 | etype,value,tb = sys.exc_info() |
|
1631 | etype,value,tb = sys.exc_info() | |
1627 | self.CustomTB(etype,value,tb) |
|
1632 | self.CustomTB(etype,value,tb) | |
1628 | except: |
|
1633 | except: | |
1629 | self.showtraceback() |
|
1634 | self.showtraceback() | |
1630 | else: |
|
1635 | else: | |
1631 | outflag = 0 |
|
1636 | outflag = 0 | |
1632 | if code.softspace(sys.stdout, 0): |
|
1637 | if code.softspace(sys.stdout, 0): | |
1633 |
|
1638 | |||
1634 | # Flush out code object which has been run (and source) |
|
1639 | # Flush out code object which has been run (and source) | |
1635 | self.code_to_run = None |
|
1640 | self.code_to_run = None | |
1636 | return outflag |
|
1641 | return outflag | |
1637 |
|
1642 | |||
1638 | def raw_input(self, prompt=""): |
|
1643 | def raw_input(self, prompt=""): | |
1639 | """Write a prompt and read a line. |
|
1644 | """Write a prompt and read a line. | |
1640 |
|
1645 | |||
1641 | The returned line does not include the trailing newline. |
|
1646 | The returned line does not include the trailing newline. | |
1642 | When the user enters the EOF key sequence, EOFError is raised. |
|
1647 | When the user enters the EOF key sequence, EOFError is raised. | |
1643 |
|
1648 | |||
1644 | The base implementation uses the built-in function |
|
1649 | The base implementation uses the built-in function | |
1645 | raw_input(); a subclass may replace this with a different |
|
1650 | raw_input(); a subclass may replace this with a different | |
1646 | implementation. |
|
1651 | implementation. | |
1647 | """ |
|
1652 | """ | |
1648 | return self.prefilter(raw_input_original(prompt), |
|
1653 | return self.prefilter(raw_input_original(prompt), | |
1649 | prompt==self.outputcache.prompt2) |
|
1654 | prompt==self.outputcache.prompt2) | |
1650 |
|
1655 | |||
1651 | def split_user_input(self,line): |
|
1656 | def split_user_input(self,line): | |
1652 | """Split user input into pre-char, function part and rest.""" |
|
1657 | """Split user input into pre-char, function part and rest.""" | |
1653 |
|
1658 | |||
1654 | lsplit = self.line_split.match(line) |
|
1659 | lsplit = self.line_split.match(line) | |
1655 | if lsplit is None: # no regexp match returns None |
|
1660 | if lsplit is None: # no regexp match returns None | |
1656 | try: |
|
1661 | try: | |
1657 | iFun,theRest = line.split(None,1) |
|
1662 | iFun,theRest = line.split(None,1) | |
1658 | except ValueError: |
|
1663 | except ValueError: | |
1659 | iFun,theRest = line,'' |
|
1664 | iFun,theRest = line,'' | |
1660 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
1665 | pre = re.match('^(\s*)(.*)',line).groups()[0] | |
1661 | else: |
|
1666 | else: | |
1662 | pre,iFun,theRest = lsplit.groups() |
|
1667 | pre,iFun,theRest = lsplit.groups() | |
1663 |
|
1668 | |||
1664 | #print 'line:<%s>' % line # dbg |
|
1669 | #print 'line:<%s>' % line # dbg | |
1665 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
1670 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg | |
1666 | return pre,iFun.strip(),theRest |
|
1671 | return pre,iFun.strip(),theRest | |
1667 |
|
1672 | |||
1668 | def _prefilter(self, line, continue_prompt): |
|
1673 | def _prefilter(self, line, continue_prompt): | |
1669 | """Calls different preprocessors, depending on the form of line.""" |
|
1674 | """Calls different preprocessors, depending on the form of line.""" | |
1670 |
|
1675 | |||
1671 | # All handlers *must* return a value, even if it's blank (''). |
|
1676 | # All handlers *must* return a value, even if it's blank (''). | |
1672 |
|
1677 | |||
1673 | # Lines are NOT logged here. Handlers should process the line as |
|
1678 | # Lines are NOT logged here. Handlers should process the line as | |
1674 | # needed, update the cache AND log it (so that the input cache array |
|
1679 | # needed, update the cache AND log it (so that the input cache array | |
1675 | # stays synced). |
|
1680 | # stays synced). | |
1676 |
|
1681 | |||
1677 | # This function is _very_ delicate, and since it's also the one which |
|
1682 | # This function is _very_ delicate, and since it's also the one which | |
1678 | # determines IPython's response to user input, it must be as efficient |
|
1683 | # determines IPython's response to user input, it must be as efficient | |
1679 | # as possible. For this reason it has _many_ returns in it, trying |
|
1684 | # as possible. For this reason it has _many_ returns in it, trying | |
1680 | # always to exit as quickly as it can figure out what it needs to do. |
|
1685 | # always to exit as quickly as it can figure out what it needs to do. | |
1681 |
|
1686 | |||
1682 | # This function is the main responsible for maintaining IPython's |
|
1687 | # This function is the main responsible for maintaining IPython's | |
1683 | # behavior respectful of Python's semantics. So be _very_ careful if |
|
1688 | # behavior respectful of Python's semantics. So be _very_ careful if | |
1684 | # making changes to anything here. |
|
1689 | # making changes to anything here. | |
1685 |
|
1690 | |||
1686 | #..................................................................... |
|
1691 | #..................................................................... | |
1687 | # Code begins |
|
1692 | # Code begins | |
1688 |
|
1693 | |||
1689 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
1694 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
1690 |
|
1695 | |||
1691 | # save the line away in case we crash, so the post-mortem handler can |
|
1696 | # save the line away in case we crash, so the post-mortem handler can | |
1692 | # record it |
|
1697 | # record it | |
1693 | self._last_input_line = line |
|
1698 | self._last_input_line = line | |
1694 |
|
1699 | |||
1695 | #print '***line: <%s>' % line # dbg |
|
1700 | #print '***line: <%s>' % line # dbg | |
1696 |
|
1701 | |||
1697 | # the input history needs to track even empty lines |
|
1702 | # the input history needs to track even empty lines | |
1698 | if not line.strip(): |
|
1703 | if not line.strip(): | |
1699 | if not continue_prompt: |
|
1704 | if not continue_prompt: | |
1700 | self.outputcache.prompt_count -= 1 |
|
1705 | self.outputcache.prompt_count -= 1 | |
1701 | return self.handle_normal('',continue_prompt) |
|
1706 | return self.handle_normal('',continue_prompt) | |
1702 |
|
1707 | |||
1703 | # print '***cont',continue_prompt # dbg |
|
1708 | # print '***cont',continue_prompt # dbg | |
1704 | # special handlers are only allowed for single line statements |
|
1709 | # special handlers are only allowed for single line statements | |
1705 | if continue_prompt and not self.rc.multi_line_specials: |
|
1710 | if continue_prompt and not self.rc.multi_line_specials: | |
1706 | return self.handle_normal(line,continue_prompt) |
|
1711 | return self.handle_normal(line,continue_prompt) | |
1707 |
|
1712 | |||
1708 | # For the rest, we need the structure of the input |
|
1713 | # For the rest, we need the structure of the input | |
1709 | pre,iFun,theRest = self.split_user_input(line) |
|
1714 | pre,iFun,theRest = self.split_user_input(line) | |
1710 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1715 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
1711 |
|
1716 | |||
1712 | # First check for explicit escapes in the last/first character |
|
1717 | # First check for explicit escapes in the last/first character | |
1713 | handler = None |
|
1718 | handler = None | |
1714 | if line[-1] == self.ESC_HELP: |
|
1719 | if line[-1] == self.ESC_HELP: | |
1715 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end |
|
1720 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end | |
1716 | if handler is None: |
|
1721 | if handler is None: | |
1717 | # look at the first character of iFun, NOT of line, so we skip |
|
1722 | # look at the first character of iFun, NOT of line, so we skip | |
1718 | # leading whitespace in multiline input |
|
1723 | # leading whitespace in multiline input | |
1719 | handler = self.esc_handlers.get(iFun[0:1]) |
|
1724 | handler = self.esc_handlers.get(iFun[0:1]) | |
1720 | if handler is not None: |
|
1725 | if handler is not None: | |
1721 | return handler(line,continue_prompt,pre,iFun,theRest) |
|
1726 | return handler(line,continue_prompt,pre,iFun,theRest) | |
1722 | # Emacs ipython-mode tags certain input lines |
|
1727 | # Emacs ipython-mode tags certain input lines | |
1723 | if line.endswith('# PYTHON-MODE'): |
|
1728 | if line.endswith('# PYTHON-MODE'): | |
1724 | return self.handle_emacs(line,continue_prompt) |
|
1729 | return self.handle_emacs(line,continue_prompt) | |
1725 |
|
1730 | |||
1726 | # Next, check if we can automatically execute this thing |
|
1731 | # Next, check if we can automatically execute this thing | |
1727 |
|
1732 | |||
1728 | # Allow ! in multi-line statements if multi_line_specials is on: |
|
1733 | # Allow ! in multi-line statements if multi_line_specials is on: | |
1729 | if continue_prompt and self.rc.multi_line_specials and \ |
|
1734 | if continue_prompt and self.rc.multi_line_specials and \ | |
1730 | iFun.startswith(self.ESC_SHELL): |
|
1735 | iFun.startswith(self.ESC_SHELL): | |
1731 | return self.handle_shell_escape(line,continue_prompt, |
|
1736 | return self.handle_shell_escape(line,continue_prompt, | |
1732 | pre=pre,iFun=iFun, |
|
1737 | pre=pre,iFun=iFun, | |
1733 | theRest=theRest) |
|
1738 | theRest=theRest) | |
1734 |
|
1739 | |||
1735 | # Let's try to find if the input line is a magic fn |
|
1740 | # Let's try to find if the input line is a magic fn | |
1736 | oinfo = None |
|
1741 | oinfo = None | |
1737 | if hasattr(self,'magic_'+iFun): |
|
1742 | if hasattr(self,'magic_'+iFun): | |
1738 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1743 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
1739 | if oinfo['ismagic']: |
|
1744 | if oinfo['ismagic']: | |
1740 | # Be careful not to call magics when a variable assignment is |
|
1745 | # Be careful not to call magics when a variable assignment is | |
1741 | # being made (ls='hi', for example) |
|
1746 | # being made (ls='hi', for example) | |
1742 | if self.rc.automagic and \ |
|
1747 | if self.rc.automagic and \ | |
1743 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ |
|
1748 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ | |
1744 | (self.rc.multi_line_specials or not continue_prompt): |
|
1749 | (self.rc.multi_line_specials or not continue_prompt): | |
1745 | return self.handle_magic(line,continue_prompt, |
|
1750 | return self.handle_magic(line,continue_prompt, | |
1746 | pre,iFun,theRest) |
|
1751 | pre,iFun,theRest) | |
1747 | else: |
|
1752 | else: | |
1748 | return self.handle_normal(line,continue_prompt) |
|
1753 | return self.handle_normal(line,continue_prompt) | |
1749 |
|
1754 | |||
1750 | # If the rest of the line begins with an (in)equality, assginment or |
|
1755 | # If the rest of the line begins with an (in)equality, assginment or | |
1751 | # function call, we should not call _ofind but simply execute it. |
|
1756 | # function call, we should not call _ofind but simply execute it. | |
1752 | # This avoids spurious geattr() accesses on objects upon assignment. |
|
1757 | # This avoids spurious geattr() accesses on objects upon assignment. | |
1753 | # |
|
1758 | # | |
1754 | # It also allows users to assign to either alias or magic names true |
|
1759 | # It also allows users to assign to either alias or magic names true | |
1755 | # python variables (the magic/alias systems always take second seat to |
|
1760 | # python variables (the magic/alias systems always take second seat to | |
1756 | # true python code). |
|
1761 | # true python code). | |
1757 | if theRest and theRest[0] in '!=()': |
|
1762 | if theRest and theRest[0] in '!=()': | |
1758 | return self.handle_normal(line,continue_prompt) |
|
1763 | return self.handle_normal(line,continue_prompt) | |
1759 |
|
1764 | |||
1760 | if oinfo is None: |
|
1765 | if oinfo is None: | |
1761 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1766 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
1762 |
|
1767 | |||
1763 | if not oinfo['found']: |
|
1768 | if not oinfo['found']: | |
1764 | return self.handle_normal(line,continue_prompt) |
|
1769 | return self.handle_normal(line,continue_prompt) | |
1765 | else: |
|
1770 | else: | |
1766 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg |
|
1771 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg | |
1767 | if oinfo['isalias']: |
|
1772 | if oinfo['isalias']: | |
1768 | return self.handle_alias(line,continue_prompt, |
|
1773 | return self.handle_alias(line,continue_prompt, | |
1769 | pre,iFun,theRest) |
|
1774 | pre,iFun,theRest) | |
1770 |
|
1775 | |||
1771 | if self.rc.autocall and \ |
|
1776 | if self.rc.autocall and \ | |
1772 | not self.re_exclude_auto.match(theRest) and \ |
|
1777 | not self.re_exclude_auto.match(theRest) and \ | |
1773 | self.re_fun_name.match(iFun) and \ |
|
1778 | self.re_fun_name.match(iFun) and \ | |
1774 | callable(oinfo['obj']) : |
|
1779 | callable(oinfo['obj']) : | |
1775 | #print 'going auto' # dbg |
|
1780 | #print 'going auto' # dbg | |
1776 | return self.handle_auto(line,continue_prompt,pre,iFun,theRest) |
|
1781 | return self.handle_auto(line,continue_prompt,pre,iFun,theRest) | |
1777 | else: |
|
1782 | else: | |
1778 | #print 'was callable?', callable(oinfo['obj']) # dbg |
|
1783 | #print 'was callable?', callable(oinfo['obj']) # dbg | |
1779 | return self.handle_normal(line,continue_prompt) |
|
1784 | return self.handle_normal(line,continue_prompt) | |
1780 |
|
1785 | |||
1781 | # If we get here, we have a normal Python line. Log and return. |
|
1786 | # If we get here, we have a normal Python line. Log and return. | |
1782 | return self.handle_normal(line,continue_prompt) |
|
1787 | return self.handle_normal(line,continue_prompt) | |
1783 |
|
1788 | |||
1784 | def _prefilter_dumb(self, line, continue_prompt): |
|
1789 | def _prefilter_dumb(self, line, continue_prompt): | |
1785 | """simple prefilter function, for debugging""" |
|
1790 | """simple prefilter function, for debugging""" | |
1786 | return self.handle_normal(line,continue_prompt) |
|
1791 | return self.handle_normal(line,continue_prompt) | |
1787 |
|
1792 | |||
1788 | # Set the default prefilter() function (this can be user-overridden) |
|
1793 | # Set the default prefilter() function (this can be user-overridden) | |
1789 | prefilter = _prefilter |
|
1794 | prefilter = _prefilter | |
1790 |
|
1795 | |||
1791 | def handle_normal(self,line,continue_prompt=None, |
|
1796 | def handle_normal(self,line,continue_prompt=None, | |
1792 | pre=None,iFun=None,theRest=None): |
|
1797 | pre=None,iFun=None,theRest=None): | |
1793 | """Handle normal input lines. Use as a template for handlers.""" |
|
1798 | """Handle normal input lines. Use as a template for handlers.""" | |
1794 |
|
1799 | |||
1795 | self.log(line,continue_prompt) |
|
1800 | self.log(line,continue_prompt) | |
1796 | self.update_cache(line) |
|
1801 | self.update_cache(line) | |
1797 | return line |
|
1802 | return line | |
1798 |
|
1803 | |||
1799 | def handle_alias(self,line,continue_prompt=None, |
|
1804 | def handle_alias(self,line,continue_prompt=None, | |
1800 | pre=None,iFun=None,theRest=None): |
|
1805 | pre=None,iFun=None,theRest=None): | |
1801 | """Handle alias input lines. """ |
|
1806 | """Handle alias input lines. """ | |
1802 |
|
1807 | |||
1803 | theRest = esc_quotes(theRest) |
|
1808 | theRest = esc_quotes(theRest) | |
1804 | line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest) |
|
1809 | line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest) | |
1805 | self.log(line_out,continue_prompt) |
|
1810 | self.log(line_out,continue_prompt) | |
1806 | self.update_cache(line_out) |
|
1811 | self.update_cache(line_out) | |
1807 | return line_out |
|
1812 | return line_out | |
1808 |
|
1813 | |||
1809 | def handle_shell_escape(self, line, continue_prompt=None, |
|
1814 | def handle_shell_escape(self, line, continue_prompt=None, | |
1810 | pre=None,iFun=None,theRest=None): |
|
1815 | pre=None,iFun=None,theRest=None): | |
1811 | """Execute the line in a shell, empty return value""" |
|
1816 | """Execute the line in a shell, empty return value""" | |
1812 |
|
1817 | |||
1813 | #print 'line in :', `line` # dbg |
|
1818 | #print 'line in :', `line` # dbg | |
1814 | # Example of a special handler. Others follow a similar pattern. |
|
1819 | # Example of a special handler. Others follow a similar pattern. | |
1815 | if continue_prompt: # multi-line statements |
|
1820 | if continue_prompt: # multi-line statements | |
1816 | if iFun.startswith('!!'): |
|
1821 | if iFun.startswith('!!'): | |
1817 | print 'SyntaxError: !! is not allowed in multiline statements' |
|
1822 | print 'SyntaxError: !! is not allowed in multiline statements' | |
1818 | return pre |
|
1823 | return pre | |
1819 | else: |
|
1824 | else: | |
1820 | cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"') |
|
1825 | cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"') | |
1821 | line_out = '%s%s.system("%s")' % (pre,self.name,cmd) |
|
1826 | line_out = '%s%s.system("%s")' % (pre,self.name,cmd) | |
1822 | #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')' |
|
1827 | #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')' | |
1823 | else: # single-line input |
|
1828 | else: # single-line input | |
1824 | if line.startswith('!!'): |
|
1829 | if line.startswith('!!'): | |
1825 | # rewrite iFun/theRest to properly hold the call to %sx and |
|
1830 | # rewrite iFun/theRest to properly hold the call to %sx and | |
1826 | # the actual command to be executed, so handle_magic can work |
|
1831 | # the actual command to be executed, so handle_magic can work | |
1827 | # correctly |
|
1832 | # correctly | |
1828 | theRest = '%s %s' % (iFun[2:],theRest) |
|
1833 | theRest = '%s %s' % (iFun[2:],theRest) | |
1829 | iFun = 'sx' |
|
1834 | iFun = 'sx' | |
1830 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]), |
|
1835 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]), | |
1831 | continue_prompt,pre,iFun,theRest) |
|
1836 | continue_prompt,pre,iFun,theRest) | |
1832 | else: |
|
1837 | else: | |
1833 | cmd = esc_quotes(line[1:]) |
|
1838 | cmd = esc_quotes(line[1:]) | |
1834 | line_out = '%s.system("%s")' % (self.name,cmd) |
|
1839 | line_out = '%s.system("%s")' % (self.name,cmd) | |
1835 | #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')' |
|
1840 | #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')' | |
1836 | # update cache/log and return |
|
1841 | # update cache/log and return | |
1837 | self.log(line_out,continue_prompt) |
|
1842 | self.log(line_out,continue_prompt) | |
1838 | self.update_cache(line_out) # readline cache gets normal line |
|
1843 | self.update_cache(line_out) # readline cache gets normal line | |
1839 | #print 'line out r:', `line_out` # dbg |
|
1844 | #print 'line out r:', `line_out` # dbg | |
1840 | #print 'line out s:', line_out # dbg |
|
1845 | #print 'line out s:', line_out # dbg | |
1841 | return line_out |
|
1846 | return line_out | |
1842 |
|
1847 | |||
1843 | def handle_magic(self, line, continue_prompt=None, |
|
1848 | def handle_magic(self, line, continue_prompt=None, | |
1844 | pre=None,iFun=None,theRest=None): |
|
1849 | pre=None,iFun=None,theRest=None): | |
1845 | """Execute magic functions. |
|
1850 | """Execute magic functions. | |
1846 |
|
1851 | |||
1847 | Also log them with a prepended # so the log is clean Python.""" |
|
1852 | Also log them with a prepended # so the log is clean Python.""" | |
1848 |
|
1853 | |||
1849 | cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest))) |
|
1854 | cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest))) | |
1850 | self.log(cmd,continue_prompt) |
|
1855 | self.log(cmd,continue_prompt) | |
1851 | self.update_cache(line) |
|
1856 | self.update_cache(line) | |
1852 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
1857 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
1853 | return cmd |
|
1858 | return cmd | |
1854 |
|
1859 | |||
1855 | def handle_auto(self, line, continue_prompt=None, |
|
1860 | def handle_auto(self, line, continue_prompt=None, | |
1856 | pre=None,iFun=None,theRest=None): |
|
1861 | pre=None,iFun=None,theRest=None): | |
1857 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
1862 | """Hande lines which can be auto-executed, quoting if requested.""" | |
1858 |
|
1863 | |||
1859 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1864 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
1860 |
|
1865 | |||
1861 | # This should only be active for single-line input! |
|
1866 | # This should only be active for single-line input! | |
1862 | if continue_prompt: |
|
1867 | if continue_prompt: | |
1863 | return line |
|
1868 | return line | |
1864 |
|
1869 | |||
1865 | if pre == self.ESC_QUOTE: |
|
1870 | if pre == self.ESC_QUOTE: | |
1866 | # Auto-quote splitting on whitespace |
|
1871 | # Auto-quote splitting on whitespace | |
1867 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
1872 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
1868 | elif pre == self.ESC_QUOTE2: |
|
1873 | elif pre == self.ESC_QUOTE2: | |
1869 | # Auto-quote whole string |
|
1874 | # Auto-quote whole string | |
1870 | newcmd = '%s("%s")' % (iFun,theRest) |
|
1875 | newcmd = '%s("%s")' % (iFun,theRest) | |
1871 | else: |
|
1876 | else: | |
1872 | # Auto-paren |
|
1877 | # Auto-paren | |
1873 | if theRest[0:1] in ('=','['): |
|
1878 | if theRest[0:1] in ('=','['): | |
1874 | # Don't autocall in these cases. They can be either |
|
1879 | # Don't autocall in these cases. They can be either | |
1875 | # rebindings of an existing callable's name, or item access |
|
1880 | # rebindings of an existing callable's name, or item access | |
1876 | # for an object which is BOTH callable and implements |
|
1881 | # for an object which is BOTH callable and implements | |
1877 | # __getitem__. |
|
1882 | # __getitem__. | |
1878 | return '%s %s' % (iFun,theRest) |
|
1883 | return '%s %s' % (iFun,theRest) | |
1879 | if theRest.endswith(';'): |
|
1884 | if theRest.endswith(';'): | |
1880 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
1885 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
1881 | else: |
|
1886 | else: | |
1882 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
1887 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
1883 |
|
1888 | |||
1884 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd |
|
1889 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd | |
1885 | # log what is now valid Python, not the actual user input (without the |
|
1890 | # log what is now valid Python, not the actual user input (without the | |
1886 | # final newline) |
|
1891 | # final newline) | |
1887 | self.log(newcmd,continue_prompt) |
|
1892 | self.log(newcmd,continue_prompt) | |
1888 | return newcmd |
|
1893 | return newcmd | |
1889 |
|
1894 | |||
1890 | def handle_help(self, line, continue_prompt=None, |
|
1895 | def handle_help(self, line, continue_prompt=None, | |
1891 | pre=None,iFun=None,theRest=None): |
|
1896 | pre=None,iFun=None,theRest=None): | |
1892 | """Try to get some help for the object. |
|
1897 | """Try to get some help for the object. | |
1893 |
|
1898 | |||
1894 | obj? or ?obj -> basic information. |
|
1899 | obj? or ?obj -> basic information. | |
1895 | obj?? or ??obj -> more details. |
|
1900 | obj?? or ??obj -> more details. | |
1896 | """ |
|
1901 | """ | |
1897 |
|
1902 | |||
1898 | # We need to make sure that we don't process lines which would be |
|
1903 | # We need to make sure that we don't process lines which would be | |
1899 | # otherwise valid python, such as "x=1 # what?" |
|
1904 | # otherwise valid python, such as "x=1 # what?" | |
1900 | try: |
|
1905 | try: | |
1901 | code.compile_command(line) |
|
1906 | code.compile_command(line) | |
1902 | except SyntaxError: |
|
1907 | except SyntaxError: | |
1903 | # We should only handle as help stuff which is NOT valid syntax |
|
1908 | # We should only handle as help stuff which is NOT valid syntax | |
1904 | if line[0]==self.ESC_HELP: |
|
1909 | if line[0]==self.ESC_HELP: | |
1905 | line = line[1:] |
|
1910 | line = line[1:] | |
1906 | elif line[-1]==self.ESC_HELP: |
|
1911 | elif line[-1]==self.ESC_HELP: | |
1907 | line = line[:-1] |
|
1912 | line = line[:-1] | |
1908 | self.log('#?'+line) |
|
1913 | self.log('#?'+line) | |
1909 | self.update_cache(line) |
|
1914 | self.update_cache(line) | |
1910 | if line: |
|
1915 | if line: | |
1911 | self.magic_pinfo(line) |
|
1916 | self.magic_pinfo(line) | |
1912 | else: |
|
1917 | else: | |
1913 | page(self.usage,screen_lines=self.rc.screen_length) |
|
1918 | page(self.usage,screen_lines=self.rc.screen_length) | |
1914 | return '' # Empty string is needed here! |
|
1919 | return '' # Empty string is needed here! | |
1915 | except: |
|
1920 | except: | |
1916 | # Pass any other exceptions through to the normal handler |
|
1921 | # Pass any other exceptions through to the normal handler | |
1917 | return self.handle_normal(line,continue_prompt) |
|
1922 | return self.handle_normal(line,continue_prompt) | |
1918 | else: |
|
1923 | else: | |
1919 | # If the code compiles ok, we should handle it normally |
|
1924 | # If the code compiles ok, we should handle it normally | |
1920 | return self.handle_normal(line,continue_prompt) |
|
1925 | return self.handle_normal(line,continue_prompt) | |
1921 |
|
1926 | |||
1922 | def handle_emacs(self,line,continue_prompt=None, |
|
1927 | def handle_emacs(self,line,continue_prompt=None, | |
1923 | pre=None,iFun=None,theRest=None): |
|
1928 | pre=None,iFun=None,theRest=None): | |
1924 | """Handle input lines marked by python-mode.""" |
|
1929 | """Handle input lines marked by python-mode.""" | |
1925 |
|
1930 | |||
1926 | # Currently, nothing is done. Later more functionality can be added |
|
1931 | # Currently, nothing is done. Later more functionality can be added | |
1927 | # here if needed. |
|
1932 | # here if needed. | |
1928 |
|
1933 | |||
1929 | # The input cache shouldn't be updated |
|
1934 | # The input cache shouldn't be updated | |
1930 |
|
1935 | |||
1931 | return line |
|
1936 | return line | |
1932 |
|
1937 | |||
1933 | def write(self,data): |
|
1938 | def write(self,data): | |
1934 | """Write a string to the default output""" |
|
1939 | """Write a string to the default output""" | |
1935 | Term.cout.write(data) |
|
1940 | Term.cout.write(data) | |
1936 |
|
1941 | |||
1937 | def write_err(self,data): |
|
1942 | def write_err(self,data): | |
1938 | """Write a string to the default error output""" |
|
1943 | """Write a string to the default error output""" | |
1939 | Term.cerr.write(data) |
|
1944 | Term.cerr.write(data) | |
1940 |
|
1945 | |||
1941 | def safe_execfile(self,fname,*where,**kw): |
|
1946 | def safe_execfile(self,fname,*where,**kw): | |
1942 | fname = os.path.expanduser(fname) |
|
1947 | fname = os.path.expanduser(fname) | |
1943 |
|
1948 | |||
1944 | # find things also in current directory |
|
1949 | # find things also in current directory | |
1945 | dname = os.path.dirname(fname) |
|
1950 | dname = os.path.dirname(fname) | |
1946 | if not sys.path.count(dname): |
|
1951 | if not sys.path.count(dname): | |
1947 | sys.path.append(dname) |
|
1952 | sys.path.append(dname) | |
1948 |
|
1953 | |||
1949 | try: |
|
1954 | try: | |
1950 | xfile = open(fname) |
|
1955 | xfile = open(fname) | |
1951 | except: |
|
1956 | except: | |
1952 | print >> Term.cerr, \ |
|
1957 | print >> Term.cerr, \ | |
1953 | 'Could not open file <%s> for safe execution.' % fname |
|
1958 | 'Could not open file <%s> for safe execution.' % fname | |
1954 | return None |
|
1959 | return None | |
1955 |
|
1960 | |||
1956 | kw.setdefault('islog',0) |
|
1961 | kw.setdefault('islog',0) | |
1957 | kw.setdefault('quiet',1) |
|
1962 | kw.setdefault('quiet',1) | |
1958 | kw.setdefault('exit_ignore',0) |
|
1963 | kw.setdefault('exit_ignore',0) | |
1959 | first = xfile.readline() |
|
1964 | first = xfile.readline() | |
1960 | _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip() |
|
1965 | _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip() | |
1961 | xfile.close() |
|
1966 | xfile.close() | |
1962 | # line by line execution |
|
1967 | # line by line execution | |
1963 | if first.startswith(_LOGHEAD) or kw['islog']: |
|
1968 | if first.startswith(_LOGHEAD) or kw['islog']: | |
1964 | print 'Loading log file <%s> one line at a time...' % fname |
|
1969 | print 'Loading log file <%s> one line at a time...' % fname | |
1965 | if kw['quiet']: |
|
1970 | if kw['quiet']: | |
1966 | stdout_save = sys.stdout |
|
1971 | stdout_save = sys.stdout | |
1967 | sys.stdout = StringIO.StringIO() |
|
1972 | sys.stdout = StringIO.StringIO() | |
1968 | try: |
|
1973 | try: | |
1969 | globs,locs = where[0:2] |
|
1974 | globs,locs = where[0:2] | |
1970 | except: |
|
1975 | except: | |
1971 | try: |
|
1976 | try: | |
1972 | globs = locs = where[0] |
|
1977 | globs = locs = where[0] | |
1973 | except: |
|
1978 | except: | |
1974 | globs = locs = globals() |
|
1979 | globs = locs = globals() | |
1975 | badblocks = [] |
|
1980 | badblocks = [] | |
1976 |
|
1981 | |||
1977 | # we also need to identify indented blocks of code when replaying |
|
1982 | # we also need to identify indented blocks of code when replaying | |
1978 | # logs and put them together before passing them to an exec |
|
1983 | # logs and put them together before passing them to an exec | |
1979 | # statement. This takes a bit of regexp and look-ahead work in the |
|
1984 | # statement. This takes a bit of regexp and look-ahead work in the | |
1980 | # file. It's easiest if we swallow the whole thing in memory |
|
1985 | # file. It's easiest if we swallow the whole thing in memory | |
1981 | # first, and manually walk through the lines list moving the |
|
1986 | # first, and manually walk through the lines list moving the | |
1982 | # counter ourselves. |
|
1987 | # counter ourselves. | |
1983 | indent_re = re.compile('\s+\S') |
|
1988 | indent_re = re.compile('\s+\S') | |
1984 | xfile = open(fname) |
|
1989 | xfile = open(fname) | |
1985 | filelines = xfile.readlines() |
|
1990 | filelines = xfile.readlines() | |
1986 | xfile.close() |
|
1991 | xfile.close() | |
1987 | nlines = len(filelines) |
|
1992 | nlines = len(filelines) | |
1988 | lnum = 0 |
|
1993 | lnum = 0 | |
1989 | while lnum < nlines: |
|
1994 | while lnum < nlines: | |
1990 | line = filelines[lnum] |
|
1995 | line = filelines[lnum] | |
1991 | lnum += 1 |
|
1996 | lnum += 1 | |
1992 | # don't re-insert logger status info into cache |
|
1997 | # don't re-insert logger status info into cache | |
1993 | if line.startswith('#log#'): |
|
1998 | if line.startswith('#log#'): | |
1994 | continue |
|
1999 | continue | |
1995 | elif line.startswith('#%s'% self.ESC_MAGIC): |
|
2000 | elif line.startswith('#%s'% self.ESC_MAGIC): | |
1996 | self.update_cache(line[1:]) |
|
2001 | self.update_cache(line[1:]) | |
1997 | line = magic2python(line) |
|
2002 | line = magic2python(line) | |
1998 | elif line.startswith('#!'): |
|
2003 | elif line.startswith('#!'): | |
1999 | self.update_cache(line[1:]) |
|
2004 | self.update_cache(line[1:]) | |
2000 | else: |
|
2005 | else: | |
2001 | # build a block of code (maybe a single line) for execution |
|
2006 | # build a block of code (maybe a single line) for execution | |
2002 | block = line |
|
2007 | block = line | |
2003 | try: |
|
2008 | try: | |
2004 | next = filelines[lnum] # lnum has already incremented |
|
2009 | next = filelines[lnum] # lnum has already incremented | |
2005 | except: |
|
2010 | except: | |
2006 | next = None |
|
2011 | next = None | |
2007 | while next and indent_re.match(next): |
|
2012 | while next and indent_re.match(next): | |
2008 | block += next |
|
2013 | block += next | |
2009 | lnum += 1 |
|
2014 | lnum += 1 | |
2010 | try: |
|
2015 | try: | |
2011 | next = filelines[lnum] |
|
2016 | next = filelines[lnum] | |
2012 | except: |
|
2017 | except: | |
2013 | next = None |
|
2018 | next = None | |
2014 | # now execute the block of one or more lines |
|
2019 | # now execute the block of one or more lines | |
2015 | try: |
|
2020 | try: | |
2016 | exec block in globs,locs |
|
2021 | exec block in globs,locs | |
2017 | self.update_cache(block.rstrip()) |
|
2022 | self.update_cache(block.rstrip()) | |
2018 | except SystemExit: |
|
2023 | except SystemExit: | |
2019 | pass |
|
2024 | pass | |
2020 | except: |
|
2025 | except: | |
2021 | badblocks.append(block.rstrip()) |
|
2026 | badblocks.append(block.rstrip()) | |
2022 | if kw['quiet']: # restore stdout |
|
2027 | if kw['quiet']: # restore stdout | |
2023 | sys.stdout.close() |
|
2028 | sys.stdout.close() | |
2024 | sys.stdout = stdout_save |
|
2029 | sys.stdout = stdout_save | |
2025 | print 'Finished replaying log file <%s>' % fname |
|
2030 | print 'Finished replaying log file <%s>' % fname | |
2026 | if badblocks: |
|
2031 | if badblocks: | |
2027 | print >> sys.stderr, \ |
|
2032 | print >> sys.stderr, \ | |
2028 | '\nThe following lines/blocks in file <%s> reported errors:' \ |
|
2033 | '\nThe following lines/blocks in file <%s> reported errors:' \ | |
2029 | % fname |
|
2034 | % fname | |
2030 | for badline in badblocks: |
|
2035 | for badline in badblocks: | |
2031 | print >> sys.stderr, badline |
|
2036 | print >> sys.stderr, badline | |
2032 | else: # regular file execution |
|
2037 | else: # regular file execution | |
2033 | try: |
|
2038 | try: | |
2034 | execfile(fname,*where) |
|
2039 | execfile(fname,*where) | |
2035 | except SyntaxError: |
|
2040 | except SyntaxError: | |
2036 | etype, evalue = sys.exc_info()[0:2] |
|
2041 | etype, evalue = sys.exc_info()[0:2] | |
2037 | self.SyntaxTB(etype,evalue,[]) |
|
2042 | self.SyntaxTB(etype,evalue,[]) | |
2038 | warn('Failure executing file: <%s>' % fname) |
|
2043 | warn('Failure executing file: <%s>' % fname) | |
2039 | except SystemExit,status: |
|
2044 | except SystemExit,status: | |
2040 | if not kw['exit_ignore']: |
|
2045 | if not kw['exit_ignore']: | |
2041 | self.InteractiveTB() |
|
2046 | self.InteractiveTB() | |
2042 | warn('Failure executing file: <%s>' % fname) |
|
2047 | warn('Failure executing file: <%s>' % fname) | |
2043 | except: |
|
2048 | except: | |
2044 | self.InteractiveTB() |
|
2049 | self.InteractiveTB() | |
2045 | warn('Failure executing file: <%s>' % fname) |
|
2050 | warn('Failure executing file: <%s>' % fname) | |
2046 |
|
2051 | |||
2047 | #************************* end of file <iplib.py> ***************************** |
|
2052 | #************************* 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 |
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