Show More
@@ -1,3024 +1,3014 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 18 |
|
4 | $Id: Magic.py 1845 2006-10-27 20:35:47Z fptest $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 |
|
13 | |||
14 | #**************************************************************************** |
|
14 | #**************************************************************************** | |
15 | # Modules and globals |
|
15 | # Modules and globals | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
18 | __author__ = '%s <%s>\n%s <%s>' % \ | |
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
20 | __license__ = Release.license |
|
20 | __license__ = Release.license | |
21 |
|
21 | |||
22 | # Python standard modules |
|
22 | # Python standard modules | |
23 | import __builtin__ |
|
23 | import __builtin__ | |
24 | import bdb |
|
24 | import bdb | |
25 | import inspect |
|
25 | import inspect | |
26 | import os |
|
26 | import os | |
27 | import pdb |
|
27 | import pdb | |
28 | import pydoc |
|
28 | import pydoc | |
29 | import shlex |
|
|||
30 | import sys |
|
29 | import sys | |
31 | import re |
|
30 | import re | |
32 | import tempfile |
|
31 | import tempfile | |
33 | import time |
|
32 | import time | |
34 | import cPickle as pickle |
|
33 | import cPickle as pickle | |
35 | import textwrap |
|
34 | import textwrap | |
36 | from cStringIO import StringIO |
|
35 | from cStringIO import StringIO | |
37 | from getopt import getopt,GetoptError |
|
36 | from getopt import getopt,GetoptError | |
38 | from pprint import pprint, pformat |
|
37 | from pprint import pprint, pformat | |
39 |
|
38 | |||
40 | # profile isn't bundled by default in Debian for license reasons |
|
39 | # profile isn't bundled by default in Debian for license reasons | |
41 | try: |
|
40 | try: | |
42 | import profile,pstats |
|
41 | import profile,pstats | |
43 | except ImportError: |
|
42 | except ImportError: | |
44 | profile = pstats = None |
|
43 | profile = pstats = None | |
45 |
|
44 | |||
46 | # Homebrewed |
|
45 | # Homebrewed | |
47 | import IPython |
|
46 | import IPython | |
48 | from IPython import Debugger, OInspect, wildcard |
|
47 | from IPython import Debugger, OInspect, wildcard | |
49 | from IPython.FakeModule import FakeModule |
|
48 | from IPython.FakeModule import FakeModule | |
50 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
49 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
51 | from IPython.PyColorize import Parser |
|
50 | from IPython.PyColorize import Parser | |
52 | from IPython.ipstruct import Struct |
|
51 | from IPython.ipstruct import Struct | |
53 | from IPython.macro import Macro |
|
52 | from IPython.macro import Macro | |
54 | from IPython.genutils import * |
|
53 | from IPython.genutils import * | |
55 | from IPython import platutils |
|
54 | from IPython import platutils | |
56 |
|
55 | |||
57 | #*************************************************************************** |
|
56 | #*************************************************************************** | |
58 | # Utility functions |
|
57 | # Utility functions | |
59 | def on_off(tag): |
|
58 | def on_off(tag): | |
60 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
59 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
61 | return ['OFF','ON'][tag] |
|
60 | return ['OFF','ON'][tag] | |
62 |
|
61 | |||
63 | class Bunch: pass |
|
62 | class Bunch: pass | |
64 |
|
63 | |||
65 | def arg_split(s,posix=True): |
|
|||
66 | """Split a command line's arguments in a shell-like manner. |
|
|||
67 |
|
||||
68 | This is a modified version of the standard library's shlex.split() |
|
|||
69 | function, but with a default of posix=False for splitting, so that quotes |
|
|||
70 | in inputs are respected.""" |
|
|||
71 |
|
||||
72 | lex = shlex.shlex(s, posix=posix) |
|
|||
73 | lex.whitespace_split = True |
|
|||
74 | return list(lex) |
|
|||
75 |
|
||||
76 | #*************************************************************************** |
|
64 | #*************************************************************************** | |
77 | # Main class implementing Magic functionality |
|
65 | # Main class implementing Magic functionality | |
78 | class Magic: |
|
66 | class Magic: | |
79 | """Magic functions for InteractiveShell. |
|
67 | """Magic functions for InteractiveShell. | |
80 |
|
68 | |||
81 | Shell functions which can be reached as %function_name. All magic |
|
69 | Shell functions which can be reached as %function_name. All magic | |
82 | functions should accept a string, which they can parse for their own |
|
70 | functions should accept a string, which they can parse for their own | |
83 | needs. This can make some functions easier to type, eg `%cd ../` |
|
71 | needs. This can make some functions easier to type, eg `%cd ../` | |
84 | vs. `%cd("../")` |
|
72 | vs. `%cd("../")` | |
85 |
|
73 | |||
86 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
74 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
87 | at the command line, but it is is needed in the definition. """ |
|
75 | at the command line, but it is is needed in the definition. """ | |
88 |
|
76 | |||
89 | # class globals |
|
77 | # class globals | |
90 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
78 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
91 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
79 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
92 |
|
80 | |||
93 | #...................................................................... |
|
81 | #...................................................................... | |
94 | # some utility functions |
|
82 | # some utility functions | |
95 |
|
83 | |||
96 | def __init__(self,shell): |
|
84 | def __init__(self,shell): | |
97 |
|
85 | |||
98 | self.options_table = {} |
|
86 | self.options_table = {} | |
99 | if profile is None: |
|
87 | if profile is None: | |
100 | self.magic_prun = self.profile_missing_notice |
|
88 | self.magic_prun = self.profile_missing_notice | |
101 | self.shell = shell |
|
89 | self.shell = shell | |
102 |
|
90 | |||
103 | # namespace for holding state we may need |
|
91 | # namespace for holding state we may need | |
104 | self._magic_state = Bunch() |
|
92 | self._magic_state = Bunch() | |
105 |
|
93 | |||
106 | def profile_missing_notice(self, *args, **kwargs): |
|
94 | def profile_missing_notice(self, *args, **kwargs): | |
107 | error("""\ |
|
95 | error("""\ | |
108 | The profile module could not be found. If you are a Debian user, |
|
96 | The profile module could not be found. If you are a Debian user, | |
109 | it has been removed from the standard Debian package because of its non-free |
|
97 | it has been removed from the standard Debian package because of its non-free | |
110 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
98 | license. To use profiling, please install"python2.3-profiler" from non-free.""") | |
111 |
|
99 | |||
112 | def default_option(self,fn,optstr): |
|
100 | def default_option(self,fn,optstr): | |
113 | """Make an entry in the options_table for fn, with value optstr""" |
|
101 | """Make an entry in the options_table for fn, with value optstr""" | |
114 |
|
102 | |||
115 | if fn not in self.lsmagic(): |
|
103 | if fn not in self.lsmagic(): | |
116 | error("%s is not a magic function" % fn) |
|
104 | error("%s is not a magic function" % fn) | |
117 | self.options_table[fn] = optstr |
|
105 | self.options_table[fn] = optstr | |
118 |
|
106 | |||
119 | def lsmagic(self): |
|
107 | def lsmagic(self): | |
120 | """Return a list of currently available magic functions. |
|
108 | """Return a list of currently available magic functions. | |
121 |
|
109 | |||
122 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
110 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
123 | ['magic_ls','magic_cd',...]""" |
|
111 | ['magic_ls','magic_cd',...]""" | |
124 |
|
112 | |||
125 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
113 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
126 |
|
114 | |||
127 | # magics in class definition |
|
115 | # magics in class definition | |
128 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
116 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
129 | callable(Magic.__dict__[fn]) |
|
117 | callable(Magic.__dict__[fn]) | |
130 | # in instance namespace (run-time user additions) |
|
118 | # in instance namespace (run-time user additions) | |
131 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
119 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
132 | callable(self.__dict__[fn]) |
|
120 | callable(self.__dict__[fn]) | |
133 | # and bound magics by user (so they can access self): |
|
121 | # and bound magics by user (so they can access self): | |
134 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
122 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
135 | callable(self.__class__.__dict__[fn]) |
|
123 | callable(self.__class__.__dict__[fn]) | |
136 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
124 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
137 | filter(inst_magic,self.__dict__.keys()) + \ |
|
125 | filter(inst_magic,self.__dict__.keys()) + \ | |
138 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
126 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
139 | out = [] |
|
127 | out = [] | |
140 | for fn in magics: |
|
128 | for fn in magics: | |
141 | out.append(fn.replace('magic_','',1)) |
|
129 | out.append(fn.replace('magic_','',1)) | |
142 | out.sort() |
|
130 | out.sort() | |
143 | return out |
|
131 | return out | |
144 |
|
132 | |||
145 | def extract_input_slices(self,slices,raw=False): |
|
133 | def extract_input_slices(self,slices,raw=False): | |
146 | """Return as a string a set of input history slices. |
|
134 | """Return as a string a set of input history slices. | |
147 |
|
135 | |||
148 | Inputs: |
|
136 | Inputs: | |
149 |
|
137 | |||
150 | - slices: the set of slices is given as a list of strings (like |
|
138 | - slices: the set of slices is given as a list of strings (like | |
151 | ['1','4:8','9'], since this function is for use by magic functions |
|
139 | ['1','4:8','9'], since this function is for use by magic functions | |
152 | which get their arguments as strings. |
|
140 | which get their arguments as strings. | |
153 |
|
141 | |||
154 | Optional inputs: |
|
142 | Optional inputs: | |
155 |
|
143 | |||
156 | - raw(False): by default, the processed input is used. If this is |
|
144 | - raw(False): by default, the processed input is used. If this is | |
157 | true, the raw input history is used instead. |
|
145 | true, the raw input history is used instead. | |
158 |
|
146 | |||
159 | Note that slices can be called with two notations: |
|
147 | Note that slices can be called with two notations: | |
160 |
|
148 | |||
161 | N:M -> standard python form, means including items N...(M-1). |
|
149 | N:M -> standard python form, means including items N...(M-1). | |
162 |
|
150 | |||
163 | N-M -> include items N..M (closed endpoint).""" |
|
151 | N-M -> include items N..M (closed endpoint).""" | |
164 |
|
152 | |||
165 | if raw: |
|
153 | if raw: | |
166 | hist = self.shell.input_hist_raw |
|
154 | hist = self.shell.input_hist_raw | |
167 | else: |
|
155 | else: | |
168 | hist = self.shell.input_hist |
|
156 | hist = self.shell.input_hist | |
169 |
|
157 | |||
170 | cmds = [] |
|
158 | cmds = [] | |
171 | for chunk in slices: |
|
159 | for chunk in slices: | |
172 | if ':' in chunk: |
|
160 | if ':' in chunk: | |
173 | ini,fin = map(int,chunk.split(':')) |
|
161 | ini,fin = map(int,chunk.split(':')) | |
174 | elif '-' in chunk: |
|
162 | elif '-' in chunk: | |
175 | ini,fin = map(int,chunk.split('-')) |
|
163 | ini,fin = map(int,chunk.split('-')) | |
176 | fin += 1 |
|
164 | fin += 1 | |
177 | else: |
|
165 | else: | |
178 | ini = int(chunk) |
|
166 | ini = int(chunk) | |
179 | fin = ini+1 |
|
167 | fin = ini+1 | |
180 | cmds.append(hist[ini:fin]) |
|
168 | cmds.append(hist[ini:fin]) | |
181 | return cmds |
|
169 | return cmds | |
182 |
|
170 | |||
183 | def _ofind(self, oname, namespaces=None): |
|
171 | def _ofind(self, oname, namespaces=None): | |
184 | """Find an object in the available namespaces. |
|
172 | """Find an object in the available namespaces. | |
185 |
|
173 | |||
186 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
174 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
187 |
|
175 | |||
188 | Has special code to detect magic functions. |
|
176 | Has special code to detect magic functions. | |
189 | """ |
|
177 | """ | |
190 |
|
178 | |||
191 | oname = oname.strip() |
|
179 | oname = oname.strip() | |
192 |
|
180 | |||
193 | alias_ns = None |
|
181 | alias_ns = None | |
194 | if namespaces is None: |
|
182 | if namespaces is None: | |
195 | # Namespaces to search in: |
|
183 | # Namespaces to search in: | |
196 | # Put them in a list. The order is important so that we |
|
184 | # Put them in a list. The order is important so that we | |
197 | # find things in the same order that Python finds them. |
|
185 | # find things in the same order that Python finds them. | |
198 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
186 | namespaces = [ ('Interactive', self.shell.user_ns), | |
199 | ('IPython internal', self.shell.internal_ns), |
|
187 | ('IPython internal', self.shell.internal_ns), | |
200 | ('Python builtin', __builtin__.__dict__), |
|
188 | ('Python builtin', __builtin__.__dict__), | |
201 | ('Alias', self.shell.alias_table), |
|
189 | ('Alias', self.shell.alias_table), | |
202 | ] |
|
190 | ] | |
203 | alias_ns = self.shell.alias_table |
|
191 | alias_ns = self.shell.alias_table | |
204 |
|
192 | |||
205 | # initialize results to 'null' |
|
193 | # initialize results to 'null' | |
206 | found = 0; obj = None; ospace = None; ds = None; |
|
194 | found = 0; obj = None; ospace = None; ds = None; | |
207 | ismagic = 0; isalias = 0; parent = None |
|
195 | ismagic = 0; isalias = 0; parent = None | |
208 |
|
196 | |||
209 | # Look for the given name by splitting it in parts. If the head is |
|
197 | # Look for the given name by splitting it in parts. If the head is | |
210 | # found, then we look for all the remaining parts as members, and only |
|
198 | # found, then we look for all the remaining parts as members, and only | |
211 | # declare success if we can find them all. |
|
199 | # declare success if we can find them all. | |
212 | oname_parts = oname.split('.') |
|
200 | oname_parts = oname.split('.') | |
213 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
201 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
214 | for nsname,ns in namespaces: |
|
202 | for nsname,ns in namespaces: | |
215 | try: |
|
203 | try: | |
216 | obj = ns[oname_head] |
|
204 | obj = ns[oname_head] | |
217 | except KeyError: |
|
205 | except KeyError: | |
218 | continue |
|
206 | continue | |
219 | else: |
|
207 | else: | |
220 | for part in oname_rest: |
|
208 | for part in oname_rest: | |
221 | try: |
|
209 | try: | |
222 | parent = obj |
|
210 | parent = obj | |
223 | obj = getattr(obj,part) |
|
211 | obj = getattr(obj,part) | |
224 | except: |
|
212 | except: | |
225 | # Blanket except b/c some badly implemented objects |
|
213 | # Blanket except b/c some badly implemented objects | |
226 | # allow __getattr__ to raise exceptions other than |
|
214 | # allow __getattr__ to raise exceptions other than | |
227 | # AttributeError, which then crashes IPython. |
|
215 | # AttributeError, which then crashes IPython. | |
228 | break |
|
216 | break | |
229 | else: |
|
217 | else: | |
230 | # If we finish the for loop (no break), we got all members |
|
218 | # If we finish the for loop (no break), we got all members | |
231 | found = 1 |
|
219 | found = 1 | |
232 | ospace = nsname |
|
220 | ospace = nsname | |
233 | if ns == alias_ns: |
|
221 | if ns == alias_ns: | |
234 | isalias = 1 |
|
222 | isalias = 1 | |
235 | break # namespace loop |
|
223 | break # namespace loop | |
236 |
|
224 | |||
237 | # Try to see if it's magic |
|
225 | # Try to see if it's magic | |
238 | if not found: |
|
226 | if not found: | |
239 | if oname.startswith(self.shell.ESC_MAGIC): |
|
227 | if oname.startswith(self.shell.ESC_MAGIC): | |
240 | oname = oname[1:] |
|
228 | oname = oname[1:] | |
241 | obj = getattr(self,'magic_'+oname,None) |
|
229 | obj = getattr(self,'magic_'+oname,None) | |
242 | if obj is not None: |
|
230 | if obj is not None: | |
243 | found = 1 |
|
231 | found = 1 | |
244 | ospace = 'IPython internal' |
|
232 | ospace = 'IPython internal' | |
245 | ismagic = 1 |
|
233 | ismagic = 1 | |
246 |
|
234 | |||
247 | # Last try: special-case some literals like '', [], {}, etc: |
|
235 | # Last try: special-case some literals like '', [], {}, etc: | |
248 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
236 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
249 | obj = eval(oname_head) |
|
237 | obj = eval(oname_head) | |
250 | found = 1 |
|
238 | found = 1 | |
251 | ospace = 'Interactive' |
|
239 | ospace = 'Interactive' | |
252 |
|
240 | |||
253 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
241 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
254 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
242 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
255 |
|
243 | |||
256 | def arg_err(self,func): |
|
244 | def arg_err(self,func): | |
257 | """Print docstring if incorrect arguments were passed""" |
|
245 | """Print docstring if incorrect arguments were passed""" | |
258 | print 'Error in arguments:' |
|
246 | print 'Error in arguments:' | |
259 | print OInspect.getdoc(func) |
|
247 | print OInspect.getdoc(func) | |
260 |
|
248 | |||
261 | def format_latex(self,strng): |
|
249 | def format_latex(self,strng): | |
262 | """Format a string for latex inclusion.""" |
|
250 | """Format a string for latex inclusion.""" | |
263 |
|
251 | |||
264 | # Characters that need to be escaped for latex: |
|
252 | # Characters that need to be escaped for latex: | |
265 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
253 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
266 | # Magic command names as headers: |
|
254 | # Magic command names as headers: | |
267 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
255 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
268 | re.MULTILINE) |
|
256 | re.MULTILINE) | |
269 | # Magic commands |
|
257 | # Magic commands | |
270 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
258 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
271 | re.MULTILINE) |
|
259 | re.MULTILINE) | |
272 | # Paragraph continue |
|
260 | # Paragraph continue | |
273 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
261 | par_re = re.compile(r'\\$',re.MULTILINE) | |
274 |
|
262 | |||
275 | # The "\n" symbol |
|
263 | # The "\n" symbol | |
276 | newline_re = re.compile(r'\\n') |
|
264 | newline_re = re.compile(r'\\n') | |
277 |
|
265 | |||
278 | # Now build the string for output: |
|
266 | # Now build the string for output: | |
279 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
267 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
280 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
268 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
281 | strng) |
|
269 | strng) | |
282 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
270 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
283 | strng = par_re.sub(r'\\\\',strng) |
|
271 | strng = par_re.sub(r'\\\\',strng) | |
284 | strng = escape_re.sub(r'\\\1',strng) |
|
272 | strng = escape_re.sub(r'\\\1',strng) | |
285 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
273 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
286 | return strng |
|
274 | return strng | |
287 |
|
275 | |||
288 | def format_screen(self,strng): |
|
276 | def format_screen(self,strng): | |
289 | """Format a string for screen printing. |
|
277 | """Format a string for screen printing. | |
290 |
|
278 | |||
291 | This removes some latex-type format codes.""" |
|
279 | This removes some latex-type format codes.""" | |
292 | # Paragraph continue |
|
280 | # Paragraph continue | |
293 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
281 | par_re = re.compile(r'\\$',re.MULTILINE) | |
294 | strng = par_re.sub('',strng) |
|
282 | strng = par_re.sub('',strng) | |
295 | return strng |
|
283 | return strng | |
296 |
|
284 | |||
297 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
285 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
298 | """Parse options passed to an argument string. |
|
286 | """Parse options passed to an argument string. | |
299 |
|
287 | |||
300 | The interface is similar to that of getopt(), but it returns back a |
|
288 | The interface is similar to that of getopt(), but it returns back a | |
301 | Struct with the options as keys and the stripped argument string still |
|
289 | Struct with the options as keys and the stripped argument string still | |
302 | as a string. |
|
290 | as a string. | |
303 |
|
291 | |||
304 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
292 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
305 | This allows us to easily expand variables, glob files, quote |
|
293 | This allows us to easily expand variables, glob files, quote | |
306 | arguments, etc. |
|
294 | arguments, etc. | |
307 |
|
295 | |||
308 | Options: |
|
296 | Options: | |
309 | -mode: default 'string'. If given as 'list', the argument string is |
|
297 | -mode: default 'string'. If given as 'list', the argument string is | |
310 | returned as a list (split on whitespace) instead of a string. |
|
298 | returned as a list (split on whitespace) instead of a string. | |
311 |
|
299 | |||
312 | -list_all: put all option values in lists. Normally only options |
|
300 | -list_all: put all option values in lists. Normally only options | |
313 | appearing more than once are put in a list. |
|
301 | appearing more than once are put in a list. | |
314 |
|
302 | |||
315 | -posix (True): whether to split the input line in POSIX mode or not, |
|
303 | -posix (True): whether to split the input line in POSIX mode or not, | |
316 | as per the conventions outlined in the shlex module from the |
|
304 | as per the conventions outlined in the shlex module from the | |
317 | standard library.""" |
|
305 | standard library.""" | |
318 |
|
306 | |||
319 | # inject default options at the beginning of the input line |
|
307 | # inject default options at the beginning of the input line | |
320 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
308 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
321 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
309 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
322 |
|
310 | |||
323 | mode = kw.get('mode','string') |
|
311 | mode = kw.get('mode','string') | |
324 | if mode not in ['string','list']: |
|
312 | if mode not in ['string','list']: | |
325 | raise ValueError,'incorrect mode given: %s' % mode |
|
313 | raise ValueError,'incorrect mode given: %s' % mode | |
326 | # Get options |
|
314 | # Get options | |
327 | list_all = kw.get('list_all',0) |
|
315 | list_all = kw.get('list_all',0) | |
328 | posix = kw.get('posix',True) |
|
316 | posix = kw.get('posix',True) | |
329 |
|
317 | |||
330 | # Check if we have more than one argument to warrant extra processing: |
|
318 | # Check if we have more than one argument to warrant extra processing: | |
331 | odict = {} # Dictionary with options |
|
319 | odict = {} # Dictionary with options | |
332 | args = arg_str.split() |
|
320 | args = arg_str.split() | |
333 | if len(args) >= 1: |
|
321 | if len(args) >= 1: | |
334 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
322 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
335 | # need to look for options |
|
323 | # need to look for options | |
336 | argv = arg_split(arg_str,posix) |
|
324 | argv = arg_split(arg_str,posix) | |
337 | # Do regular option processing |
|
325 | # Do regular option processing | |
338 | try: |
|
326 | try: | |
339 | opts,args = getopt(argv,opt_str,*long_opts) |
|
327 | opts,args = getopt(argv,opt_str,*long_opts) | |
340 | except GetoptError,e: |
|
328 | except GetoptError,e: | |
341 | raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
329 | raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
342 | " ".join(long_opts))) |
|
330 | " ".join(long_opts))) | |
343 | for o,a in opts: |
|
331 | for o,a in opts: | |
344 | if o.startswith('--'): |
|
332 | if o.startswith('--'): | |
345 | o = o[2:] |
|
333 | o = o[2:] | |
346 | else: |
|
334 | else: | |
347 | o = o[1:] |
|
335 | o = o[1:] | |
348 | try: |
|
336 | try: | |
349 | odict[o].append(a) |
|
337 | odict[o].append(a) | |
350 | except AttributeError: |
|
338 | except AttributeError: | |
351 | odict[o] = [odict[o],a] |
|
339 | odict[o] = [odict[o],a] | |
352 | except KeyError: |
|
340 | except KeyError: | |
353 | if list_all: |
|
341 | if list_all: | |
354 | odict[o] = [a] |
|
342 | odict[o] = [a] | |
355 | else: |
|
343 | else: | |
356 | odict[o] = a |
|
344 | odict[o] = a | |
357 |
|
345 | |||
358 | # Prepare opts,args for return |
|
346 | # Prepare opts,args for return | |
359 | opts = Struct(odict) |
|
347 | opts = Struct(odict) | |
360 | if mode == 'string': |
|
348 | if mode == 'string': | |
361 | args = ' '.join(args) |
|
349 | args = ' '.join(args) | |
362 |
|
350 | |||
363 | return opts,args |
|
351 | return opts,args | |
364 |
|
352 | |||
365 | #...................................................................... |
|
353 | #...................................................................... | |
366 | # And now the actual magic functions |
|
354 | # And now the actual magic functions | |
367 |
|
355 | |||
368 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
356 | # Functions for IPython shell work (vars,funcs, config, etc) | |
369 | def magic_lsmagic(self, parameter_s = ''): |
|
357 | def magic_lsmagic(self, parameter_s = ''): | |
370 | """List currently available magic functions.""" |
|
358 | """List currently available magic functions.""" | |
371 | mesc = self.shell.ESC_MAGIC |
|
359 | mesc = self.shell.ESC_MAGIC | |
372 | print 'Available magic functions:\n'+mesc+\ |
|
360 | print 'Available magic functions:\n'+mesc+\ | |
373 | (' '+mesc).join(self.lsmagic()) |
|
361 | (' '+mesc).join(self.lsmagic()) | |
374 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
362 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
375 | return None |
|
363 | return None | |
376 |
|
364 | |||
377 | def magic_magic(self, parameter_s = ''): |
|
365 | def magic_magic(self, parameter_s = ''): | |
378 | """Print information about the magic function system.""" |
|
366 | """Print information about the magic function system.""" | |
379 |
|
367 | |||
380 | mode = '' |
|
368 | mode = '' | |
381 | try: |
|
369 | try: | |
382 | if parameter_s.split()[0] == '-latex': |
|
370 | if parameter_s.split()[0] == '-latex': | |
383 | mode = 'latex' |
|
371 | mode = 'latex' | |
384 | if parameter_s.split()[0] == '-brief': |
|
372 | if parameter_s.split()[0] == '-brief': | |
385 | mode = 'brief' |
|
373 | mode = 'brief' | |
386 | except: |
|
374 | except: | |
387 | pass |
|
375 | pass | |
388 |
|
376 | |||
389 | magic_docs = [] |
|
377 | magic_docs = [] | |
390 | for fname in self.lsmagic(): |
|
378 | for fname in self.lsmagic(): | |
391 | mname = 'magic_' + fname |
|
379 | mname = 'magic_' + fname | |
392 | for space in (Magic,self,self.__class__): |
|
380 | for space in (Magic,self,self.__class__): | |
393 | try: |
|
381 | try: | |
394 | fn = space.__dict__[mname] |
|
382 | fn = space.__dict__[mname] | |
395 | except KeyError: |
|
383 | except KeyError: | |
396 | pass |
|
384 | pass | |
397 | else: |
|
385 | else: | |
398 | break |
|
386 | break | |
399 | if mode == 'brief': |
|
387 | if mode == 'brief': | |
400 | # only first line |
|
388 | # only first line | |
401 | fndoc = fn.__doc__.split('\n',1)[0] |
|
389 | fndoc = fn.__doc__.split('\n',1)[0] | |
402 | else: |
|
390 | else: | |
403 | fndoc = fn.__doc__ |
|
391 | fndoc = fn.__doc__ | |
404 |
|
392 | |||
405 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
393 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
406 | fname,fndoc)) |
|
394 | fname,fndoc)) | |
407 | magic_docs = ''.join(magic_docs) |
|
395 | magic_docs = ''.join(magic_docs) | |
408 |
|
396 | |||
409 | if mode == 'latex': |
|
397 | if mode == 'latex': | |
410 | print self.format_latex(magic_docs) |
|
398 | print self.format_latex(magic_docs) | |
411 | return |
|
399 | return | |
412 | else: |
|
400 | else: | |
413 | magic_docs = self.format_screen(magic_docs) |
|
401 | magic_docs = self.format_screen(magic_docs) | |
414 | if mode == 'brief': |
|
402 | if mode == 'brief': | |
415 | return magic_docs |
|
403 | return magic_docs | |
416 |
|
404 | |||
417 | outmsg = """ |
|
405 | outmsg = """ | |
418 | IPython's 'magic' functions |
|
406 | IPython's 'magic' functions | |
419 | =========================== |
|
407 | =========================== | |
420 |
|
408 | |||
421 | The magic function system provides a series of functions which allow you to |
|
409 | The magic function system provides a series of functions which allow you to | |
422 | control the behavior of IPython itself, plus a lot of system-type |
|
410 | control the behavior of IPython itself, plus a lot of system-type | |
423 | features. All these functions are prefixed with a % character, but parameters |
|
411 | features. All these functions are prefixed with a % character, but parameters | |
424 | are given without parentheses or quotes. |
|
412 | are given without parentheses or quotes. | |
425 |
|
413 | |||
426 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
414 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
427 | %automagic function), you don't need to type in the % explicitly. By default, |
|
415 | %automagic function), you don't need to type in the % explicitly. By default, | |
428 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
416 | IPython ships with automagic on, so you should only rarely need the % escape. | |
429 |
|
417 | |||
430 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
418 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
431 | to 'mydir', if it exists. |
|
419 | to 'mydir', if it exists. | |
432 |
|
420 | |||
433 | You can define your own magic functions to extend the system. See the supplied |
|
421 | You can define your own magic functions to extend the system. See the supplied | |
434 | ipythonrc and example-magic.py files for details (in your ipython |
|
422 | ipythonrc and example-magic.py files for details (in your ipython | |
435 | configuration directory, typically $HOME/.ipython/). |
|
423 | configuration directory, typically $HOME/.ipython/). | |
436 |
|
424 | |||
437 | You can also define your own aliased names for magic functions. In your |
|
425 | You can also define your own aliased names for magic functions. In your | |
438 | ipythonrc file, placing a line like: |
|
426 | ipythonrc file, placing a line like: | |
439 |
|
427 | |||
440 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
428 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
441 |
|
429 | |||
442 | will define %pf as a new name for %profile. |
|
430 | will define %pf as a new name for %profile. | |
443 |
|
431 | |||
444 | You can also call magics in code using the ipmagic() function, which IPython |
|
432 | You can also call magics in code using the ipmagic() function, which IPython | |
445 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
433 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
446 |
|
434 | |||
447 | For a list of the available magic functions, use %lsmagic. For a description |
|
435 | For a list of the available magic functions, use %lsmagic. For a description | |
448 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
436 | of any of them, type %magic_name?, e.g. '%cd?'. | |
449 |
|
437 | |||
450 | Currently the magic system has the following functions:\n""" |
|
438 | Currently the magic system has the following functions:\n""" | |
451 |
|
439 | |||
452 | mesc = self.shell.ESC_MAGIC |
|
440 | mesc = self.shell.ESC_MAGIC | |
453 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
441 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
454 | "\n\n%s%s\n\n%s" % (outmsg, |
|
442 | "\n\n%s%s\n\n%s" % (outmsg, | |
455 | magic_docs,mesc,mesc, |
|
443 | magic_docs,mesc,mesc, | |
456 | (' '+mesc).join(self.lsmagic()), |
|
444 | (' '+mesc).join(self.lsmagic()), | |
457 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
445 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
458 |
|
446 | |||
459 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
447 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
460 |
|
448 | |||
461 | def magic_automagic(self, parameter_s = ''): |
|
449 | def magic_automagic(self, parameter_s = ''): | |
462 | """Make magic functions callable without having to type the initial %. |
|
450 | """Make magic functions callable without having to type the initial %. | |
463 |
|
451 | |||
464 | Toggles on/off (when off, you must call it as %automagic, of |
|
452 | Toggles on/off (when off, you must call it as %automagic, of | |
465 | course). Note that magic functions have lowest priority, so if there's |
|
453 | course). Note that magic functions have lowest priority, so if there's | |
466 | a variable whose name collides with that of a magic fn, automagic |
|
454 | a variable whose name collides with that of a magic fn, automagic | |
467 | won't work for that function (you get the variable instead). However, |
|
455 | won't work for that function (you get the variable instead). However, | |
468 | if you delete the variable (del var), the previously shadowed magic |
|
456 | if you delete the variable (del var), the previously shadowed magic | |
469 | function becomes visible to automagic again.""" |
|
457 | function becomes visible to automagic again.""" | |
470 |
|
458 | |||
471 | rc = self.shell.rc |
|
459 | rc = self.shell.rc | |
472 | rc.automagic = not rc.automagic |
|
460 | rc.automagic = not rc.automagic | |
473 | print '\n' + Magic.auto_status[rc.automagic] |
|
461 | print '\n' + Magic.auto_status[rc.automagic] | |
474 |
|
462 | |||
475 | def magic_autocall(self, parameter_s = ''): |
|
463 | def magic_autocall(self, parameter_s = ''): | |
476 | """Make functions callable without having to type parentheses. |
|
464 | """Make functions callable without having to type parentheses. | |
477 |
|
465 | |||
478 | Usage: |
|
466 | Usage: | |
479 |
|
467 | |||
480 | %autocall [mode] |
|
468 | %autocall [mode] | |
481 |
|
469 | |||
482 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
470 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
483 | value is toggled on and off (remembering the previous state).""" |
|
471 | value is toggled on and off (remembering the previous state).""" | |
484 |
|
472 | |||
485 | rc = self.shell.rc |
|
473 | rc = self.shell.rc | |
486 |
|
474 | |||
487 | if parameter_s: |
|
475 | if parameter_s: | |
488 | arg = int(parameter_s) |
|
476 | arg = int(parameter_s) | |
489 | else: |
|
477 | else: | |
490 | arg = 'toggle' |
|
478 | arg = 'toggle' | |
491 |
|
479 | |||
492 | if not arg in (0,1,2,'toggle'): |
|
480 | if not arg in (0,1,2,'toggle'): | |
493 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
481 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
494 | return |
|
482 | return | |
495 |
|
483 | |||
496 | if arg in (0,1,2): |
|
484 | if arg in (0,1,2): | |
497 | rc.autocall = arg |
|
485 | rc.autocall = arg | |
498 | else: # toggle |
|
486 | else: # toggle | |
499 | if rc.autocall: |
|
487 | if rc.autocall: | |
500 | self._magic_state.autocall_save = rc.autocall |
|
488 | self._magic_state.autocall_save = rc.autocall | |
501 | rc.autocall = 0 |
|
489 | rc.autocall = 0 | |
502 | else: |
|
490 | else: | |
503 | try: |
|
491 | try: | |
504 | rc.autocall = self._magic_state.autocall_save |
|
492 | rc.autocall = self._magic_state.autocall_save | |
505 | except AttributeError: |
|
493 | except AttributeError: | |
506 | rc.autocall = self._magic_state.autocall_save = 1 |
|
494 | rc.autocall = self._magic_state.autocall_save = 1 | |
507 |
|
495 | |||
508 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
496 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] | |
509 |
|
497 | |||
510 | def magic_autoindent(self, parameter_s = ''): |
|
498 | def magic_autoindent(self, parameter_s = ''): | |
511 | """Toggle autoindent on/off (if available).""" |
|
499 | """Toggle autoindent on/off (if available).""" | |
512 |
|
500 | |||
513 | self.shell.set_autoindent() |
|
501 | self.shell.set_autoindent() | |
514 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
502 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
515 |
|
503 | |||
516 | def magic_system_verbose(self, parameter_s = ''): |
|
504 | def magic_system_verbose(self, parameter_s = ''): | |
517 | """Toggle verbose printing of system calls on/off.""" |
|
505 | """Toggle verbose printing of system calls on/off.""" | |
518 |
|
506 | |||
519 | self.shell.rc_set_toggle('system_verbose') |
|
507 | self.shell.rc_set_toggle('system_verbose') | |
520 | print "System verbose printing is:",\ |
|
508 | print "System verbose printing is:",\ | |
521 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
509 | ['OFF','ON'][self.shell.rc.system_verbose] | |
522 |
|
510 | |||
523 | def magic_history(self, parameter_s = ''): |
|
511 | def magic_history(self, parameter_s = ''): | |
524 | """Print input history (_i<n> variables), with most recent last. |
|
512 | """Print input history (_i<n> variables), with most recent last. | |
525 |
|
513 | |||
526 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
514 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
527 | %history n -> print at most n inputs\\ |
|
515 | %history n -> print at most n inputs\\ | |
528 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
516 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
529 |
|
517 | |||
530 | Each input's number <n> is shown, and is accessible as the |
|
518 | Each input's number <n> is shown, and is accessible as the | |
531 | automatically generated variable _i<n>. Multi-line statements are |
|
519 | automatically generated variable _i<n>. Multi-line statements are | |
532 | printed starting at a new line for easy copy/paste. |
|
520 | printed starting at a new line for easy copy/paste. | |
533 |
|
521 | |||
534 |
|
522 | |||
535 | Options: |
|
523 | Options: | |
536 |
|
524 | |||
537 | -n: do NOT print line numbers. This is useful if you want to get a |
|
525 | -n: do NOT print line numbers. This is useful if you want to get a | |
538 | printout of many lines which can be directly pasted into a text |
|
526 | printout of many lines which can be directly pasted into a text | |
539 | editor. |
|
527 | editor. | |
540 |
|
528 | |||
541 | This feature is only available if numbered prompts are in use. |
|
529 | This feature is only available if numbered prompts are in use. | |
542 |
|
530 | |||
543 | -r: print the 'raw' history. IPython filters your input and |
|
531 | -r: print the 'raw' history. IPython filters your input and | |
544 | converts it all into valid Python source before executing it (things |
|
532 | converts it all into valid Python source before executing it (things | |
545 | like magics or aliases are turned into function calls, for |
|
533 | like magics or aliases are turned into function calls, for | |
546 | example). With this option, you'll see the unfiltered history |
|
534 | example). With this option, you'll see the unfiltered history | |
547 | instead of the filtered version: '%cd /' will be seen as '%cd /' |
|
535 | instead of the filtered version: '%cd /' will be seen as '%cd /' | |
548 | instead of '_ip.magic("%cd /")'. |
|
536 | instead of '_ip.magic("%cd /")'. | |
549 | """ |
|
537 | """ | |
550 |
|
538 | |||
551 | shell = self.shell |
|
539 | shell = self.shell | |
552 | if not shell.outputcache.do_full_cache: |
|
540 | if not shell.outputcache.do_full_cache: | |
553 | print 'This feature is only available if numbered prompts are in use.' |
|
541 | print 'This feature is only available if numbered prompts are in use.' | |
554 | return |
|
542 | return | |
555 | opts,args = self.parse_options(parameter_s,'nr',mode='list') |
|
543 | opts,args = self.parse_options(parameter_s,'nr',mode='list') | |
556 |
|
544 | |||
557 | if opts.has_key('r'): |
|
545 | if opts.has_key('r'): | |
558 | input_hist = shell.input_hist_raw |
|
546 | input_hist = shell.input_hist_raw | |
559 | else: |
|
547 | else: | |
560 | input_hist = shell.input_hist |
|
548 | input_hist = shell.input_hist | |
561 |
|
549 | |||
562 | default_length = 40 |
|
550 | default_length = 40 | |
563 | if len(args) == 0: |
|
551 | if len(args) == 0: | |
564 | final = len(input_hist) |
|
552 | final = len(input_hist) | |
565 | init = max(1,final-default_length) |
|
553 | init = max(1,final-default_length) | |
566 | elif len(args) == 1: |
|
554 | elif len(args) == 1: | |
567 | final = len(input_hist) |
|
555 | final = len(input_hist) | |
568 | init = max(1,final-int(args[0])) |
|
556 | init = max(1,final-int(args[0])) | |
569 | elif len(args) == 2: |
|
557 | elif len(args) == 2: | |
570 | init,final = map(int,args) |
|
558 | init,final = map(int,args) | |
571 | else: |
|
559 | else: | |
572 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
560 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
573 | print self.magic_hist.__doc__ |
|
561 | print self.magic_hist.__doc__ | |
574 | return |
|
562 | return | |
575 | width = len(str(final)) |
|
563 | width = len(str(final)) | |
576 | line_sep = ['','\n'] |
|
564 | line_sep = ['','\n'] | |
577 | print_nums = not opts.has_key('n') |
|
565 | print_nums = not opts.has_key('n') | |
578 | for in_num in range(init,final): |
|
566 | for in_num in range(init,final): | |
579 | inline = input_hist[in_num] |
|
567 | inline = input_hist[in_num] | |
580 | multiline = int(inline.count('\n') > 1) |
|
568 | multiline = int(inline.count('\n') > 1) | |
581 | if print_nums: |
|
569 | if print_nums: | |
582 | print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), |
|
570 | print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), | |
583 | print inline, |
|
571 | print inline, | |
584 |
|
572 | |||
585 | def magic_hist(self, parameter_s=''): |
|
573 | def magic_hist(self, parameter_s=''): | |
586 | """Alternate name for %history.""" |
|
574 | """Alternate name for %history.""" | |
587 | return self.magic_history(parameter_s) |
|
575 | return self.magic_history(parameter_s) | |
588 |
|
576 | |||
589 | def magic_p(self, parameter_s=''): |
|
577 | def magic_p(self, parameter_s=''): | |
590 | """Just a short alias for Python's 'print'.""" |
|
578 | """Just a short alias for Python's 'print'.""" | |
591 | exec 'print ' + parameter_s in self.shell.user_ns |
|
579 | exec 'print ' + parameter_s in self.shell.user_ns | |
592 |
|
580 | |||
593 | def magic_r(self, parameter_s=''): |
|
581 | def magic_r(self, parameter_s=''): | |
594 | """Repeat previous input. |
|
582 | """Repeat previous input. | |
595 |
|
583 | |||
596 | If given an argument, repeats the previous command which starts with |
|
584 | If given an argument, repeats the previous command which starts with | |
597 | the same string, otherwise it just repeats the previous input. |
|
585 | the same string, otherwise it just repeats the previous input. | |
598 |
|
586 | |||
599 | Shell escaped commands (with ! as first character) are not recognized |
|
587 | Shell escaped commands (with ! as first character) are not recognized | |
600 | by this system, only pure python code and magic commands. |
|
588 | by this system, only pure python code and magic commands. | |
601 | """ |
|
589 | """ | |
602 |
|
590 | |||
603 | start = parameter_s.strip() |
|
591 | start = parameter_s.strip() | |
604 | esc_magic = self.shell.ESC_MAGIC |
|
592 | esc_magic = self.shell.ESC_MAGIC | |
605 | # Identify magic commands even if automagic is on (which means |
|
593 | # Identify magic commands even if automagic is on (which means | |
606 | # the in-memory version is different from that typed by the user). |
|
594 | # the in-memory version is different from that typed by the user). | |
607 | if self.shell.rc.automagic: |
|
595 | if self.shell.rc.automagic: | |
608 | start_magic = esc_magic+start |
|
596 | start_magic = esc_magic+start | |
609 | else: |
|
597 | else: | |
610 | start_magic = start |
|
598 | start_magic = start | |
611 | # Look through the input history in reverse |
|
599 | # Look through the input history in reverse | |
612 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
600 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
613 | input = self.shell.input_hist[n] |
|
601 | input = self.shell.input_hist[n] | |
614 | # skip plain 'r' lines so we don't recurse to infinity |
|
602 | # skip plain 'r' lines so we don't recurse to infinity | |
615 | if input != '_ip.magic("r")\n' and \ |
|
603 | if input != '_ip.magic("r")\n' and \ | |
616 | (input.startswith(start) or input.startswith(start_magic)): |
|
604 | (input.startswith(start) or input.startswith(start_magic)): | |
617 | #print 'match',`input` # dbg |
|
605 | #print 'match',`input` # dbg | |
618 | print 'Executing:',input, |
|
606 | print 'Executing:',input, | |
619 | self.shell.runlines(input) |
|
607 | self.shell.runlines(input) | |
620 | return |
|
608 | return | |
621 | print 'No previous input matching `%s` found.' % start |
|
609 | print 'No previous input matching `%s` found.' % start | |
622 |
|
610 | |||
623 | def magic_page(self, parameter_s=''): |
|
611 | def magic_page(self, parameter_s=''): | |
624 | """Pretty print the object and display it through a pager. |
|
612 | """Pretty print the object and display it through a pager. | |
625 |
|
613 | |||
626 | If no parameter is given, use _ (last output).""" |
|
614 | If no parameter is given, use _ (last output).""" | |
627 | # After a function contributed by Olivier Aubert, slightly modified. |
|
615 | # After a function contributed by Olivier Aubert, slightly modified. | |
628 |
|
616 | |||
629 | oname = parameter_s and parameter_s or '_' |
|
617 | oname = parameter_s and parameter_s or '_' | |
630 | info = self._ofind(oname) |
|
618 | info = self._ofind(oname) | |
631 | if info['found']: |
|
619 | if info['found']: | |
632 | page(pformat(info['obj'])) |
|
620 | page(pformat(info['obj'])) | |
633 | else: |
|
621 | else: | |
634 | print 'Object `%s` not found' % oname |
|
622 | print 'Object `%s` not found' % oname | |
635 |
|
623 | |||
636 | def magic_profile(self, parameter_s=''): |
|
624 | def magic_profile(self, parameter_s=''): | |
637 | """Print your currently active IPyhton profile.""" |
|
625 | """Print your currently active IPyhton profile.""" | |
638 | if self.shell.rc.profile: |
|
626 | if self.shell.rc.profile: | |
639 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
627 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
640 | else: |
|
628 | else: | |
641 | print 'No profile active.' |
|
629 | print 'No profile active.' | |
642 |
|
630 | |||
643 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
631 | def _inspect(self,meth,oname,namespaces=None,**kw): | |
644 | """Generic interface to the inspector system. |
|
632 | """Generic interface to the inspector system. | |
645 |
|
633 | |||
646 | This function is meant to be called by pdef, pdoc & friends.""" |
|
634 | This function is meant to be called by pdef, pdoc & friends.""" | |
647 |
|
635 | |||
648 | oname = oname.strip() |
|
636 | oname = oname.strip() | |
649 | info = Struct(self._ofind(oname, namespaces)) |
|
637 | info = Struct(self._ofind(oname, namespaces)) | |
650 |
|
638 | |||
651 | if info.found: |
|
639 | if info.found: | |
652 | # Get the docstring of the class property if it exists. |
|
640 | # Get the docstring of the class property if it exists. | |
653 | path = oname.split('.') |
|
641 | path = oname.split('.') | |
654 | root = '.'.join(path[:-1]) |
|
642 | root = '.'.join(path[:-1]) | |
655 | if info.parent is not None: |
|
643 | if info.parent is not None: | |
656 | try: |
|
644 | try: | |
657 | target = getattr(info.parent, '__class__') |
|
645 | target = getattr(info.parent, '__class__') | |
658 | # The object belongs to a class instance. |
|
646 | # The object belongs to a class instance. | |
659 | try: |
|
647 | try: | |
660 | target = getattr(target, path[-1]) |
|
648 | target = getattr(target, path[-1]) | |
661 | # The class defines the object. |
|
649 | # The class defines the object. | |
662 | if isinstance(target, property): |
|
650 | if isinstance(target, property): | |
663 | oname = root + '.__class__.' + path[-1] |
|
651 | oname = root + '.__class__.' + path[-1] | |
664 | info = Struct(self._ofind(oname)) |
|
652 | info = Struct(self._ofind(oname)) | |
665 | except AttributeError: pass |
|
653 | except AttributeError: pass | |
666 | except AttributeError: pass |
|
654 | except AttributeError: pass | |
667 |
|
655 | |||
668 | pmethod = getattr(self.shell.inspector,meth) |
|
656 | pmethod = getattr(self.shell.inspector,meth) | |
669 | formatter = info.ismagic and self.format_screen or None |
|
657 | formatter = info.ismagic and self.format_screen or None | |
670 | if meth == 'pdoc': |
|
658 | if meth == 'pdoc': | |
671 | pmethod(info.obj,oname,formatter) |
|
659 | pmethod(info.obj,oname,formatter) | |
672 | elif meth == 'pinfo': |
|
660 | elif meth == 'pinfo': | |
673 | pmethod(info.obj,oname,formatter,info,**kw) |
|
661 | pmethod(info.obj,oname,formatter,info,**kw) | |
674 | else: |
|
662 | else: | |
675 | pmethod(info.obj,oname) |
|
663 | pmethod(info.obj,oname) | |
676 | else: |
|
664 | else: | |
677 | print 'Object `%s` not found.' % oname |
|
665 | print 'Object `%s` not found.' % oname | |
678 | return 'not found' # so callers can take other action |
|
666 | return 'not found' # so callers can take other action | |
679 |
|
667 | |||
680 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
668 | def magic_pdef(self, parameter_s='', namespaces=None): | |
681 | """Print the definition header for any callable object. |
|
669 | """Print the definition header for any callable object. | |
682 |
|
670 | |||
683 | If the object is a class, print the constructor information.""" |
|
671 | If the object is a class, print the constructor information.""" | |
684 | print "+++" |
|
672 | print "+++" | |
685 | self._inspect('pdef',parameter_s, namespaces) |
|
673 | self._inspect('pdef',parameter_s, namespaces) | |
686 |
|
674 | |||
687 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
675 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
688 | """Print the docstring for an object. |
|
676 | """Print the docstring for an object. | |
689 |
|
677 | |||
690 | If the given object is a class, it will print both the class and the |
|
678 | If the given object is a class, it will print both the class and the | |
691 | constructor docstrings.""" |
|
679 | constructor docstrings.""" | |
692 | self._inspect('pdoc',parameter_s, namespaces) |
|
680 | self._inspect('pdoc',parameter_s, namespaces) | |
693 |
|
681 | |||
694 | def magic_psource(self, parameter_s='', namespaces=None): |
|
682 | def magic_psource(self, parameter_s='', namespaces=None): | |
695 | """Print (or run through pager) the source code for an object.""" |
|
683 | """Print (or run through pager) the source code for an object.""" | |
696 | self._inspect('psource',parameter_s, namespaces) |
|
684 | self._inspect('psource',parameter_s, namespaces) | |
697 |
|
685 | |||
698 | def magic_pfile(self, parameter_s=''): |
|
686 | def magic_pfile(self, parameter_s=''): | |
699 | """Print (or run through pager) the file where an object is defined. |
|
687 | """Print (or run through pager) the file where an object is defined. | |
700 |
|
688 | |||
701 | The file opens at the line where the object definition begins. IPython |
|
689 | The file opens at the line where the object definition begins. IPython | |
702 | will honor the environment variable PAGER if set, and otherwise will |
|
690 | will honor the environment variable PAGER if set, and otherwise will | |
703 | do its best to print the file in a convenient form. |
|
691 | do its best to print the file in a convenient form. | |
704 |
|
692 | |||
705 | If the given argument is not an object currently defined, IPython will |
|
693 | If the given argument is not an object currently defined, IPython will | |
706 | try to interpret it as a filename (automatically adding a .py extension |
|
694 | try to interpret it as a filename (automatically adding a .py extension | |
707 | if needed). You can thus use %pfile as a syntax highlighting code |
|
695 | if needed). You can thus use %pfile as a syntax highlighting code | |
708 | viewer.""" |
|
696 | viewer.""" | |
709 |
|
697 | |||
710 | # first interpret argument as an object name |
|
698 | # first interpret argument as an object name | |
711 | out = self._inspect('pfile',parameter_s) |
|
699 | out = self._inspect('pfile',parameter_s) | |
712 | # if not, try the input as a filename |
|
700 | # if not, try the input as a filename | |
713 | if out == 'not found': |
|
701 | if out == 'not found': | |
714 | try: |
|
702 | try: | |
715 | filename = get_py_filename(parameter_s) |
|
703 | filename = get_py_filename(parameter_s) | |
716 | except IOError,msg: |
|
704 | except IOError,msg: | |
717 | print msg |
|
705 | print msg | |
718 | return |
|
706 | return | |
719 | page(self.shell.inspector.format(file(filename).read())) |
|
707 | page(self.shell.inspector.format(file(filename).read())) | |
720 |
|
708 | |||
721 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
709 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
722 | """Provide detailed information about an object. |
|
710 | """Provide detailed information about an object. | |
723 |
|
711 | |||
724 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
712 | '%pinfo object' is just a synonym for object? or ?object.""" | |
725 |
|
713 | |||
726 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
714 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
727 |
|
715 | |||
728 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
716 | # detail_level: 0 -> obj? , 1 -> obj?? | |
729 | detail_level = 0 |
|
717 | detail_level = 0 | |
730 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
718 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
731 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
719 | # happen if the user types 'pinfo foo?' at the cmd line. | |
732 | pinfo,qmark1,oname,qmark2 = \ |
|
720 | pinfo,qmark1,oname,qmark2 = \ | |
733 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
721 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
734 | if pinfo or qmark1 or qmark2: |
|
722 | if pinfo or qmark1 or qmark2: | |
735 | detail_level = 1 |
|
723 | detail_level = 1 | |
736 | if "*" in oname: |
|
724 | if "*" in oname: | |
737 | self.magic_psearch(oname) |
|
725 | self.magic_psearch(oname) | |
738 | else: |
|
726 | else: | |
739 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
727 | self._inspect('pinfo', oname, detail_level=detail_level, | |
740 | namespaces=namespaces) |
|
728 | namespaces=namespaces) | |
741 |
|
729 | |||
742 | def magic_psearch(self, parameter_s=''): |
|
730 | def magic_psearch(self, parameter_s=''): | |
743 | """Search for object in namespaces by wildcard. |
|
731 | """Search for object in namespaces by wildcard. | |
744 |
|
732 | |||
745 | %psearch [options] PATTERN [OBJECT TYPE] |
|
733 | %psearch [options] PATTERN [OBJECT TYPE] | |
746 |
|
734 | |||
747 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
735 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
748 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
736 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
749 | rest of the command line must be unchanged (options come first), so |
|
737 | rest of the command line must be unchanged (options come first), so | |
750 | for example the following forms are equivalent |
|
738 | for example the following forms are equivalent | |
751 |
|
739 | |||
752 | %psearch -i a* function |
|
740 | %psearch -i a* function | |
753 | -i a* function? |
|
741 | -i a* function? | |
754 | ?-i a* function |
|
742 | ?-i a* function | |
755 |
|
743 | |||
756 | Arguments: |
|
744 | Arguments: | |
757 |
|
745 | |||
758 | PATTERN |
|
746 | PATTERN | |
759 |
|
747 | |||
760 | where PATTERN is a string containing * as a wildcard similar to its |
|
748 | where PATTERN is a string containing * as a wildcard similar to its | |
761 | use in a shell. The pattern is matched in all namespaces on the |
|
749 | use in a shell. The pattern is matched in all namespaces on the | |
762 | search path. By default objects starting with a single _ are not |
|
750 | search path. By default objects starting with a single _ are not | |
763 | matched, many IPython generated objects have a single |
|
751 | matched, many IPython generated objects have a single | |
764 | underscore. The default is case insensitive matching. Matching is |
|
752 | underscore. The default is case insensitive matching. Matching is | |
765 | also done on the attributes of objects and not only on the objects |
|
753 | also done on the attributes of objects and not only on the objects | |
766 | in a module. |
|
754 | in a module. | |
767 |
|
755 | |||
768 | [OBJECT TYPE] |
|
756 | [OBJECT TYPE] | |
769 |
|
757 | |||
770 | Is the name of a python type from the types module. The name is |
|
758 | Is the name of a python type from the types module. The name is | |
771 | given in lowercase without the ending type, ex. StringType is |
|
759 | given in lowercase without the ending type, ex. StringType is | |
772 | written string. By adding a type here only objects matching the |
|
760 | written string. By adding a type here only objects matching the | |
773 | given type are matched. Using all here makes the pattern match all |
|
761 | given type are matched. Using all here makes the pattern match all | |
774 | types (this is the default). |
|
762 | types (this is the default). | |
775 |
|
763 | |||
776 | Options: |
|
764 | Options: | |
777 |
|
765 | |||
778 | -a: makes the pattern match even objects whose names start with a |
|
766 | -a: makes the pattern match even objects whose names start with a | |
779 | single underscore. These names are normally ommitted from the |
|
767 | single underscore. These names are normally ommitted from the | |
780 | search. |
|
768 | search. | |
781 |
|
769 | |||
782 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
770 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
783 | these options is given, the default is read from your ipythonrc |
|
771 | these options is given, the default is read from your ipythonrc | |
784 | file. The option name which sets this value is |
|
772 | file. The option name which sets this value is | |
785 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
773 | 'wildcards_case_sensitive'. If this option is not specified in your | |
786 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
774 | ipythonrc file, IPython's internal default is to do a case sensitive | |
787 | search. |
|
775 | search. | |
788 |
|
776 | |||
789 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
777 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
790 | specifiy can be searched in any of the following namespaces: |
|
778 | specifiy can be searched in any of the following namespaces: | |
791 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
779 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
792 | 'builtin' and 'user' are the search defaults. Note that you should |
|
780 | 'builtin' and 'user' are the search defaults. Note that you should | |
793 | not use quotes when specifying namespaces. |
|
781 | not use quotes when specifying namespaces. | |
794 |
|
782 | |||
795 | 'Builtin' contains the python module builtin, 'user' contains all |
|
783 | 'Builtin' contains the python module builtin, 'user' contains all | |
796 | user data, 'alias' only contain the shell aliases and no python |
|
784 | user data, 'alias' only contain the shell aliases and no python | |
797 | objects, 'internal' contains objects used by IPython. The |
|
785 | objects, 'internal' contains objects used by IPython. The | |
798 | 'user_global' namespace is only used by embedded IPython instances, |
|
786 | 'user_global' namespace is only used by embedded IPython instances, | |
799 | and it contains module-level globals. You can add namespaces to the |
|
787 | and it contains module-level globals. You can add namespaces to the | |
800 | search with -s or exclude them with -e (these options can be given |
|
788 | search with -s or exclude them with -e (these options can be given | |
801 | more than once). |
|
789 | more than once). | |
802 |
|
790 | |||
803 | Examples: |
|
791 | Examples: | |
804 |
|
792 | |||
805 | %psearch a* -> objects beginning with an a |
|
793 | %psearch a* -> objects beginning with an a | |
806 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
794 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
807 | %psearch a* function -> all functions beginning with an a |
|
795 | %psearch a* function -> all functions beginning with an a | |
808 | %psearch re.e* -> objects beginning with an e in module re |
|
796 | %psearch re.e* -> objects beginning with an e in module re | |
809 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
797 | %psearch r*.e* -> objects that start with e in modules starting in r | |
810 | %psearch r*.* string -> all strings in modules beginning with r |
|
798 | %psearch r*.* string -> all strings in modules beginning with r | |
811 |
|
799 | |||
812 | Case sensitve search: |
|
800 | Case sensitve search: | |
813 |
|
801 | |||
814 | %psearch -c a* list all object beginning with lower case a |
|
802 | %psearch -c a* list all object beginning with lower case a | |
815 |
|
803 | |||
816 | Show objects beginning with a single _: |
|
804 | Show objects beginning with a single _: | |
817 |
|
805 | |||
818 | %psearch -a _* list objects beginning with a single underscore""" |
|
806 | %psearch -a _* list objects beginning with a single underscore""" | |
819 |
|
807 | |||
820 | # default namespaces to be searched |
|
808 | # default namespaces to be searched | |
821 | def_search = ['user','builtin'] |
|
809 | def_search = ['user','builtin'] | |
822 |
|
810 | |||
823 | # Process options/args |
|
811 | # Process options/args | |
824 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
812 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
825 | opt = opts.get |
|
813 | opt = opts.get | |
826 | shell = self.shell |
|
814 | shell = self.shell | |
827 | psearch = shell.inspector.psearch |
|
815 | psearch = shell.inspector.psearch | |
828 |
|
816 | |||
829 | # select case options |
|
817 | # select case options | |
830 | if opts.has_key('i'): |
|
818 | if opts.has_key('i'): | |
831 | ignore_case = True |
|
819 | ignore_case = True | |
832 | elif opts.has_key('c'): |
|
820 | elif opts.has_key('c'): | |
833 | ignore_case = False |
|
821 | ignore_case = False | |
834 | else: |
|
822 | else: | |
835 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
823 | ignore_case = not shell.rc.wildcards_case_sensitive | |
836 |
|
824 | |||
837 | # Build list of namespaces to search from user options |
|
825 | # Build list of namespaces to search from user options | |
838 | def_search.extend(opt('s',[])) |
|
826 | def_search.extend(opt('s',[])) | |
839 | ns_exclude = ns_exclude=opt('e',[]) |
|
827 | ns_exclude = ns_exclude=opt('e',[]) | |
840 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
828 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
841 |
|
829 | |||
842 | # Call the actual search |
|
830 | # Call the actual search | |
843 | try: |
|
831 | try: | |
844 | psearch(args,shell.ns_table,ns_search, |
|
832 | psearch(args,shell.ns_table,ns_search, | |
845 | show_all=opt('a'),ignore_case=ignore_case) |
|
833 | show_all=opt('a'),ignore_case=ignore_case) | |
846 | except: |
|
834 | except: | |
847 | shell.showtraceback() |
|
835 | shell.showtraceback() | |
848 |
|
836 | |||
849 | def magic_who_ls(self, parameter_s=''): |
|
837 | def magic_who_ls(self, parameter_s=''): | |
850 | """Return a sorted list of all interactive variables. |
|
838 | """Return a sorted list of all interactive variables. | |
851 |
|
839 | |||
852 | If arguments are given, only variables of types matching these |
|
840 | If arguments are given, only variables of types matching these | |
853 | arguments are returned.""" |
|
841 | arguments are returned.""" | |
854 |
|
842 | |||
855 | user_ns = self.shell.user_ns |
|
843 | user_ns = self.shell.user_ns | |
856 | internal_ns = self.shell.internal_ns |
|
844 | internal_ns = self.shell.internal_ns | |
857 | user_config_ns = self.shell.user_config_ns |
|
845 | user_config_ns = self.shell.user_config_ns | |
858 | out = [] |
|
846 | out = [] | |
859 | typelist = parameter_s.split() |
|
847 | typelist = parameter_s.split() | |
860 |
|
848 | |||
861 | for i in user_ns: |
|
849 | for i in user_ns: | |
862 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
850 | if not (i.startswith('_') or i.startswith('_i')) \ | |
863 | and not (i in internal_ns or i in user_config_ns): |
|
851 | and not (i in internal_ns or i in user_config_ns): | |
864 | if typelist: |
|
852 | if typelist: | |
865 | if type(user_ns[i]).__name__ in typelist: |
|
853 | if type(user_ns[i]).__name__ in typelist: | |
866 | out.append(i) |
|
854 | out.append(i) | |
867 | else: |
|
855 | else: | |
868 | out.append(i) |
|
856 | out.append(i) | |
869 | out.sort() |
|
857 | out.sort() | |
870 | return out |
|
858 | return out | |
871 |
|
859 | |||
872 | def magic_who(self, parameter_s=''): |
|
860 | def magic_who(self, parameter_s=''): | |
873 | """Print all interactive variables, with some minimal formatting. |
|
861 | """Print all interactive variables, with some minimal formatting. | |
874 |
|
862 | |||
875 | If any arguments are given, only variables whose type matches one of |
|
863 | If any arguments are given, only variables whose type matches one of | |
876 | these are printed. For example: |
|
864 | these are printed. For example: | |
877 |
|
865 | |||
878 | %who function str |
|
866 | %who function str | |
879 |
|
867 | |||
880 | will only list functions and strings, excluding all other types of |
|
868 | will only list functions and strings, excluding all other types of | |
881 | variables. To find the proper type names, simply use type(var) at a |
|
869 | variables. To find the proper type names, simply use type(var) at a | |
882 | command line to see how python prints type names. For example: |
|
870 | command line to see how python prints type names. For example: | |
883 |
|
871 | |||
884 | In [1]: type('hello')\\ |
|
872 | In [1]: type('hello')\\ | |
885 | Out[1]: <type 'str'> |
|
873 | Out[1]: <type 'str'> | |
886 |
|
874 | |||
887 | indicates that the type name for strings is 'str'. |
|
875 | indicates that the type name for strings is 'str'. | |
888 |
|
876 | |||
889 | %who always excludes executed names loaded through your configuration |
|
877 | %who always excludes executed names loaded through your configuration | |
890 | file and things which are internal to IPython. |
|
878 | file and things which are internal to IPython. | |
891 |
|
879 | |||
892 | This is deliberate, as typically you may load many modules and the |
|
880 | This is deliberate, as typically you may load many modules and the | |
893 | purpose of %who is to show you only what you've manually defined.""" |
|
881 | purpose of %who is to show you only what you've manually defined.""" | |
894 |
|
882 | |||
895 | varlist = self.magic_who_ls(parameter_s) |
|
883 | varlist = self.magic_who_ls(parameter_s) | |
896 | if not varlist: |
|
884 | if not varlist: | |
897 | print 'Interactive namespace is empty.' |
|
885 | print 'Interactive namespace is empty.' | |
898 | return |
|
886 | return | |
899 |
|
887 | |||
900 | # if we have variables, move on... |
|
888 | # if we have variables, move on... | |
901 |
|
889 | |||
902 | # stupid flushing problem: when prompts have no separators, stdout is |
|
890 | # stupid flushing problem: when prompts have no separators, stdout is | |
903 | # getting lost. I'm starting to think this is a python bug. I'm having |
|
891 | # getting lost. I'm starting to think this is a python bug. I'm having | |
904 | # to force a flush with a print because even a sys.stdout.flush |
|
892 | # to force a flush with a print because even a sys.stdout.flush | |
905 | # doesn't seem to do anything! |
|
893 | # doesn't seem to do anything! | |
906 |
|
894 | |||
907 | count = 0 |
|
895 | count = 0 | |
908 | for i in varlist: |
|
896 | for i in varlist: | |
909 | print i+'\t', |
|
897 | print i+'\t', | |
910 | count += 1 |
|
898 | count += 1 | |
911 | if count > 8: |
|
899 | if count > 8: | |
912 | count = 0 |
|
900 | count = 0 | |
913 |
|
901 | |||
914 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? |
|
902 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? | |
915 |
|
903 | |||
916 | print # well, this does force a flush at the expense of an extra \n |
|
904 | print # well, this does force a flush at the expense of an extra \n | |
917 |
|
905 | |||
918 | def magic_whos(self, parameter_s=''): |
|
906 | def magic_whos(self, parameter_s=''): | |
919 | """Like %who, but gives some extra information about each variable. |
|
907 | """Like %who, but gives some extra information about each variable. | |
920 |
|
908 | |||
921 | The same type filtering of %who can be applied here. |
|
909 | The same type filtering of %who can be applied here. | |
922 |
|
910 | |||
923 | For all variables, the type is printed. Additionally it prints: |
|
911 | For all variables, the type is printed. Additionally it prints: | |
924 |
|
912 | |||
925 | - For {},[],(): their length. |
|
913 | - For {},[],(): their length. | |
926 |
|
914 | |||
927 | - For Numeric arrays, a summary with shape, number of elements, |
|
915 | - For Numeric arrays, a summary with shape, number of elements, | |
928 | typecode and size in memory. |
|
916 | typecode and size in memory. | |
929 |
|
917 | |||
930 | - Everything else: a string representation, snipping their middle if |
|
918 | - Everything else: a string representation, snipping their middle if | |
931 | too long.""" |
|
919 | too long.""" | |
932 |
|
920 | |||
933 | varnames = self.magic_who_ls(parameter_s) |
|
921 | varnames = self.magic_who_ls(parameter_s) | |
934 | if not varnames: |
|
922 | if not varnames: | |
935 | print 'Interactive namespace is empty.' |
|
923 | print 'Interactive namespace is empty.' | |
936 | return |
|
924 | return | |
937 |
|
925 | |||
938 | # if we have variables, move on... |
|
926 | # if we have variables, move on... | |
939 |
|
927 | |||
940 | # for these types, show len() instead of data: |
|
928 | # for these types, show len() instead of data: | |
941 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
929 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
942 |
|
930 | |||
943 | # for Numeric arrays, display summary info |
|
931 | # for Numeric arrays, display summary info | |
944 | try: |
|
932 | try: | |
945 | import Numeric |
|
933 | import Numeric | |
946 | except ImportError: |
|
934 | except ImportError: | |
947 | array_type = None |
|
935 | array_type = None | |
948 | else: |
|
936 | else: | |
949 | array_type = Numeric.ArrayType.__name__ |
|
937 | array_type = Numeric.ArrayType.__name__ | |
950 |
|
938 | |||
951 | # Find all variable names and types so we can figure out column sizes |
|
939 | # Find all variable names and types so we can figure out column sizes | |
952 | get_vars = lambda i: self.shell.user_ns[i] |
|
940 | get_vars = lambda i: self.shell.user_ns[i] | |
953 | type_name = lambda v: type(v).__name__ |
|
941 | type_name = lambda v: type(v).__name__ | |
954 | varlist = map(get_vars,varnames) |
|
942 | varlist = map(get_vars,varnames) | |
955 |
|
943 | |||
956 | typelist = [] |
|
944 | typelist = [] | |
957 | for vv in varlist: |
|
945 | for vv in varlist: | |
958 | tt = type_name(vv) |
|
946 | tt = type_name(vv) | |
959 | if tt=='instance': |
|
947 | if tt=='instance': | |
960 | typelist.append(str(vv.__class__)) |
|
948 | typelist.append(str(vv.__class__)) | |
961 | else: |
|
949 | else: | |
962 | typelist.append(tt) |
|
950 | typelist.append(tt) | |
963 |
|
951 | |||
964 | # column labels and # of spaces as separator |
|
952 | # column labels and # of spaces as separator | |
965 | varlabel = 'Variable' |
|
953 | varlabel = 'Variable' | |
966 | typelabel = 'Type' |
|
954 | typelabel = 'Type' | |
967 | datalabel = 'Data/Info' |
|
955 | datalabel = 'Data/Info' | |
968 | colsep = 3 |
|
956 | colsep = 3 | |
969 | # variable format strings |
|
957 | # variable format strings | |
970 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
958 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
971 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
959 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
972 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
960 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
973 | # find the size of the columns to format the output nicely |
|
961 | # find the size of the columns to format the output nicely | |
974 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
962 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
975 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
963 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
976 | # table header |
|
964 | # table header | |
977 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
965 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
978 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
966 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
979 | # and the table itself |
|
967 | # and the table itself | |
980 | kb = 1024 |
|
968 | kb = 1024 | |
981 | Mb = 1048576 # kb**2 |
|
969 | Mb = 1048576 # kb**2 | |
982 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
970 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
983 | print itpl(vformat), |
|
971 | print itpl(vformat), | |
984 | if vtype in seq_types: |
|
972 | if vtype in seq_types: | |
985 | print len(var) |
|
973 | print len(var) | |
986 | elif vtype==array_type: |
|
974 | elif vtype==array_type: | |
987 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
975 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
988 | vsize = Numeric.size(var) |
|
976 | vsize = Numeric.size(var) | |
989 | vbytes = vsize*var.itemsize() |
|
977 | vbytes = vsize*var.itemsize() | |
990 | if vbytes < 100000: |
|
978 | if vbytes < 100000: | |
991 | print aformat % (vshape,vsize,var.typecode(),vbytes) |
|
979 | print aformat % (vshape,vsize,var.typecode(),vbytes) | |
992 | else: |
|
980 | else: | |
993 | print aformat % (vshape,vsize,var.typecode(),vbytes), |
|
981 | print aformat % (vshape,vsize,var.typecode(),vbytes), | |
994 | if vbytes < Mb: |
|
982 | if vbytes < Mb: | |
995 | print '(%s kb)' % (vbytes/kb,) |
|
983 | print '(%s kb)' % (vbytes/kb,) | |
996 | else: |
|
984 | else: | |
997 | print '(%s Mb)' % (vbytes/Mb,) |
|
985 | print '(%s Mb)' % (vbytes/Mb,) | |
998 | else: |
|
986 | else: | |
999 | vstr = str(var).replace('\n','\\n') |
|
987 | vstr = str(var).replace('\n','\\n') | |
1000 | if len(vstr) < 50: |
|
988 | if len(vstr) < 50: | |
1001 | print vstr |
|
989 | print vstr | |
1002 | else: |
|
990 | else: | |
1003 | printpl(vfmt_short) |
|
991 | printpl(vfmt_short) | |
1004 |
|
992 | |||
1005 | def magic_reset(self, parameter_s=''): |
|
993 | def magic_reset(self, parameter_s=''): | |
1006 | """Resets the namespace by removing all names defined by the user. |
|
994 | """Resets the namespace by removing all names defined by the user. | |
1007 |
|
995 | |||
1008 | Input/Output history are left around in case you need them.""" |
|
996 | Input/Output history are left around in case you need them.""" | |
1009 |
|
997 | |||
1010 | ans = self.shell.ask_yes_no( |
|
998 | ans = self.shell.ask_yes_no( | |
1011 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
999 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1012 | if not ans: |
|
1000 | if not ans: | |
1013 | print 'Nothing done.' |
|
1001 | print 'Nothing done.' | |
1014 | return |
|
1002 | return | |
1015 | user_ns = self.shell.user_ns |
|
1003 | user_ns = self.shell.user_ns | |
1016 | for i in self.magic_who_ls(): |
|
1004 | for i in self.magic_who_ls(): | |
1017 | del(user_ns[i]) |
|
1005 | del(user_ns[i]) | |
1018 |
|
1006 | |||
1019 | def magic_config(self,parameter_s=''): |
|
1007 | def magic_config(self,parameter_s=''): | |
1020 | """Show IPython's internal configuration.""" |
|
1008 | """Show IPython's internal configuration.""" | |
1021 |
|
1009 | |||
1022 | page('Current configuration structure:\n'+ |
|
1010 | page('Current configuration structure:\n'+ | |
1023 | pformat(self.shell.rc.dict())) |
|
1011 | pformat(self.shell.rc.dict())) | |
1024 |
|
1012 | |||
1025 | def magic_logstart(self,parameter_s=''): |
|
1013 | def magic_logstart(self,parameter_s=''): | |
1026 | """Start logging anywhere in a session. |
|
1014 | """Start logging anywhere in a session. | |
1027 |
|
1015 | |||
1028 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1016 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1029 |
|
1017 | |||
1030 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1018 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1031 | current directory, in 'rotate' mode (see below). |
|
1019 | current directory, in 'rotate' mode (see below). | |
1032 |
|
1020 | |||
1033 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1021 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1034 | history up to that point and then continues logging. |
|
1022 | history up to that point and then continues logging. | |
1035 |
|
1023 | |||
1036 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1024 | %logstart takes a second optional parameter: logging mode. This can be one | |
1037 | of (note that the modes are given unquoted):\\ |
|
1025 | of (note that the modes are given unquoted):\\ | |
1038 | append: well, that says it.\\ |
|
1026 | append: well, that says it.\\ | |
1039 | backup: rename (if exists) to name~ and start name.\\ |
|
1027 | backup: rename (if exists) to name~ and start name.\\ | |
1040 | global: single logfile in your home dir, appended to.\\ |
|
1028 | global: single logfile in your home dir, appended to.\\ | |
1041 | over : overwrite existing log.\\ |
|
1029 | over : overwrite existing log.\\ | |
1042 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1030 | rotate: create rotating logs name.1~, name.2~, etc. | |
1043 |
|
1031 | |||
1044 | Options: |
|
1032 | Options: | |
1045 |
|
1033 | |||
1046 | -o: log also IPython's output. In this mode, all commands which |
|
1034 | -o: log also IPython's output. In this mode, all commands which | |
1047 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1035 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1048 | their corresponding input line. The output lines are always |
|
1036 | their corresponding input line. The output lines are always | |
1049 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1037 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1050 | Python code. |
|
1038 | Python code. | |
1051 |
|
1039 | |||
1052 | Since this marker is always the same, filtering only the output from |
|
1040 | Since this marker is always the same, filtering only the output from | |
1053 | a log is very easy, using for example a simple awk call: |
|
1041 | a log is very easy, using for example a simple awk call: | |
1054 |
|
1042 | |||
1055 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1043 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1056 |
|
1044 | |||
1057 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1045 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1058 | input, so that user lines are logged in their final form, converted |
|
1046 | input, so that user lines are logged in their final form, converted | |
1059 | into valid Python. For example, %Exit is logged as |
|
1047 | into valid Python. For example, %Exit is logged as | |
1060 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1048 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1061 | exactly as typed, with no transformations applied. |
|
1049 | exactly as typed, with no transformations applied. | |
1062 |
|
1050 | |||
1063 | -t: put timestamps before each input line logged (these are put in |
|
1051 | -t: put timestamps before each input line logged (these are put in | |
1064 | comments).""" |
|
1052 | comments).""" | |
1065 |
|
1053 | |||
1066 | opts,par = self.parse_options(parameter_s,'ort') |
|
1054 | opts,par = self.parse_options(parameter_s,'ort') | |
1067 | log_output = 'o' in opts |
|
1055 | log_output = 'o' in opts | |
1068 | log_raw_input = 'r' in opts |
|
1056 | log_raw_input = 'r' in opts | |
1069 | timestamp = 't' in opts |
|
1057 | timestamp = 't' in opts | |
1070 |
|
1058 | |||
1071 | rc = self.shell.rc |
|
1059 | rc = self.shell.rc | |
1072 | logger = self.shell.logger |
|
1060 | logger = self.shell.logger | |
1073 |
|
1061 | |||
1074 | # if no args are given, the defaults set in the logger constructor by |
|
1062 | # if no args are given, the defaults set in the logger constructor by | |
1075 | # ipytohn remain valid |
|
1063 | # ipytohn remain valid | |
1076 | if par: |
|
1064 | if par: | |
1077 | try: |
|
1065 | try: | |
1078 | logfname,logmode = par.split() |
|
1066 | logfname,logmode = par.split() | |
1079 | except: |
|
1067 | except: | |
1080 | logfname = par |
|
1068 | logfname = par | |
1081 | logmode = 'backup' |
|
1069 | logmode = 'backup' | |
1082 | else: |
|
1070 | else: | |
1083 | logfname = logger.logfname |
|
1071 | logfname = logger.logfname | |
1084 | logmode = logger.logmode |
|
1072 | logmode = logger.logmode | |
1085 | # put logfname into rc struct as if it had been called on the command |
|
1073 | # put logfname into rc struct as if it had been called on the command | |
1086 | # line, so it ends up saved in the log header Save it in case we need |
|
1074 | # line, so it ends up saved in the log header Save it in case we need | |
1087 | # to restore it... |
|
1075 | # to restore it... | |
1088 | old_logfile = rc.opts.get('logfile','') |
|
1076 | old_logfile = rc.opts.get('logfile','') | |
1089 | if logfname: |
|
1077 | if logfname: | |
1090 | logfname = os.path.expanduser(logfname) |
|
1078 | logfname = os.path.expanduser(logfname) | |
1091 | rc.opts.logfile = logfname |
|
1079 | rc.opts.logfile = logfname | |
1092 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1080 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) | |
1093 | try: |
|
1081 | try: | |
1094 | started = logger.logstart(logfname,loghead,logmode, |
|
1082 | started = logger.logstart(logfname,loghead,logmode, | |
1095 | log_output,timestamp,log_raw_input) |
|
1083 | log_output,timestamp,log_raw_input) | |
1096 | except: |
|
1084 | except: | |
1097 | rc.opts.logfile = old_logfile |
|
1085 | rc.opts.logfile = old_logfile | |
1098 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1086 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1099 | else: |
|
1087 | else: | |
1100 | # log input history up to this point, optionally interleaving |
|
1088 | # log input history up to this point, optionally interleaving | |
1101 | # output if requested |
|
1089 | # output if requested | |
1102 |
|
1090 | |||
1103 | if timestamp: |
|
1091 | if timestamp: | |
1104 | # disable timestamping for the previous history, since we've |
|
1092 | # disable timestamping for the previous history, since we've | |
1105 | # lost those already (no time machine here). |
|
1093 | # lost those already (no time machine here). | |
1106 | logger.timestamp = False |
|
1094 | logger.timestamp = False | |
1107 |
|
1095 | |||
1108 | if log_raw_input: |
|
1096 | if log_raw_input: | |
1109 | input_hist = self.shell.input_hist_raw |
|
1097 | input_hist = self.shell.input_hist_raw | |
1110 | else: |
|
1098 | else: | |
1111 | input_hist = self.shell.input_hist |
|
1099 | input_hist = self.shell.input_hist | |
1112 |
|
1100 | |||
1113 | if log_output: |
|
1101 | if log_output: | |
1114 | log_write = logger.log_write |
|
1102 | log_write = logger.log_write | |
1115 | output_hist = self.shell.output_hist |
|
1103 | output_hist = self.shell.output_hist | |
1116 | for n in range(1,len(input_hist)-1): |
|
1104 | for n in range(1,len(input_hist)-1): | |
1117 | log_write(input_hist[n].rstrip()) |
|
1105 | log_write(input_hist[n].rstrip()) | |
1118 | if n in output_hist: |
|
1106 | if n in output_hist: | |
1119 | log_write(repr(output_hist[n]),'output') |
|
1107 | log_write(repr(output_hist[n]),'output') | |
1120 | else: |
|
1108 | else: | |
1121 | logger.log_write(input_hist[1:]) |
|
1109 | logger.log_write(input_hist[1:]) | |
1122 | if timestamp: |
|
1110 | if timestamp: | |
1123 | # re-enable timestamping |
|
1111 | # re-enable timestamping | |
1124 | logger.timestamp = True |
|
1112 | logger.timestamp = True | |
1125 |
|
1113 | |||
1126 | print ('Activating auto-logging. ' |
|
1114 | print ('Activating auto-logging. ' | |
1127 | 'Current session state plus future input saved.') |
|
1115 | 'Current session state plus future input saved.') | |
1128 | logger.logstate() |
|
1116 | logger.logstate() | |
1129 |
|
1117 | |||
1130 | def magic_logoff(self,parameter_s=''): |
|
1118 | def magic_logoff(self,parameter_s=''): | |
1131 | """Temporarily stop logging. |
|
1119 | """Temporarily stop logging. | |
1132 |
|
1120 | |||
1133 | You must have previously started logging.""" |
|
1121 | You must have previously started logging.""" | |
1134 | self.shell.logger.switch_log(0) |
|
1122 | self.shell.logger.switch_log(0) | |
1135 |
|
1123 | |||
1136 | def magic_logon(self,parameter_s=''): |
|
1124 | def magic_logon(self,parameter_s=''): | |
1137 | """Restart logging. |
|
1125 | """Restart logging. | |
1138 |
|
1126 | |||
1139 | This function is for restarting logging which you've temporarily |
|
1127 | This function is for restarting logging which you've temporarily | |
1140 | stopped with %logoff. For starting logging for the first time, you |
|
1128 | stopped with %logoff. For starting logging for the first time, you | |
1141 | must use the %logstart function, which allows you to specify an |
|
1129 | must use the %logstart function, which allows you to specify an | |
1142 | optional log filename.""" |
|
1130 | optional log filename.""" | |
1143 |
|
1131 | |||
1144 | self.shell.logger.switch_log(1) |
|
1132 | self.shell.logger.switch_log(1) | |
1145 |
|
1133 | |||
1146 | def magic_logstate(self,parameter_s=''): |
|
1134 | def magic_logstate(self,parameter_s=''): | |
1147 | """Print the status of the logging system.""" |
|
1135 | """Print the status of the logging system.""" | |
1148 |
|
1136 | |||
1149 | self.shell.logger.logstate() |
|
1137 | self.shell.logger.logstate() | |
1150 |
|
1138 | |||
1151 | def magic_pdb(self, parameter_s=''): |
|
1139 | def magic_pdb(self, parameter_s=''): | |
1152 | """Control the calling of the pdb interactive debugger. |
|
1140 | """Control the calling of the pdb interactive debugger. | |
1153 |
|
1141 | |||
1154 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1142 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1155 | argument it works as a toggle. |
|
1143 | argument it works as a toggle. | |
1156 |
|
1144 | |||
1157 | When an exception is triggered, IPython can optionally call the |
|
1145 | When an exception is triggered, IPython can optionally call the | |
1158 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1146 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1159 | this feature on and off.""" |
|
1147 | this feature on and off.""" | |
1160 |
|
1148 | |||
1161 | par = parameter_s.strip().lower() |
|
1149 | par = parameter_s.strip().lower() | |
1162 |
|
1150 | |||
1163 | if par: |
|
1151 | if par: | |
1164 | try: |
|
1152 | try: | |
1165 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1153 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1166 | except KeyError: |
|
1154 | except KeyError: | |
1167 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1155 | print ('Incorrect argument. Use on/1, off/0, ' | |
1168 | 'or nothing for a toggle.') |
|
1156 | 'or nothing for a toggle.') | |
1169 | return |
|
1157 | return | |
1170 | else: |
|
1158 | else: | |
1171 | # toggle |
|
1159 | # toggle | |
1172 | new_pdb = not self.shell.InteractiveTB.call_pdb |
|
1160 | new_pdb = not self.shell.InteractiveTB.call_pdb | |
1173 |
|
1161 | |||
1174 | # set on the shell |
|
1162 | # set on the shell | |
1175 | self.shell.call_pdb = new_pdb |
|
1163 | self.shell.call_pdb = new_pdb | |
1176 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1164 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1177 |
|
1165 | |||
1178 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1166 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1179 | opts=None,arg_lst=None,prog_ns=None): |
|
1167 | opts=None,arg_lst=None,prog_ns=None): | |
1180 |
|
1168 | |||
1181 | """Run a statement through the python code profiler. |
|
1169 | """Run a statement through the python code profiler. | |
1182 |
|
1170 | |||
1183 | Usage:\\ |
|
1171 | Usage:\\ | |
1184 | %prun [options] statement |
|
1172 | %prun [options] statement | |
1185 |
|
1173 | |||
1186 | The given statement (which doesn't require quote marks) is run via the |
|
1174 | The given statement (which doesn't require quote marks) is run via the | |
1187 | python profiler in a manner similar to the profile.run() function. |
|
1175 | python profiler in a manner similar to the profile.run() function. | |
1188 | Namespaces are internally managed to work correctly; profile.run |
|
1176 | Namespaces are internally managed to work correctly; profile.run | |
1189 | cannot be used in IPython because it makes certain assumptions about |
|
1177 | cannot be used in IPython because it makes certain assumptions about | |
1190 | namespaces which do not hold under IPython. |
|
1178 | namespaces which do not hold under IPython. | |
1191 |
|
1179 | |||
1192 | Options: |
|
1180 | Options: | |
1193 |
|
1181 | |||
1194 | -l <limit>: you can place restrictions on what or how much of the |
|
1182 | -l <limit>: you can place restrictions on what or how much of the | |
1195 | profile gets printed. The limit value can be: |
|
1183 | profile gets printed. The limit value can be: | |
1196 |
|
1184 | |||
1197 | * A string: only information for function names containing this string |
|
1185 | * A string: only information for function names containing this string | |
1198 | is printed. |
|
1186 | is printed. | |
1199 |
|
1187 | |||
1200 | * An integer: only these many lines are printed. |
|
1188 | * An integer: only these many lines are printed. | |
1201 |
|
1189 | |||
1202 | * A float (between 0 and 1): this fraction of the report is printed |
|
1190 | * A float (between 0 and 1): this fraction of the report is printed | |
1203 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1191 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1204 |
|
1192 | |||
1205 | You can combine several limits with repeated use of the option. For |
|
1193 | You can combine several limits with repeated use of the option. For | |
1206 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1194 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1207 | information about class constructors. |
|
1195 | information about class constructors. | |
1208 |
|
1196 | |||
1209 | -r: return the pstats.Stats object generated by the profiling. This |
|
1197 | -r: return the pstats.Stats object generated by the profiling. This | |
1210 | object has all the information about the profile in it, and you can |
|
1198 | object has all the information about the profile in it, and you can | |
1211 | later use it for further analysis or in other functions. |
|
1199 | later use it for further analysis or in other functions. | |
1212 |
|
1200 | |||
1213 | Since magic functions have a particular form of calling which prevents |
|
1201 | Since magic functions have a particular form of calling which prevents | |
1214 | you from writing something like:\\ |
|
1202 | you from writing something like:\\ | |
1215 | In [1]: p = %prun -r print 4 # invalid!\\ |
|
1203 | In [1]: p = %prun -r print 4 # invalid!\\ | |
1216 | you must instead use IPython's automatic variables to assign this:\\ |
|
1204 | you must instead use IPython's automatic variables to assign this:\\ | |
1217 | In [1]: %prun -r print 4 \\ |
|
1205 | In [1]: %prun -r print 4 \\ | |
1218 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ |
|
1206 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ | |
1219 | In [2]: stats = _ |
|
1207 | In [2]: stats = _ | |
1220 |
|
1208 | |||
1221 | If you really need to assign this value via an explicit function call, |
|
1209 | If you really need to assign this value via an explicit function call, | |
1222 | you can always tap directly into the true name of the magic function |
|
1210 | you can always tap directly into the true name of the magic function | |
1223 | by using the _ip.magic function:\\ |
|
1211 | by using the _ip.magic function:\\ | |
1224 | In [3]: stats = _ip.magic('prun','-r print 4') |
|
1212 | In [3]: stats = _ip.magic('prun','-r print 4') | |
1225 |
|
1213 | |||
1226 | You can type _ip.magic? for more details. |
|
1214 | You can type _ip.magic? for more details. | |
1227 |
|
1215 | |||
1228 | -s <key>: sort profile by given key. You can provide more than one key |
|
1216 | -s <key>: sort profile by given key. You can provide more than one key | |
1229 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1217 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1230 | default sorting key is 'time'. |
|
1218 | default sorting key is 'time'. | |
1231 |
|
1219 | |||
1232 | The following is copied verbatim from the profile documentation |
|
1220 | The following is copied verbatim from the profile documentation | |
1233 | referenced below: |
|
1221 | referenced below: | |
1234 |
|
1222 | |||
1235 | When more than one key is provided, additional keys are used as |
|
1223 | When more than one key is provided, additional keys are used as | |
1236 | secondary criteria when the there is equality in all keys selected |
|
1224 | secondary criteria when the there is equality in all keys selected | |
1237 | before them. |
|
1225 | before them. | |
1238 |
|
1226 | |||
1239 | Abbreviations can be used for any key names, as long as the |
|
1227 | Abbreviations can be used for any key names, as long as the | |
1240 | abbreviation is unambiguous. The following are the keys currently |
|
1228 | abbreviation is unambiguous. The following are the keys currently | |
1241 | defined: |
|
1229 | defined: | |
1242 |
|
1230 | |||
1243 | Valid Arg Meaning\\ |
|
1231 | Valid Arg Meaning\\ | |
1244 | "calls" call count\\ |
|
1232 | "calls" call count\\ | |
1245 | "cumulative" cumulative time\\ |
|
1233 | "cumulative" cumulative time\\ | |
1246 | "file" file name\\ |
|
1234 | "file" file name\\ | |
1247 | "module" file name\\ |
|
1235 | "module" file name\\ | |
1248 | "pcalls" primitive call count\\ |
|
1236 | "pcalls" primitive call count\\ | |
1249 | "line" line number\\ |
|
1237 | "line" line number\\ | |
1250 | "name" function name\\ |
|
1238 | "name" function name\\ | |
1251 | "nfl" name/file/line\\ |
|
1239 | "nfl" name/file/line\\ | |
1252 | "stdname" standard name\\ |
|
1240 | "stdname" standard name\\ | |
1253 | "time" internal time |
|
1241 | "time" internal time | |
1254 |
|
1242 | |||
1255 | Note that all sorts on statistics are in descending order (placing |
|
1243 | Note that all sorts on statistics are in descending order (placing | |
1256 | most time consuming items first), where as name, file, and line number |
|
1244 | most time consuming items first), where as name, file, and line number | |
1257 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1245 | searches are in ascending order (i.e., alphabetical). The subtle | |
1258 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1246 | distinction between "nfl" and "stdname" is that the standard name is a | |
1259 | sort of the name as printed, which means that the embedded line |
|
1247 | sort of the name as printed, which means that the embedded line | |
1260 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1248 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1261 | would (if the file names were the same) appear in the string order |
|
1249 | would (if the file names were the same) appear in the string order | |
1262 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1250 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1263 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1251 | line numbers. In fact, sort_stats("nfl") is the same as | |
1264 | sort_stats("name", "file", "line"). |
|
1252 | sort_stats("name", "file", "line"). | |
1265 |
|
1253 | |||
1266 | -T <filename>: save profile results as shown on screen to a text |
|
1254 | -T <filename>: save profile results as shown on screen to a text | |
1267 | file. The profile is still shown on screen. |
|
1255 | file. The profile is still shown on screen. | |
1268 |
|
1256 | |||
1269 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1257 | -D <filename>: save (via dump_stats) profile statistics to given | |
1270 | filename. This data is in a format understod by the pstats module, and |
|
1258 | filename. This data is in a format understod by the pstats module, and | |
1271 | is generated by a call to the dump_stats() method of profile |
|
1259 | is generated by a call to the dump_stats() method of profile | |
1272 | objects. The profile is still shown on screen. |
|
1260 | objects. The profile is still shown on screen. | |
1273 |
|
1261 | |||
1274 | If you want to run complete programs under the profiler's control, use |
|
1262 | If you want to run complete programs under the profiler's control, use | |
1275 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1263 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1276 | contains profiler specific options as described here. |
|
1264 | contains profiler specific options as described here. | |
1277 |
|
1265 | |||
1278 | You can read the complete documentation for the profile module with:\\ |
|
1266 | You can read the complete documentation for the profile module with:\\ | |
1279 | In [1]: import profile; profile.help() """ |
|
1267 | In [1]: import profile; profile.help() """ | |
1280 |
|
1268 | |||
1281 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1269 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1282 | # protect user quote marks |
|
1270 | # protect user quote marks | |
1283 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1271 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1284 |
|
1272 | |||
1285 | if user_mode: # regular user call |
|
1273 | if user_mode: # regular user call | |
1286 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1274 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1287 | list_all=1) |
|
1275 | list_all=1) | |
1288 | namespace = self.shell.user_ns |
|
1276 | namespace = self.shell.user_ns | |
1289 | else: # called to run a program by %run -p |
|
1277 | else: # called to run a program by %run -p | |
1290 | try: |
|
1278 | try: | |
1291 | filename = get_py_filename(arg_lst[0]) |
|
1279 | filename = get_py_filename(arg_lst[0]) | |
1292 | except IOError,msg: |
|
1280 | except IOError,msg: | |
1293 | error(msg) |
|
1281 | error(msg) | |
1294 | return |
|
1282 | return | |
1295 |
|
1283 | |||
1296 | arg_str = 'execfile(filename,prog_ns)' |
|
1284 | arg_str = 'execfile(filename,prog_ns)' | |
1297 | namespace = locals() |
|
1285 | namespace = locals() | |
1298 |
|
1286 | |||
1299 | opts.merge(opts_def) |
|
1287 | opts.merge(opts_def) | |
1300 |
|
1288 | |||
1301 | prof = profile.Profile() |
|
1289 | prof = profile.Profile() | |
1302 | try: |
|
1290 | try: | |
1303 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1291 | prof = prof.runctx(arg_str,namespace,namespace) | |
1304 | sys_exit = '' |
|
1292 | sys_exit = '' | |
1305 | except SystemExit: |
|
1293 | except SystemExit: | |
1306 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1294 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1307 |
|
1295 | |||
1308 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1296 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1309 |
|
1297 | |||
1310 | lims = opts.l |
|
1298 | lims = opts.l | |
1311 | if lims: |
|
1299 | if lims: | |
1312 | lims = [] # rebuild lims with ints/floats/strings |
|
1300 | lims = [] # rebuild lims with ints/floats/strings | |
1313 | for lim in opts.l: |
|
1301 | for lim in opts.l: | |
1314 | try: |
|
1302 | try: | |
1315 | lims.append(int(lim)) |
|
1303 | lims.append(int(lim)) | |
1316 | except ValueError: |
|
1304 | except ValueError: | |
1317 | try: |
|
1305 | try: | |
1318 | lims.append(float(lim)) |
|
1306 | lims.append(float(lim)) | |
1319 | except ValueError: |
|
1307 | except ValueError: | |
1320 | lims.append(lim) |
|
1308 | lims.append(lim) | |
1321 |
|
1309 | |||
1322 | # trap output |
|
1310 | # trap output | |
1323 | sys_stdout = sys.stdout |
|
1311 | sys_stdout = sys.stdout | |
1324 | stdout_trap = StringIO() |
|
1312 | stdout_trap = StringIO() | |
1325 | try: |
|
1313 | try: | |
1326 | sys.stdout = stdout_trap |
|
1314 | sys.stdout = stdout_trap | |
1327 | stats.print_stats(*lims) |
|
1315 | stats.print_stats(*lims) | |
1328 | finally: |
|
1316 | finally: | |
1329 | sys.stdout = sys_stdout |
|
1317 | sys.stdout = sys_stdout | |
1330 | output = stdout_trap.getvalue() |
|
1318 | output = stdout_trap.getvalue() | |
1331 | output = output.rstrip() |
|
1319 | output = output.rstrip() | |
1332 |
|
1320 | |||
1333 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1321 | page(output,screen_lines=self.shell.rc.screen_length) | |
1334 | print sys_exit, |
|
1322 | print sys_exit, | |
1335 |
|
1323 | |||
1336 | dump_file = opts.D[0] |
|
1324 | dump_file = opts.D[0] | |
1337 | text_file = opts.T[0] |
|
1325 | text_file = opts.T[0] | |
1338 | if dump_file: |
|
1326 | if dump_file: | |
1339 | prof.dump_stats(dump_file) |
|
1327 | prof.dump_stats(dump_file) | |
1340 | print '\n*** Profile stats marshalled to file',\ |
|
1328 | print '\n*** Profile stats marshalled to file',\ | |
1341 | `dump_file`+'.',sys_exit |
|
1329 | `dump_file`+'.',sys_exit | |
1342 | if text_file: |
|
1330 | if text_file: | |
1343 | file(text_file,'w').write(output) |
|
1331 | file(text_file,'w').write(output) | |
1344 | print '\n*** Profile printout saved to text file',\ |
|
1332 | print '\n*** Profile printout saved to text file',\ | |
1345 | `text_file`+'.',sys_exit |
|
1333 | `text_file`+'.',sys_exit | |
1346 |
|
1334 | |||
1347 | if opts.has_key('r'): |
|
1335 | if opts.has_key('r'): | |
1348 | return stats |
|
1336 | return stats | |
1349 | else: |
|
1337 | else: | |
1350 | return None |
|
1338 | return None | |
1351 |
|
1339 | |||
1352 | def magic_run(self, parameter_s ='',runner=None): |
|
1340 | def magic_run(self, parameter_s ='',runner=None): | |
1353 | """Run the named file inside IPython as a program. |
|
1341 | """Run the named file inside IPython as a program. | |
1354 |
|
1342 | |||
1355 | Usage:\\ |
|
1343 | Usage:\\ | |
1356 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1344 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1357 |
|
1345 | |||
1358 | Parameters after the filename are passed as command-line arguments to |
|
1346 | Parameters after the filename are passed as command-line arguments to | |
1359 | the program (put in sys.argv). Then, control returns to IPython's |
|
1347 | the program (put in sys.argv). Then, control returns to IPython's | |
1360 | prompt. |
|
1348 | prompt. | |
1361 |
|
1349 | |||
1362 | This is similar to running at a system prompt:\\ |
|
1350 | This is similar to running at a system prompt:\\ | |
1363 | $ python file args\\ |
|
1351 | $ python file args\\ | |
1364 | but with the advantage of giving you IPython's tracebacks, and of |
|
1352 | but with the advantage of giving you IPython's tracebacks, and of | |
1365 | loading all variables into your interactive namespace for further use |
|
1353 | loading all variables into your interactive namespace for further use | |
1366 | (unless -p is used, see below). |
|
1354 | (unless -p is used, see below). | |
1367 |
|
1355 | |||
1368 | The file is executed in a namespace initially consisting only of |
|
1356 | The file is executed in a namespace initially consisting only of | |
1369 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1357 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1370 | sees its environment as if it were being run as a stand-alone |
|
1358 | sees its environment as if it were being run as a stand-alone | |
1371 | program. But after execution, the IPython interactive namespace gets |
|
1359 | program. But after execution, the IPython interactive namespace gets | |
1372 | updated with all variables defined in the program (except for __name__ |
|
1360 | updated with all variables defined in the program (except for __name__ | |
1373 | and sys.argv). This allows for very convenient loading of code for |
|
1361 | and sys.argv). This allows for very convenient loading of code for | |
1374 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1362 | interactive work, while giving each program a 'clean sheet' to run in. | |
1375 |
|
1363 | |||
1376 | Options: |
|
1364 | Options: | |
1377 |
|
1365 | |||
1378 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1366 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1379 | without extension (as python does under import). This allows running |
|
1367 | without extension (as python does under import). This allows running | |
1380 | scripts and reloading the definitions in them without calling code |
|
1368 | scripts and reloading the definitions in them without calling code | |
1381 | protected by an ' if __name__ == "__main__" ' clause. |
|
1369 | protected by an ' if __name__ == "__main__" ' clause. | |
1382 |
|
1370 | |||
1383 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1371 | -i: run the file in IPython's namespace instead of an empty one. This | |
1384 | is useful if you are experimenting with code written in a text editor |
|
1372 | is useful if you are experimenting with code written in a text editor | |
1385 | which depends on variables defined interactively. |
|
1373 | which depends on variables defined interactively. | |
1386 |
|
1374 | |||
1387 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1375 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1388 | being run. This is particularly useful if IPython is being used to |
|
1376 | being run. This is particularly useful if IPython is being used to | |
1389 | run unittests, which always exit with a sys.exit() call. In such |
|
1377 | run unittests, which always exit with a sys.exit() call. In such | |
1390 | cases you are interested in the output of the test results, not in |
|
1378 | cases you are interested in the output of the test results, not in | |
1391 | seeing a traceback of the unittest module. |
|
1379 | seeing a traceback of the unittest module. | |
1392 |
|
1380 | |||
1393 | -t: print timing information at the end of the run. IPython will give |
|
1381 | -t: print timing information at the end of the run. IPython will give | |
1394 | you an estimated CPU time consumption for your script, which under |
|
1382 | you an estimated CPU time consumption for your script, which under | |
1395 | Unix uses the resource module to avoid the wraparound problems of |
|
1383 | Unix uses the resource module to avoid the wraparound problems of | |
1396 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1384 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1397 | is also given (for Windows platforms this is reported as 0.0). |
|
1385 | is also given (for Windows platforms this is reported as 0.0). | |
1398 |
|
1386 | |||
1399 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1387 | If -t is given, an additional -N<N> option can be given, where <N> | |
1400 | must be an integer indicating how many times you want the script to |
|
1388 | must be an integer indicating how many times you want the script to | |
1401 | run. The final timing report will include total and per run results. |
|
1389 | run. The final timing report will include total and per run results. | |
1402 |
|
1390 | |||
1403 | For example (testing the script uniq_stable.py): |
|
1391 | For example (testing the script uniq_stable.py): | |
1404 |
|
1392 | |||
1405 | In [1]: run -t uniq_stable |
|
1393 | In [1]: run -t uniq_stable | |
1406 |
|
1394 | |||
1407 | IPython CPU timings (estimated):\\ |
|
1395 | IPython CPU timings (estimated):\\ | |
1408 | User : 0.19597 s.\\ |
|
1396 | User : 0.19597 s.\\ | |
1409 | System: 0.0 s.\\ |
|
1397 | System: 0.0 s.\\ | |
1410 |
|
1398 | |||
1411 | In [2]: run -t -N5 uniq_stable |
|
1399 | In [2]: run -t -N5 uniq_stable | |
1412 |
|
1400 | |||
1413 | IPython CPU timings (estimated):\\ |
|
1401 | IPython CPU timings (estimated):\\ | |
1414 | Total runs performed: 5\\ |
|
1402 | Total runs performed: 5\\ | |
1415 | Times : Total Per run\\ |
|
1403 | Times : Total Per run\\ | |
1416 | User : 0.910862 s, 0.1821724 s.\\ |
|
1404 | User : 0.910862 s, 0.1821724 s.\\ | |
1417 | System: 0.0 s, 0.0 s. |
|
1405 | System: 0.0 s, 0.0 s. | |
1418 |
|
1406 | |||
1419 | -d: run your program under the control of pdb, the Python debugger. |
|
1407 | -d: run your program under the control of pdb, the Python debugger. | |
1420 | This allows you to execute your program step by step, watch variables, |
|
1408 | This allows you to execute your program step by step, watch variables, | |
1421 | etc. Internally, what IPython does is similar to calling: |
|
1409 | etc. Internally, what IPython does is similar to calling: | |
1422 |
|
1410 | |||
1423 | pdb.run('execfile("YOURFILENAME")') |
|
1411 | pdb.run('execfile("YOURFILENAME")') | |
1424 |
|
1412 | |||
1425 | with a breakpoint set on line 1 of your file. You can change the line |
|
1413 | with a breakpoint set on line 1 of your file. You can change the line | |
1426 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1414 | number for this automatic breakpoint to be <N> by using the -bN option | |
1427 | (where N must be an integer). For example: |
|
1415 | (where N must be an integer). For example: | |
1428 |
|
1416 | |||
1429 | %run -d -b40 myscript |
|
1417 | %run -d -b40 myscript | |
1430 |
|
1418 | |||
1431 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1419 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1432 | the first breakpoint must be set on a line which actually does |
|
1420 | the first breakpoint must be set on a line which actually does | |
1433 | something (not a comment or docstring) for it to stop execution. |
|
1421 | something (not a comment or docstring) for it to stop execution. | |
1434 |
|
1422 | |||
1435 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1423 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1436 | first enter 'c' (without qoutes) to start execution up to the first |
|
1424 | first enter 'c' (without qoutes) to start execution up to the first | |
1437 | breakpoint. |
|
1425 | breakpoint. | |
1438 |
|
1426 | |||
1439 | Entering 'help' gives information about the use of the debugger. You |
|
1427 | Entering 'help' gives information about the use of the debugger. You | |
1440 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1428 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1441 | at a prompt. |
|
1429 | at a prompt. | |
1442 |
|
1430 | |||
1443 | -p: run program under the control of the Python profiler module (which |
|
1431 | -p: run program under the control of the Python profiler module (which | |
1444 | prints a detailed report of execution times, function calls, etc). |
|
1432 | prints a detailed report of execution times, function calls, etc). | |
1445 |
|
1433 | |||
1446 | You can pass other options after -p which affect the behavior of the |
|
1434 | You can pass other options after -p which affect the behavior of the | |
1447 | profiler itself. See the docs for %prun for details. |
|
1435 | profiler itself. See the docs for %prun for details. | |
1448 |
|
1436 | |||
1449 | In this mode, the program's variables do NOT propagate back to the |
|
1437 | In this mode, the program's variables do NOT propagate back to the | |
1450 | IPython interactive namespace (because they remain in the namespace |
|
1438 | IPython interactive namespace (because they remain in the namespace | |
1451 | where the profiler executes them). |
|
1439 | where the profiler executes them). | |
1452 |
|
1440 | |||
1453 | Internally this triggers a call to %prun, see its documentation for |
|
1441 | Internally this triggers a call to %prun, see its documentation for | |
1454 | details on the options available specifically for profiling.""" |
|
1442 | details on the options available specifically for profiling.""" | |
1455 |
|
1443 | |||
1456 | # get arguments and set sys.argv for program to be run. |
|
1444 | # get arguments and set sys.argv for program to be run. | |
1457 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1445 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1458 | mode='list',list_all=1) |
|
1446 | mode='list',list_all=1) | |
1459 |
|
1447 | |||
1460 | try: |
|
1448 | try: | |
1461 | filename = get_py_filename(arg_lst[0]) |
|
1449 | filename = get_py_filename(arg_lst[0]) | |
1462 | except IndexError: |
|
1450 | except IndexError: | |
1463 | warn('you must provide at least a filename.') |
|
1451 | warn('you must provide at least a filename.') | |
1464 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1452 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1465 | return |
|
1453 | return | |
1466 | except IOError,msg: |
|
1454 | except IOError,msg: | |
1467 | error(msg) |
|
1455 | error(msg) | |
1468 | return |
|
1456 | return | |
1469 |
|
1457 | |||
1470 | # Control the response to exit() calls made by the script being run |
|
1458 | # Control the response to exit() calls made by the script being run | |
1471 | exit_ignore = opts.has_key('e') |
|
1459 | exit_ignore = opts.has_key('e') | |
1472 |
|
1460 | |||
1473 | # Make sure that the running script gets a proper sys.argv as if it |
|
1461 | # Make sure that the running script gets a proper sys.argv as if it | |
1474 | # were run from a system shell. |
|
1462 | # were run from a system shell. | |
1475 | save_argv = sys.argv # save it for later restoring |
|
1463 | save_argv = sys.argv # save it for later restoring | |
1476 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1464 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1477 |
|
1465 | |||
1478 | if opts.has_key('i'): |
|
1466 | if opts.has_key('i'): | |
1479 | prog_ns = self.shell.user_ns |
|
1467 | prog_ns = self.shell.user_ns | |
1480 | __name__save = self.shell.user_ns['__name__'] |
|
1468 | __name__save = self.shell.user_ns['__name__'] | |
1481 | prog_ns['__name__'] = '__main__' |
|
1469 | prog_ns['__name__'] = '__main__' | |
1482 | else: |
|
1470 | else: | |
1483 | if opts.has_key('n'): |
|
1471 | if opts.has_key('n'): | |
1484 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1472 | name = os.path.splitext(os.path.basename(filename))[0] | |
1485 | else: |
|
1473 | else: | |
1486 | name = '__main__' |
|
1474 | name = '__main__' | |
1487 | prog_ns = {'__name__':name} |
|
1475 | prog_ns = {'__name__':name} | |
1488 |
|
1476 | |||
1489 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1477 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1490 | # set the __file__ global in the script's namespace |
|
1478 | # set the __file__ global in the script's namespace | |
1491 | prog_ns['__file__'] = filename |
|
1479 | prog_ns['__file__'] = filename | |
1492 |
|
1480 | |||
1493 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1481 | # pickle fix. See iplib for an explanation. But we need to make sure | |
1494 | # that, if we overwrite __main__, we replace it at the end |
|
1482 | # that, if we overwrite __main__, we replace it at the end | |
1495 | if prog_ns['__name__'] == '__main__': |
|
1483 | if prog_ns['__name__'] == '__main__': | |
1496 | restore_main = sys.modules['__main__'] |
|
1484 | restore_main = sys.modules['__main__'] | |
1497 | else: |
|
1485 | else: | |
1498 | restore_main = False |
|
1486 | restore_main = False | |
1499 |
|
1487 | |||
1500 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1488 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) | |
1501 |
|
1489 | |||
1502 | stats = None |
|
1490 | stats = None | |
1503 | try: |
|
1491 | try: | |
1504 | if opts.has_key('p'): |
|
1492 | if opts.has_key('p'): | |
1505 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1493 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1506 | else: |
|
1494 | else: | |
1507 | if opts.has_key('d'): |
|
1495 | if opts.has_key('d'): | |
1508 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1496 | deb = Debugger.Pdb(self.shell.rc.colors) | |
1509 | # reset Breakpoint state, which is moronically kept |
|
1497 | # reset Breakpoint state, which is moronically kept | |
1510 | # in a class |
|
1498 | # in a class | |
1511 | bdb.Breakpoint.next = 1 |
|
1499 | bdb.Breakpoint.next = 1 | |
1512 | bdb.Breakpoint.bplist = {} |
|
1500 | bdb.Breakpoint.bplist = {} | |
1513 | bdb.Breakpoint.bpbynumber = [None] |
|
1501 | bdb.Breakpoint.bpbynumber = [None] | |
1514 | # Set an initial breakpoint to stop execution |
|
1502 | # Set an initial breakpoint to stop execution | |
1515 | maxtries = 10 |
|
1503 | maxtries = 10 | |
1516 | bp = int(opts.get('b',[1])[0]) |
|
1504 | bp = int(opts.get('b',[1])[0]) | |
1517 | checkline = deb.checkline(filename,bp) |
|
1505 | checkline = deb.checkline(filename,bp) | |
1518 | if not checkline: |
|
1506 | if not checkline: | |
1519 | for bp in range(bp+1,bp+maxtries+1): |
|
1507 | for bp in range(bp+1,bp+maxtries+1): | |
1520 | if deb.checkline(filename,bp): |
|
1508 | if deb.checkline(filename,bp): | |
1521 | break |
|
1509 | break | |
1522 | else: |
|
1510 | else: | |
1523 | msg = ("\nI failed to find a valid line to set " |
|
1511 | msg = ("\nI failed to find a valid line to set " | |
1524 | "a breakpoint\n" |
|
1512 | "a breakpoint\n" | |
1525 | "after trying up to line: %s.\n" |
|
1513 | "after trying up to line: %s.\n" | |
1526 | "Please set a valid breakpoint manually " |
|
1514 | "Please set a valid breakpoint manually " | |
1527 | "with the -b option." % bp) |
|
1515 | "with the -b option." % bp) | |
1528 | error(msg) |
|
1516 | error(msg) | |
1529 | return |
|
1517 | return | |
1530 | # if we find a good linenumber, set the breakpoint |
|
1518 | # if we find a good linenumber, set the breakpoint | |
1531 | deb.do_break('%s:%s' % (filename,bp)) |
|
1519 | deb.do_break('%s:%s' % (filename,bp)) | |
1532 | # Start file run |
|
1520 | # Start file run | |
1533 | print "NOTE: Enter 'c' at the", |
|
1521 | print "NOTE: Enter 'c' at the", | |
1534 | print "ipdb> prompt to start your script." |
|
1522 | print "ipdb> prompt to start your script." | |
1535 | try: |
|
1523 | try: | |
1536 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1524 | deb.run('execfile("%s")' % filename,prog_ns) | |
1537 | except: |
|
1525 | except: | |
1538 | etype, value, tb = sys.exc_info() |
|
1526 | etype, value, tb = sys.exc_info() | |
1539 | # Skip three frames in the traceback: the %run one, |
|
1527 | # Skip three frames in the traceback: the %run one, | |
1540 | # one inside bdb.py, and the command-line typed by the |
|
1528 | # one inside bdb.py, and the command-line typed by the | |
1541 | # user (run by exec in pdb itself). |
|
1529 | # user (run by exec in pdb itself). | |
1542 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1530 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1543 | else: |
|
1531 | else: | |
1544 | if runner is None: |
|
1532 | if runner is None: | |
1545 | runner = self.shell.safe_execfile |
|
1533 | runner = self.shell.safe_execfile | |
1546 | if opts.has_key('t'): |
|
1534 | if opts.has_key('t'): | |
1547 | try: |
|
1535 | try: | |
1548 | nruns = int(opts['N'][0]) |
|
1536 | nruns = int(opts['N'][0]) | |
1549 | if nruns < 1: |
|
1537 | if nruns < 1: | |
1550 | error('Number of runs must be >=1') |
|
1538 | error('Number of runs must be >=1') | |
1551 | return |
|
1539 | return | |
1552 | except (KeyError): |
|
1540 | except (KeyError): | |
1553 | nruns = 1 |
|
1541 | nruns = 1 | |
1554 | if nruns == 1: |
|
1542 | if nruns == 1: | |
1555 | t0 = clock2() |
|
1543 | t0 = clock2() | |
1556 |
runner(filename,prog_ns,prog_ns, |
|
1544 | runner(filename,prog_ns,prog_ns, | |
|
1545 | exit_ignore=exit_ignore) | |||
1557 | t1 = clock2() |
|
1546 | t1 = clock2() | |
1558 | t_usr = t1[0]-t0[0] |
|
1547 | t_usr = t1[0]-t0[0] | |
1559 | t_sys = t1[1]-t1[1] |
|
1548 | t_sys = t1[1]-t1[1] | |
1560 | print "\nIPython CPU timings (estimated):" |
|
1549 | print "\nIPython CPU timings (estimated):" | |
1561 | print " User : %10s s." % t_usr |
|
1550 | print " User : %10s s." % t_usr | |
1562 | print " System: %10s s." % t_sys |
|
1551 | print " System: %10s s." % t_sys | |
1563 | else: |
|
1552 | else: | |
1564 | runs = range(nruns) |
|
1553 | runs = range(nruns) | |
1565 | t0 = clock2() |
|
1554 | t0 = clock2() | |
1566 | for nr in runs: |
|
1555 | for nr in runs: | |
1567 |
runner(filename,prog_ns,prog_ns, |
|
1556 | runner(filename,prog_ns,prog_ns, | |
|
1557 | exit_ignore=exit_ignore) | |||
1568 | t1 = clock2() |
|
1558 | t1 = clock2() | |
1569 | t_usr = t1[0]-t0[0] |
|
1559 | t_usr = t1[0]-t0[0] | |
1570 | t_sys = t1[1]-t1[1] |
|
1560 | t_sys = t1[1]-t1[1] | |
1571 | print "\nIPython CPU timings (estimated):" |
|
1561 | print "\nIPython CPU timings (estimated):" | |
1572 | print "Total runs performed:",nruns |
|
1562 | print "Total runs performed:",nruns | |
1573 | print " Times : %10s %10s" % ('Total','Per run') |
|
1563 | print " Times : %10s %10s" % ('Total','Per run') | |
1574 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1564 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1575 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1565 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1576 |
|
1566 | |||
1577 | else: |
|
1567 | else: | |
1578 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1568 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1579 | if opts.has_key('i'): |
|
1569 | if opts.has_key('i'): | |
1580 | self.shell.user_ns['__name__'] = __name__save |
|
1570 | self.shell.user_ns['__name__'] = __name__save | |
1581 | else: |
|
1571 | else: | |
1582 | # update IPython interactive namespace |
|
1572 | # update IPython interactive namespace | |
1583 | del prog_ns['__name__'] |
|
1573 | del prog_ns['__name__'] | |
1584 | self.shell.user_ns.update(prog_ns) |
|
1574 | self.shell.user_ns.update(prog_ns) | |
1585 | finally: |
|
1575 | finally: | |
1586 | sys.argv = save_argv |
|
1576 | sys.argv = save_argv | |
1587 | if restore_main: |
|
1577 | if restore_main: | |
1588 | sys.modules['__main__'] = restore_main |
|
1578 | sys.modules['__main__'] = restore_main | |
1589 | return stats |
|
1579 | return stats | |
1590 |
|
1580 | |||
1591 | def magic_runlog(self, parameter_s =''): |
|
1581 | def magic_runlog(self, parameter_s =''): | |
1592 | """Run files as logs. |
|
1582 | """Run files as logs. | |
1593 |
|
1583 | |||
1594 | Usage:\\ |
|
1584 | Usage:\\ | |
1595 | %runlog file1 file2 ... |
|
1585 | %runlog file1 file2 ... | |
1596 |
|
1586 | |||
1597 | Run the named files (treating them as log files) in sequence inside |
|
1587 | Run the named files (treating them as log files) in sequence inside | |
1598 | the interpreter, and return to the prompt. This is much slower than |
|
1588 | the interpreter, and return to the prompt. This is much slower than | |
1599 | %run because each line is executed in a try/except block, but it |
|
1589 | %run because each line is executed in a try/except block, but it | |
1600 | allows running files with syntax errors in them. |
|
1590 | allows running files with syntax errors in them. | |
1601 |
|
1591 | |||
1602 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1592 | Normally IPython will guess when a file is one of its own logfiles, so | |
1603 | you can typically use %run even for logs. This shorthand allows you to |
|
1593 | you can typically use %run even for logs. This shorthand allows you to | |
1604 | force any file to be treated as a log file.""" |
|
1594 | force any file to be treated as a log file.""" | |
1605 |
|
1595 | |||
1606 | for f in parameter_s.split(): |
|
1596 | for f in parameter_s.split(): | |
1607 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1597 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1608 | self.shell.user_ns,islog=1) |
|
1598 | self.shell.user_ns,islog=1) | |
1609 |
|
1599 | |||
1610 | def magic_timeit(self, parameter_s =''): |
|
1600 | def magic_timeit(self, parameter_s =''): | |
1611 | """Time execution of a Python statement or expression |
|
1601 | """Time execution of a Python statement or expression | |
1612 |
|
1602 | |||
1613 | Usage:\\ |
|
1603 | Usage:\\ | |
1614 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1604 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1615 |
|
1605 | |||
1616 | Time execution of a Python statement or expression using the timeit |
|
1606 | Time execution of a Python statement or expression using the timeit | |
1617 | module. |
|
1607 | module. | |
1618 |
|
1608 | |||
1619 | Options: |
|
1609 | Options: | |
1620 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1610 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1621 | is not given, a fitting value is chosen. |
|
1611 | is not given, a fitting value is chosen. | |
1622 |
|
1612 | |||
1623 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1613 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1624 | Default: 3 |
|
1614 | Default: 3 | |
1625 |
|
1615 | |||
1626 | -t: use time.time to measure the time, which is the default on Unix. |
|
1616 | -t: use time.time to measure the time, which is the default on Unix. | |
1627 | This function measures wall time. |
|
1617 | This function measures wall time. | |
1628 |
|
1618 | |||
1629 | -c: use time.clock to measure the time, which is the default on |
|
1619 | -c: use time.clock to measure the time, which is the default on | |
1630 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1620 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1631 | instead and returns the CPU user time. |
|
1621 | instead and returns the CPU user time. | |
1632 |
|
1622 | |||
1633 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1623 | -p<P>: use a precision of <P> digits to display the timing result. | |
1634 | Default: 3 |
|
1624 | Default: 3 | |
1635 |
|
1625 | |||
1636 |
|
1626 | |||
1637 | Examples:\\ |
|
1627 | Examples:\\ | |
1638 | In [1]: %timeit pass |
|
1628 | In [1]: %timeit pass | |
1639 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1629 | 10000000 loops, best of 3: 53.3 ns per loop | |
1640 |
|
1630 | |||
1641 | In [2]: u = None |
|
1631 | In [2]: u = None | |
1642 |
|
1632 | |||
1643 | In [3]: %timeit u is None |
|
1633 | In [3]: %timeit u is None | |
1644 | 10000000 loops, best of 3: 184 ns per loop |
|
1634 | 10000000 loops, best of 3: 184 ns per loop | |
1645 |
|
1635 | |||
1646 | In [4]: %timeit -r 4 u == None |
|
1636 | In [4]: %timeit -r 4 u == None | |
1647 | 1000000 loops, best of 4: 242 ns per loop |
|
1637 | 1000000 loops, best of 4: 242 ns per loop | |
1648 |
|
1638 | |||
1649 | In [5]: import time |
|
1639 | In [5]: import time | |
1650 |
|
1640 | |||
1651 | In [6]: %timeit -n1 time.sleep(2) |
|
1641 | In [6]: %timeit -n1 time.sleep(2) | |
1652 | 1 loops, best of 3: 2 s per loop |
|
1642 | 1 loops, best of 3: 2 s per loop | |
1653 |
|
1643 | |||
1654 |
|
1644 | |||
1655 | The times reported by %timeit will be slightly higher than those |
|
1645 | The times reported by %timeit will be slightly higher than those | |
1656 | reported by the timeit.py script when variables are accessed. This is |
|
1646 | reported by the timeit.py script when variables are accessed. This is | |
1657 | due to the fact that %timeit executes the statement in the namespace |
|
1647 | due to the fact that %timeit executes the statement in the namespace | |
1658 | of the shell, compared with timeit.py, which uses a single setup |
|
1648 | of the shell, compared with timeit.py, which uses a single setup | |
1659 | statement to import function or create variables. Generally, the bias |
|
1649 | statement to import function or create variables. Generally, the bias | |
1660 | does not matter as long as results from timeit.py are not mixed with |
|
1650 | does not matter as long as results from timeit.py are not mixed with | |
1661 | those from %timeit.""" |
|
1651 | those from %timeit.""" | |
1662 |
|
1652 | |||
1663 | import timeit |
|
1653 | import timeit | |
1664 | import math |
|
1654 | import math | |
1665 |
|
1655 | |||
1666 | units = ["s", "ms", "\xc2\xb5s", "ns"] |
|
1656 | units = ["s", "ms", "\xc2\xb5s", "ns"] | |
1667 | scaling = [1, 1e3, 1e6, 1e9] |
|
1657 | scaling = [1, 1e3, 1e6, 1e9] | |
1668 |
|
1658 | |||
1669 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1659 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1670 | posix=False) |
|
1660 | posix=False) | |
1671 | if stmt == "": |
|
1661 | if stmt == "": | |
1672 | return |
|
1662 | return | |
1673 | timefunc = timeit.default_timer |
|
1663 | timefunc = timeit.default_timer | |
1674 | number = int(getattr(opts, "n", 0)) |
|
1664 | number = int(getattr(opts, "n", 0)) | |
1675 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1665 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1676 | precision = int(getattr(opts, "p", 3)) |
|
1666 | precision = int(getattr(opts, "p", 3)) | |
1677 | if hasattr(opts, "t"): |
|
1667 | if hasattr(opts, "t"): | |
1678 | timefunc = time.time |
|
1668 | timefunc = time.time | |
1679 | if hasattr(opts, "c"): |
|
1669 | if hasattr(opts, "c"): | |
1680 | timefunc = clock |
|
1670 | timefunc = clock | |
1681 |
|
1671 | |||
1682 | timer = timeit.Timer(timer=timefunc) |
|
1672 | timer = timeit.Timer(timer=timefunc) | |
1683 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1673 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1684 | # but is there a better way to achieve that the code stmt has access |
|
1674 | # but is there a better way to achieve that the code stmt has access | |
1685 | # to the shell namespace? |
|
1675 | # to the shell namespace? | |
1686 |
|
1676 | |||
1687 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1677 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1688 | 'setup': "pass"} |
|
1678 | 'setup': "pass"} | |
1689 | code = compile(src, "<magic-timeit>", "exec") |
|
1679 | code = compile(src, "<magic-timeit>", "exec") | |
1690 | ns = {} |
|
1680 | ns = {} | |
1691 | exec code in self.shell.user_ns, ns |
|
1681 | exec code in self.shell.user_ns, ns | |
1692 | timer.inner = ns["inner"] |
|
1682 | timer.inner = ns["inner"] | |
1693 |
|
1683 | |||
1694 | if number == 0: |
|
1684 | if number == 0: | |
1695 | # determine number so that 0.2 <= total time < 2.0 |
|
1685 | # determine number so that 0.2 <= total time < 2.0 | |
1696 | number = 1 |
|
1686 | number = 1 | |
1697 | for i in range(1, 10): |
|
1687 | for i in range(1, 10): | |
1698 | number *= 10 |
|
1688 | number *= 10 | |
1699 | if timer.timeit(number) >= 0.2: |
|
1689 | if timer.timeit(number) >= 0.2: | |
1700 | break |
|
1690 | break | |
1701 |
|
1691 | |||
1702 | best = min(timer.repeat(repeat, number)) / number |
|
1692 | best = min(timer.repeat(repeat, number)) / number | |
1703 |
|
1693 | |||
1704 | if best > 0.0: |
|
1694 | if best > 0.0: | |
1705 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1695 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1706 | else: |
|
1696 | else: | |
1707 | order = 3 |
|
1697 | order = 3 | |
1708 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1698 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1709 | precision, |
|
1699 | precision, | |
1710 | best * scaling[order], |
|
1700 | best * scaling[order], | |
1711 | units[order]) |
|
1701 | units[order]) | |
1712 |
|
1702 | |||
1713 | def magic_time(self,parameter_s = ''): |
|
1703 | def magic_time(self,parameter_s = ''): | |
1714 | """Time execution of a Python statement or expression. |
|
1704 | """Time execution of a Python statement or expression. | |
1715 |
|
1705 | |||
1716 | The CPU and wall clock times are printed, and the value of the |
|
1706 | The CPU and wall clock times are printed, and the value of the | |
1717 | expression (if any) is returned. Note that under Win32, system time |
|
1707 | expression (if any) is returned. Note that under Win32, system time | |
1718 | is always reported as 0, since it can not be measured. |
|
1708 | is always reported as 0, since it can not be measured. | |
1719 |
|
1709 | |||
1720 | This function provides very basic timing functionality. In Python |
|
1710 | This function provides very basic timing functionality. In Python | |
1721 | 2.3, the timeit module offers more control and sophistication, so this |
|
1711 | 2.3, the timeit module offers more control and sophistication, so this | |
1722 | could be rewritten to use it (patches welcome). |
|
1712 | could be rewritten to use it (patches welcome). | |
1723 |
|
1713 | |||
1724 | Some examples: |
|
1714 | Some examples: | |
1725 |
|
1715 | |||
1726 | In [1]: time 2**128 |
|
1716 | In [1]: time 2**128 | |
1727 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1717 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1728 | Wall time: 0.00 |
|
1718 | Wall time: 0.00 | |
1729 | Out[1]: 340282366920938463463374607431768211456L |
|
1719 | Out[1]: 340282366920938463463374607431768211456L | |
1730 |
|
1720 | |||
1731 | In [2]: n = 1000000 |
|
1721 | In [2]: n = 1000000 | |
1732 |
|
1722 | |||
1733 | In [3]: time sum(range(n)) |
|
1723 | In [3]: time sum(range(n)) | |
1734 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1724 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1735 | Wall time: 1.37 |
|
1725 | Wall time: 1.37 | |
1736 | Out[3]: 499999500000L |
|
1726 | Out[3]: 499999500000L | |
1737 |
|
1727 | |||
1738 | In [4]: time print 'hello world' |
|
1728 | In [4]: time print 'hello world' | |
1739 | hello world |
|
1729 | hello world | |
1740 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1730 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1741 | Wall time: 0.00 |
|
1731 | Wall time: 0.00 | |
1742 | """ |
|
1732 | """ | |
1743 |
|
1733 | |||
1744 | # fail immediately if the given expression can't be compiled |
|
1734 | # fail immediately if the given expression can't be compiled | |
1745 | try: |
|
1735 | try: | |
1746 | mode = 'eval' |
|
1736 | mode = 'eval' | |
1747 | code = compile(parameter_s,'<timed eval>',mode) |
|
1737 | code = compile(parameter_s,'<timed eval>',mode) | |
1748 | except SyntaxError: |
|
1738 | except SyntaxError: | |
1749 | mode = 'exec' |
|
1739 | mode = 'exec' | |
1750 | code = compile(parameter_s,'<timed exec>',mode) |
|
1740 | code = compile(parameter_s,'<timed exec>',mode) | |
1751 | # skew measurement as little as possible |
|
1741 | # skew measurement as little as possible | |
1752 | glob = self.shell.user_ns |
|
1742 | glob = self.shell.user_ns | |
1753 | clk = clock2 |
|
1743 | clk = clock2 | |
1754 | wtime = time.time |
|
1744 | wtime = time.time | |
1755 | # time execution |
|
1745 | # time execution | |
1756 | wall_st = wtime() |
|
1746 | wall_st = wtime() | |
1757 | if mode=='eval': |
|
1747 | if mode=='eval': | |
1758 | st = clk() |
|
1748 | st = clk() | |
1759 | out = eval(code,glob) |
|
1749 | out = eval(code,glob) | |
1760 | end = clk() |
|
1750 | end = clk() | |
1761 | else: |
|
1751 | else: | |
1762 | st = clk() |
|
1752 | st = clk() | |
1763 | exec code in glob |
|
1753 | exec code in glob | |
1764 | end = clk() |
|
1754 | end = clk() | |
1765 | out = None |
|
1755 | out = None | |
1766 | wall_end = wtime() |
|
1756 | wall_end = wtime() | |
1767 | # Compute actual times and report |
|
1757 | # Compute actual times and report | |
1768 | wall_time = wall_end-wall_st |
|
1758 | wall_time = wall_end-wall_st | |
1769 | cpu_user = end[0]-st[0] |
|
1759 | cpu_user = end[0]-st[0] | |
1770 | cpu_sys = end[1]-st[1] |
|
1760 | cpu_sys = end[1]-st[1] | |
1771 | cpu_tot = cpu_user+cpu_sys |
|
1761 | cpu_tot = cpu_user+cpu_sys | |
1772 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1762 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1773 | (cpu_user,cpu_sys,cpu_tot) |
|
1763 | (cpu_user,cpu_sys,cpu_tot) | |
1774 | print "Wall time: %.2f" % wall_time |
|
1764 | print "Wall time: %.2f" % wall_time | |
1775 | return out |
|
1765 | return out | |
1776 |
|
1766 | |||
1777 | def magic_macro(self,parameter_s = ''): |
|
1767 | def magic_macro(self,parameter_s = ''): | |
1778 | """Define a set of input lines as a macro for future re-execution. |
|
1768 | """Define a set of input lines as a macro for future re-execution. | |
1779 |
|
1769 | |||
1780 | Usage:\\ |
|
1770 | Usage:\\ | |
1781 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1771 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1782 |
|
1772 | |||
1783 | Options: |
|
1773 | Options: | |
1784 |
|
1774 | |||
1785 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1775 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1786 | so that magics are loaded in their transformed version to valid |
|
1776 | so that magics are loaded in their transformed version to valid | |
1787 | Python. If this option is given, the raw input as typed as the |
|
1777 | Python. If this option is given, the raw input as typed as the | |
1788 | command line is used instead. |
|
1778 | command line is used instead. | |
1789 |
|
1779 | |||
1790 | This will define a global variable called `name` which is a string |
|
1780 | This will define a global variable called `name` which is a string | |
1791 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1781 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1792 | above) from your input history into a single string. This variable |
|
1782 | above) from your input history into a single string. This variable | |
1793 | acts like an automatic function which re-executes those lines as if |
|
1783 | acts like an automatic function which re-executes those lines as if | |
1794 | you had typed them. You just type 'name' at the prompt and the code |
|
1784 | you had typed them. You just type 'name' at the prompt and the code | |
1795 | executes. |
|
1785 | executes. | |
1796 |
|
1786 | |||
1797 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1787 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1798 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1788 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1799 | using the lines numbered 5,6 and 7. |
|
1789 | using the lines numbered 5,6 and 7. | |
1800 |
|
1790 | |||
1801 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1791 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1802 | notation, where N:M means numbers N through M-1. |
|
1792 | notation, where N:M means numbers N through M-1. | |
1803 |
|
1793 | |||
1804 | For example, if your history contains (%hist prints it): |
|
1794 | For example, if your history contains (%hist prints it): | |
1805 |
|
1795 | |||
1806 | 44: x=1\\ |
|
1796 | 44: x=1\\ | |
1807 | 45: y=3\\ |
|
1797 | 45: y=3\\ | |
1808 | 46: z=x+y\\ |
|
1798 | 46: z=x+y\\ | |
1809 | 47: print x\\ |
|
1799 | 47: print x\\ | |
1810 | 48: a=5\\ |
|
1800 | 48: a=5\\ | |
1811 | 49: print 'x',x,'y',y\\ |
|
1801 | 49: print 'x',x,'y',y\\ | |
1812 |
|
1802 | |||
1813 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1803 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1814 | called my_macro with: |
|
1804 | called my_macro with: | |
1815 |
|
1805 | |||
1816 | In [51]: %macro my_macro 44-47 49 |
|
1806 | In [51]: %macro my_macro 44-47 49 | |
1817 |
|
1807 | |||
1818 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1808 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1819 | in one pass. |
|
1809 | in one pass. | |
1820 |
|
1810 | |||
1821 | You don't need to give the line-numbers in order, and any given line |
|
1811 | You don't need to give the line-numbers in order, and any given line | |
1822 | number can appear multiple times. You can assemble macros with any |
|
1812 | number can appear multiple times. You can assemble macros with any | |
1823 | lines from your input history in any order. |
|
1813 | lines from your input history in any order. | |
1824 |
|
1814 | |||
1825 | The macro is a simple object which holds its value in an attribute, |
|
1815 | The macro is a simple object which holds its value in an attribute, | |
1826 | but IPython's display system checks for macros and executes them as |
|
1816 | but IPython's display system checks for macros and executes them as | |
1827 | code instead of printing them when you type their name. |
|
1817 | code instead of printing them when you type their name. | |
1828 |
|
1818 | |||
1829 | You can view a macro's contents by explicitly printing it with: |
|
1819 | You can view a macro's contents by explicitly printing it with: | |
1830 |
|
1820 | |||
1831 | 'print macro_name'. |
|
1821 | 'print macro_name'. | |
1832 |
|
1822 | |||
1833 | For one-off cases which DON'T contain magic function calls in them you |
|
1823 | For one-off cases which DON'T contain magic function calls in them you | |
1834 | can obtain similar results by explicitly executing slices from your |
|
1824 | can obtain similar results by explicitly executing slices from your | |
1835 | input history with: |
|
1825 | input history with: | |
1836 |
|
1826 | |||
1837 | In [60]: exec In[44:48]+In[49]""" |
|
1827 | In [60]: exec In[44:48]+In[49]""" | |
1838 |
|
1828 | |||
1839 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1829 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1840 | name,ranges = args[0], args[1:] |
|
1830 | name,ranges = args[0], args[1:] | |
1841 | #print 'rng',ranges # dbg |
|
1831 | #print 'rng',ranges # dbg | |
1842 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1832 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1843 | macro = Macro(lines) |
|
1833 | macro = Macro(lines) | |
1844 | self.shell.user_ns.update({name:macro}) |
|
1834 | self.shell.user_ns.update({name:macro}) | |
1845 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1835 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1846 | print 'Macro contents:' |
|
1836 | print 'Macro contents:' | |
1847 | print macro, |
|
1837 | print macro, | |
1848 |
|
1838 | |||
1849 | def magic_save(self,parameter_s = ''): |
|
1839 | def magic_save(self,parameter_s = ''): | |
1850 | """Save a set of lines to a given filename. |
|
1840 | """Save a set of lines to a given filename. | |
1851 |
|
1841 | |||
1852 | Usage:\\ |
|
1842 | Usage:\\ | |
1853 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1843 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1854 |
|
1844 | |||
1855 | Options: |
|
1845 | Options: | |
1856 |
|
1846 | |||
1857 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1847 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1858 | so that magics are loaded in their transformed version to valid |
|
1848 | so that magics are loaded in their transformed version to valid | |
1859 | Python. If this option is given, the raw input as typed as the |
|
1849 | Python. If this option is given, the raw input as typed as the | |
1860 | command line is used instead. |
|
1850 | command line is used instead. | |
1861 |
|
1851 | |||
1862 | This function uses the same syntax as %macro for line extraction, but |
|
1852 | This function uses the same syntax as %macro for line extraction, but | |
1863 | instead of creating a macro it saves the resulting string to the |
|
1853 | instead of creating a macro it saves the resulting string to the | |
1864 | filename you specify. |
|
1854 | filename you specify. | |
1865 |
|
1855 | |||
1866 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1856 | It adds a '.py' extension to the file if you don't do so yourself, and | |
1867 | it asks for confirmation before overwriting existing files.""" |
|
1857 | it asks for confirmation before overwriting existing files.""" | |
1868 |
|
1858 | |||
1869 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1859 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1870 | fname,ranges = args[0], args[1:] |
|
1860 | fname,ranges = args[0], args[1:] | |
1871 | if not fname.endswith('.py'): |
|
1861 | if not fname.endswith('.py'): | |
1872 | fname += '.py' |
|
1862 | fname += '.py' | |
1873 | if os.path.isfile(fname): |
|
1863 | if os.path.isfile(fname): | |
1874 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1864 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
1875 | if ans.lower() not in ['y','yes']: |
|
1865 | if ans.lower() not in ['y','yes']: | |
1876 | print 'Operation cancelled.' |
|
1866 | print 'Operation cancelled.' | |
1877 | return |
|
1867 | return | |
1878 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
1868 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
1879 | f = file(fname,'w') |
|
1869 | f = file(fname,'w') | |
1880 | f.write(cmds) |
|
1870 | f.write(cmds) | |
1881 | f.close() |
|
1871 | f.close() | |
1882 | print 'The following commands were written to file `%s`:' % fname |
|
1872 | print 'The following commands were written to file `%s`:' % fname | |
1883 | print cmds |
|
1873 | print cmds | |
1884 |
|
1874 | |||
1885 | def _edit_macro(self,mname,macro): |
|
1875 | def _edit_macro(self,mname,macro): | |
1886 | """open an editor with the macro data in a file""" |
|
1876 | """open an editor with the macro data in a file""" | |
1887 | filename = self.shell.mktempfile(macro.value) |
|
1877 | filename = self.shell.mktempfile(macro.value) | |
1888 | self.shell.hooks.editor(filename) |
|
1878 | self.shell.hooks.editor(filename) | |
1889 |
|
1879 | |||
1890 | # and make a new macro object, to replace the old one |
|
1880 | # and make a new macro object, to replace the old one | |
1891 | mfile = open(filename) |
|
1881 | mfile = open(filename) | |
1892 | mvalue = mfile.read() |
|
1882 | mvalue = mfile.read() | |
1893 | mfile.close() |
|
1883 | mfile.close() | |
1894 | self.shell.user_ns[mname] = Macro(mvalue) |
|
1884 | self.shell.user_ns[mname] = Macro(mvalue) | |
1895 |
|
1885 | |||
1896 | def magic_ed(self,parameter_s=''): |
|
1886 | def magic_ed(self,parameter_s=''): | |
1897 | """Alias to %edit.""" |
|
1887 | """Alias to %edit.""" | |
1898 | return self.magic_edit(parameter_s) |
|
1888 | return self.magic_edit(parameter_s) | |
1899 |
|
1889 | |||
1900 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
1890 | def magic_edit(self,parameter_s='',last_call=['','']): | |
1901 | """Bring up an editor and execute the resulting code. |
|
1891 | """Bring up an editor and execute the resulting code. | |
1902 |
|
1892 | |||
1903 | Usage: |
|
1893 | Usage: | |
1904 | %edit [options] [args] |
|
1894 | %edit [options] [args] | |
1905 |
|
1895 | |||
1906 | %edit runs IPython's editor hook. The default version of this hook is |
|
1896 | %edit runs IPython's editor hook. The default version of this hook is | |
1907 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1897 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
1908 | environment variable $EDITOR. If this isn't found, it will default to |
|
1898 | environment variable $EDITOR. If this isn't found, it will default to | |
1909 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1899 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
1910 | docstring for how to change the editor hook. |
|
1900 | docstring for how to change the editor hook. | |
1911 |
|
1901 | |||
1912 | You can also set the value of this editor via the command line option |
|
1902 | You can also set the value of this editor via the command line option | |
1913 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
1903 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
1914 | specifically for IPython an editor different from your typical default |
|
1904 | specifically for IPython an editor different from your typical default | |
1915 | (and for Windows users who typically don't set environment variables). |
|
1905 | (and for Windows users who typically don't set environment variables). | |
1916 |
|
1906 | |||
1917 | This command allows you to conveniently edit multi-line code right in |
|
1907 | This command allows you to conveniently edit multi-line code right in | |
1918 | your IPython session. |
|
1908 | your IPython session. | |
1919 |
|
1909 | |||
1920 | If called without arguments, %edit opens up an empty editor with a |
|
1910 | If called without arguments, %edit opens up an empty editor with a | |
1921 | temporary file and will execute the contents of this file when you |
|
1911 | temporary file and will execute the contents of this file when you | |
1922 | close it (don't forget to save it!). |
|
1912 | close it (don't forget to save it!). | |
1923 |
|
1913 | |||
1924 |
|
1914 | |||
1925 | Options: |
|
1915 | Options: | |
1926 |
|
1916 | |||
1927 | -n <number>: open the editor at a specified line number. By default, |
|
1917 | -n <number>: open the editor at a specified line number. By default, | |
1928 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
1918 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
1929 | you can configure this by providing your own modified hook if your |
|
1919 | you can configure this by providing your own modified hook if your | |
1930 | favorite editor supports line-number specifications with a different |
|
1920 | favorite editor supports line-number specifications with a different | |
1931 | syntax. |
|
1921 | syntax. | |
1932 |
|
1922 | |||
1933 | -p: this will call the editor with the same data as the previous time |
|
1923 | -p: this will call the editor with the same data as the previous time | |
1934 | it was used, regardless of how long ago (in your current session) it |
|
1924 | it was used, regardless of how long ago (in your current session) it | |
1935 | was. |
|
1925 | was. | |
1936 |
|
1926 | |||
1937 | -r: use 'raw' input. This option only applies to input taken from the |
|
1927 | -r: use 'raw' input. This option only applies to input taken from the | |
1938 | user's history. By default, the 'processed' history is used, so that |
|
1928 | user's history. By default, the 'processed' history is used, so that | |
1939 | magics are loaded in their transformed version to valid Python. If |
|
1929 | magics are loaded in their transformed version to valid Python. If | |
1940 | this option is given, the raw input as typed as the command line is |
|
1930 | this option is given, the raw input as typed as the command line is | |
1941 | used instead. When you exit the editor, it will be executed by |
|
1931 | used instead. When you exit the editor, it will be executed by | |
1942 | IPython's own processor. |
|
1932 | IPython's own processor. | |
1943 |
|
1933 | |||
1944 | -x: do not execute the edited code immediately upon exit. This is |
|
1934 | -x: do not execute the edited code immediately upon exit. This is | |
1945 | mainly useful if you are editing programs which need to be called with |
|
1935 | mainly useful if you are editing programs which need to be called with | |
1946 | command line arguments, which you can then do using %run. |
|
1936 | command line arguments, which you can then do using %run. | |
1947 |
|
1937 | |||
1948 |
|
1938 | |||
1949 | Arguments: |
|
1939 | Arguments: | |
1950 |
|
1940 | |||
1951 | If arguments are given, the following possibilites exist: |
|
1941 | If arguments are given, the following possibilites exist: | |
1952 |
|
1942 | |||
1953 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
1943 | - The arguments are numbers or pairs of colon-separated numbers (like | |
1954 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
1944 | 1 4:8 9). These are interpreted as lines of previous input to be | |
1955 | loaded into the editor. The syntax is the same of the %macro command. |
|
1945 | loaded into the editor. The syntax is the same of the %macro command. | |
1956 |
|
1946 | |||
1957 | - If the argument doesn't start with a number, it is evaluated as a |
|
1947 | - If the argument doesn't start with a number, it is evaluated as a | |
1958 | variable and its contents loaded into the editor. You can thus edit |
|
1948 | variable and its contents loaded into the editor. You can thus edit | |
1959 | any string which contains python code (including the result of |
|
1949 | any string which contains python code (including the result of | |
1960 | previous edits). |
|
1950 | previous edits). | |
1961 |
|
1951 | |||
1962 | - If the argument is the name of an object (other than a string), |
|
1952 | - If the argument is the name of an object (other than a string), | |
1963 | IPython will try to locate the file where it was defined and open the |
|
1953 | IPython will try to locate the file where it was defined and open the | |
1964 | editor at the point where it is defined. You can use `%edit function` |
|
1954 | editor at the point where it is defined. You can use `%edit function` | |
1965 | to load an editor exactly at the point where 'function' is defined, |
|
1955 | to load an editor exactly at the point where 'function' is defined, | |
1966 | edit it and have the file be executed automatically. |
|
1956 | edit it and have the file be executed automatically. | |
1967 |
|
1957 | |||
1968 | If the object is a macro (see %macro for details), this opens up your |
|
1958 | If the object is a macro (see %macro for details), this opens up your | |
1969 | specified editor with a temporary file containing the macro's data. |
|
1959 | specified editor with a temporary file containing the macro's data. | |
1970 | Upon exit, the macro is reloaded with the contents of the file. |
|
1960 | Upon exit, the macro is reloaded with the contents of the file. | |
1971 |
|
1961 | |||
1972 | Note: opening at an exact line is only supported under Unix, and some |
|
1962 | Note: opening at an exact line is only supported under Unix, and some | |
1973 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
1963 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
1974 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
1964 | '+NUMBER' parameter necessary for this feature. Good editors like | |
1975 | (X)Emacs, vi, jed, pico and joe all do. |
|
1965 | (X)Emacs, vi, jed, pico and joe all do. | |
1976 |
|
1966 | |||
1977 | - If the argument is not found as a variable, IPython will look for a |
|
1967 | - If the argument is not found as a variable, IPython will look for a | |
1978 | file with that name (adding .py if necessary) and load it into the |
|
1968 | file with that name (adding .py if necessary) and load it into the | |
1979 | editor. It will execute its contents with execfile() when you exit, |
|
1969 | editor. It will execute its contents with execfile() when you exit, | |
1980 | loading any code in the file into your interactive namespace. |
|
1970 | loading any code in the file into your interactive namespace. | |
1981 |
|
1971 | |||
1982 | After executing your code, %edit will return as output the code you |
|
1972 | After executing your code, %edit will return as output the code you | |
1983 | typed in the editor (except when it was an existing file). This way |
|
1973 | typed in the editor (except when it was an existing file). This way | |
1984 | you can reload the code in further invocations of %edit as a variable, |
|
1974 | you can reload the code in further invocations of %edit as a variable, | |
1985 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
1975 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
1986 | the output. |
|
1976 | the output. | |
1987 |
|
1977 | |||
1988 | Note that %edit is also available through the alias %ed. |
|
1978 | Note that %edit is also available through the alias %ed. | |
1989 |
|
1979 | |||
1990 | This is an example of creating a simple function inside the editor and |
|
1980 | This is an example of creating a simple function inside the editor and | |
1991 | then modifying it. First, start up the editor: |
|
1981 | then modifying it. First, start up the editor: | |
1992 |
|
1982 | |||
1993 | In [1]: ed\\ |
|
1983 | In [1]: ed\\ | |
1994 | Editing... done. Executing edited code...\\ |
|
1984 | Editing... done. Executing edited code...\\ | |
1995 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
1985 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' | |
1996 |
|
1986 | |||
1997 | We can then call the function foo(): |
|
1987 | We can then call the function foo(): | |
1998 |
|
1988 | |||
1999 | In [2]: foo()\\ |
|
1989 | In [2]: foo()\\ | |
2000 | foo() was defined in an editing session |
|
1990 | foo() was defined in an editing session | |
2001 |
|
1991 | |||
2002 | Now we edit foo. IPython automatically loads the editor with the |
|
1992 | Now we edit foo. IPython automatically loads the editor with the | |
2003 | (temporary) file where foo() was previously defined: |
|
1993 | (temporary) file where foo() was previously defined: | |
2004 |
|
1994 | |||
2005 | In [3]: ed foo\\ |
|
1995 | In [3]: ed foo\\ | |
2006 | Editing... done. Executing edited code... |
|
1996 | Editing... done. Executing edited code... | |
2007 |
|
1997 | |||
2008 | And if we call foo() again we get the modified version: |
|
1998 | And if we call foo() again we get the modified version: | |
2009 |
|
1999 | |||
2010 | In [4]: foo()\\ |
|
2000 | In [4]: foo()\\ | |
2011 | foo() has now been changed! |
|
2001 | foo() has now been changed! | |
2012 |
|
2002 | |||
2013 | Here is an example of how to edit a code snippet successive |
|
2003 | Here is an example of how to edit a code snippet successive | |
2014 | times. First we call the editor: |
|
2004 | times. First we call the editor: | |
2015 |
|
2005 | |||
2016 | In [8]: ed\\ |
|
2006 | In [8]: ed\\ | |
2017 | Editing... done. Executing edited code...\\ |
|
2007 | Editing... done. Executing edited code...\\ | |
2018 | hello\\ |
|
2008 | hello\\ | |
2019 | Out[8]: "print 'hello'\\n" |
|
2009 | Out[8]: "print 'hello'\\n" | |
2020 |
|
2010 | |||
2021 | Now we call it again with the previous output (stored in _): |
|
2011 | Now we call it again with the previous output (stored in _): | |
2022 |
|
2012 | |||
2023 | In [9]: ed _\\ |
|
2013 | In [9]: ed _\\ | |
2024 | Editing... done. Executing edited code...\\ |
|
2014 | Editing... done. Executing edited code...\\ | |
2025 | hello world\\ |
|
2015 | hello world\\ | |
2026 | Out[9]: "print 'hello world'\\n" |
|
2016 | Out[9]: "print 'hello world'\\n" | |
2027 |
|
2017 | |||
2028 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2018 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2029 |
|
2019 | |||
2030 | In [10]: ed _8\\ |
|
2020 | In [10]: ed _8\\ | |
2031 | Editing... done. Executing edited code...\\ |
|
2021 | Editing... done. Executing edited code...\\ | |
2032 | hello again\\ |
|
2022 | hello again\\ | |
2033 | Out[10]: "print 'hello again'\\n" |
|
2023 | Out[10]: "print 'hello again'\\n" | |
2034 |
|
2024 | |||
2035 |
|
2025 | |||
2036 | Changing the default editor hook: |
|
2026 | Changing the default editor hook: | |
2037 |
|
2027 | |||
2038 | If you wish to write your own editor hook, you can put it in a |
|
2028 | If you wish to write your own editor hook, you can put it in a | |
2039 | configuration file which you load at startup time. The default hook |
|
2029 | configuration file which you load at startup time. The default hook | |
2040 | is defined in the IPython.hooks module, and you can use that as a |
|
2030 | is defined in the IPython.hooks module, and you can use that as a | |
2041 | starting example for further modifications. That file also has |
|
2031 | starting example for further modifications. That file also has | |
2042 | general instructions on how to set a new hook for use once you've |
|
2032 | general instructions on how to set a new hook for use once you've | |
2043 | defined it.""" |
|
2033 | defined it.""" | |
2044 |
|
2034 | |||
2045 | # FIXME: This function has become a convoluted mess. It needs a |
|
2035 | # FIXME: This function has become a convoluted mess. It needs a | |
2046 | # ground-up rewrite with clean, simple logic. |
|
2036 | # ground-up rewrite with clean, simple logic. | |
2047 |
|
2037 | |||
2048 | def make_filename(arg): |
|
2038 | def make_filename(arg): | |
2049 | "Make a filename from the given args" |
|
2039 | "Make a filename from the given args" | |
2050 | try: |
|
2040 | try: | |
2051 | filename = get_py_filename(arg) |
|
2041 | filename = get_py_filename(arg) | |
2052 | except IOError: |
|
2042 | except IOError: | |
2053 | if args.endswith('.py'): |
|
2043 | if args.endswith('.py'): | |
2054 | filename = arg |
|
2044 | filename = arg | |
2055 | else: |
|
2045 | else: | |
2056 | filename = None |
|
2046 | filename = None | |
2057 | return filename |
|
2047 | return filename | |
2058 |
|
2048 | |||
2059 | # custom exceptions |
|
2049 | # custom exceptions | |
2060 | class DataIsObject(Exception): pass |
|
2050 | class DataIsObject(Exception): pass | |
2061 |
|
2051 | |||
2062 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2052 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2063 | # Set a few locals from the options for convenience: |
|
2053 | # Set a few locals from the options for convenience: | |
2064 | opts_p = opts.has_key('p') |
|
2054 | opts_p = opts.has_key('p') | |
2065 | opts_r = opts.has_key('r') |
|
2055 | opts_r = opts.has_key('r') | |
2066 |
|
2056 | |||
2067 | # Default line number value |
|
2057 | # Default line number value | |
2068 | lineno = opts.get('n',None) |
|
2058 | lineno = opts.get('n',None) | |
2069 |
|
2059 | |||
2070 | if opts_p: |
|
2060 | if opts_p: | |
2071 | args = '_%s' % last_call[0] |
|
2061 | args = '_%s' % last_call[0] | |
2072 | if not self.shell.user_ns.has_key(args): |
|
2062 | if not self.shell.user_ns.has_key(args): | |
2073 | args = last_call[1] |
|
2063 | args = last_call[1] | |
2074 |
|
2064 | |||
2075 | # use last_call to remember the state of the previous call, but don't |
|
2065 | # use last_call to remember the state of the previous call, but don't | |
2076 | # let it be clobbered by successive '-p' calls. |
|
2066 | # let it be clobbered by successive '-p' calls. | |
2077 | try: |
|
2067 | try: | |
2078 | last_call[0] = self.shell.outputcache.prompt_count |
|
2068 | last_call[0] = self.shell.outputcache.prompt_count | |
2079 | if not opts_p: |
|
2069 | if not opts_p: | |
2080 | last_call[1] = parameter_s |
|
2070 | last_call[1] = parameter_s | |
2081 | except: |
|
2071 | except: | |
2082 | pass |
|
2072 | pass | |
2083 |
|
2073 | |||
2084 | # by default this is done with temp files, except when the given |
|
2074 | # by default this is done with temp files, except when the given | |
2085 | # arg is a filename |
|
2075 | # arg is a filename | |
2086 | use_temp = 1 |
|
2076 | use_temp = 1 | |
2087 |
|
2077 | |||
2088 | if re.match(r'\d',args): |
|
2078 | if re.match(r'\d',args): | |
2089 | # Mode where user specifies ranges of lines, like in %macro. |
|
2079 | # Mode where user specifies ranges of lines, like in %macro. | |
2090 | # This means that you can't edit files whose names begin with |
|
2080 | # This means that you can't edit files whose names begin with | |
2091 | # numbers this way. Tough. |
|
2081 | # numbers this way. Tough. | |
2092 | ranges = args.split() |
|
2082 | ranges = args.split() | |
2093 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2083 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2094 | elif args.endswith('.py'): |
|
2084 | elif args.endswith('.py'): | |
2095 | filename = make_filename(args) |
|
2085 | filename = make_filename(args) | |
2096 | data = '' |
|
2086 | data = '' | |
2097 | use_temp = 0 |
|
2087 | use_temp = 0 | |
2098 | elif args: |
|
2088 | elif args: | |
2099 | try: |
|
2089 | try: | |
2100 | # Load the parameter given as a variable. If not a string, |
|
2090 | # Load the parameter given as a variable. If not a string, | |
2101 | # process it as an object instead (below) |
|
2091 | # process it as an object instead (below) | |
2102 |
|
2092 | |||
2103 | #print '*** args',args,'type',type(args) # dbg |
|
2093 | #print '*** args',args,'type',type(args) # dbg | |
2104 | data = eval(args,self.shell.user_ns) |
|
2094 | data = eval(args,self.shell.user_ns) | |
2105 | if not type(data) in StringTypes: |
|
2095 | if not type(data) in StringTypes: | |
2106 | raise DataIsObject |
|
2096 | raise DataIsObject | |
2107 |
|
2097 | |||
2108 | except (NameError,SyntaxError): |
|
2098 | except (NameError,SyntaxError): | |
2109 | # given argument is not a variable, try as a filename |
|
2099 | # given argument is not a variable, try as a filename | |
2110 | filename = make_filename(args) |
|
2100 | filename = make_filename(args) | |
2111 | if filename is None: |
|
2101 | if filename is None: | |
2112 | warn("Argument given (%s) can't be found as a variable " |
|
2102 | warn("Argument given (%s) can't be found as a variable " | |
2113 | "or as a filename." % args) |
|
2103 | "or as a filename." % args) | |
2114 | return |
|
2104 | return | |
2115 |
|
2105 | |||
2116 | data = '' |
|
2106 | data = '' | |
2117 | use_temp = 0 |
|
2107 | use_temp = 0 | |
2118 | except DataIsObject: |
|
2108 | except DataIsObject: | |
2119 |
|
2109 | |||
2120 | # macros have a special edit function |
|
2110 | # macros have a special edit function | |
2121 | if isinstance(data,Macro): |
|
2111 | if isinstance(data,Macro): | |
2122 | self._edit_macro(args,data) |
|
2112 | self._edit_macro(args,data) | |
2123 | return |
|
2113 | return | |
2124 |
|
2114 | |||
2125 | # For objects, try to edit the file where they are defined |
|
2115 | # For objects, try to edit the file where they are defined | |
2126 | try: |
|
2116 | try: | |
2127 | filename = inspect.getabsfile(data) |
|
2117 | filename = inspect.getabsfile(data) | |
2128 | datafile = 1 |
|
2118 | datafile = 1 | |
2129 | except TypeError: |
|
2119 | except TypeError: | |
2130 | filename = make_filename(args) |
|
2120 | filename = make_filename(args) | |
2131 | datafile = 1 |
|
2121 | datafile = 1 | |
2132 | warn('Could not find file where `%s` is defined.\n' |
|
2122 | warn('Could not find file where `%s` is defined.\n' | |
2133 | 'Opening a file named `%s`' % (args,filename)) |
|
2123 | 'Opening a file named `%s`' % (args,filename)) | |
2134 | # Now, make sure we can actually read the source (if it was in |
|
2124 | # Now, make sure we can actually read the source (if it was in | |
2135 | # a temp file it's gone by now). |
|
2125 | # a temp file it's gone by now). | |
2136 | if datafile: |
|
2126 | if datafile: | |
2137 | try: |
|
2127 | try: | |
2138 | if lineno is None: |
|
2128 | if lineno is None: | |
2139 | lineno = inspect.getsourcelines(data)[1] |
|
2129 | lineno = inspect.getsourcelines(data)[1] | |
2140 | except IOError: |
|
2130 | except IOError: | |
2141 | filename = make_filename(args) |
|
2131 | filename = make_filename(args) | |
2142 | if filename is None: |
|
2132 | if filename is None: | |
2143 | warn('The file `%s` where `%s` was defined cannot ' |
|
2133 | warn('The file `%s` where `%s` was defined cannot ' | |
2144 | 'be read.' % (filename,data)) |
|
2134 | 'be read.' % (filename,data)) | |
2145 | return |
|
2135 | return | |
2146 | use_temp = 0 |
|
2136 | use_temp = 0 | |
2147 | else: |
|
2137 | else: | |
2148 | data = '' |
|
2138 | data = '' | |
2149 |
|
2139 | |||
2150 | if use_temp: |
|
2140 | if use_temp: | |
2151 | filename = self.shell.mktempfile(data) |
|
2141 | filename = self.shell.mktempfile(data) | |
2152 | print 'IPython will make a temporary file named:',filename |
|
2142 | print 'IPython will make a temporary file named:',filename | |
2153 |
|
2143 | |||
2154 | # do actual editing here |
|
2144 | # do actual editing here | |
2155 | print 'Editing...', |
|
2145 | print 'Editing...', | |
2156 | sys.stdout.flush() |
|
2146 | sys.stdout.flush() | |
2157 | self.shell.hooks.editor(filename,lineno) |
|
2147 | self.shell.hooks.editor(filename,lineno) | |
2158 | if opts.has_key('x'): # -x prevents actual execution |
|
2148 | if opts.has_key('x'): # -x prevents actual execution | |
2159 |
|
2149 | |||
2160 | else: |
|
2150 | else: | |
2161 | print 'done. Executing edited code...' |
|
2151 | print 'done. Executing edited code...' | |
2162 | if opts_r: |
|
2152 | if opts_r: | |
2163 | self.shell.runlines(file_read(filename)) |
|
2153 | self.shell.runlines(file_read(filename)) | |
2164 | else: |
|
2154 | else: | |
2165 | self.shell.safe_execfile(filename,self.shell.user_ns) |
|
2155 | self.shell.safe_execfile(filename,self.shell.user_ns) | |
2166 | if use_temp: |
|
2156 | if use_temp: | |
2167 | try: |
|
2157 | try: | |
2168 | return open(filename).read() |
|
2158 | return open(filename).read() | |
2169 | except IOError,msg: |
|
2159 | except IOError,msg: | |
2170 | if msg.filename == filename: |
|
2160 | if msg.filename == filename: | |
2171 | warn('File not found. Did you forget to save?') |
|
2161 | warn('File not found. Did you forget to save?') | |
2172 | return |
|
2162 | return | |
2173 | else: |
|
2163 | else: | |
2174 | self.shell.showtraceback() |
|
2164 | self.shell.showtraceback() | |
2175 |
|
2165 | |||
2176 | def magic_xmode(self,parameter_s = ''): |
|
2166 | def magic_xmode(self,parameter_s = ''): | |
2177 | """Switch modes for the exception handlers. |
|
2167 | """Switch modes for the exception handlers. | |
2178 |
|
2168 | |||
2179 | Valid modes: Plain, Context and Verbose. |
|
2169 | Valid modes: Plain, Context and Verbose. | |
2180 |
|
2170 | |||
2181 | If called without arguments, acts as a toggle.""" |
|
2171 | If called without arguments, acts as a toggle.""" | |
2182 |
|
2172 | |||
2183 | def xmode_switch_err(name): |
|
2173 | def xmode_switch_err(name): | |
2184 | warn('Error changing %s exception modes.\n%s' % |
|
2174 | warn('Error changing %s exception modes.\n%s' % | |
2185 | (name,sys.exc_info()[1])) |
|
2175 | (name,sys.exc_info()[1])) | |
2186 |
|
2176 | |||
2187 | shell = self.shell |
|
2177 | shell = self.shell | |
2188 | new_mode = parameter_s.strip().capitalize() |
|
2178 | new_mode = parameter_s.strip().capitalize() | |
2189 | try: |
|
2179 | try: | |
2190 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2180 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2191 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2181 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2192 | except: |
|
2182 | except: | |
2193 | xmode_switch_err('user') |
|
2183 | xmode_switch_err('user') | |
2194 |
|
2184 | |||
2195 | # threaded shells use a special handler in sys.excepthook |
|
2185 | # threaded shells use a special handler in sys.excepthook | |
2196 | if shell.isthreaded: |
|
2186 | if shell.isthreaded: | |
2197 | try: |
|
2187 | try: | |
2198 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2188 | shell.sys_excepthook.set_mode(mode=new_mode) | |
2199 | except: |
|
2189 | except: | |
2200 | xmode_switch_err('threaded') |
|
2190 | xmode_switch_err('threaded') | |
2201 |
|
2191 | |||
2202 | def magic_colors(self,parameter_s = ''): |
|
2192 | def magic_colors(self,parameter_s = ''): | |
2203 | """Switch color scheme for prompts, info system and exception handlers. |
|
2193 | """Switch color scheme for prompts, info system and exception handlers. | |
2204 |
|
2194 | |||
2205 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2195 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2206 |
|
2196 | |||
2207 | Color scheme names are not case-sensitive.""" |
|
2197 | Color scheme names are not case-sensitive.""" | |
2208 |
|
2198 | |||
2209 | def color_switch_err(name): |
|
2199 | def color_switch_err(name): | |
2210 | warn('Error changing %s color schemes.\n%s' % |
|
2200 | warn('Error changing %s color schemes.\n%s' % | |
2211 | (name,sys.exc_info()[1])) |
|
2201 | (name,sys.exc_info()[1])) | |
2212 |
|
2202 | |||
2213 |
|
2203 | |||
2214 | new_scheme = parameter_s.strip() |
|
2204 | new_scheme = parameter_s.strip() | |
2215 | if not new_scheme: |
|
2205 | if not new_scheme: | |
2216 | print 'You must specify a color scheme.' |
|
2206 | print 'You must specify a color scheme.' | |
2217 | return |
|
2207 | return | |
2218 | import IPython.rlineimpl as readline |
|
2208 | import IPython.rlineimpl as readline | |
2219 | if not readline.have_readline: |
|
2209 | if not readline.have_readline: | |
2220 | msg = """\ |
|
2210 | msg = """\ | |
2221 | Proper color support under MS Windows requires the pyreadline library. |
|
2211 | Proper color support under MS Windows requires the pyreadline library. | |
2222 | You can find it at: |
|
2212 | You can find it at: | |
2223 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2213 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2224 | Gary's readline needs the ctypes module, from: |
|
2214 | Gary's readline needs the ctypes module, from: | |
2225 | http://starship.python.net/crew/theller/ctypes |
|
2215 | http://starship.python.net/crew/theller/ctypes | |
2226 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2216 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2227 |
|
2217 | |||
2228 | Defaulting color scheme to 'NoColor'""" |
|
2218 | Defaulting color scheme to 'NoColor'""" | |
2229 | new_scheme = 'NoColor' |
|
2219 | new_scheme = 'NoColor' | |
2230 | warn(msg) |
|
2220 | warn(msg) | |
2231 | # local shortcut |
|
2221 | # local shortcut | |
2232 | shell = self.shell |
|
2222 | shell = self.shell | |
2233 |
|
2223 | |||
2234 | # Set prompt colors |
|
2224 | # Set prompt colors | |
2235 | try: |
|
2225 | try: | |
2236 | shell.outputcache.set_colors(new_scheme) |
|
2226 | shell.outputcache.set_colors(new_scheme) | |
2237 | except: |
|
2227 | except: | |
2238 | color_switch_err('prompt') |
|
2228 | color_switch_err('prompt') | |
2239 | else: |
|
2229 | else: | |
2240 | shell.rc.colors = \ |
|
2230 | shell.rc.colors = \ | |
2241 | shell.outputcache.color_table.active_scheme_name |
|
2231 | shell.outputcache.color_table.active_scheme_name | |
2242 | # Set exception colors |
|
2232 | # Set exception colors | |
2243 | try: |
|
2233 | try: | |
2244 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2234 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2245 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2235 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2246 | except: |
|
2236 | except: | |
2247 | color_switch_err('exception') |
|
2237 | color_switch_err('exception') | |
2248 |
|
2238 | |||
2249 | # threaded shells use a verbose traceback in sys.excepthook |
|
2239 | # threaded shells use a verbose traceback in sys.excepthook | |
2250 | if shell.isthreaded: |
|
2240 | if shell.isthreaded: | |
2251 | try: |
|
2241 | try: | |
2252 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2242 | shell.sys_excepthook.set_colors(scheme=new_scheme) | |
2253 | except: |
|
2243 | except: | |
2254 | color_switch_err('system exception handler') |
|
2244 | color_switch_err('system exception handler') | |
2255 |
|
2245 | |||
2256 | # Set info (for 'object?') colors |
|
2246 | # Set info (for 'object?') colors | |
2257 | if shell.rc.color_info: |
|
2247 | if shell.rc.color_info: | |
2258 | try: |
|
2248 | try: | |
2259 | shell.inspector.set_active_scheme(new_scheme) |
|
2249 | shell.inspector.set_active_scheme(new_scheme) | |
2260 | except: |
|
2250 | except: | |
2261 | color_switch_err('object inspector') |
|
2251 | color_switch_err('object inspector') | |
2262 | else: |
|
2252 | else: | |
2263 | shell.inspector.set_active_scheme('NoColor') |
|
2253 | shell.inspector.set_active_scheme('NoColor') | |
2264 |
|
2254 | |||
2265 | def magic_color_info(self,parameter_s = ''): |
|
2255 | def magic_color_info(self,parameter_s = ''): | |
2266 | """Toggle color_info. |
|
2256 | """Toggle color_info. | |
2267 |
|
2257 | |||
2268 | The color_info configuration parameter controls whether colors are |
|
2258 | The color_info configuration parameter controls whether colors are | |
2269 | used for displaying object details (by things like %psource, %pfile or |
|
2259 | used for displaying object details (by things like %psource, %pfile or | |
2270 | the '?' system). This function toggles this value with each call. |
|
2260 | the '?' system). This function toggles this value with each call. | |
2271 |
|
2261 | |||
2272 | Note that unless you have a fairly recent pager (less works better |
|
2262 | Note that unless you have a fairly recent pager (less works better | |
2273 | than more) in your system, using colored object information displays |
|
2263 | than more) in your system, using colored object information displays | |
2274 | will not work properly. Test it and see.""" |
|
2264 | will not work properly. Test it and see.""" | |
2275 |
|
2265 | |||
2276 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2266 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
2277 | self.magic_colors(self.shell.rc.colors) |
|
2267 | self.magic_colors(self.shell.rc.colors) | |
2278 | print 'Object introspection functions have now coloring:', |
|
2268 | print 'Object introspection functions have now coloring:', | |
2279 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2269 | print ['OFF','ON'][self.shell.rc.color_info] | |
2280 |
|
2270 | |||
2281 | def magic_Pprint(self, parameter_s=''): |
|
2271 | def magic_Pprint(self, parameter_s=''): | |
2282 | """Toggle pretty printing on/off.""" |
|
2272 | """Toggle pretty printing on/off.""" | |
2283 |
|
2273 | |||
2284 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2274 | self.shell.rc.pprint = 1 - self.shell.rc.pprint | |
2285 | print 'Pretty printing has been turned', \ |
|
2275 | print 'Pretty printing has been turned', \ | |
2286 | ['OFF','ON'][self.shell.rc.pprint] |
|
2276 | ['OFF','ON'][self.shell.rc.pprint] | |
2287 |
|
2277 | |||
2288 | def magic_exit(self, parameter_s=''): |
|
2278 | def magic_exit(self, parameter_s=''): | |
2289 | """Exit IPython, confirming if configured to do so. |
|
2279 | """Exit IPython, confirming if configured to do so. | |
2290 |
|
2280 | |||
2291 | You can configure whether IPython asks for confirmation upon exit by |
|
2281 | You can configure whether IPython asks for confirmation upon exit by | |
2292 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2282 | setting the confirm_exit flag in the ipythonrc file.""" | |
2293 |
|
2283 | |||
2294 | self.shell.exit() |
|
2284 | self.shell.exit() | |
2295 |
|
2285 | |||
2296 | def magic_quit(self, parameter_s=''): |
|
2286 | def magic_quit(self, parameter_s=''): | |
2297 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2287 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
2298 |
|
2288 | |||
2299 | self.shell.exit() |
|
2289 | self.shell.exit() | |
2300 |
|
2290 | |||
2301 | def magic_Exit(self, parameter_s=''): |
|
2291 | def magic_Exit(self, parameter_s=''): | |
2302 | """Exit IPython without confirmation.""" |
|
2292 | """Exit IPython without confirmation.""" | |
2303 |
|
2293 | |||
2304 | self.shell.exit_now = True |
|
2294 | self.shell.exit_now = True | |
2305 |
|
2295 | |||
2306 | def magic_Quit(self, parameter_s=''): |
|
2296 | def magic_Quit(self, parameter_s=''): | |
2307 | """Exit IPython without confirmation (like %Exit).""" |
|
2297 | """Exit IPython without confirmation (like %Exit).""" | |
2308 |
|
2298 | |||
2309 | self.shell.exit_now = True |
|
2299 | self.shell.exit_now = True | |
2310 |
|
2300 | |||
2311 | #...................................................................... |
|
2301 | #...................................................................... | |
2312 | # Functions to implement unix shell-type things |
|
2302 | # Functions to implement unix shell-type things | |
2313 |
|
2303 | |||
2314 | def magic_alias(self, parameter_s = ''): |
|
2304 | def magic_alias(self, parameter_s = ''): | |
2315 | """Define an alias for a system command. |
|
2305 | """Define an alias for a system command. | |
2316 |
|
2306 | |||
2317 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2307 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2318 |
|
2308 | |||
2319 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2309 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2320 | params' (from your underlying operating system). |
|
2310 | params' (from your underlying operating system). | |
2321 |
|
2311 | |||
2322 | Aliases have lower precedence than magic functions and Python normal |
|
2312 | Aliases have lower precedence than magic functions and Python normal | |
2323 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2313 | variables, so if 'foo' is both a Python variable and an alias, the | |
2324 | alias can not be executed until 'del foo' removes the Python variable. |
|
2314 | alias can not be executed until 'del foo' removes the Python variable. | |
2325 |
|
2315 | |||
2326 | You can use the %l specifier in an alias definition to represent the |
|
2316 | You can use the %l specifier in an alias definition to represent the | |
2327 | whole line when the alias is called. For example: |
|
2317 | whole line when the alias is called. For example: | |
2328 |
|
2318 | |||
2329 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
2319 | In [2]: alias all echo "Input in brackets: <%l>"\\ | |
2330 | In [3]: all hello world\\ |
|
2320 | In [3]: all hello world\\ | |
2331 | Input in brackets: <hello world> |
|
2321 | Input in brackets: <hello world> | |
2332 |
|
2322 | |||
2333 | You can also define aliases with parameters using %s specifiers (one |
|
2323 | You can also define aliases with parameters using %s specifiers (one | |
2334 | per parameter): |
|
2324 | per parameter): | |
2335 |
|
2325 | |||
2336 | In [1]: alias parts echo first %s second %s\\ |
|
2326 | In [1]: alias parts echo first %s second %s\\ | |
2337 | In [2]: %parts A B\\ |
|
2327 | In [2]: %parts A B\\ | |
2338 | first A second B\\ |
|
2328 | first A second B\\ | |
2339 | In [3]: %parts A\\ |
|
2329 | In [3]: %parts A\\ | |
2340 | Incorrect number of arguments: 2 expected.\\ |
|
2330 | Incorrect number of arguments: 2 expected.\\ | |
2341 | parts is an alias to: 'echo first %s second %s' |
|
2331 | parts is an alias to: 'echo first %s second %s' | |
2342 |
|
2332 | |||
2343 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2333 | Note that %l and %s are mutually exclusive. You can only use one or | |
2344 | the other in your aliases. |
|
2334 | the other in your aliases. | |
2345 |
|
2335 | |||
2346 | Aliases expand Python variables just like system calls using ! or !! |
|
2336 | Aliases expand Python variables just like system calls using ! or !! | |
2347 | do: all expressions prefixed with '$' get expanded. For details of |
|
2337 | do: all expressions prefixed with '$' get expanded. For details of | |
2348 | the semantic rules, see PEP-215: |
|
2338 | the semantic rules, see PEP-215: | |
2349 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2339 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2350 | IPython for variable expansion. If you want to access a true shell |
|
2340 | IPython for variable expansion. If you want to access a true shell | |
2351 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2341 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2352 |
|
2342 | |||
2353 | In [6]: alias show echo\\ |
|
2343 | In [6]: alias show echo\\ | |
2354 | In [7]: PATH='A Python string'\\ |
|
2344 | In [7]: PATH='A Python string'\\ | |
2355 | In [8]: show $PATH\\ |
|
2345 | In [8]: show $PATH\\ | |
2356 | A Python string\\ |
|
2346 | A Python string\\ | |
2357 | In [9]: show $$PATH\\ |
|
2347 | In [9]: show $$PATH\\ | |
2358 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2348 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2359 |
|
2349 | |||
2360 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2350 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2361 | and %rehashx functions, which automatically create aliases for the |
|
2351 | and %rehashx functions, which automatically create aliases for the | |
2362 | contents of your $PATH. |
|
2352 | contents of your $PATH. | |
2363 |
|
2353 | |||
2364 | If called with no parameters, %alias prints the current alias table.""" |
|
2354 | If called with no parameters, %alias prints the current alias table.""" | |
2365 |
|
2355 | |||
2366 | par = parameter_s.strip() |
|
2356 | par = parameter_s.strip() | |
2367 | if not par: |
|
2357 | if not par: | |
2368 | stored = self.db.get('stored_aliases', {} ) |
|
2358 | stored = self.db.get('stored_aliases', {} ) | |
2369 | atab = self.shell.alias_table |
|
2359 | atab = self.shell.alias_table | |
2370 | aliases = atab.keys() |
|
2360 | aliases = atab.keys() | |
2371 | aliases.sort() |
|
2361 | aliases.sort() | |
2372 | res = [] |
|
2362 | res = [] | |
2373 | showlast = [] |
|
2363 | showlast = [] | |
2374 | for alias in aliases: |
|
2364 | for alias in aliases: | |
2375 | tgt = atab[alias][1] |
|
2365 | tgt = atab[alias][1] | |
2376 | # 'interesting' aliases |
|
2366 | # 'interesting' aliases | |
2377 | if (alias in stored or |
|
2367 | if (alias in stored or | |
2378 | alias != os.path.splitext(tgt)[0] or |
|
2368 | alias != os.path.splitext(tgt)[0] or | |
2379 | ' ' in tgt): |
|
2369 | ' ' in tgt): | |
2380 | showlast.append((alias, tgt)) |
|
2370 | showlast.append((alias, tgt)) | |
2381 | else: |
|
2371 | else: | |
2382 | res.append((alias, tgt )) |
|
2372 | res.append((alias, tgt )) | |
2383 |
|
2373 | |||
2384 | # show most interesting aliases last |
|
2374 | # show most interesting aliases last | |
2385 | res.extend(showlast) |
|
2375 | res.extend(showlast) | |
2386 | print "Total number of aliases:",len(aliases) |
|
2376 | print "Total number of aliases:",len(aliases) | |
2387 | return res |
|
2377 | return res | |
2388 | try: |
|
2378 | try: | |
2389 | alias,cmd = par.split(None,1) |
|
2379 | alias,cmd = par.split(None,1) | |
2390 | except: |
|
2380 | except: | |
2391 | print OInspect.getdoc(self.magic_alias) |
|
2381 | print OInspect.getdoc(self.magic_alias) | |
2392 | else: |
|
2382 | else: | |
2393 | nargs = cmd.count('%s') |
|
2383 | nargs = cmd.count('%s') | |
2394 | if nargs>0 and cmd.find('%l')>=0: |
|
2384 | if nargs>0 and cmd.find('%l')>=0: | |
2395 | error('The %s and %l specifiers are mutually exclusive ' |
|
2385 | error('The %s and %l specifiers are mutually exclusive ' | |
2396 | 'in alias definitions.') |
|
2386 | 'in alias definitions.') | |
2397 | else: # all looks OK |
|
2387 | else: # all looks OK | |
2398 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2388 | self.shell.alias_table[alias] = (nargs,cmd) | |
2399 | self.shell.alias_table_validate(verbose=0) |
|
2389 | self.shell.alias_table_validate(verbose=0) | |
2400 | # end magic_alias |
|
2390 | # end magic_alias | |
2401 |
|
2391 | |||
2402 | def magic_unalias(self, parameter_s = ''): |
|
2392 | def magic_unalias(self, parameter_s = ''): | |
2403 | """Remove an alias""" |
|
2393 | """Remove an alias""" | |
2404 |
|
2394 | |||
2405 | aname = parameter_s.strip() |
|
2395 | aname = parameter_s.strip() | |
2406 | if aname in self.shell.alias_table: |
|
2396 | if aname in self.shell.alias_table: | |
2407 | del self.shell.alias_table[aname] |
|
2397 | del self.shell.alias_table[aname] | |
2408 | stored = self.db.get('stored_aliases', {} ) |
|
2398 | stored = self.db.get('stored_aliases', {} ) | |
2409 | if aname in stored: |
|
2399 | if aname in stored: | |
2410 | print "Removing %stored alias",aname |
|
2400 | print "Removing %stored alias",aname | |
2411 | del stored[aname] |
|
2401 | del stored[aname] | |
2412 | self.db['stored_aliases'] = stored |
|
2402 | self.db['stored_aliases'] = stored | |
2413 |
|
2403 | |||
2414 | def magic_rehash(self, parameter_s = ''): |
|
2404 | def magic_rehash(self, parameter_s = ''): | |
2415 | """Update the alias table with all entries in $PATH. |
|
2405 | """Update the alias table with all entries in $PATH. | |
2416 |
|
2406 | |||
2417 | This version does no checks on execute permissions or whether the |
|
2407 | This version does no checks on execute permissions or whether the | |
2418 | contents of $PATH are truly files (instead of directories or something |
|
2408 | contents of $PATH are truly files (instead of directories or something | |
2419 | else). For such a safer (but slower) version, use %rehashx.""" |
|
2409 | else). For such a safer (but slower) version, use %rehashx.""" | |
2420 |
|
2410 | |||
2421 | # This function (and rehashx) manipulate the alias_table directly |
|
2411 | # This function (and rehashx) manipulate the alias_table directly | |
2422 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
2412 | # rather than calling magic_alias, for speed reasons. A rehash on a | |
2423 | # typical Linux box involves several thousand entries, so efficiency |
|
2413 | # typical Linux box involves several thousand entries, so efficiency | |
2424 | # here is a top concern. |
|
2414 | # here is a top concern. | |
2425 |
|
2415 | |||
2426 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
2416 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) | |
2427 | alias_table = self.shell.alias_table |
|
2417 | alias_table = self.shell.alias_table | |
2428 | for pdir in path: |
|
2418 | for pdir in path: | |
2429 | for ff in os.listdir(pdir): |
|
2419 | for ff in os.listdir(pdir): | |
2430 | # each entry in the alias table must be (N,name), where |
|
2420 | # each entry in the alias table must be (N,name), where | |
2431 | # N is the number of positional arguments of the alias. |
|
2421 | # N is the number of positional arguments of the alias. | |
2432 | alias_table[ff] = (0,ff) |
|
2422 | alias_table[ff] = (0,ff) | |
2433 | # Make sure the alias table doesn't contain keywords or builtins |
|
2423 | # Make sure the alias table doesn't contain keywords or builtins | |
2434 | self.shell.alias_table_validate() |
|
2424 | self.shell.alias_table_validate() | |
2435 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
2425 | # Call again init_auto_alias() so we get 'rm -i' and other modified | |
2436 | # aliases since %rehash will probably clobber them |
|
2426 | # aliases since %rehash will probably clobber them | |
2437 | self.shell.init_auto_alias() |
|
2427 | self.shell.init_auto_alias() | |
2438 |
|
2428 | |||
2439 | def magic_rehashx(self, parameter_s = ''): |
|
2429 | def magic_rehashx(self, parameter_s = ''): | |
2440 | """Update the alias table with all executable files in $PATH. |
|
2430 | """Update the alias table with all executable files in $PATH. | |
2441 |
|
2431 | |||
2442 | This version explicitly checks that every entry in $PATH is a file |
|
2432 | This version explicitly checks that every entry in $PATH is a file | |
2443 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2433 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2444 |
|
2434 | |||
2445 | Under Windows, it checks executability as a match agains a |
|
2435 | Under Windows, it checks executability as a match agains a | |
2446 | '|'-separated string of extensions, stored in the IPython config |
|
2436 | '|'-separated string of extensions, stored in the IPython config | |
2447 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ |
|
2437 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ | |
2448 |
|
2438 | |||
2449 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2439 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2450 | os.environ['PATH'].split(os.pathsep)] |
|
2440 | os.environ['PATH'].split(os.pathsep)] | |
2451 | path = filter(os.path.isdir,path) |
|
2441 | path = filter(os.path.isdir,path) | |
2452 |
|
2442 | |||
2453 | alias_table = self.shell.alias_table |
|
2443 | alias_table = self.shell.alias_table | |
2454 | syscmdlist = [] |
|
2444 | syscmdlist = [] | |
2455 | if os.name == 'posix': |
|
2445 | if os.name == 'posix': | |
2456 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2446 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2457 | os.access(fname,os.X_OK) |
|
2447 | os.access(fname,os.X_OK) | |
2458 | else: |
|
2448 | else: | |
2459 |
|
2449 | |||
2460 | try: |
|
2450 | try: | |
2461 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2451 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2462 | except KeyError: |
|
2452 | except KeyError: | |
2463 | winext = 'exe|com|bat|py' |
|
2453 | winext = 'exe|com|bat|py' | |
2464 | if 'py' not in winext: |
|
2454 | if 'py' not in winext: | |
2465 | winext += '|py' |
|
2455 | winext += '|py' | |
2466 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2456 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2467 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2457 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2468 | savedir = os.getcwd() |
|
2458 | savedir = os.getcwd() | |
2469 | try: |
|
2459 | try: | |
2470 | # write the whole loop for posix/Windows so we don't have an if in |
|
2460 | # write the whole loop for posix/Windows so we don't have an if in | |
2471 | # the innermost part |
|
2461 | # the innermost part | |
2472 | if os.name == 'posix': |
|
2462 | if os.name == 'posix': | |
2473 | for pdir in path: |
|
2463 | for pdir in path: | |
2474 | os.chdir(pdir) |
|
2464 | os.chdir(pdir) | |
2475 | for ff in os.listdir(pdir): |
|
2465 | for ff in os.listdir(pdir): | |
2476 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2466 | if isexec(ff) and ff not in self.shell.no_alias: | |
2477 | # each entry in the alias table must be (N,name), |
|
2467 | # each entry in the alias table must be (N,name), | |
2478 | # where N is the number of positional arguments of the |
|
2468 | # where N is the number of positional arguments of the | |
2479 | # alias. |
|
2469 | # alias. | |
2480 | alias_table[ff] = (0,ff) |
|
2470 | alias_table[ff] = (0,ff) | |
2481 | syscmdlist.append(ff) |
|
2471 | syscmdlist.append(ff) | |
2482 | else: |
|
2472 | else: | |
2483 | for pdir in path: |
|
2473 | for pdir in path: | |
2484 | os.chdir(pdir) |
|
2474 | os.chdir(pdir) | |
2485 | for ff in os.listdir(pdir): |
|
2475 | for ff in os.listdir(pdir): | |
2486 | if isexec(ff) and os.path.splitext(ff)[0] not in self.shell.no_alias: |
|
2476 | if isexec(ff) and os.path.splitext(ff)[0] not in self.shell.no_alias: | |
2487 | alias_table[execre.sub(r'\1',ff)] = (0,ff) |
|
2477 | alias_table[execre.sub(r'\1',ff)] = (0,ff) | |
2488 | syscmdlist.append(ff) |
|
2478 | syscmdlist.append(ff) | |
2489 | # Make sure the alias table doesn't contain keywords or builtins |
|
2479 | # Make sure the alias table doesn't contain keywords or builtins | |
2490 | self.shell.alias_table_validate() |
|
2480 | self.shell.alias_table_validate() | |
2491 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2481 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2492 | # modified aliases since %rehashx will probably clobber them |
|
2482 | # modified aliases since %rehashx will probably clobber them | |
2493 | self.shell.init_auto_alias() |
|
2483 | self.shell.init_auto_alias() | |
2494 | db = self.getapi().db |
|
2484 | db = self.getapi().db | |
2495 | db['syscmdlist'] = syscmdlist |
|
2485 | db['syscmdlist'] = syscmdlist | |
2496 | finally: |
|
2486 | finally: | |
2497 | os.chdir(savedir) |
|
2487 | os.chdir(savedir) | |
2498 |
|
2488 | |||
2499 | def magic_pwd(self, parameter_s = ''): |
|
2489 | def magic_pwd(self, parameter_s = ''): | |
2500 | """Return the current working directory path.""" |
|
2490 | """Return the current working directory path.""" | |
2501 | return os.getcwd() |
|
2491 | return os.getcwd() | |
2502 |
|
2492 | |||
2503 | def magic_cd(self, parameter_s=''): |
|
2493 | def magic_cd(self, parameter_s=''): | |
2504 | """Change the current working directory. |
|
2494 | """Change the current working directory. | |
2505 |
|
2495 | |||
2506 | This command automatically maintains an internal list of directories |
|
2496 | This command automatically maintains an internal list of directories | |
2507 | you visit during your IPython session, in the variable _dh. The |
|
2497 | you visit during your IPython session, in the variable _dh. The | |
2508 | command %dhist shows this history nicely formatted. |
|
2498 | command %dhist shows this history nicely formatted. | |
2509 |
|
2499 | |||
2510 | Usage: |
|
2500 | Usage: | |
2511 |
|
2501 | |||
2512 | cd 'dir': changes to directory 'dir'. |
|
2502 | cd 'dir': changes to directory 'dir'. | |
2513 |
|
2503 | |||
2514 | cd -: changes to the last visited directory. |
|
2504 | cd -: changes to the last visited directory. | |
2515 |
|
2505 | |||
2516 | cd -<n>: changes to the n-th directory in the directory history. |
|
2506 | cd -<n>: changes to the n-th directory in the directory history. | |
2517 |
|
2507 | |||
2518 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2508 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2519 | (note: cd <bookmark_name> is enough if there is no |
|
2509 | (note: cd <bookmark_name> is enough if there is no | |
2520 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2510 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2521 |
|
2511 | |||
2522 | Options: |
|
2512 | Options: | |
2523 |
|
2513 | |||
2524 | -q: quiet. Do not print the working directory after the cd command is |
|
2514 | -q: quiet. Do not print the working directory after the cd command is | |
2525 | executed. By default IPython's cd command does print this directory, |
|
2515 | executed. By default IPython's cd command does print this directory, | |
2526 | since the default prompts do not display path information. |
|
2516 | since the default prompts do not display path information. | |
2527 |
|
2517 | |||
2528 | Note that !cd doesn't work for this purpose because the shell where |
|
2518 | Note that !cd doesn't work for this purpose because the shell where | |
2529 | !command runs is immediately discarded after executing 'command'.""" |
|
2519 | !command runs is immediately discarded after executing 'command'.""" | |
2530 |
|
2520 | |||
2531 | parameter_s = parameter_s.strip() |
|
2521 | parameter_s = parameter_s.strip() | |
2532 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2522 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2533 |
|
2523 | |||
2534 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2524 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2535 | # jump in directory history by number |
|
2525 | # jump in directory history by number | |
2536 | if numcd: |
|
2526 | if numcd: | |
2537 | nn = int(numcd.group(2)) |
|
2527 | nn = int(numcd.group(2)) | |
2538 | try: |
|
2528 | try: | |
2539 | ps = self.shell.user_ns['_dh'][nn] |
|
2529 | ps = self.shell.user_ns['_dh'][nn] | |
2540 | except IndexError: |
|
2530 | except IndexError: | |
2541 | print 'The requested directory does not exist in history.' |
|
2531 | print 'The requested directory does not exist in history.' | |
2542 | return |
|
2532 | return | |
2543 | else: |
|
2533 | else: | |
2544 | opts = {} |
|
2534 | opts = {} | |
2545 | else: |
|
2535 | else: | |
2546 | #turn all non-space-escaping backslashes to slashes, |
|
2536 | #turn all non-space-escaping backslashes to slashes, | |
2547 | # for c:\windows\directory\names\ |
|
2537 | # for c:\windows\directory\names\ | |
2548 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2538 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2549 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2539 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2550 | # jump to previous |
|
2540 | # jump to previous | |
2551 | if ps == '-': |
|
2541 | if ps == '-': | |
2552 | try: |
|
2542 | try: | |
2553 | ps = self.shell.user_ns['_dh'][-2] |
|
2543 | ps = self.shell.user_ns['_dh'][-2] | |
2554 | except IndexError: |
|
2544 | except IndexError: | |
2555 | print 'No previous directory to change to.' |
|
2545 | print 'No previous directory to change to.' | |
2556 | return |
|
2546 | return | |
2557 | # jump to bookmark if needed |
|
2547 | # jump to bookmark if needed | |
2558 | else: |
|
2548 | else: | |
2559 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2549 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2560 | bkms = self.db.get('bookmarks', {}) |
|
2550 | bkms = self.db.get('bookmarks', {}) | |
2561 |
|
2551 | |||
2562 | if bkms.has_key(ps): |
|
2552 | if bkms.has_key(ps): | |
2563 | target = bkms[ps] |
|
2553 | target = bkms[ps] | |
2564 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2554 | print '(bookmark:%s) -> %s' % (ps,target) | |
2565 | ps = target |
|
2555 | ps = target | |
2566 | else: |
|
2556 | else: | |
2567 | if opts.has_key('b'): |
|
2557 | if opts.has_key('b'): | |
2568 | error("Bookmark '%s' not found. " |
|
2558 | error("Bookmark '%s' not found. " | |
2569 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2559 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2570 | return |
|
2560 | return | |
2571 |
|
2561 | |||
2572 | # at this point ps should point to the target dir |
|
2562 | # at this point ps should point to the target dir | |
2573 | if ps: |
|
2563 | if ps: | |
2574 | try: |
|
2564 | try: | |
2575 | os.chdir(os.path.expanduser(ps)) |
|
2565 | os.chdir(os.path.expanduser(ps)) | |
2576 | ttitle = ("IPy:" + ( |
|
2566 | ttitle = ("IPy:" + ( | |
2577 | os.getcwd() == '/' and '/' or os.path.basename(os.getcwd()))) |
|
2567 | os.getcwd() == '/' and '/' or os.path.basename(os.getcwd()))) | |
2578 | platutils.set_term_title(ttitle) |
|
2568 | platutils.set_term_title(ttitle) | |
2579 | except OSError: |
|
2569 | except OSError: | |
2580 | print sys.exc_info()[1] |
|
2570 | print sys.exc_info()[1] | |
2581 | else: |
|
2571 | else: | |
2582 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2572 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2583 | else: |
|
2573 | else: | |
2584 | os.chdir(self.shell.home_dir) |
|
2574 | os.chdir(self.shell.home_dir) | |
2585 | platutils.set_term_title("IPy:~") |
|
2575 | platutils.set_term_title("IPy:~") | |
2586 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2576 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2587 | if not 'q' in opts: |
|
2577 | if not 'q' in opts: | |
2588 | print self.shell.user_ns['_dh'][-1] |
|
2578 | print self.shell.user_ns['_dh'][-1] | |
2589 |
|
2579 | |||
2590 | def magic_dhist(self, parameter_s=''): |
|
2580 | def magic_dhist(self, parameter_s=''): | |
2591 | """Print your history of visited directories. |
|
2581 | """Print your history of visited directories. | |
2592 |
|
2582 | |||
2593 | %dhist -> print full history\\ |
|
2583 | %dhist -> print full history\\ | |
2594 | %dhist n -> print last n entries only\\ |
|
2584 | %dhist n -> print last n entries only\\ | |
2595 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2585 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2596 |
|
2586 | |||
2597 | This history is automatically maintained by the %cd command, and |
|
2587 | This history is automatically maintained by the %cd command, and | |
2598 | always available as the global list variable _dh. You can use %cd -<n> |
|
2588 | always available as the global list variable _dh. You can use %cd -<n> | |
2599 | to go to directory number <n>.""" |
|
2589 | to go to directory number <n>.""" | |
2600 |
|
2590 | |||
2601 | dh = self.shell.user_ns['_dh'] |
|
2591 | dh = self.shell.user_ns['_dh'] | |
2602 | if parameter_s: |
|
2592 | if parameter_s: | |
2603 | try: |
|
2593 | try: | |
2604 | args = map(int,parameter_s.split()) |
|
2594 | args = map(int,parameter_s.split()) | |
2605 | except: |
|
2595 | except: | |
2606 | self.arg_err(Magic.magic_dhist) |
|
2596 | self.arg_err(Magic.magic_dhist) | |
2607 | return |
|
2597 | return | |
2608 | if len(args) == 1: |
|
2598 | if len(args) == 1: | |
2609 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2599 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2610 | elif len(args) == 2: |
|
2600 | elif len(args) == 2: | |
2611 | ini,fin = args |
|
2601 | ini,fin = args | |
2612 | else: |
|
2602 | else: | |
2613 | self.arg_err(Magic.magic_dhist) |
|
2603 | self.arg_err(Magic.magic_dhist) | |
2614 | return |
|
2604 | return | |
2615 | else: |
|
2605 | else: | |
2616 | ini,fin = 0,len(dh) |
|
2606 | ini,fin = 0,len(dh) | |
2617 | nlprint(dh, |
|
2607 | nlprint(dh, | |
2618 | header = 'Directory history (kept in _dh)', |
|
2608 | header = 'Directory history (kept in _dh)', | |
2619 | start=ini,stop=fin) |
|
2609 | start=ini,stop=fin) | |
2620 |
|
2610 | |||
2621 | def magic_env(self, parameter_s=''): |
|
2611 | def magic_env(self, parameter_s=''): | |
2622 | """List environment variables.""" |
|
2612 | """List environment variables.""" | |
2623 |
|
2613 | |||
2624 | return os.environ.data |
|
2614 | return os.environ.data | |
2625 |
|
2615 | |||
2626 | def magic_pushd(self, parameter_s=''): |
|
2616 | def magic_pushd(self, parameter_s=''): | |
2627 | """Place the current dir on stack and change directory. |
|
2617 | """Place the current dir on stack and change directory. | |
2628 |
|
2618 | |||
2629 | Usage:\\ |
|
2619 | Usage:\\ | |
2630 | %pushd ['dirname'] |
|
2620 | %pushd ['dirname'] | |
2631 |
|
2621 | |||
2632 | %pushd with no arguments does a %pushd to your home directory. |
|
2622 | %pushd with no arguments does a %pushd to your home directory. | |
2633 | """ |
|
2623 | """ | |
2634 | if parameter_s == '': parameter_s = '~' |
|
2624 | if parameter_s == '': parameter_s = '~' | |
2635 | dir_s = self.shell.dir_stack |
|
2625 | dir_s = self.shell.dir_stack | |
2636 | if len(dir_s)>0 and os.path.expanduser(parameter_s) != \ |
|
2626 | if len(dir_s)>0 and os.path.expanduser(parameter_s) != \ | |
2637 | os.path.expanduser(self.shell.dir_stack[0]): |
|
2627 | os.path.expanduser(self.shell.dir_stack[0]): | |
2638 | try: |
|
2628 | try: | |
2639 | self.magic_cd(parameter_s) |
|
2629 | self.magic_cd(parameter_s) | |
2640 | dir_s.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2630 | dir_s.insert(0,os.getcwd().replace(self.home_dir,'~')) | |
2641 | self.magic_dirs() |
|
2631 | self.magic_dirs() | |
2642 | except: |
|
2632 | except: | |
2643 | print 'Invalid directory' |
|
2633 | print 'Invalid directory' | |
2644 | else: |
|
2634 | else: | |
2645 | print 'You are already there!' |
|
2635 | print 'You are already there!' | |
2646 |
|
2636 | |||
2647 | def magic_popd(self, parameter_s=''): |
|
2637 | def magic_popd(self, parameter_s=''): | |
2648 | """Change to directory popped off the top of the stack. |
|
2638 | """Change to directory popped off the top of the stack. | |
2649 | """ |
|
2639 | """ | |
2650 | if len (self.shell.dir_stack) > 1: |
|
2640 | if len (self.shell.dir_stack) > 1: | |
2651 | self.shell.dir_stack.pop(0) |
|
2641 | self.shell.dir_stack.pop(0) | |
2652 | self.magic_cd(self.shell.dir_stack[0]) |
|
2642 | self.magic_cd(self.shell.dir_stack[0]) | |
2653 | print self.shell.dir_stack[0] |
|
2643 | print self.shell.dir_stack[0] | |
2654 | else: |
|
2644 | else: | |
2655 | print "You can't remove the starting directory from the stack:",\ |
|
2645 | print "You can't remove the starting directory from the stack:",\ | |
2656 | self.shell.dir_stack |
|
2646 | self.shell.dir_stack | |
2657 |
|
2647 | |||
2658 | def magic_dirs(self, parameter_s=''): |
|
2648 | def magic_dirs(self, parameter_s=''): | |
2659 | """Return the current directory stack.""" |
|
2649 | """Return the current directory stack.""" | |
2660 |
|
2650 | |||
2661 | return self.shell.dir_stack[:] |
|
2651 | return self.shell.dir_stack[:] | |
2662 |
|
2652 | |||
2663 | def magic_sc(self, parameter_s=''): |
|
2653 | def magic_sc(self, parameter_s=''): | |
2664 | """Shell capture - execute a shell command and capture its output. |
|
2654 | """Shell capture - execute a shell command and capture its output. | |
2665 |
|
2655 | |||
2666 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2656 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2667 |
|
2657 | |||
2668 | You should use the form 'var = !command' instead. Example: |
|
2658 | You should use the form 'var = !command' instead. Example: | |
2669 |
|
2659 | |||
2670 | "%sc -l myfiles = ls ~" should now be written as |
|
2660 | "%sc -l myfiles = ls ~" should now be written as | |
2671 |
|
2661 | |||
2672 | "myfiles = !ls ~" |
|
2662 | "myfiles = !ls ~" | |
2673 |
|
2663 | |||
2674 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2664 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2675 | below. |
|
2665 | below. | |
2676 |
|
2666 | |||
2677 | -- |
|
2667 | -- | |
2678 | %sc [options] varname=command |
|
2668 | %sc [options] varname=command | |
2679 |
|
2669 | |||
2680 | IPython will run the given command using commands.getoutput(), and |
|
2670 | IPython will run the given command using commands.getoutput(), and | |
2681 | will then update the user's interactive namespace with a variable |
|
2671 | will then update the user's interactive namespace with a variable | |
2682 | called varname, containing the value of the call. Your command can |
|
2672 | called varname, containing the value of the call. Your command can | |
2683 | contain shell wildcards, pipes, etc. |
|
2673 | contain shell wildcards, pipes, etc. | |
2684 |
|
2674 | |||
2685 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2675 | The '=' sign in the syntax is mandatory, and the variable name you | |
2686 | supply must follow Python's standard conventions for valid names. |
|
2676 | supply must follow Python's standard conventions for valid names. | |
2687 |
|
2677 | |||
2688 | (A special format without variable name exists for internal use) |
|
2678 | (A special format without variable name exists for internal use) | |
2689 |
|
2679 | |||
2690 | Options: |
|
2680 | Options: | |
2691 |
|
2681 | |||
2692 | -l: list output. Split the output on newlines into a list before |
|
2682 | -l: list output. Split the output on newlines into a list before | |
2693 | assigning it to the given variable. By default the output is stored |
|
2683 | assigning it to the given variable. By default the output is stored | |
2694 | as a single string. |
|
2684 | as a single string. | |
2695 |
|
2685 | |||
2696 | -v: verbose. Print the contents of the variable. |
|
2686 | -v: verbose. Print the contents of the variable. | |
2697 |
|
2687 | |||
2698 | In most cases you should not need to split as a list, because the |
|
2688 | In most cases you should not need to split as a list, because the | |
2699 | returned value is a special type of string which can automatically |
|
2689 | returned value is a special type of string which can automatically | |
2700 | provide its contents either as a list (split on newlines) or as a |
|
2690 | provide its contents either as a list (split on newlines) or as a | |
2701 | space-separated string. These are convenient, respectively, either |
|
2691 | space-separated string. These are convenient, respectively, either | |
2702 | for sequential processing or to be passed to a shell command. |
|
2692 | for sequential processing or to be passed to a shell command. | |
2703 |
|
2693 | |||
2704 | For example: |
|
2694 | For example: | |
2705 |
|
2695 | |||
2706 | # Capture into variable a |
|
2696 | # Capture into variable a | |
2707 | In [9]: sc a=ls *py |
|
2697 | In [9]: sc a=ls *py | |
2708 |
|
2698 | |||
2709 | # a is a string with embedded newlines |
|
2699 | # a is a string with embedded newlines | |
2710 | In [10]: a |
|
2700 | In [10]: a | |
2711 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2701 | Out[10]: 'setup.py\nwin32_manual_post_install.py' | |
2712 |
|
2702 | |||
2713 | # which can be seen as a list: |
|
2703 | # which can be seen as a list: | |
2714 | In [11]: a.l |
|
2704 | In [11]: a.l | |
2715 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2705 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] | |
2716 |
|
2706 | |||
2717 | # or as a whitespace-separated string: |
|
2707 | # or as a whitespace-separated string: | |
2718 | In [12]: a.s |
|
2708 | In [12]: a.s | |
2719 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2709 | Out[12]: 'setup.py win32_manual_post_install.py' | |
2720 |
|
2710 | |||
2721 | # a.s is useful to pass as a single command line: |
|
2711 | # a.s is useful to pass as a single command line: | |
2722 | In [13]: !wc -l $a.s |
|
2712 | In [13]: !wc -l $a.s | |
2723 | 146 setup.py |
|
2713 | 146 setup.py | |
2724 | 130 win32_manual_post_install.py |
|
2714 | 130 win32_manual_post_install.py | |
2725 | 276 total |
|
2715 | 276 total | |
2726 |
|
2716 | |||
2727 | # while the list form is useful to loop over: |
|
2717 | # while the list form is useful to loop over: | |
2728 | In [14]: for f in a.l: |
|
2718 | In [14]: for f in a.l: | |
2729 | ....: !wc -l $f |
|
2719 | ....: !wc -l $f | |
2730 | ....: |
|
2720 | ....: | |
2731 | 146 setup.py |
|
2721 | 146 setup.py | |
2732 | 130 win32_manual_post_install.py |
|
2722 | 130 win32_manual_post_install.py | |
2733 |
|
2723 | |||
2734 | Similiarly, the lists returned by the -l option are also special, in |
|
2724 | Similiarly, the lists returned by the -l option are also special, in | |
2735 | the sense that you can equally invoke the .s attribute on them to |
|
2725 | the sense that you can equally invoke the .s attribute on them to | |
2736 | automatically get a whitespace-separated string from their contents: |
|
2726 | automatically get a whitespace-separated string from their contents: | |
2737 |
|
2727 | |||
2738 | In [1]: sc -l b=ls *py |
|
2728 | In [1]: sc -l b=ls *py | |
2739 |
|
2729 | |||
2740 | In [2]: b |
|
2730 | In [2]: b | |
2741 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2731 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] | |
2742 |
|
2732 | |||
2743 | In [3]: b.s |
|
2733 | In [3]: b.s | |
2744 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2734 | Out[3]: 'setup.py win32_manual_post_install.py' | |
2745 |
|
2735 | |||
2746 | In summary, both the lists and strings used for ouptut capture have |
|
2736 | In summary, both the lists and strings used for ouptut capture have | |
2747 | the following special attributes: |
|
2737 | the following special attributes: | |
2748 |
|
2738 | |||
2749 | .l (or .list) : value as list. |
|
2739 | .l (or .list) : value as list. | |
2750 | .n (or .nlstr): value as newline-separated string. |
|
2740 | .n (or .nlstr): value as newline-separated string. | |
2751 | .s (or .spstr): value as space-separated string. |
|
2741 | .s (or .spstr): value as space-separated string. | |
2752 | """ |
|
2742 | """ | |
2753 |
|
2743 | |||
2754 | opts,args = self.parse_options(parameter_s,'lv') |
|
2744 | opts,args = self.parse_options(parameter_s,'lv') | |
2755 | # Try to get a variable name and command to run |
|
2745 | # Try to get a variable name and command to run | |
2756 | try: |
|
2746 | try: | |
2757 | # the variable name must be obtained from the parse_options |
|
2747 | # the variable name must be obtained from the parse_options | |
2758 | # output, which uses shlex.split to strip options out. |
|
2748 | # output, which uses shlex.split to strip options out. | |
2759 | var,_ = args.split('=',1) |
|
2749 | var,_ = args.split('=',1) | |
2760 | var = var.strip() |
|
2750 | var = var.strip() | |
2761 | # But the the command has to be extracted from the original input |
|
2751 | # But the the command has to be extracted from the original input | |
2762 | # parameter_s, not on what parse_options returns, to avoid the |
|
2752 | # parameter_s, not on what parse_options returns, to avoid the | |
2763 | # quote stripping which shlex.split performs on it. |
|
2753 | # quote stripping which shlex.split performs on it. | |
2764 | _,cmd = parameter_s.split('=',1) |
|
2754 | _,cmd = parameter_s.split('=',1) | |
2765 | except ValueError: |
|
2755 | except ValueError: | |
2766 | var,cmd = '','' |
|
2756 | var,cmd = '','' | |
2767 | # If all looks ok, proceed |
|
2757 | # If all looks ok, proceed | |
2768 | out,err = self.shell.getoutputerror(cmd) |
|
2758 | out,err = self.shell.getoutputerror(cmd) | |
2769 | if err: |
|
2759 | if err: | |
2770 | print >> Term.cerr,err |
|
2760 | print >> Term.cerr,err | |
2771 | if opts.has_key('l'): |
|
2761 | if opts.has_key('l'): | |
2772 | out = SList(out.split('\n')) |
|
2762 | out = SList(out.split('\n')) | |
2773 | else: |
|
2763 | else: | |
2774 | out = LSString(out) |
|
2764 | out = LSString(out) | |
2775 | if opts.has_key('v'): |
|
2765 | if opts.has_key('v'): | |
2776 | print '%s ==\n%s' % (var,pformat(out)) |
|
2766 | print '%s ==\n%s' % (var,pformat(out)) | |
2777 | if var: |
|
2767 | if var: | |
2778 | self.shell.user_ns.update({var:out}) |
|
2768 | self.shell.user_ns.update({var:out}) | |
2779 | else: |
|
2769 | else: | |
2780 | return out |
|
2770 | return out | |
2781 |
|
2771 | |||
2782 | def magic_sx(self, parameter_s=''): |
|
2772 | def magic_sx(self, parameter_s=''): | |
2783 | """Shell execute - run a shell command and capture its output. |
|
2773 | """Shell execute - run a shell command and capture its output. | |
2784 |
|
2774 | |||
2785 | %sx command |
|
2775 | %sx command | |
2786 |
|
2776 | |||
2787 | IPython will run the given command using commands.getoutput(), and |
|
2777 | IPython will run the given command using commands.getoutput(), and | |
2788 | return the result formatted as a list (split on '\\n'). Since the |
|
2778 | return the result formatted as a list (split on '\\n'). Since the | |
2789 | output is _returned_, it will be stored in ipython's regular output |
|
2779 | output is _returned_, it will be stored in ipython's regular output | |
2790 | cache Out[N] and in the '_N' automatic variables. |
|
2780 | cache Out[N] and in the '_N' automatic variables. | |
2791 |
|
2781 | |||
2792 | Notes: |
|
2782 | Notes: | |
2793 |
|
2783 | |||
2794 | 1) If an input line begins with '!!', then %sx is automatically |
|
2784 | 1) If an input line begins with '!!', then %sx is automatically | |
2795 | invoked. That is, while: |
|
2785 | invoked. That is, while: | |
2796 | !ls |
|
2786 | !ls | |
2797 | causes ipython to simply issue system('ls'), typing |
|
2787 | causes ipython to simply issue system('ls'), typing | |
2798 | !!ls |
|
2788 | !!ls | |
2799 | is a shorthand equivalent to: |
|
2789 | is a shorthand equivalent to: | |
2800 | %sx ls |
|
2790 | %sx ls | |
2801 |
|
2791 | |||
2802 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2792 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2803 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2793 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2804 | to process line-oriented shell output via further python commands. |
|
2794 | to process line-oriented shell output via further python commands. | |
2805 | %sc is meant to provide much finer control, but requires more |
|
2795 | %sc is meant to provide much finer control, but requires more | |
2806 | typing. |
|
2796 | typing. | |
2807 |
|
2797 | |||
2808 | 3) Just like %sc -l, this is a list with special attributes: |
|
2798 | 3) Just like %sc -l, this is a list with special attributes: | |
2809 |
|
2799 | |||
2810 | .l (or .list) : value as list. |
|
2800 | .l (or .list) : value as list. | |
2811 | .n (or .nlstr): value as newline-separated string. |
|
2801 | .n (or .nlstr): value as newline-separated string. | |
2812 | .s (or .spstr): value as whitespace-separated string. |
|
2802 | .s (or .spstr): value as whitespace-separated string. | |
2813 |
|
2803 | |||
2814 | This is very useful when trying to use such lists as arguments to |
|
2804 | This is very useful when trying to use such lists as arguments to | |
2815 | system commands.""" |
|
2805 | system commands.""" | |
2816 |
|
2806 | |||
2817 | if parameter_s: |
|
2807 | if parameter_s: | |
2818 | out,err = self.shell.getoutputerror(parameter_s) |
|
2808 | out,err = self.shell.getoutputerror(parameter_s) | |
2819 | if err: |
|
2809 | if err: | |
2820 | print >> Term.cerr,err |
|
2810 | print >> Term.cerr,err | |
2821 | return SList(out.split('\n')) |
|
2811 | return SList(out.split('\n')) | |
2822 |
|
2812 | |||
2823 | def magic_bg(self, parameter_s=''): |
|
2813 | def magic_bg(self, parameter_s=''): | |
2824 | """Run a job in the background, in a separate thread. |
|
2814 | """Run a job in the background, in a separate thread. | |
2825 |
|
2815 | |||
2826 | For example, |
|
2816 | For example, | |
2827 |
|
2817 | |||
2828 | %bg myfunc(x,y,z=1) |
|
2818 | %bg myfunc(x,y,z=1) | |
2829 |
|
2819 | |||
2830 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2820 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
2831 | execution starts, a message will be printed indicating the job |
|
2821 | execution starts, a message will be printed indicating the job | |
2832 | number. If your job number is 5, you can use |
|
2822 | number. If your job number is 5, you can use | |
2833 |
|
2823 | |||
2834 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2824 | myvar = jobs.result(5) or myvar = jobs[5].result | |
2835 |
|
2825 | |||
2836 | to assign this result to variable 'myvar'. |
|
2826 | to assign this result to variable 'myvar'. | |
2837 |
|
2827 | |||
2838 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2828 | IPython has a job manager, accessible via the 'jobs' object. You can | |
2839 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2829 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
2840 | its attributes. All attributes not starting with an underscore are |
|
2830 | its attributes. All attributes not starting with an underscore are | |
2841 | meant for public use. |
|
2831 | meant for public use. | |
2842 |
|
2832 | |||
2843 | In particular, look at the jobs.new() method, which is used to create |
|
2833 | In particular, look at the jobs.new() method, which is used to create | |
2844 | new jobs. This magic %bg function is just a convenience wrapper |
|
2834 | new jobs. This magic %bg function is just a convenience wrapper | |
2845 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2835 | around jobs.new(), for expression-based jobs. If you want to create a | |
2846 | new job with an explicit function object and arguments, you must call |
|
2836 | new job with an explicit function object and arguments, you must call | |
2847 | jobs.new() directly. |
|
2837 | jobs.new() directly. | |
2848 |
|
2838 | |||
2849 | The jobs.new docstring also describes in detail several important |
|
2839 | The jobs.new docstring also describes in detail several important | |
2850 | caveats associated with a thread-based model for background job |
|
2840 | caveats associated with a thread-based model for background job | |
2851 | execution. Type jobs.new? for details. |
|
2841 | execution. Type jobs.new? for details. | |
2852 |
|
2842 | |||
2853 | You can check the status of all jobs with jobs.status(). |
|
2843 | You can check the status of all jobs with jobs.status(). | |
2854 |
|
2844 | |||
2855 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2845 | The jobs variable is set by IPython into the Python builtin namespace. | |
2856 | If you ever declare a variable named 'jobs', you will shadow this |
|
2846 | If you ever declare a variable named 'jobs', you will shadow this | |
2857 | name. You can either delete your global jobs variable to regain |
|
2847 | name. You can either delete your global jobs variable to regain | |
2858 | access to the job manager, or make a new name and assign it manually |
|
2848 | access to the job manager, or make a new name and assign it manually | |
2859 | to the manager (stored in IPython's namespace). For example, to |
|
2849 | to the manager (stored in IPython's namespace). For example, to | |
2860 | assign the job manager to the Jobs name, use: |
|
2850 | assign the job manager to the Jobs name, use: | |
2861 |
|
2851 | |||
2862 | Jobs = __builtins__.jobs""" |
|
2852 | Jobs = __builtins__.jobs""" | |
2863 |
|
2853 | |||
2864 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2854 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
2865 |
|
2855 | |||
2866 |
|
2856 | |||
2867 | def magic_bookmark(self, parameter_s=''): |
|
2857 | def magic_bookmark(self, parameter_s=''): | |
2868 | """Manage IPython's bookmark system. |
|
2858 | """Manage IPython's bookmark system. | |
2869 |
|
2859 | |||
2870 | %bookmark <name> - set bookmark to current dir |
|
2860 | %bookmark <name> - set bookmark to current dir | |
2871 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2861 | %bookmark <name> <dir> - set bookmark to <dir> | |
2872 | %bookmark -l - list all bookmarks |
|
2862 | %bookmark -l - list all bookmarks | |
2873 | %bookmark -d <name> - remove bookmark |
|
2863 | %bookmark -d <name> - remove bookmark | |
2874 | %bookmark -r - remove all bookmarks |
|
2864 | %bookmark -r - remove all bookmarks | |
2875 |
|
2865 | |||
2876 | You can later on access a bookmarked folder with: |
|
2866 | You can later on access a bookmarked folder with: | |
2877 | %cd -b <name> |
|
2867 | %cd -b <name> | |
2878 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2868 | or simply '%cd <name>' if there is no directory called <name> AND | |
2879 | there is such a bookmark defined. |
|
2869 | there is such a bookmark defined. | |
2880 |
|
2870 | |||
2881 | Your bookmarks persist through IPython sessions, but they are |
|
2871 | Your bookmarks persist through IPython sessions, but they are | |
2882 | associated with each profile.""" |
|
2872 | associated with each profile.""" | |
2883 |
|
2873 | |||
2884 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2874 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
2885 | if len(args) > 2: |
|
2875 | if len(args) > 2: | |
2886 | error('You can only give at most two arguments') |
|
2876 | error('You can only give at most two arguments') | |
2887 | return |
|
2877 | return | |
2888 |
|
2878 | |||
2889 | bkms = self.db.get('bookmarks',{}) |
|
2879 | bkms = self.db.get('bookmarks',{}) | |
2890 |
|
2880 | |||
2891 | if opts.has_key('d'): |
|
2881 | if opts.has_key('d'): | |
2892 | try: |
|
2882 | try: | |
2893 | todel = args[0] |
|
2883 | todel = args[0] | |
2894 | except IndexError: |
|
2884 | except IndexError: | |
2895 | error('You must provide a bookmark to delete') |
|
2885 | error('You must provide a bookmark to delete') | |
2896 | else: |
|
2886 | else: | |
2897 | try: |
|
2887 | try: | |
2898 | del bkms[todel] |
|
2888 | del bkms[todel] | |
2899 | except: |
|
2889 | except: | |
2900 | error("Can't delete bookmark '%s'" % todel) |
|
2890 | error("Can't delete bookmark '%s'" % todel) | |
2901 | elif opts.has_key('r'): |
|
2891 | elif opts.has_key('r'): | |
2902 | bkms = {} |
|
2892 | bkms = {} | |
2903 | elif opts.has_key('l'): |
|
2893 | elif opts.has_key('l'): | |
2904 | bks = bkms.keys() |
|
2894 | bks = bkms.keys() | |
2905 | bks.sort() |
|
2895 | bks.sort() | |
2906 | if bks: |
|
2896 | if bks: | |
2907 | size = max(map(len,bks)) |
|
2897 | size = max(map(len,bks)) | |
2908 | else: |
|
2898 | else: | |
2909 | size = 0 |
|
2899 | size = 0 | |
2910 | fmt = '%-'+str(size)+'s -> %s' |
|
2900 | fmt = '%-'+str(size)+'s -> %s' | |
2911 | print 'Current bookmarks:' |
|
2901 | print 'Current bookmarks:' | |
2912 | for bk in bks: |
|
2902 | for bk in bks: | |
2913 | print fmt % (bk,bkms[bk]) |
|
2903 | print fmt % (bk,bkms[bk]) | |
2914 | else: |
|
2904 | else: | |
2915 | if not args: |
|
2905 | if not args: | |
2916 | error("You must specify the bookmark name") |
|
2906 | error("You must specify the bookmark name") | |
2917 | elif len(args)==1: |
|
2907 | elif len(args)==1: | |
2918 | bkms[args[0]] = os.getcwd() |
|
2908 | bkms[args[0]] = os.getcwd() | |
2919 | elif len(args)==2: |
|
2909 | elif len(args)==2: | |
2920 | bkms[args[0]] = args[1] |
|
2910 | bkms[args[0]] = args[1] | |
2921 | self.db['bookmarks'] = bkms |
|
2911 | self.db['bookmarks'] = bkms | |
2922 |
|
2912 | |||
2923 | def magic_pycat(self, parameter_s=''): |
|
2913 | def magic_pycat(self, parameter_s=''): | |
2924 | """Show a syntax-highlighted file through a pager. |
|
2914 | """Show a syntax-highlighted file through a pager. | |
2925 |
|
2915 | |||
2926 | This magic is similar to the cat utility, but it will assume the file |
|
2916 | This magic is similar to the cat utility, but it will assume the file | |
2927 | to be Python source and will show it with syntax highlighting. """ |
|
2917 | to be Python source and will show it with syntax highlighting. """ | |
2928 |
|
2918 | |||
2929 | try: |
|
2919 | try: | |
2930 | filename = get_py_filename(parameter_s) |
|
2920 | filename = get_py_filename(parameter_s) | |
2931 | cont = file_read(filename) |
|
2921 | cont = file_read(filename) | |
2932 | except IOError: |
|
2922 | except IOError: | |
2933 | try: |
|
2923 | try: | |
2934 | cont = eval(parameter_s,self.user_ns) |
|
2924 | cont = eval(parameter_s,self.user_ns) | |
2935 | except NameError: |
|
2925 | except NameError: | |
2936 | cont = None |
|
2926 | cont = None | |
2937 | if cont is None: |
|
2927 | if cont is None: | |
2938 | print "Error: no such file or variable" |
|
2928 | print "Error: no such file or variable" | |
2939 | return |
|
2929 | return | |
2940 |
|
2930 | |||
2941 | page(self.shell.pycolorize(cont), |
|
2931 | page(self.shell.pycolorize(cont), | |
2942 | screen_lines=self.shell.rc.screen_length) |
|
2932 | screen_lines=self.shell.rc.screen_length) | |
2943 |
|
2933 | |||
2944 | def magic_cpaste(self, parameter_s=''): |
|
2934 | def magic_cpaste(self, parameter_s=''): | |
2945 | """Allows you to paste & execute a pre-formatted code block from clipboard |
|
2935 | """Allows you to paste & execute a pre-formatted code block from clipboard | |
2946 |
|
2936 | |||
2947 | You must terminate the block with '--' (two minus-signs) alone on the |
|
2937 | You must terminate the block with '--' (two minus-signs) alone on the | |
2948 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
2938 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
2949 | is the new sentinel for this operation) |
|
2939 | is the new sentinel for this operation) | |
2950 |
|
2940 | |||
2951 | The block is dedented prior to execution to enable execution of |
|
2941 | The block is dedented prior to execution to enable execution of | |
2952 | method definitions. '>' characters at the beginning of a line is |
|
2942 | method definitions. '>' characters at the beginning of a line is | |
2953 | ignored, to allow pasting directly from e-mails. The executed block |
|
2943 | ignored, to allow pasting directly from e-mails. The executed block | |
2954 | is also assigned to variable named 'pasted_block' for later editing |
|
2944 | is also assigned to variable named 'pasted_block' for later editing | |
2955 | with '%edit pasted_block'. |
|
2945 | with '%edit pasted_block'. | |
2956 |
|
2946 | |||
2957 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
2947 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
2958 | This assigns the pasted block to variable 'foo' as string, without |
|
2948 | This assigns the pasted block to variable 'foo' as string, without | |
2959 | dedenting or executing it. |
|
2949 | dedenting or executing it. | |
2960 |
|
2950 | |||
2961 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
2951 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
2962 | Just press enter and type -- (and press enter again) and the block |
|
2952 | Just press enter and type -- (and press enter again) and the block | |
2963 | will be what was just pasted. |
|
2953 | will be what was just pasted. | |
2964 |
|
2954 | |||
2965 | IPython statements (magics, shell escapes) are not supported (yet). |
|
2955 | IPython statements (magics, shell escapes) are not supported (yet). | |
2966 | """ |
|
2956 | """ | |
2967 | opts,args = self.parse_options(parameter_s,'s:',mode='string') |
|
2957 | opts,args = self.parse_options(parameter_s,'s:',mode='string') | |
2968 | par = args.strip() |
|
2958 | par = args.strip() | |
2969 | sentinel = opts.get('s','--') |
|
2959 | sentinel = opts.get('s','--') | |
2970 |
|
2960 | |||
2971 | from IPython import iplib |
|
2961 | from IPython import iplib | |
2972 | lines = [] |
|
2962 | lines = [] | |
2973 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
2963 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
2974 | while 1: |
|
2964 | while 1: | |
2975 | l = iplib.raw_input_original(':') |
|
2965 | l = iplib.raw_input_original(':') | |
2976 | if l ==sentinel: |
|
2966 | if l ==sentinel: | |
2977 | break |
|
2967 | break | |
2978 | lines.append(l.lstrip('>')) |
|
2968 | lines.append(l.lstrip('>')) | |
2979 | block = "\n".join(lines) + '\n' |
|
2969 | block = "\n".join(lines) + '\n' | |
2980 | #print "block:\n",block |
|
2970 | #print "block:\n",block | |
2981 | if not par: |
|
2971 | if not par: | |
2982 | b = textwrap.dedent(block) |
|
2972 | b = textwrap.dedent(block) | |
2983 | exec b in self.user_ns |
|
2973 | exec b in self.user_ns | |
2984 | self.user_ns['pasted_block'] = b |
|
2974 | self.user_ns['pasted_block'] = b | |
2985 | else: |
|
2975 | else: | |
2986 | self.user_ns[par] = block |
|
2976 | self.user_ns[par] = block | |
2987 | print "Block assigned to '%s'" % par |
|
2977 | print "Block assigned to '%s'" % par | |
2988 |
|
2978 | |||
2989 | def magic_quickref(self,arg): |
|
2979 | def magic_quickref(self,arg): | |
2990 | """ Show a quick reference sheet """ |
|
2980 | """ Show a quick reference sheet """ | |
2991 | import IPython.usage |
|
2981 | import IPython.usage | |
2992 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
2982 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') | |
2993 |
|
2983 | |||
2994 | page(qr) |
|
2984 | page(qr) | |
2995 |
|
2985 | |||
2996 | def magic_upgrade(self,arg): |
|
2986 | def magic_upgrade(self,arg): | |
2997 | """ Upgrade your IPython installation |
|
2987 | """ Upgrade your IPython installation | |
2998 |
|
2988 | |||
2999 | This will copy the config files that don't yet exist in your |
|
2989 | This will copy the config files that don't yet exist in your | |
3000 | ipython dir from the system config dir. Use this after upgrading |
|
2990 | ipython dir from the system config dir. Use this after upgrading | |
3001 | IPython if you don't wish to delete your .ipython dir. |
|
2991 | IPython if you don't wish to delete your .ipython dir. | |
3002 |
|
2992 | |||
3003 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
2993 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
3004 | new users) |
|
2994 | new users) | |
3005 |
|
2995 | |||
3006 | """ |
|
2996 | """ | |
3007 | ip = self.getapi() |
|
2997 | ip = self.getapi() | |
3008 | ipinstallation = path(IPython.__file__).dirname() |
|
2998 | ipinstallation = path(IPython.__file__).dirname() | |
3009 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') |
|
2999 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') | |
3010 | src_config = ipinstallation / 'UserConfig' |
|
3000 | src_config = ipinstallation / 'UserConfig' | |
3011 | userdir = path(ip.options.ipythondir) |
|
3001 | userdir = path(ip.options.ipythondir) | |
3012 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3002 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
3013 | print ">",cmd |
|
3003 | print ">",cmd | |
3014 | shell(cmd) |
|
3004 | shell(cmd) | |
3015 | if arg == '-nolegacy': |
|
3005 | if arg == '-nolegacy': | |
3016 | legacy = userdir.files('ipythonrc*') |
|
3006 | legacy = userdir.files('ipythonrc*') | |
3017 | print "Nuking legacy files:",legacy |
|
3007 | print "Nuking legacy files:",legacy | |
3018 |
|
3008 | |||
3019 | [p.remove() for p in legacy] |
|
3009 | [p.remove() for p in legacy] | |
3020 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3010 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
3021 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3011 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
3022 |
|
3012 | |||
3023 |
|
3013 | |||
3024 | # end Magic |
|
3014 | # end Magic |
@@ -1,1707 +1,1719 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 1 |
|
8 | $Id: genutils.py 1845 2006-10-27 20:35:47Z fptest $""" | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
19 | __license__ = Release.license |
|
19 | __license__ = Release.license | |
20 |
|
20 | |||
21 | #**************************************************************************** |
|
21 | #**************************************************************************** | |
22 | # required modules from the Python standard library |
|
22 | # required modules from the Python standard library | |
23 | import __main__ |
|
23 | import __main__ | |
24 | import commands |
|
24 | import commands | |
25 | import os |
|
25 | import os | |
26 | import re |
|
26 | import re | |
|
27 | import shlex | |||
27 | import shutil |
|
28 | import shutil | |
28 | import sys |
|
29 | import sys | |
29 | import tempfile |
|
30 | import tempfile | |
30 | import time |
|
31 | import time | |
31 | import types |
|
32 | import types | |
32 |
|
33 | |||
33 | # Other IPython utilities |
|
34 | # Other IPython utilities | |
34 | from IPython.Itpl import Itpl,itpl,printpl |
|
35 | from IPython.Itpl import Itpl,itpl,printpl | |
35 | from IPython import DPyGetOpt |
|
36 | from IPython import DPyGetOpt | |
36 | from path import path |
|
37 | from path import path | |
37 | if os.name == "nt": |
|
38 | if os.name == "nt": | |
38 | from IPython.winconsole import get_console_size |
|
39 | from IPython.winconsole import get_console_size | |
39 |
|
40 | |||
40 | #**************************************************************************** |
|
41 | #**************************************************************************** | |
41 | # Exceptions |
|
42 | # Exceptions | |
42 | class Error(Exception): |
|
43 | class Error(Exception): | |
43 | """Base class for exceptions in this module.""" |
|
44 | """Base class for exceptions in this module.""" | |
44 | pass |
|
45 | pass | |
45 |
|
46 | |||
46 | #---------------------------------------------------------------------------- |
|
47 | #---------------------------------------------------------------------------- | |
47 | class IOStream: |
|
48 | class IOStream: | |
48 | def __init__(self,stream,fallback): |
|
49 | def __init__(self,stream,fallback): | |
49 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
50 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): | |
50 | stream = fallback |
|
51 | stream = fallback | |
51 | self.stream = stream |
|
52 | self.stream = stream | |
52 | self._swrite = stream.write |
|
53 | self._swrite = stream.write | |
53 | self.flush = stream.flush |
|
54 | self.flush = stream.flush | |
54 |
|
55 | |||
55 | def write(self,data): |
|
56 | def write(self,data): | |
56 | try: |
|
57 | try: | |
57 | self._swrite(data) |
|
58 | self._swrite(data) | |
58 | except: |
|
59 | except: | |
59 | try: |
|
60 | try: | |
60 | # print handles some unicode issues which may trip a plain |
|
61 | # print handles some unicode issues which may trip a plain | |
61 | # write() call. Attempt to emulate write() by using a |
|
62 | # write() call. Attempt to emulate write() by using a | |
62 | # trailing comma |
|
63 | # trailing comma | |
63 | print >> self.stream, data, |
|
64 | print >> self.stream, data, | |
64 | except: |
|
65 | except: | |
65 | # if we get here, something is seriously broken. |
|
66 | # if we get here, something is seriously broken. | |
66 | print >> sys.stderr, \ |
|
67 | print >> sys.stderr, \ | |
67 | 'ERROR - failed to write data to stream:', self.stream |
|
68 | 'ERROR - failed to write data to stream:', self.stream | |
68 |
|
69 | |||
69 | class IOTerm: |
|
70 | class IOTerm: | |
70 | """ Term holds the file or file-like objects for handling I/O operations. |
|
71 | """ Term holds the file or file-like objects for handling I/O operations. | |
71 |
|
72 | |||
72 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
73 | These are normally just sys.stdin, sys.stdout and sys.stderr but for | |
73 | Windows they can can replaced to allow editing the strings before they are |
|
74 | Windows they can can replaced to allow editing the strings before they are | |
74 | displayed.""" |
|
75 | displayed.""" | |
75 |
|
76 | |||
76 | # In the future, having IPython channel all its I/O operations through |
|
77 | # In the future, having IPython channel all its I/O operations through | |
77 | # this class will make it easier to embed it into other environments which |
|
78 | # this class will make it easier to embed it into other environments which | |
78 | # are not a normal terminal (such as a GUI-based shell) |
|
79 | # are not a normal terminal (such as a GUI-based shell) | |
79 | def __init__(self,cin=None,cout=None,cerr=None): |
|
80 | def __init__(self,cin=None,cout=None,cerr=None): | |
80 | self.cin = IOStream(cin,sys.stdin) |
|
81 | self.cin = IOStream(cin,sys.stdin) | |
81 | self.cout = IOStream(cout,sys.stdout) |
|
82 | self.cout = IOStream(cout,sys.stdout) | |
82 | self.cerr = IOStream(cerr,sys.stderr) |
|
83 | self.cerr = IOStream(cerr,sys.stderr) | |
83 |
|
84 | |||
84 | # Global variable to be used for all I/O |
|
85 | # Global variable to be used for all I/O | |
85 | Term = IOTerm() |
|
86 | Term = IOTerm() | |
86 |
|
87 | |||
87 | import IPython.rlineimpl as readline |
|
88 | import IPython.rlineimpl as readline | |
88 | # Remake Term to use the readline i/o facilities |
|
89 | # Remake Term to use the readline i/o facilities | |
89 | if sys.platform == 'win32' and readline.have_readline: |
|
90 | if sys.platform == 'win32' and readline.have_readline: | |
90 |
|
91 | |||
91 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) |
|
92 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) | |
92 |
|
93 | |||
93 |
|
94 | |||
94 | #**************************************************************************** |
|
95 | #**************************************************************************** | |
95 | # Generic warning/error printer, used by everything else |
|
96 | # Generic warning/error printer, used by everything else | |
96 | def warn(msg,level=2,exit_val=1): |
|
97 | def warn(msg,level=2,exit_val=1): | |
97 | """Standard warning printer. Gives formatting consistency. |
|
98 | """Standard warning printer. Gives formatting consistency. | |
98 |
|
99 | |||
99 | Output is sent to Term.cerr (sys.stderr by default). |
|
100 | Output is sent to Term.cerr (sys.stderr by default). | |
100 |
|
101 | |||
101 | Options: |
|
102 | Options: | |
102 |
|
103 | |||
103 | -level(2): allows finer control: |
|
104 | -level(2): allows finer control: | |
104 | 0 -> Do nothing, dummy function. |
|
105 | 0 -> Do nothing, dummy function. | |
105 | 1 -> Print message. |
|
106 | 1 -> Print message. | |
106 | 2 -> Print 'WARNING:' + message. (Default level). |
|
107 | 2 -> Print 'WARNING:' + message. (Default level). | |
107 | 3 -> Print 'ERROR:' + message. |
|
108 | 3 -> Print 'ERROR:' + message. | |
108 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
109 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). | |
109 |
|
110 | |||
110 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
111 | -exit_val (1): exit value returned by sys.exit() for a level 4 | |
111 | warning. Ignored for all other levels.""" |
|
112 | warning. Ignored for all other levels.""" | |
112 |
|
113 | |||
113 | if level>0: |
|
114 | if level>0: | |
114 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
115 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] | |
115 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
116 | print >> Term.cerr, '%s%s' % (header[level],msg) | |
116 | if level == 4: |
|
117 | if level == 4: | |
117 | print >> Term.cerr,'Exiting.\n' |
|
118 | print >> Term.cerr,'Exiting.\n' | |
118 | sys.exit(exit_val) |
|
119 | sys.exit(exit_val) | |
119 |
|
120 | |||
120 | def info(msg): |
|
121 | def info(msg): | |
121 | """Equivalent to warn(msg,level=1).""" |
|
122 | """Equivalent to warn(msg,level=1).""" | |
122 |
|
123 | |||
123 | warn(msg,level=1) |
|
124 | warn(msg,level=1) | |
124 |
|
125 | |||
125 | def error(msg): |
|
126 | def error(msg): | |
126 | """Equivalent to warn(msg,level=3).""" |
|
127 | """Equivalent to warn(msg,level=3).""" | |
127 |
|
128 | |||
128 | warn(msg,level=3) |
|
129 | warn(msg,level=3) | |
129 |
|
130 | |||
130 | def fatal(msg,exit_val=1): |
|
131 | def fatal(msg,exit_val=1): | |
131 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
132 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" | |
132 |
|
133 | |||
133 | warn(msg,exit_val=exit_val,level=4) |
|
134 | warn(msg,exit_val=exit_val,level=4) | |
134 |
|
135 | |||
135 | #--------------------------------------------------------------------------- |
|
136 | #--------------------------------------------------------------------------- | |
136 | # Debugging routines |
|
137 | # Debugging routines | |
137 | # |
|
138 | # | |
138 | def debugx(expr,pre_msg=''): |
|
139 | def debugx(expr,pre_msg=''): | |
139 | """Print the value of an expression from the caller's frame. |
|
140 | """Print the value of an expression from the caller's frame. | |
140 |
|
141 | |||
141 | Takes an expression, evaluates it in the caller's frame and prints both |
|
142 | Takes an expression, evaluates it in the caller's frame and prints both | |
142 | the given expression and the resulting value (as well as a debug mark |
|
143 | the given expression and the resulting value (as well as a debug mark | |
143 | indicating the name of the calling function. The input must be of a form |
|
144 | indicating the name of the calling function. The input must be of a form | |
144 | suitable for eval(). |
|
145 | suitable for eval(). | |
145 |
|
146 | |||
146 | An optional message can be passed, which will be prepended to the printed |
|
147 | An optional message can be passed, which will be prepended to the printed | |
147 | expr->value pair.""" |
|
148 | expr->value pair.""" | |
148 |
|
149 | |||
149 | cf = sys._getframe(1) |
|
150 | cf = sys._getframe(1) | |
150 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, |
|
151 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, | |
151 | eval(expr,cf.f_globals,cf.f_locals)) |
|
152 | eval(expr,cf.f_globals,cf.f_locals)) | |
152 |
|
153 | |||
153 | # deactivate it by uncommenting the following line, which makes it a no-op |
|
154 | # deactivate it by uncommenting the following line, which makes it a no-op | |
154 | #def debugx(expr,pre_msg=''): pass |
|
155 | #def debugx(expr,pre_msg=''): pass | |
155 |
|
156 | |||
156 | #---------------------------------------------------------------------------- |
|
157 | #---------------------------------------------------------------------------- | |
157 | StringTypes = types.StringTypes |
|
158 | StringTypes = types.StringTypes | |
158 |
|
159 | |||
159 | # Basic timing functionality |
|
160 | # Basic timing functionality | |
160 |
|
161 | |||
161 | # If possible (Unix), use the resource module instead of time.clock() |
|
162 | # If possible (Unix), use the resource module instead of time.clock() | |
162 | try: |
|
163 | try: | |
163 | import resource |
|
164 | import resource | |
164 | def clock(): |
|
165 | def clock(): | |
165 | """clock() -> floating point number |
|
166 | """clock() -> floating point number | |
166 |
|
167 | |||
167 | Return the CPU time in seconds (user time only, system time is |
|
168 | Return the CPU time in seconds (user time only, system time is | |
168 | ignored) since the start of the process. This is done via a call to |
|
169 | ignored) since the start of the process. This is done via a call to | |
169 | resource.getrusage, so it avoids the wraparound problems in |
|
170 | resource.getrusage, so it avoids the wraparound problems in | |
170 | time.clock().""" |
|
171 | time.clock().""" | |
171 |
|
172 | |||
172 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
173 | return resource.getrusage(resource.RUSAGE_SELF)[0] | |
173 |
|
174 | |||
174 | def clock2(): |
|
175 | def clock2(): | |
175 | """clock2() -> (t_user,t_system) |
|
176 | """clock2() -> (t_user,t_system) | |
176 |
|
177 | |||
177 | Similar to clock(), but return a tuple of user/system times.""" |
|
178 | Similar to clock(), but return a tuple of user/system times.""" | |
178 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
179 | return resource.getrusage(resource.RUSAGE_SELF)[:2] | |
179 |
|
180 | |||
180 | except ImportError: |
|
181 | except ImportError: | |
181 | clock = time.clock |
|
182 | clock = time.clock | |
182 | def clock2(): |
|
183 | def clock2(): | |
183 | """Under windows, system CPU time can't be measured. |
|
184 | """Under windows, system CPU time can't be measured. | |
184 |
|
185 | |||
185 | This just returns clock() and zero.""" |
|
186 | This just returns clock() and zero.""" | |
186 | return time.clock(),0.0 |
|
187 | return time.clock(),0.0 | |
187 |
|
188 | |||
188 | def timings_out(reps,func,*args,**kw): |
|
189 | def timings_out(reps,func,*args,**kw): | |
189 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
190 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) | |
190 |
|
191 | |||
191 | Execute a function reps times, return a tuple with the elapsed total |
|
192 | Execute a function reps times, return a tuple with the elapsed total | |
192 | CPU time in seconds, the time per call and the function's output. |
|
193 | CPU time in seconds, the time per call and the function's output. | |
193 |
|
194 | |||
194 | Under Unix, the return value is the sum of user+system time consumed by |
|
195 | Under Unix, the return value is the sum of user+system time consumed by | |
195 | the process, computed via the resource module. This prevents problems |
|
196 | the process, computed via the resource module. This prevents problems | |
196 | related to the wraparound effect which the time.clock() function has. |
|
197 | related to the wraparound effect which the time.clock() function has. | |
197 |
|
198 | |||
198 | Under Windows the return value is in wall clock seconds. See the |
|
199 | Under Windows the return value is in wall clock seconds. See the | |
199 | documentation for the time module for more details.""" |
|
200 | documentation for the time module for more details.""" | |
200 |
|
201 | |||
201 | reps = int(reps) |
|
202 | reps = int(reps) | |
202 | assert reps >=1, 'reps must be >= 1' |
|
203 | assert reps >=1, 'reps must be >= 1' | |
203 | if reps==1: |
|
204 | if reps==1: | |
204 | start = clock() |
|
205 | start = clock() | |
205 | out = func(*args,**kw) |
|
206 | out = func(*args,**kw) | |
206 | tot_time = clock()-start |
|
207 | tot_time = clock()-start | |
207 | else: |
|
208 | else: | |
208 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
209 | rng = xrange(reps-1) # the last time is executed separately to store output | |
209 | start = clock() |
|
210 | start = clock() | |
210 | for dummy in rng: func(*args,**kw) |
|
211 | for dummy in rng: func(*args,**kw) | |
211 | out = func(*args,**kw) # one last time |
|
212 | out = func(*args,**kw) # one last time | |
212 | tot_time = clock()-start |
|
213 | tot_time = clock()-start | |
213 | av_time = tot_time / reps |
|
214 | av_time = tot_time / reps | |
214 | return tot_time,av_time,out |
|
215 | return tot_time,av_time,out | |
215 |
|
216 | |||
216 | def timings(reps,func,*args,**kw): |
|
217 | def timings(reps,func,*args,**kw): | |
217 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
218 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) | |
218 |
|
219 | |||
219 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
220 | Execute a function reps times, return a tuple with the elapsed total CPU | |
220 | time in seconds and the time per call. These are just the first two values |
|
221 | time in seconds and the time per call. These are just the first two values | |
221 | in timings_out().""" |
|
222 | in timings_out().""" | |
222 |
|
223 | |||
223 | return timings_out(reps,func,*args,**kw)[0:2] |
|
224 | return timings_out(reps,func,*args,**kw)[0:2] | |
224 |
|
225 | |||
225 | def timing(func,*args,**kw): |
|
226 | def timing(func,*args,**kw): | |
226 | """timing(func,*args,**kw) -> t_total |
|
227 | """timing(func,*args,**kw) -> t_total | |
227 |
|
228 | |||
228 | Execute a function once, return the elapsed total CPU time in |
|
229 | Execute a function once, return the elapsed total CPU time in | |
229 | seconds. This is just the first value in timings_out().""" |
|
230 | seconds. This is just the first value in timings_out().""" | |
230 |
|
231 | |||
231 | return timings_out(1,func,*args,**kw)[0] |
|
232 | return timings_out(1,func,*args,**kw)[0] | |
232 |
|
233 | |||
233 | #**************************************************************************** |
|
234 | #**************************************************************************** | |
234 | # file and system |
|
235 | # file and system | |
235 |
|
236 | |||
|
237 | def arg_split(s,posix=False): | |||
|
238 | """Split a command line's arguments in a shell-like manner. | |||
|
239 | ||||
|
240 | This is a modified version of the standard library's shlex.split() | |||
|
241 | function, but with a default of posix=False for splitting, so that quotes | |||
|
242 | in inputs are respected.""" | |||
|
243 | ||||
|
244 | lex = shlex.shlex(s, posix=posix) | |||
|
245 | lex.whitespace_split = True | |||
|
246 | return list(lex) | |||
|
247 | ||||
236 | def system(cmd,verbose=0,debug=0,header=''): |
|
248 | def system(cmd,verbose=0,debug=0,header=''): | |
237 | """Execute a system command, return its exit status. |
|
249 | """Execute a system command, return its exit status. | |
238 |
|
250 | |||
239 | Options: |
|
251 | Options: | |
240 |
|
252 | |||
241 | - verbose (0): print the command to be executed. |
|
253 | - verbose (0): print the command to be executed. | |
242 |
|
254 | |||
243 | - debug (0): only print, do not actually execute. |
|
255 | - debug (0): only print, do not actually execute. | |
244 |
|
256 | |||
245 | - header (''): Header to print on screen prior to the executed command (it |
|
257 | - header (''): Header to print on screen prior to the executed command (it | |
246 | is only prepended to the command, no newlines are added). |
|
258 | is only prepended to the command, no newlines are added). | |
247 |
|
259 | |||
248 | Note: a stateful version of this function is available through the |
|
260 | Note: a stateful version of this function is available through the | |
249 | SystemExec class.""" |
|
261 | SystemExec class.""" | |
250 |
|
262 | |||
251 | stat = 0 |
|
263 | stat = 0 | |
252 | if verbose or debug: print header+cmd |
|
264 | if verbose or debug: print header+cmd | |
253 | sys.stdout.flush() |
|
265 | sys.stdout.flush() | |
254 | if not debug: stat = os.system(cmd) |
|
266 | if not debug: stat = os.system(cmd) | |
255 | return stat |
|
267 | return stat | |
256 |
|
268 | |||
257 | # This function is used by ipython in a lot of places to make system calls. |
|
269 | # This function is used by ipython in a lot of places to make system calls. | |
258 | # We need it to be slightly different under win32, due to the vagaries of |
|
270 | # We need it to be slightly different under win32, due to the vagaries of | |
259 | # 'network shares'. A win32 override is below. |
|
271 | # 'network shares'. A win32 override is below. | |
260 |
|
272 | |||
261 | def shell(cmd,verbose=0,debug=0,header=''): |
|
273 | def shell(cmd,verbose=0,debug=0,header=''): | |
262 | """Execute a command in the system shell, always return None. |
|
274 | """Execute a command in the system shell, always return None. | |
263 |
|
275 | |||
264 | Options: |
|
276 | Options: | |
265 |
|
277 | |||
266 | - verbose (0): print the command to be executed. |
|
278 | - verbose (0): print the command to be executed. | |
267 |
|
279 | |||
268 | - debug (0): only print, do not actually execute. |
|
280 | - debug (0): only print, do not actually execute. | |
269 |
|
281 | |||
270 | - header (''): Header to print on screen prior to the executed command (it |
|
282 | - header (''): Header to print on screen prior to the executed command (it | |
271 | is only prepended to the command, no newlines are added). |
|
283 | is only prepended to the command, no newlines are added). | |
272 |
|
284 | |||
273 | Note: this is similar to genutils.system(), but it returns None so it can |
|
285 | Note: this is similar to genutils.system(), but it returns None so it can | |
274 | be conveniently used in interactive loops without getting the return value |
|
286 | be conveniently used in interactive loops without getting the return value | |
275 | (typically 0) printed many times.""" |
|
287 | (typically 0) printed many times.""" | |
276 |
|
288 | |||
277 | stat = 0 |
|
289 | stat = 0 | |
278 | if verbose or debug: print header+cmd |
|
290 | if verbose or debug: print header+cmd | |
279 | # flush stdout so we don't mangle python's buffering |
|
291 | # flush stdout so we don't mangle python's buffering | |
280 | sys.stdout.flush() |
|
292 | sys.stdout.flush() | |
281 | if not debug: |
|
293 | if not debug: | |
282 | os.system(cmd) |
|
294 | os.system(cmd) | |
283 |
|
295 | |||
284 | # override shell() for win32 to deal with network shares |
|
296 | # override shell() for win32 to deal with network shares | |
285 | if os.name in ('nt','dos'): |
|
297 | if os.name in ('nt','dos'): | |
286 |
|
298 | |||
287 | shell_ori = shell |
|
299 | shell_ori = shell | |
288 |
|
300 | |||
289 | def shell(cmd,verbose=0,debug=0,header=''): |
|
301 | def shell(cmd,verbose=0,debug=0,header=''): | |
290 | if os.getcwd().startswith(r"\\"): |
|
302 | if os.getcwd().startswith(r"\\"): | |
291 | path = os.getcwd() |
|
303 | path = os.getcwd() | |
292 | # change to c drive (cannot be on UNC-share when issuing os.system, |
|
304 | # change to c drive (cannot be on UNC-share when issuing os.system, | |
293 | # as cmd.exe cannot handle UNC addresses) |
|
305 | # as cmd.exe cannot handle UNC addresses) | |
294 | os.chdir("c:") |
|
306 | os.chdir("c:") | |
295 | # issue pushd to the UNC-share and then run the command |
|
307 | # issue pushd to the UNC-share and then run the command | |
296 | try: |
|
308 | try: | |
297 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) |
|
309 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) | |
298 | finally: |
|
310 | finally: | |
299 | os.chdir(path) |
|
311 | os.chdir(path) | |
300 | else: |
|
312 | else: | |
301 | shell_ori(cmd,verbose,debug,header) |
|
313 | shell_ori(cmd,verbose,debug,header) | |
302 |
|
314 | |||
303 | shell.__doc__ = shell_ori.__doc__ |
|
315 | shell.__doc__ = shell_ori.__doc__ | |
304 |
|
316 | |||
305 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
317 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): | |
306 | """Dummy substitute for perl's backquotes. |
|
318 | """Dummy substitute for perl's backquotes. | |
307 |
|
319 | |||
308 | Executes a command and returns the output. |
|
320 | Executes a command and returns the output. | |
309 |
|
321 | |||
310 | Accepts the same arguments as system(), plus: |
|
322 | Accepts the same arguments as system(), plus: | |
311 |
|
323 | |||
312 | - split(0): if true, the output is returned as a list split on newlines. |
|
324 | - split(0): if true, the output is returned as a list split on newlines. | |
313 |
|
325 | |||
314 | Note: a stateful version of this function is available through the |
|
326 | Note: a stateful version of this function is available through the | |
315 | SystemExec class. |
|
327 | SystemExec class. | |
316 |
|
328 | |||
317 | This is pretty much deprecated and rarely used, |
|
329 | This is pretty much deprecated and rarely used, | |
318 | genutils.getoutputerror may be what you need. |
|
330 | genutils.getoutputerror may be what you need. | |
319 |
|
331 | |||
320 | """ |
|
332 | """ | |
321 |
|
333 | |||
322 | if verbose or debug: print header+cmd |
|
334 | if verbose or debug: print header+cmd | |
323 | if not debug: |
|
335 | if not debug: | |
324 | output = os.popen(cmd).read() |
|
336 | output = os.popen(cmd).read() | |
325 | # stipping last \n is here for backwards compat. |
|
337 | # stipping last \n is here for backwards compat. | |
326 | if output.endswith('\n'): |
|
338 | if output.endswith('\n'): | |
327 | output = output[:-1] |
|
339 | output = output[:-1] | |
328 | if split: |
|
340 | if split: | |
329 | return output.split('\n') |
|
341 | return output.split('\n') | |
330 | else: |
|
342 | else: | |
331 | return output |
|
343 | return output | |
332 |
|
344 | |||
333 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
345 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): | |
334 | """Return (standard output,standard error) of executing cmd in a shell. |
|
346 | """Return (standard output,standard error) of executing cmd in a shell. | |
335 |
|
347 | |||
336 | Accepts the same arguments as system(), plus: |
|
348 | Accepts the same arguments as system(), plus: | |
337 |
|
349 | |||
338 | - split(0): if true, each of stdout/err is returned as a list split on |
|
350 | - split(0): if true, each of stdout/err is returned as a list split on | |
339 | newlines. |
|
351 | newlines. | |
340 |
|
352 | |||
341 | Note: a stateful version of this function is available through the |
|
353 | Note: a stateful version of this function is available through the | |
342 | SystemExec class.""" |
|
354 | SystemExec class.""" | |
343 |
|
355 | |||
344 | if verbose or debug: print header+cmd |
|
356 | if verbose or debug: print header+cmd | |
345 | if not cmd: |
|
357 | if not cmd: | |
346 | if split: |
|
358 | if split: | |
347 | return [],[] |
|
359 | return [],[] | |
348 | else: |
|
360 | else: | |
349 | return '','' |
|
361 | return '','' | |
350 | if not debug: |
|
362 | if not debug: | |
351 | pin,pout,perr = os.popen3(cmd) |
|
363 | pin,pout,perr = os.popen3(cmd) | |
352 | tout = pout.read().rstrip() |
|
364 | tout = pout.read().rstrip() | |
353 | terr = perr.read().rstrip() |
|
365 | terr = perr.read().rstrip() | |
354 | pin.close() |
|
366 | pin.close() | |
355 | pout.close() |
|
367 | pout.close() | |
356 | perr.close() |
|
368 | perr.close() | |
357 | if split: |
|
369 | if split: | |
358 | return tout.split('\n'),terr.split('\n') |
|
370 | return tout.split('\n'),terr.split('\n') | |
359 | else: |
|
371 | else: | |
360 | return tout,terr |
|
372 | return tout,terr | |
361 |
|
373 | |||
362 | # for compatibility with older naming conventions |
|
374 | # for compatibility with older naming conventions | |
363 | xsys = system |
|
375 | xsys = system | |
364 | bq = getoutput |
|
376 | bq = getoutput | |
365 |
|
377 | |||
366 | class SystemExec: |
|
378 | class SystemExec: | |
367 | """Access the system and getoutput functions through a stateful interface. |
|
379 | """Access the system and getoutput functions through a stateful interface. | |
368 |
|
380 | |||
369 | Note: here we refer to the system and getoutput functions from this |
|
381 | Note: here we refer to the system and getoutput functions from this | |
370 | library, not the ones from the standard python library. |
|
382 | library, not the ones from the standard python library. | |
371 |
|
383 | |||
372 | This class offers the system and getoutput functions as methods, but the |
|
384 | This class offers the system and getoutput functions as methods, but the | |
373 | verbose, debug and header parameters can be set for the instance (at |
|
385 | verbose, debug and header parameters can be set for the instance (at | |
374 | creation time or later) so that they don't need to be specified on each |
|
386 | creation time or later) so that they don't need to be specified on each | |
375 | call. |
|
387 | call. | |
376 |
|
388 | |||
377 | For efficiency reasons, there's no way to override the parameters on a |
|
389 | For efficiency reasons, there's no way to override the parameters on a | |
378 | per-call basis other than by setting instance attributes. If you need |
|
390 | per-call basis other than by setting instance attributes. If you need | |
379 | local overrides, it's best to directly call system() or getoutput(). |
|
391 | local overrides, it's best to directly call system() or getoutput(). | |
380 |
|
392 | |||
381 | The following names are provided as alternate options: |
|
393 | The following names are provided as alternate options: | |
382 | - xsys: alias to system |
|
394 | - xsys: alias to system | |
383 | - bq: alias to getoutput |
|
395 | - bq: alias to getoutput | |
384 |
|
396 | |||
385 | An instance can then be created as: |
|
397 | An instance can then be created as: | |
386 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
398 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') | |
387 |
|
399 | |||
388 | And used as: |
|
400 | And used as: | |
389 | >>> sysexec.xsys('pwd') |
|
401 | >>> sysexec.xsys('pwd') | |
390 | >>> dirlist = sysexec.bq('ls -l') |
|
402 | >>> dirlist = sysexec.bq('ls -l') | |
391 | """ |
|
403 | """ | |
392 |
|
404 | |||
393 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
405 | def __init__(self,verbose=0,debug=0,header='',split=0): | |
394 | """Specify the instance's values for verbose, debug and header.""" |
|
406 | """Specify the instance's values for verbose, debug and header.""" | |
395 | setattr_list(self,'verbose debug header split') |
|
407 | setattr_list(self,'verbose debug header split') | |
396 |
|
408 | |||
397 | def system(self,cmd): |
|
409 | def system(self,cmd): | |
398 | """Stateful interface to system(), with the same keyword parameters.""" |
|
410 | """Stateful interface to system(), with the same keyword parameters.""" | |
399 |
|
411 | |||
400 | system(cmd,self.verbose,self.debug,self.header) |
|
412 | system(cmd,self.verbose,self.debug,self.header) | |
401 |
|
413 | |||
402 | def shell(self,cmd): |
|
414 | def shell(self,cmd): | |
403 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
415 | """Stateful interface to shell(), with the same keyword parameters.""" | |
404 |
|
416 | |||
405 | shell(cmd,self.verbose,self.debug,self.header) |
|
417 | shell(cmd,self.verbose,self.debug,self.header) | |
406 |
|
418 | |||
407 | xsys = system # alias |
|
419 | xsys = system # alias | |
408 |
|
420 | |||
409 | def getoutput(self,cmd): |
|
421 | def getoutput(self,cmd): | |
410 | """Stateful interface to getoutput().""" |
|
422 | """Stateful interface to getoutput().""" | |
411 |
|
423 | |||
412 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
424 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) | |
413 |
|
425 | |||
414 | def getoutputerror(self,cmd): |
|
426 | def getoutputerror(self,cmd): | |
415 | """Stateful interface to getoutputerror().""" |
|
427 | """Stateful interface to getoutputerror().""" | |
416 |
|
428 | |||
417 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
429 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) | |
418 |
|
430 | |||
419 | bq = getoutput # alias |
|
431 | bq = getoutput # alias | |
420 |
|
432 | |||
421 | #----------------------------------------------------------------------------- |
|
433 | #----------------------------------------------------------------------------- | |
422 | def mutex_opts(dict,ex_op): |
|
434 | def mutex_opts(dict,ex_op): | |
423 | """Check for presence of mutually exclusive keys in a dict. |
|
435 | """Check for presence of mutually exclusive keys in a dict. | |
424 |
|
436 | |||
425 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
437 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" | |
426 | for op1,op2 in ex_op: |
|
438 | for op1,op2 in ex_op: | |
427 | if op1 in dict and op2 in dict: |
|
439 | if op1 in dict and op2 in dict: | |
428 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
440 | raise ValueError,'\n*** ERROR in Arguments *** '\ | |
429 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
441 | 'Options '+op1+' and '+op2+' are mutually exclusive.' | |
430 |
|
442 | |||
431 | #----------------------------------------------------------------------------- |
|
443 | #----------------------------------------------------------------------------- | |
432 | def get_py_filename(name): |
|
444 | def get_py_filename(name): | |
433 | """Return a valid python filename in the current directory. |
|
445 | """Return a valid python filename in the current directory. | |
434 |
|
446 | |||
435 | If the given name is not a file, it adds '.py' and searches again. |
|
447 | If the given name is not a file, it adds '.py' and searches again. | |
436 | Raises IOError with an informative message if the file isn't found.""" |
|
448 | Raises IOError with an informative message if the file isn't found.""" | |
437 |
|
449 | |||
438 | name = os.path.expanduser(name) |
|
450 | name = os.path.expanduser(name) | |
439 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
451 | if not os.path.isfile(name) and not name.endswith('.py'): | |
440 | name += '.py' |
|
452 | name += '.py' | |
441 | if os.path.isfile(name): |
|
453 | if os.path.isfile(name): | |
442 | return name |
|
454 | return name | |
443 | else: |
|
455 | else: | |
444 | raise IOError,'File `%s` not found.' % name |
|
456 | raise IOError,'File `%s` not found.' % name | |
445 |
|
457 | |||
446 | #----------------------------------------------------------------------------- |
|
458 | #----------------------------------------------------------------------------- | |
447 | def filefind(fname,alt_dirs = None): |
|
459 | def filefind(fname,alt_dirs = None): | |
448 | """Return the given filename either in the current directory, if it |
|
460 | """Return the given filename either in the current directory, if it | |
449 | exists, or in a specified list of directories. |
|
461 | exists, or in a specified list of directories. | |
450 |
|
462 | |||
451 | ~ expansion is done on all file and directory names. |
|
463 | ~ expansion is done on all file and directory names. | |
452 |
|
464 | |||
453 | Upon an unsuccessful search, raise an IOError exception.""" |
|
465 | Upon an unsuccessful search, raise an IOError exception.""" | |
454 |
|
466 | |||
455 | if alt_dirs is None: |
|
467 | if alt_dirs is None: | |
456 | try: |
|
468 | try: | |
457 | alt_dirs = get_home_dir() |
|
469 | alt_dirs = get_home_dir() | |
458 | except HomeDirError: |
|
470 | except HomeDirError: | |
459 | alt_dirs = os.getcwd() |
|
471 | alt_dirs = os.getcwd() | |
460 | search = [fname] + list_strings(alt_dirs) |
|
472 | search = [fname] + list_strings(alt_dirs) | |
461 | search = map(os.path.expanduser,search) |
|
473 | search = map(os.path.expanduser,search) | |
462 | #print 'search list for',fname,'list:',search # dbg |
|
474 | #print 'search list for',fname,'list:',search # dbg | |
463 | fname = search[0] |
|
475 | fname = search[0] | |
464 | if os.path.isfile(fname): |
|
476 | if os.path.isfile(fname): | |
465 | return fname |
|
477 | return fname | |
466 | for direc in search[1:]: |
|
478 | for direc in search[1:]: | |
467 | testname = os.path.join(direc,fname) |
|
479 | testname = os.path.join(direc,fname) | |
468 | #print 'testname',testname # dbg |
|
480 | #print 'testname',testname # dbg | |
469 | if os.path.isfile(testname): |
|
481 | if os.path.isfile(testname): | |
470 | return testname |
|
482 | return testname | |
471 | raise IOError,'File' + `fname` + \ |
|
483 | raise IOError,'File' + `fname` + \ | |
472 | ' not found in current or supplied directories:' + `alt_dirs` |
|
484 | ' not found in current or supplied directories:' + `alt_dirs` | |
473 |
|
485 | |||
474 | #---------------------------------------------------------------------------- |
|
486 | #---------------------------------------------------------------------------- | |
475 | def file_read(filename): |
|
487 | def file_read(filename): | |
476 | """Read a file and close it. Returns the file source.""" |
|
488 | """Read a file and close it. Returns the file source.""" | |
477 | fobj = open(filename,'r'); |
|
489 | fobj = open(filename,'r'); | |
478 | source = fobj.read(); |
|
490 | source = fobj.read(); | |
479 | fobj.close() |
|
491 | fobj.close() | |
480 | return source |
|
492 | return source | |
481 |
|
493 | |||
482 | def file_readlines(filename): |
|
494 | def file_readlines(filename): | |
483 | """Read a file and close it. Returns the file source using readlines().""" |
|
495 | """Read a file and close it. Returns the file source using readlines().""" | |
484 | fobj = open(filename,'r'); |
|
496 | fobj = open(filename,'r'); | |
485 | lines = fobj.readlines(); |
|
497 | lines = fobj.readlines(); | |
486 | fobj.close() |
|
498 | fobj.close() | |
487 | return lines |
|
499 | return lines | |
488 |
|
500 | |||
489 | #---------------------------------------------------------------------------- |
|
501 | #---------------------------------------------------------------------------- | |
490 | def target_outdated(target,deps): |
|
502 | def target_outdated(target,deps): | |
491 | """Determine whether a target is out of date. |
|
503 | """Determine whether a target is out of date. | |
492 |
|
504 | |||
493 | target_outdated(target,deps) -> 1/0 |
|
505 | target_outdated(target,deps) -> 1/0 | |
494 |
|
506 | |||
495 | deps: list of filenames which MUST exist. |
|
507 | deps: list of filenames which MUST exist. | |
496 | target: single filename which may or may not exist. |
|
508 | target: single filename which may or may not exist. | |
497 |
|
509 | |||
498 | If target doesn't exist or is older than any file listed in deps, return |
|
510 | If target doesn't exist or is older than any file listed in deps, return | |
499 | true, otherwise return false. |
|
511 | true, otherwise return false. | |
500 | """ |
|
512 | """ | |
501 | try: |
|
513 | try: | |
502 | target_time = os.path.getmtime(target) |
|
514 | target_time = os.path.getmtime(target) | |
503 | except os.error: |
|
515 | except os.error: | |
504 | return 1 |
|
516 | return 1 | |
505 | for dep in deps: |
|
517 | for dep in deps: | |
506 | dep_time = os.path.getmtime(dep) |
|
518 | dep_time = os.path.getmtime(dep) | |
507 | if dep_time > target_time: |
|
519 | if dep_time > target_time: | |
508 | #print "For target",target,"Dep failed:",dep # dbg |
|
520 | #print "For target",target,"Dep failed:",dep # dbg | |
509 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
521 | #print "times (dep,tar):",dep_time,target_time # dbg | |
510 | return 1 |
|
522 | return 1 | |
511 | return 0 |
|
523 | return 0 | |
512 |
|
524 | |||
513 | #----------------------------------------------------------------------------- |
|
525 | #----------------------------------------------------------------------------- | |
514 | def target_update(target,deps,cmd): |
|
526 | def target_update(target,deps,cmd): | |
515 | """Update a target with a given command given a list of dependencies. |
|
527 | """Update a target with a given command given a list of dependencies. | |
516 |
|
528 | |||
517 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
529 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
518 |
|
530 | |||
519 | This is just a wrapper around target_outdated() which calls the given |
|
531 | This is just a wrapper around target_outdated() which calls the given | |
520 | command if target is outdated.""" |
|
532 | command if target is outdated.""" | |
521 |
|
533 | |||
522 | if target_outdated(target,deps): |
|
534 | if target_outdated(target,deps): | |
523 | xsys(cmd) |
|
535 | xsys(cmd) | |
524 |
|
536 | |||
525 | #---------------------------------------------------------------------------- |
|
537 | #---------------------------------------------------------------------------- | |
526 | def unquote_ends(istr): |
|
538 | def unquote_ends(istr): | |
527 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
539 | """Remove a single pair of quotes from the endpoints of a string.""" | |
528 |
|
540 | |||
529 | if not istr: |
|
541 | if not istr: | |
530 | return istr |
|
542 | return istr | |
531 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
543 | if (istr[0]=="'" and istr[-1]=="'") or \ | |
532 | (istr[0]=='"' and istr[-1]=='"'): |
|
544 | (istr[0]=='"' and istr[-1]=='"'): | |
533 | return istr[1:-1] |
|
545 | return istr[1:-1] | |
534 | else: |
|
546 | else: | |
535 | return istr |
|
547 | return istr | |
536 |
|
548 | |||
537 | #---------------------------------------------------------------------------- |
|
549 | #---------------------------------------------------------------------------- | |
538 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
550 | def process_cmdline(argv,names=[],defaults={},usage=''): | |
539 | """ Process command-line options and arguments. |
|
551 | """ Process command-line options and arguments. | |
540 |
|
552 | |||
541 | Arguments: |
|
553 | Arguments: | |
542 |
|
554 | |||
543 | - argv: list of arguments, typically sys.argv. |
|
555 | - argv: list of arguments, typically sys.argv. | |
544 |
|
556 | |||
545 | - names: list of option names. See DPyGetOpt docs for details on options |
|
557 | - names: list of option names. See DPyGetOpt docs for details on options | |
546 | syntax. |
|
558 | syntax. | |
547 |
|
559 | |||
548 | - defaults: dict of default values. |
|
560 | - defaults: dict of default values. | |
549 |
|
561 | |||
550 | - usage: optional usage notice to print if a wrong argument is passed. |
|
562 | - usage: optional usage notice to print if a wrong argument is passed. | |
551 |
|
563 | |||
552 | Return a dict of options and a list of free arguments.""" |
|
564 | Return a dict of options and a list of free arguments.""" | |
553 |
|
565 | |||
554 | getopt = DPyGetOpt.DPyGetOpt() |
|
566 | getopt = DPyGetOpt.DPyGetOpt() | |
555 | getopt.setIgnoreCase(0) |
|
567 | getopt.setIgnoreCase(0) | |
556 | getopt.parseConfiguration(names) |
|
568 | getopt.parseConfiguration(names) | |
557 |
|
569 | |||
558 | try: |
|
570 | try: | |
559 | getopt.processArguments(argv) |
|
571 | getopt.processArguments(argv) | |
560 | except: |
|
572 | except: | |
561 | print usage |
|
573 | print usage | |
562 | warn(`sys.exc_value`,level=4) |
|
574 | warn(`sys.exc_value`,level=4) | |
563 |
|
575 | |||
564 | defaults.update(getopt.optionValues) |
|
576 | defaults.update(getopt.optionValues) | |
565 | args = getopt.freeValues |
|
577 | args = getopt.freeValues | |
566 |
|
578 | |||
567 | return defaults,args |
|
579 | return defaults,args | |
568 |
|
580 | |||
569 | #---------------------------------------------------------------------------- |
|
581 | #---------------------------------------------------------------------------- | |
570 | def optstr2types(ostr): |
|
582 | def optstr2types(ostr): | |
571 | """Convert a string of option names to a dict of type mappings. |
|
583 | """Convert a string of option names to a dict of type mappings. | |
572 |
|
584 | |||
573 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
585 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} | |
574 |
|
586 | |||
575 | This is used to get the types of all the options in a string formatted |
|
587 | This is used to get the types of all the options in a string formatted | |
576 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
588 | with the conventions of DPyGetOpt. The 'type' None is used for options | |
577 | which are strings (they need no further conversion). This function's main |
|
589 | which are strings (they need no further conversion). This function's main | |
578 | use is to get a typemap for use with read_dict(). |
|
590 | use is to get a typemap for use with read_dict(). | |
579 | """ |
|
591 | """ | |
580 |
|
592 | |||
581 | typeconv = {None:'',int:'',float:''} |
|
593 | typeconv = {None:'',int:'',float:''} | |
582 | typemap = {'s':None,'i':int,'f':float} |
|
594 | typemap = {'s':None,'i':int,'f':float} | |
583 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
595 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') | |
584 |
|
596 | |||
585 | for w in ostr.split(): |
|
597 | for w in ostr.split(): | |
586 | oname,alias,otype = opt_re.match(w).groups() |
|
598 | oname,alias,otype = opt_re.match(w).groups() | |
587 | if otype == '' or alias == '!': # simple switches are integers too |
|
599 | if otype == '' or alias == '!': # simple switches are integers too | |
588 | otype = 'i' |
|
600 | otype = 'i' | |
589 | typeconv[typemap[otype]] += oname + ' ' |
|
601 | typeconv[typemap[otype]] += oname + ' ' | |
590 | return typeconv |
|
602 | return typeconv | |
591 |
|
603 | |||
592 | #---------------------------------------------------------------------------- |
|
604 | #---------------------------------------------------------------------------- | |
593 | def read_dict(filename,type_conv=None,**opt): |
|
605 | def read_dict(filename,type_conv=None,**opt): | |
594 |
|
606 | |||
595 | """Read a dictionary of key=value pairs from an input file, optionally |
|
607 | """Read a dictionary of key=value pairs from an input file, optionally | |
596 | performing conversions on the resulting values. |
|
608 | performing conversions on the resulting values. | |
597 |
|
609 | |||
598 | read_dict(filename,type_conv,**opt) -> dict |
|
610 | read_dict(filename,type_conv,**opt) -> dict | |
599 |
|
611 | |||
600 | Only one value per line is accepted, the format should be |
|
612 | Only one value per line is accepted, the format should be | |
601 | # optional comments are ignored |
|
613 | # optional comments are ignored | |
602 | key value\n |
|
614 | key value\n | |
603 |
|
615 | |||
604 | Args: |
|
616 | Args: | |
605 |
|
617 | |||
606 | - type_conv: A dictionary specifying which keys need to be converted to |
|
618 | - type_conv: A dictionary specifying which keys need to be converted to | |
607 | which types. By default all keys are read as strings. This dictionary |
|
619 | which types. By default all keys are read as strings. This dictionary | |
608 | should have as its keys valid conversion functions for strings |
|
620 | should have as its keys valid conversion functions for strings | |
609 | (int,long,float,complex, or your own). The value for each key |
|
621 | (int,long,float,complex, or your own). The value for each key | |
610 | (converter) should be a whitespace separated string containing the names |
|
622 | (converter) should be a whitespace separated string containing the names | |
611 | of all the entries in the file to be converted using that function. For |
|
623 | of all the entries in the file to be converted using that function. For | |
612 | keys to be left alone, use None as the conversion function (only needed |
|
624 | keys to be left alone, use None as the conversion function (only needed | |
613 | with purge=1, see below). |
|
625 | with purge=1, see below). | |
614 |
|
626 | |||
615 | - opt: dictionary with extra options as below (default in parens) |
|
627 | - opt: dictionary with extra options as below (default in parens) | |
616 |
|
628 | |||
617 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
629 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out | |
618 | of the dictionary to be returned. If purge is going to be used, the |
|
630 | of the dictionary to be returned. If purge is going to be used, the | |
619 | set of keys to be left as strings also has to be explicitly specified |
|
631 | set of keys to be left as strings also has to be explicitly specified | |
620 | using the (non-existent) conversion function None. |
|
632 | using the (non-existent) conversion function None. | |
621 |
|
633 | |||
622 | fs(None): field separator. This is the key/value separator to be used |
|
634 | fs(None): field separator. This is the key/value separator to be used | |
623 | when parsing the file. The None default means any whitespace [behavior |
|
635 | when parsing the file. The None default means any whitespace [behavior | |
624 | of string.split()]. |
|
636 | of string.split()]. | |
625 |
|
637 | |||
626 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
638 | strip(0): if 1, strip string values of leading/trailinig whitespace. | |
627 |
|
639 | |||
628 | warn(1): warning level if requested keys are not found in file. |
|
640 | warn(1): warning level if requested keys are not found in file. | |
629 | - 0: silently ignore. |
|
641 | - 0: silently ignore. | |
630 | - 1: inform but proceed. |
|
642 | - 1: inform but proceed. | |
631 | - 2: raise KeyError exception. |
|
643 | - 2: raise KeyError exception. | |
632 |
|
644 | |||
633 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
645 | no_empty(0): if 1, remove keys with whitespace strings as a value. | |
634 |
|
646 | |||
635 | unique([]): list of keys (or space separated string) which can't be |
|
647 | unique([]): list of keys (or space separated string) which can't be | |
636 | repeated. If one such key is found in the file, each new instance |
|
648 | repeated. If one such key is found in the file, each new instance | |
637 | overwrites the previous one. For keys not listed here, the behavior is |
|
649 | overwrites the previous one. For keys not listed here, the behavior is | |
638 | to make a list of all appearances. |
|
650 | to make a list of all appearances. | |
639 |
|
651 | |||
640 | Example: |
|
652 | Example: | |
641 | If the input file test.ini has: |
|
653 | If the input file test.ini has: | |
642 | i 3 |
|
654 | i 3 | |
643 | x 4.5 |
|
655 | x 4.5 | |
644 | y 5.5 |
|
656 | y 5.5 | |
645 | s hi ho |
|
657 | s hi ho | |
646 | Then: |
|
658 | Then: | |
647 |
|
659 | |||
648 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
660 | >>> type_conv={int:'i',float:'x',None:'s'} | |
649 | >>> read_dict('test.ini') |
|
661 | >>> read_dict('test.ini') | |
650 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} |
|
662 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} | |
651 | >>> read_dict('test.ini',type_conv) |
|
663 | >>> read_dict('test.ini',type_conv) | |
652 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} |
|
664 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} | |
653 | >>> read_dict('test.ini',type_conv,purge=1) |
|
665 | >>> read_dict('test.ini',type_conv,purge=1) | |
654 | {'i': 3, 's': 'hi ho', 'x': 4.5} |
|
666 | {'i': 3, 's': 'hi ho', 'x': 4.5} | |
655 | """ |
|
667 | """ | |
656 |
|
668 | |||
657 | # starting config |
|
669 | # starting config | |
658 | opt.setdefault('purge',0) |
|
670 | opt.setdefault('purge',0) | |
659 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
671 | opt.setdefault('fs',None) # field sep defaults to any whitespace | |
660 | opt.setdefault('strip',0) |
|
672 | opt.setdefault('strip',0) | |
661 | opt.setdefault('warn',1) |
|
673 | opt.setdefault('warn',1) | |
662 | opt.setdefault('no_empty',0) |
|
674 | opt.setdefault('no_empty',0) | |
663 | opt.setdefault('unique','') |
|
675 | opt.setdefault('unique','') | |
664 | if type(opt['unique']) in StringTypes: |
|
676 | if type(opt['unique']) in StringTypes: | |
665 | unique_keys = qw(opt['unique']) |
|
677 | unique_keys = qw(opt['unique']) | |
666 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
678 | elif type(opt['unique']) in (types.TupleType,types.ListType): | |
667 | unique_keys = opt['unique'] |
|
679 | unique_keys = opt['unique'] | |
668 | else: |
|
680 | else: | |
669 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
681 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' | |
670 |
|
682 | |||
671 | dict = {} |
|
683 | dict = {} | |
672 | # first read in table of values as strings |
|
684 | # first read in table of values as strings | |
673 | file = open(filename,'r') |
|
685 | file = open(filename,'r') | |
674 | for line in file.readlines(): |
|
686 | for line in file.readlines(): | |
675 | line = line.strip() |
|
687 | line = line.strip() | |
676 | if len(line) and line[0]=='#': continue |
|
688 | if len(line) and line[0]=='#': continue | |
677 | if len(line)>0: |
|
689 | if len(line)>0: | |
678 | lsplit = line.split(opt['fs'],1) |
|
690 | lsplit = line.split(opt['fs'],1) | |
679 | try: |
|
691 | try: | |
680 | key,val = lsplit |
|
692 | key,val = lsplit | |
681 | except ValueError: |
|
693 | except ValueError: | |
682 | key,val = lsplit[0],'' |
|
694 | key,val = lsplit[0],'' | |
683 | key = key.strip() |
|
695 | key = key.strip() | |
684 | if opt['strip']: val = val.strip() |
|
696 | if opt['strip']: val = val.strip() | |
685 | if val == "''" or val == '""': val = '' |
|
697 | if val == "''" or val == '""': val = '' | |
686 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
698 | if opt['no_empty'] and (val=='' or val.isspace()): | |
687 | continue |
|
699 | continue | |
688 | # if a key is found more than once in the file, build a list |
|
700 | # if a key is found more than once in the file, build a list | |
689 | # unless it's in the 'unique' list. In that case, last found in file |
|
701 | # unless it's in the 'unique' list. In that case, last found in file | |
690 | # takes precedence. User beware. |
|
702 | # takes precedence. User beware. | |
691 | try: |
|
703 | try: | |
692 | if dict[key] and key in unique_keys: |
|
704 | if dict[key] and key in unique_keys: | |
693 | dict[key] = val |
|
705 | dict[key] = val | |
694 | elif type(dict[key]) is types.ListType: |
|
706 | elif type(dict[key]) is types.ListType: | |
695 | dict[key].append(val) |
|
707 | dict[key].append(val) | |
696 | else: |
|
708 | else: | |
697 | dict[key] = [dict[key],val] |
|
709 | dict[key] = [dict[key],val] | |
698 | except KeyError: |
|
710 | except KeyError: | |
699 | dict[key] = val |
|
711 | dict[key] = val | |
700 | # purge if requested |
|
712 | # purge if requested | |
701 | if opt['purge']: |
|
713 | if opt['purge']: | |
702 | accepted_keys = qwflat(type_conv.values()) |
|
714 | accepted_keys = qwflat(type_conv.values()) | |
703 | for key in dict.keys(): |
|
715 | for key in dict.keys(): | |
704 | if key in accepted_keys: continue |
|
716 | if key in accepted_keys: continue | |
705 | del(dict[key]) |
|
717 | del(dict[key]) | |
706 | # now convert if requested |
|
718 | # now convert if requested | |
707 | if type_conv==None: return dict |
|
719 | if type_conv==None: return dict | |
708 | conversions = type_conv.keys() |
|
720 | conversions = type_conv.keys() | |
709 | try: conversions.remove(None) |
|
721 | try: conversions.remove(None) | |
710 | except: pass |
|
722 | except: pass | |
711 | for convert in conversions: |
|
723 | for convert in conversions: | |
712 | for val in qw(type_conv[convert]): |
|
724 | for val in qw(type_conv[convert]): | |
713 | try: |
|
725 | try: | |
714 | dict[val] = convert(dict[val]) |
|
726 | dict[val] = convert(dict[val]) | |
715 | except KeyError,e: |
|
727 | except KeyError,e: | |
716 | if opt['warn'] == 0: |
|
728 | if opt['warn'] == 0: | |
717 | pass |
|
729 | pass | |
718 | elif opt['warn'] == 1: |
|
730 | elif opt['warn'] == 1: | |
719 | print >>sys.stderr, 'Warning: key',val,\ |
|
731 | print >>sys.stderr, 'Warning: key',val,\ | |
720 | 'not found in file',filename |
|
732 | 'not found in file',filename | |
721 | elif opt['warn'] == 2: |
|
733 | elif opt['warn'] == 2: | |
722 | raise KeyError,e |
|
734 | raise KeyError,e | |
723 | else: |
|
735 | else: | |
724 | raise ValueError,'Warning level must be 0,1 or 2' |
|
736 | raise ValueError,'Warning level must be 0,1 or 2' | |
725 |
|
737 | |||
726 | return dict |
|
738 | return dict | |
727 |
|
739 | |||
728 | #---------------------------------------------------------------------------- |
|
740 | #---------------------------------------------------------------------------- | |
729 | def flag_calls(func): |
|
741 | def flag_calls(func): | |
730 | """Wrap a function to detect and flag when it gets called. |
|
742 | """Wrap a function to detect and flag when it gets called. | |
731 |
|
743 | |||
732 | This is a decorator which takes a function and wraps it in a function with |
|
744 | This is a decorator which takes a function and wraps it in a function with | |
733 | a 'called' attribute. wrapper.called is initialized to False. |
|
745 | a 'called' attribute. wrapper.called is initialized to False. | |
734 |
|
746 | |||
735 | The wrapper.called attribute is set to False right before each call to the |
|
747 | The wrapper.called attribute is set to False right before each call to the | |
736 | wrapped function, so if the call fails it remains False. After the call |
|
748 | wrapped function, so if the call fails it remains False. After the call | |
737 | completes, wrapper.called is set to True and the output is returned. |
|
749 | completes, wrapper.called is set to True and the output is returned. | |
738 |
|
750 | |||
739 | Testing for truth in wrapper.called allows you to determine if a call to |
|
751 | Testing for truth in wrapper.called allows you to determine if a call to | |
740 | func() was attempted and succeeded.""" |
|
752 | func() was attempted and succeeded.""" | |
741 |
|
753 | |||
742 | def wrapper(*args,**kw): |
|
754 | def wrapper(*args,**kw): | |
743 | wrapper.called = False |
|
755 | wrapper.called = False | |
744 | out = func(*args,**kw) |
|
756 | out = func(*args,**kw) | |
745 | wrapper.called = True |
|
757 | wrapper.called = True | |
746 | return out |
|
758 | return out | |
747 |
|
759 | |||
748 | wrapper.called = False |
|
760 | wrapper.called = False | |
749 | wrapper.__doc__ = func.__doc__ |
|
761 | wrapper.__doc__ = func.__doc__ | |
750 | return wrapper |
|
762 | return wrapper | |
751 |
|
763 | |||
752 | #---------------------------------------------------------------------------- |
|
764 | #---------------------------------------------------------------------------- | |
753 | class HomeDirError(Error): |
|
765 | class HomeDirError(Error): | |
754 | pass |
|
766 | pass | |
755 |
|
767 | |||
756 | def get_home_dir(): |
|
768 | def get_home_dir(): | |
757 | """Return the closest possible equivalent to a 'home' directory. |
|
769 | """Return the closest possible equivalent to a 'home' directory. | |
758 |
|
770 | |||
759 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
771 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. | |
760 |
|
772 | |||
761 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
773 | Currently only Posix and NT are implemented, a HomeDirError exception is | |
762 | raised for all other OSes. """ |
|
774 | raised for all other OSes. """ | |
763 |
|
775 | |||
764 | isdir = os.path.isdir |
|
776 | isdir = os.path.isdir | |
765 | env = os.environ |
|
777 | env = os.environ | |
766 | try: |
|
778 | try: | |
767 | homedir = env['HOME'] |
|
779 | homedir = env['HOME'] | |
768 | if not isdir(homedir): |
|
780 | if not isdir(homedir): | |
769 | # in case a user stuck some string which does NOT resolve to a |
|
781 | # in case a user stuck some string which does NOT resolve to a | |
770 | # valid path, it's as good as if we hadn't foud it |
|
782 | # valid path, it's as good as if we hadn't foud it | |
771 | raise KeyError |
|
783 | raise KeyError | |
772 | return homedir |
|
784 | return homedir | |
773 | except KeyError: |
|
785 | except KeyError: | |
774 | if os.name == 'posix': |
|
786 | if os.name == 'posix': | |
775 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
787 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' | |
776 | elif os.name == 'nt': |
|
788 | elif os.name == 'nt': | |
777 | # For some strange reason, win9x returns 'nt' for os.name. |
|
789 | # For some strange reason, win9x returns 'nt' for os.name. | |
778 | try: |
|
790 | try: | |
779 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
791 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) | |
780 | if not isdir(homedir): |
|
792 | if not isdir(homedir): | |
781 | homedir = os.path.join(env['USERPROFILE']) |
|
793 | homedir = os.path.join(env['USERPROFILE']) | |
782 | if not isdir(homedir): |
|
794 | if not isdir(homedir): | |
783 | raise HomeDirError |
|
795 | raise HomeDirError | |
784 | return homedir |
|
796 | return homedir | |
785 | except: |
|
797 | except: | |
786 | try: |
|
798 | try: | |
787 | # Use the registry to get the 'My Documents' folder. |
|
799 | # Use the registry to get the 'My Documents' folder. | |
788 | import _winreg as wreg |
|
800 | import _winreg as wreg | |
789 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
801 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, | |
790 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
802 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") | |
791 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
803 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
792 | key.Close() |
|
804 | key.Close() | |
793 | if not isdir(homedir): |
|
805 | if not isdir(homedir): | |
794 | e = ('Invalid "Personal" folder registry key ' |
|
806 | e = ('Invalid "Personal" folder registry key ' | |
795 | 'typically "My Documents".\n' |
|
807 | 'typically "My Documents".\n' | |
796 | 'Value: %s\n' |
|
808 | 'Value: %s\n' | |
797 | 'This is not a valid directory on your system.' % |
|
809 | 'This is not a valid directory on your system.' % | |
798 | homedir) |
|
810 | homedir) | |
799 | raise HomeDirError(e) |
|
811 | raise HomeDirError(e) | |
800 | return homedir |
|
812 | return homedir | |
801 | except HomeDirError: |
|
813 | except HomeDirError: | |
802 | raise |
|
814 | raise | |
803 | except: |
|
815 | except: | |
804 | return 'C:\\' |
|
816 | return 'C:\\' | |
805 | elif os.name == 'dos': |
|
817 | elif os.name == 'dos': | |
806 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
818 | # Desperate, may do absurd things in classic MacOS. May work under DOS. | |
807 | return 'C:\\' |
|
819 | return 'C:\\' | |
808 | else: |
|
820 | else: | |
809 | raise HomeDirError,'support for your operating system not implemented.' |
|
821 | raise HomeDirError,'support for your operating system not implemented.' | |
810 |
|
822 | |||
811 | #**************************************************************************** |
|
823 | #**************************************************************************** | |
812 | # strings and text |
|
824 | # strings and text | |
813 |
|
825 | |||
814 | class LSString(str): |
|
826 | class LSString(str): | |
815 | """String derivative with a special access attributes. |
|
827 | """String derivative with a special access attributes. | |
816 |
|
828 | |||
817 | These are normal strings, but with the special attributes: |
|
829 | These are normal strings, but with the special attributes: | |
818 |
|
830 | |||
819 | .l (or .list) : value as list (split on newlines). |
|
831 | .l (or .list) : value as list (split on newlines). | |
820 | .n (or .nlstr): original value (the string itself). |
|
832 | .n (or .nlstr): original value (the string itself). | |
821 | .s (or .spstr): value as whitespace-separated string. |
|
833 | .s (or .spstr): value as whitespace-separated string. | |
822 |
|
834 | |||
823 | Any values which require transformations are computed only once and |
|
835 | Any values which require transformations are computed only once and | |
824 | cached. |
|
836 | cached. | |
825 |
|
837 | |||
826 | Such strings are very useful to efficiently interact with the shell, which |
|
838 | Such strings are very useful to efficiently interact with the shell, which | |
827 | typically only understands whitespace-separated options for commands.""" |
|
839 | typically only understands whitespace-separated options for commands.""" | |
828 |
|
840 | |||
829 | def get_list(self): |
|
841 | def get_list(self): | |
830 | try: |
|
842 | try: | |
831 | return self.__list |
|
843 | return self.__list | |
832 | except AttributeError: |
|
844 | except AttributeError: | |
833 | self.__list = self.split('\n') |
|
845 | self.__list = self.split('\n') | |
834 | return self.__list |
|
846 | return self.__list | |
835 |
|
847 | |||
836 | l = list = property(get_list) |
|
848 | l = list = property(get_list) | |
837 |
|
849 | |||
838 | def get_spstr(self): |
|
850 | def get_spstr(self): | |
839 | try: |
|
851 | try: | |
840 | return self.__spstr |
|
852 | return self.__spstr | |
841 | except AttributeError: |
|
853 | except AttributeError: | |
842 | self.__spstr = self.replace('\n',' ') |
|
854 | self.__spstr = self.replace('\n',' ') | |
843 | return self.__spstr |
|
855 | return self.__spstr | |
844 |
|
856 | |||
845 | s = spstr = property(get_spstr) |
|
857 | s = spstr = property(get_spstr) | |
846 |
|
858 | |||
847 | def get_nlstr(self): |
|
859 | def get_nlstr(self): | |
848 | return self |
|
860 | return self | |
849 |
|
861 | |||
850 | n = nlstr = property(get_nlstr) |
|
862 | n = nlstr = property(get_nlstr) | |
851 |
|
863 | |||
852 | def get_paths(self): |
|
864 | def get_paths(self): | |
853 | try: |
|
865 | try: | |
854 | return self.__paths |
|
866 | return self.__paths | |
855 | except AttributeError: |
|
867 | except AttributeError: | |
856 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
868 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] | |
857 | return self.__paths |
|
869 | return self.__paths | |
858 |
|
870 | |||
859 | p = paths = property(get_paths) |
|
871 | p = paths = property(get_paths) | |
860 |
|
872 | |||
861 |
|
873 | |||
862 | #---------------------------------------------------------------------------- |
|
874 | #---------------------------------------------------------------------------- | |
863 | class SList(list): |
|
875 | class SList(list): | |
864 | """List derivative with a special access attributes. |
|
876 | """List derivative with a special access attributes. | |
865 |
|
877 | |||
866 | These are normal lists, but with the special attributes: |
|
878 | These are normal lists, but with the special attributes: | |
867 |
|
879 | |||
868 | .l (or .list) : value as list (the list itself). |
|
880 | .l (or .list) : value as list (the list itself). | |
869 | .n (or .nlstr): value as a string, joined on newlines. |
|
881 | .n (or .nlstr): value as a string, joined on newlines. | |
870 | .s (or .spstr): value as a string, joined on spaces. |
|
882 | .s (or .spstr): value as a string, joined on spaces. | |
871 |
|
883 | |||
872 | Any values which require transformations are computed only once and |
|
884 | Any values which require transformations are computed only once and | |
873 | cached.""" |
|
885 | cached.""" | |
874 |
|
886 | |||
875 | def get_list(self): |
|
887 | def get_list(self): | |
876 | return self |
|
888 | return self | |
877 |
|
889 | |||
878 | l = list = property(get_list) |
|
890 | l = list = property(get_list) | |
879 |
|
891 | |||
880 | def get_spstr(self): |
|
892 | def get_spstr(self): | |
881 | try: |
|
893 | try: | |
882 | return self.__spstr |
|
894 | return self.__spstr | |
883 | except AttributeError: |
|
895 | except AttributeError: | |
884 | self.__spstr = ' '.join(self) |
|
896 | self.__spstr = ' '.join(self) | |
885 | return self.__spstr |
|
897 | return self.__spstr | |
886 |
|
898 | |||
887 | s = spstr = property(get_spstr) |
|
899 | s = spstr = property(get_spstr) | |
888 |
|
900 | |||
889 | def get_nlstr(self): |
|
901 | def get_nlstr(self): | |
890 | try: |
|
902 | try: | |
891 | return self.__nlstr |
|
903 | return self.__nlstr | |
892 | except AttributeError: |
|
904 | except AttributeError: | |
893 | self.__nlstr = '\n'.join(self) |
|
905 | self.__nlstr = '\n'.join(self) | |
894 | return self.__nlstr |
|
906 | return self.__nlstr | |
895 |
|
907 | |||
896 | n = nlstr = property(get_nlstr) |
|
908 | n = nlstr = property(get_nlstr) | |
897 |
|
909 | |||
898 | def get_paths(self): |
|
910 | def get_paths(self): | |
899 | try: |
|
911 | try: | |
900 | return self.__paths |
|
912 | return self.__paths | |
901 | except AttributeError: |
|
913 | except AttributeError: | |
902 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
914 | self.__paths = [path(p) for p in self if os.path.exists(p)] | |
903 | return self.__paths |
|
915 | return self.__paths | |
904 |
|
916 | |||
905 | p = paths = property(get_paths) |
|
917 | p = paths = property(get_paths) | |
906 |
|
918 | |||
907 | #---------------------------------------------------------------------------- |
|
919 | #---------------------------------------------------------------------------- | |
908 | def esc_quotes(strng): |
|
920 | def esc_quotes(strng): | |
909 | """Return the input string with single and double quotes escaped out""" |
|
921 | """Return the input string with single and double quotes escaped out""" | |
910 |
|
922 | |||
911 | return strng.replace('"','\\"').replace("'","\\'") |
|
923 | return strng.replace('"','\\"').replace("'","\\'") | |
912 |
|
924 | |||
913 | #---------------------------------------------------------------------------- |
|
925 | #---------------------------------------------------------------------------- | |
914 | def make_quoted_expr(s): |
|
926 | def make_quoted_expr(s): | |
915 | """Return string s in appropriate quotes, using raw string if possible. |
|
927 | """Return string s in appropriate quotes, using raw string if possible. | |
916 |
|
928 | |||
917 | Effectively this turns string: cd \ao\ao\ |
|
929 | Effectively this turns string: cd \ao\ao\ | |
918 | to: r"cd \ao\ao\_"[:-1] |
|
930 | to: r"cd \ao\ao\_"[:-1] | |
919 |
|
931 | |||
920 | Note the use of raw string and padding at the end to allow trailing backslash. |
|
932 | Note the use of raw string and padding at the end to allow trailing backslash. | |
921 |
|
933 | |||
922 | """ |
|
934 | """ | |
923 |
|
935 | |||
924 | tail = '' |
|
936 | tail = '' | |
925 | tailpadding = '' |
|
937 | tailpadding = '' | |
926 | raw = '' |
|
938 | raw = '' | |
927 | if "\\" in s: |
|
939 | if "\\" in s: | |
928 | raw = 'r' |
|
940 | raw = 'r' | |
929 | if s.endswith('\\'): |
|
941 | if s.endswith('\\'): | |
930 | tail = '[:-1]' |
|
942 | tail = '[:-1]' | |
931 | tailpadding = '_' |
|
943 | tailpadding = '_' | |
932 | if '"' not in s: |
|
944 | if '"' not in s: | |
933 | quote = '"' |
|
945 | quote = '"' | |
934 | elif "'" not in s: |
|
946 | elif "'" not in s: | |
935 | quote = "'" |
|
947 | quote = "'" | |
936 | elif '"""' not in s and not s.endswith('"'): |
|
948 | elif '"""' not in s and not s.endswith('"'): | |
937 | quote = '"""' |
|
949 | quote = '"""' | |
938 | elif "'''" not in s and not s.endswith("'"): |
|
950 | elif "'''" not in s and not s.endswith("'"): | |
939 | quote = "'''" |
|
951 | quote = "'''" | |
940 | else: |
|
952 | else: | |
941 | # give up, backslash-escaped string will do |
|
953 | # give up, backslash-escaped string will do | |
942 | return '"%s"' % esc_quotes(s) |
|
954 | return '"%s"' % esc_quotes(s) | |
943 | res = itpl("$raw$quote$s$tailpadding$quote$tail") |
|
955 | res = itpl("$raw$quote$s$tailpadding$quote$tail") | |
944 | return res |
|
956 | return res | |
945 |
|
957 | |||
946 |
|
958 | |||
947 | #---------------------------------------------------------------------------- |
|
959 | #---------------------------------------------------------------------------- | |
948 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
960 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): | |
949 | """Take multiple lines of input. |
|
961 | """Take multiple lines of input. | |
950 |
|
962 | |||
951 | A list with each line of input as a separate element is returned when a |
|
963 | A list with each line of input as a separate element is returned when a | |
952 | termination string is entered (defaults to a single '.'). Input can also |
|
964 | termination string is entered (defaults to a single '.'). Input can also | |
953 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
965 | terminate via EOF (^D in Unix, ^Z-RET in Windows). | |
954 |
|
966 | |||
955 | Lines of input which end in \\ are joined into single entries (and a |
|
967 | Lines of input which end in \\ are joined into single entries (and a | |
956 | secondary continuation prompt is issued as long as the user terminates |
|
968 | secondary continuation prompt is issued as long as the user terminates | |
957 | lines with \\). This allows entering very long strings which are still |
|
969 | lines with \\). This allows entering very long strings which are still | |
958 | meant to be treated as single entities. |
|
970 | meant to be treated as single entities. | |
959 | """ |
|
971 | """ | |
960 |
|
972 | |||
961 | try: |
|
973 | try: | |
962 | if header: |
|
974 | if header: | |
963 | header += '\n' |
|
975 | header += '\n' | |
964 | lines = [raw_input(header + ps1)] |
|
976 | lines = [raw_input(header + ps1)] | |
965 | except EOFError: |
|
977 | except EOFError: | |
966 | return [] |
|
978 | return [] | |
967 | terminate = [terminate_str] |
|
979 | terminate = [terminate_str] | |
968 | try: |
|
980 | try: | |
969 | while lines[-1:] != terminate: |
|
981 | while lines[-1:] != terminate: | |
970 | new_line = raw_input(ps1) |
|
982 | new_line = raw_input(ps1) | |
971 | while new_line.endswith('\\'): |
|
983 | while new_line.endswith('\\'): | |
972 | new_line = new_line[:-1] + raw_input(ps2) |
|
984 | new_line = new_line[:-1] + raw_input(ps2) | |
973 | lines.append(new_line) |
|
985 | lines.append(new_line) | |
974 |
|
986 | |||
975 | return lines[:-1] # don't return the termination command |
|
987 | return lines[:-1] # don't return the termination command | |
976 | except EOFError: |
|
988 | except EOFError: | |
977 |
|
989 | |||
978 | return lines |
|
990 | return lines | |
979 |
|
991 | |||
980 | #---------------------------------------------------------------------------- |
|
992 | #---------------------------------------------------------------------------- | |
981 | def raw_input_ext(prompt='', ps2='... '): |
|
993 | def raw_input_ext(prompt='', ps2='... '): | |
982 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
994 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" | |
983 |
|
995 | |||
984 | line = raw_input(prompt) |
|
996 | line = raw_input(prompt) | |
985 | while line.endswith('\\'): |
|
997 | while line.endswith('\\'): | |
986 | line = line[:-1] + raw_input(ps2) |
|
998 | line = line[:-1] + raw_input(ps2) | |
987 | return line |
|
999 | return line | |
988 |
|
1000 | |||
989 | #---------------------------------------------------------------------------- |
|
1001 | #---------------------------------------------------------------------------- | |
990 | def ask_yes_no(prompt,default=None): |
|
1002 | def ask_yes_no(prompt,default=None): | |
991 | """Asks a question and returns an integer 1/0 (y/n) answer. |
|
1003 | """Asks a question and returns an integer 1/0 (y/n) answer. | |
992 |
|
1004 | |||
993 | If default is given (one of 'y','n'), it is used if the user input is |
|
1005 | If default is given (one of 'y','n'), it is used if the user input is | |
994 | empty. Otherwise the question is repeated until an answer is given. |
|
1006 | empty. Otherwise the question is repeated until an answer is given. | |
995 |
|
1007 | |||
996 | An EOF is treated as the default answer. If there is no default, an |
|
1008 | An EOF is treated as the default answer. If there is no default, an | |
997 | exception is raised to prevent infinite loops. |
|
1009 | exception is raised to prevent infinite loops. | |
998 |
|
1010 | |||
999 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
1011 | Valid answers are: y/yes/n/no (match is not case sensitive).""" | |
1000 |
|
1012 | |||
1001 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
1013 | answers = {'y':True,'n':False,'yes':True,'no':False} | |
1002 | ans = None |
|
1014 | ans = None | |
1003 | while ans not in answers.keys(): |
|
1015 | while ans not in answers.keys(): | |
1004 | try: |
|
1016 | try: | |
1005 | ans = raw_input(prompt+' ').lower() |
|
1017 | ans = raw_input(prompt+' ').lower() | |
1006 | if not ans: # response was an empty string |
|
1018 | if not ans: # response was an empty string | |
1007 | ans = default |
|
1019 | ans = default | |
1008 | except KeyboardInterrupt: |
|
1020 | except KeyboardInterrupt: | |
1009 | pass |
|
1021 | pass | |
1010 | except EOFError: |
|
1022 | except EOFError: | |
1011 | if default in answers.keys(): |
|
1023 | if default in answers.keys(): | |
1012 | ans = default |
|
1024 | ans = default | |
1013 |
|
1025 | |||
1014 | else: |
|
1026 | else: | |
1015 | raise |
|
1027 | raise | |
1016 |
|
1028 | |||
1017 | return answers[ans] |
|
1029 | return answers[ans] | |
1018 |
|
1030 | |||
1019 | #---------------------------------------------------------------------------- |
|
1031 | #---------------------------------------------------------------------------- | |
1020 | def marquee(txt='',width=78,mark='*'): |
|
1032 | def marquee(txt='',width=78,mark='*'): | |
1021 | """Return the input string centered in a 'marquee'.""" |
|
1033 | """Return the input string centered in a 'marquee'.""" | |
1022 | if not txt: |
|
1034 | if not txt: | |
1023 | return (mark*width)[:width] |
|
1035 | return (mark*width)[:width] | |
1024 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
1036 | nmark = (width-len(txt)-2)/len(mark)/2 | |
1025 | if nmark < 0: nmark =0 |
|
1037 | if nmark < 0: nmark =0 | |
1026 | marks = mark*nmark |
|
1038 | marks = mark*nmark | |
1027 | return '%s %s %s' % (marks,txt,marks) |
|
1039 | return '%s %s %s' % (marks,txt,marks) | |
1028 |
|
1040 | |||
1029 | #---------------------------------------------------------------------------- |
|
1041 | #---------------------------------------------------------------------------- | |
1030 | class EvalDict: |
|
1042 | class EvalDict: | |
1031 | """ |
|
1043 | """ | |
1032 | Emulate a dict which evaluates its contents in the caller's frame. |
|
1044 | Emulate a dict which evaluates its contents in the caller's frame. | |
1033 |
|
1045 | |||
1034 | Usage: |
|
1046 | Usage: | |
1035 | >>>number = 19 |
|
1047 | >>>number = 19 | |
1036 | >>>text = "python" |
|
1048 | >>>text = "python" | |
1037 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
1049 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() | |
1038 | """ |
|
1050 | """ | |
1039 |
|
1051 | |||
1040 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
1052 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a | |
1041 | # modified (shorter) version of: |
|
1053 | # modified (shorter) version of: | |
1042 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
1054 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by | |
1043 | # Skip Montanaro (skip@pobox.com). |
|
1055 | # Skip Montanaro (skip@pobox.com). | |
1044 |
|
1056 | |||
1045 | def __getitem__(self, name): |
|
1057 | def __getitem__(self, name): | |
1046 | frame = sys._getframe(1) |
|
1058 | frame = sys._getframe(1) | |
1047 | return eval(name, frame.f_globals, frame.f_locals) |
|
1059 | return eval(name, frame.f_globals, frame.f_locals) | |
1048 |
|
1060 | |||
1049 | EvalString = EvalDict # for backwards compatibility |
|
1061 | EvalString = EvalDict # for backwards compatibility | |
1050 | #---------------------------------------------------------------------------- |
|
1062 | #---------------------------------------------------------------------------- | |
1051 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
1063 | def qw(words,flat=0,sep=None,maxsplit=-1): | |
1052 | """Similar to Perl's qw() operator, but with some more options. |
|
1064 | """Similar to Perl's qw() operator, but with some more options. | |
1053 |
|
1065 | |||
1054 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
1066 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) | |
1055 |
|
1067 | |||
1056 | words can also be a list itself, and with flat=1, the output will be |
|
1068 | words can also be a list itself, and with flat=1, the output will be | |
1057 | recursively flattened. Examples: |
|
1069 | recursively flattened. Examples: | |
1058 |
|
1070 | |||
1059 | >>> qw('1 2') |
|
1071 | >>> qw('1 2') | |
1060 | ['1', '2'] |
|
1072 | ['1', '2'] | |
1061 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1073 | >>> qw(['a b','1 2',['m n','p q']]) | |
1062 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1074 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] | |
1063 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1075 | >>> qw(['a b','1 2',['m n','p q']],flat=1) | |
1064 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ |
|
1076 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ | |
1065 |
|
1077 | |||
1066 | if type(words) in StringTypes: |
|
1078 | if type(words) in StringTypes: | |
1067 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1079 | return [word.strip() for word in words.split(sep,maxsplit) | |
1068 | if word and not word.isspace() ] |
|
1080 | if word and not word.isspace() ] | |
1069 | if flat: |
|
1081 | if flat: | |
1070 | return flatten(map(qw,words,[1]*len(words))) |
|
1082 | return flatten(map(qw,words,[1]*len(words))) | |
1071 | return map(qw,words) |
|
1083 | return map(qw,words) | |
1072 |
|
1084 | |||
1073 | #---------------------------------------------------------------------------- |
|
1085 | #---------------------------------------------------------------------------- | |
1074 | def qwflat(words,sep=None,maxsplit=-1): |
|
1086 | def qwflat(words,sep=None,maxsplit=-1): | |
1075 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1087 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" | |
1076 | return qw(words,1,sep,maxsplit) |
|
1088 | return qw(words,1,sep,maxsplit) | |
1077 |
|
1089 | |||
1078 | #---------------------------------------------------------------------------- |
|
1090 | #---------------------------------------------------------------------------- | |
1079 | def qw_lol(indata): |
|
1091 | def qw_lol(indata): | |
1080 | """qw_lol('a b') -> [['a','b']], |
|
1092 | """qw_lol('a b') -> [['a','b']], | |
1081 | otherwise it's just a call to qw(). |
|
1093 | otherwise it's just a call to qw(). | |
1082 |
|
1094 | |||
1083 | We need this to make sure the modules_some keys *always* end up as a |
|
1095 | We need this to make sure the modules_some keys *always* end up as a | |
1084 | list of lists.""" |
|
1096 | list of lists.""" | |
1085 |
|
1097 | |||
1086 | if type(indata) in StringTypes: |
|
1098 | if type(indata) in StringTypes: | |
1087 | return [qw(indata)] |
|
1099 | return [qw(indata)] | |
1088 | else: |
|
1100 | else: | |
1089 | return qw(indata) |
|
1101 | return qw(indata) | |
1090 |
|
1102 | |||
1091 | #----------------------------------------------------------------------------- |
|
1103 | #----------------------------------------------------------------------------- | |
1092 | def list_strings(arg): |
|
1104 | def list_strings(arg): | |
1093 | """Always return a list of strings, given a string or list of strings |
|
1105 | """Always return a list of strings, given a string or list of strings | |
1094 | as input.""" |
|
1106 | as input.""" | |
1095 |
|
1107 | |||
1096 | if type(arg) in StringTypes: return [arg] |
|
1108 | if type(arg) in StringTypes: return [arg] | |
1097 | else: return arg |
|
1109 | else: return arg | |
1098 |
|
1110 | |||
1099 | #---------------------------------------------------------------------------- |
|
1111 | #---------------------------------------------------------------------------- | |
1100 | def grep(pat,list,case=1): |
|
1112 | def grep(pat,list,case=1): | |
1101 | """Simple minded grep-like function. |
|
1113 | """Simple minded grep-like function. | |
1102 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1114 | grep(pat,list) returns occurrences of pat in list, None on failure. | |
1103 |
|
1115 | |||
1104 | It only does simple string matching, with no support for regexps. Use the |
|
1116 | It only does simple string matching, with no support for regexps. Use the | |
1105 | option case=0 for case-insensitive matching.""" |
|
1117 | option case=0 for case-insensitive matching.""" | |
1106 |
|
1118 | |||
1107 | # This is pretty crude. At least it should implement copying only references |
|
1119 | # This is pretty crude. At least it should implement copying only references | |
1108 | # to the original data in case it's big. Now it copies the data for output. |
|
1120 | # to the original data in case it's big. Now it copies the data for output. | |
1109 | out=[] |
|
1121 | out=[] | |
1110 | if case: |
|
1122 | if case: | |
1111 | for term in list: |
|
1123 | for term in list: | |
1112 | if term.find(pat)>-1: out.append(term) |
|
1124 | if term.find(pat)>-1: out.append(term) | |
1113 | else: |
|
1125 | else: | |
1114 | lpat=pat.lower() |
|
1126 | lpat=pat.lower() | |
1115 | for term in list: |
|
1127 | for term in list: | |
1116 | if term.lower().find(lpat)>-1: out.append(term) |
|
1128 | if term.lower().find(lpat)>-1: out.append(term) | |
1117 |
|
1129 | |||
1118 | if len(out): return out |
|
1130 | if len(out): return out | |
1119 | else: return None |
|
1131 | else: return None | |
1120 |
|
1132 | |||
1121 | #---------------------------------------------------------------------------- |
|
1133 | #---------------------------------------------------------------------------- | |
1122 | def dgrep(pat,*opts): |
|
1134 | def dgrep(pat,*opts): | |
1123 | """Return grep() on dir()+dir(__builtins__). |
|
1135 | """Return grep() on dir()+dir(__builtins__). | |
1124 |
|
1136 | |||
1125 | A very common use of grep() when working interactively.""" |
|
1137 | A very common use of grep() when working interactively.""" | |
1126 |
|
1138 | |||
1127 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1139 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) | |
1128 |
|
1140 | |||
1129 | #---------------------------------------------------------------------------- |
|
1141 | #---------------------------------------------------------------------------- | |
1130 | def idgrep(pat): |
|
1142 | def idgrep(pat): | |
1131 | """Case-insensitive dgrep()""" |
|
1143 | """Case-insensitive dgrep()""" | |
1132 |
|
1144 | |||
1133 | return dgrep(pat,0) |
|
1145 | return dgrep(pat,0) | |
1134 |
|
1146 | |||
1135 | #---------------------------------------------------------------------------- |
|
1147 | #---------------------------------------------------------------------------- | |
1136 | def igrep(pat,list): |
|
1148 | def igrep(pat,list): | |
1137 | """Synonym for case-insensitive grep.""" |
|
1149 | """Synonym for case-insensitive grep.""" | |
1138 |
|
1150 | |||
1139 | return grep(pat,list,case=0) |
|
1151 | return grep(pat,list,case=0) | |
1140 |
|
1152 | |||
1141 | #---------------------------------------------------------------------------- |
|
1153 | #---------------------------------------------------------------------------- | |
1142 | def indent(str,nspaces=4,ntabs=0): |
|
1154 | def indent(str,nspaces=4,ntabs=0): | |
1143 | """Indent a string a given number of spaces or tabstops. |
|
1155 | """Indent a string a given number of spaces or tabstops. | |
1144 |
|
1156 | |||
1145 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1157 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. | |
1146 | """ |
|
1158 | """ | |
1147 | if str is None: |
|
1159 | if str is None: | |
1148 | return |
|
1160 | return | |
1149 | ind = '\t'*ntabs+' '*nspaces |
|
1161 | ind = '\t'*ntabs+' '*nspaces | |
1150 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1162 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) | |
1151 | if outstr.endswith(os.linesep+ind): |
|
1163 | if outstr.endswith(os.linesep+ind): | |
1152 | return outstr[:-len(ind)] |
|
1164 | return outstr[:-len(ind)] | |
1153 | else: |
|
1165 | else: | |
1154 | return outstr |
|
1166 | return outstr | |
1155 |
|
1167 | |||
1156 | #----------------------------------------------------------------------------- |
|
1168 | #----------------------------------------------------------------------------- | |
1157 | def native_line_ends(filename,backup=1): |
|
1169 | def native_line_ends(filename,backup=1): | |
1158 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1170 | """Convert (in-place) a file to line-ends native to the current OS. | |
1159 |
|
1171 | |||
1160 | If the optional backup argument is given as false, no backup of the |
|
1172 | If the optional backup argument is given as false, no backup of the | |
1161 | original file is left. """ |
|
1173 | original file is left. """ | |
1162 |
|
1174 | |||
1163 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1175 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} | |
1164 |
|
1176 | |||
1165 | bak_filename = filename + backup_suffixes[os.name] |
|
1177 | bak_filename = filename + backup_suffixes[os.name] | |
1166 |
|
1178 | |||
1167 | original = open(filename).read() |
|
1179 | original = open(filename).read() | |
1168 | shutil.copy2(filename,bak_filename) |
|
1180 | shutil.copy2(filename,bak_filename) | |
1169 | try: |
|
1181 | try: | |
1170 | new = open(filename,'wb') |
|
1182 | new = open(filename,'wb') | |
1171 | new.write(os.linesep.join(original.splitlines())) |
|
1183 | new.write(os.linesep.join(original.splitlines())) | |
1172 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1184 | new.write(os.linesep) # ALWAYS put an eol at the end of the file | |
1173 | new.close() |
|
1185 | new.close() | |
1174 | except: |
|
1186 | except: | |
1175 | os.rename(bak_filename,filename) |
|
1187 | os.rename(bak_filename,filename) | |
1176 | if not backup: |
|
1188 | if not backup: | |
1177 | try: |
|
1189 | try: | |
1178 | os.remove(bak_filename) |
|
1190 | os.remove(bak_filename) | |
1179 | except: |
|
1191 | except: | |
1180 | pass |
|
1192 | pass | |
1181 |
|
1193 | |||
1182 | #---------------------------------------------------------------------------- |
|
1194 | #---------------------------------------------------------------------------- | |
1183 | def get_pager_cmd(pager_cmd = None): |
|
1195 | def get_pager_cmd(pager_cmd = None): | |
1184 | """Return a pager command. |
|
1196 | """Return a pager command. | |
1185 |
|
1197 | |||
1186 | Makes some attempts at finding an OS-correct one.""" |
|
1198 | Makes some attempts at finding an OS-correct one.""" | |
1187 |
|
1199 | |||
1188 | if os.name == 'posix': |
|
1200 | if os.name == 'posix': | |
1189 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1201 | default_pager_cmd = 'less -r' # -r for color control sequences | |
1190 | elif os.name in ['nt','dos']: |
|
1202 | elif os.name in ['nt','dos']: | |
1191 | default_pager_cmd = 'type' |
|
1203 | default_pager_cmd = 'type' | |
1192 |
|
1204 | |||
1193 | if pager_cmd is None: |
|
1205 | if pager_cmd is None: | |
1194 | try: |
|
1206 | try: | |
1195 | pager_cmd = os.environ['PAGER'] |
|
1207 | pager_cmd = os.environ['PAGER'] | |
1196 | except: |
|
1208 | except: | |
1197 | pager_cmd = default_pager_cmd |
|
1209 | pager_cmd = default_pager_cmd | |
1198 | return pager_cmd |
|
1210 | return pager_cmd | |
1199 |
|
1211 | |||
1200 | #----------------------------------------------------------------------------- |
|
1212 | #----------------------------------------------------------------------------- | |
1201 | def get_pager_start(pager,start): |
|
1213 | def get_pager_start(pager,start): | |
1202 | """Return the string for paging files with an offset. |
|
1214 | """Return the string for paging files with an offset. | |
1203 |
|
1215 | |||
1204 | This is the '+N' argument which less and more (under Unix) accept. |
|
1216 | This is the '+N' argument which less and more (under Unix) accept. | |
1205 | """ |
|
1217 | """ | |
1206 |
|
1218 | |||
1207 | if pager in ['less','more']: |
|
1219 | if pager in ['less','more']: | |
1208 | if start: |
|
1220 | if start: | |
1209 | start_string = '+' + str(start) |
|
1221 | start_string = '+' + str(start) | |
1210 | else: |
|
1222 | else: | |
1211 | start_string = '' |
|
1223 | start_string = '' | |
1212 | else: |
|
1224 | else: | |
1213 | start_string = '' |
|
1225 | start_string = '' | |
1214 | return start_string |
|
1226 | return start_string | |
1215 |
|
1227 | |||
1216 | #---------------------------------------------------------------------------- |
|
1228 | #---------------------------------------------------------------------------- | |
1217 | if os.name == "nt": |
|
1229 | if os.name == "nt": | |
1218 | import msvcrt |
|
1230 | import msvcrt | |
1219 | def page_more(): |
|
1231 | def page_more(): | |
1220 | """ Smart pausing between pages |
|
1232 | """ Smart pausing between pages | |
1221 |
|
1233 | |||
1222 | @return: True if need print more lines, False if quit |
|
1234 | @return: True if need print more lines, False if quit | |
1223 | """ |
|
1235 | """ | |
1224 | Term.cout.write('---Return to continue, q to quit--- ') |
|
1236 | Term.cout.write('---Return to continue, q to quit--- ') | |
1225 | ans = msvcrt.getch() |
|
1237 | ans = msvcrt.getch() | |
1226 | if ans in ("q", "Q"): |
|
1238 | if ans in ("q", "Q"): | |
1227 | result = False |
|
1239 | result = False | |
1228 | else: |
|
1240 | else: | |
1229 | result = True |
|
1241 | result = True | |
1230 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) |
|
1242 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) | |
1231 | return result |
|
1243 | return result | |
1232 | else: |
|
1244 | else: | |
1233 | def page_more(): |
|
1245 | def page_more(): | |
1234 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1246 | ans = raw_input('---Return to continue, q to quit--- ') | |
1235 | if ans.lower().startswith('q'): |
|
1247 | if ans.lower().startswith('q'): | |
1236 | return False |
|
1248 | return False | |
1237 | else: |
|
1249 | else: | |
1238 | return True |
|
1250 | return True | |
1239 |
|
1251 | |||
1240 | esc_re = re.compile(r"(\x1b[^m]+m)") |
|
1252 | esc_re = re.compile(r"(\x1b[^m]+m)") | |
1241 |
|
1253 | |||
1242 | def page_dumb(strng,start=0,screen_lines=25): |
|
1254 | def page_dumb(strng,start=0,screen_lines=25): | |
1243 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1255 | """Very dumb 'pager' in Python, for when nothing else works. | |
1244 |
|
1256 | |||
1245 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1257 | Only moves forward, same interface as page(), except for pager_cmd and | |
1246 | mode.""" |
|
1258 | mode.""" | |
1247 |
|
1259 | |||
1248 | out_ln = strng.splitlines()[start:] |
|
1260 | out_ln = strng.splitlines()[start:] | |
1249 | screens = chop(out_ln,screen_lines-1) |
|
1261 | screens = chop(out_ln,screen_lines-1) | |
1250 | if len(screens) == 1: |
|
1262 | if len(screens) == 1: | |
1251 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1263 | print >>Term.cout, os.linesep.join(screens[0]) | |
1252 | else: |
|
1264 | else: | |
1253 | last_escape = "" |
|
1265 | last_escape = "" | |
1254 | for scr in screens[0:-1]: |
|
1266 | for scr in screens[0:-1]: | |
1255 | hunk = os.linesep.join(scr) |
|
1267 | hunk = os.linesep.join(scr) | |
1256 | print >>Term.cout, last_escape + hunk |
|
1268 | print >>Term.cout, last_escape + hunk | |
1257 | if not page_more(): |
|
1269 | if not page_more(): | |
1258 | return |
|
1270 | return | |
1259 | esc_list = esc_re.findall(hunk) |
|
1271 | esc_list = esc_re.findall(hunk) | |
1260 | if len(esc_list) > 0: |
|
1272 | if len(esc_list) > 0: | |
1261 | last_escape = esc_list[-1] |
|
1273 | last_escape = esc_list[-1] | |
1262 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) |
|
1274 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) | |
1263 |
|
1275 | |||
1264 | #---------------------------------------------------------------------------- |
|
1276 | #---------------------------------------------------------------------------- | |
1265 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1277 | def page(strng,start=0,screen_lines=0,pager_cmd = None): | |
1266 | """Print a string, piping through a pager after a certain length. |
|
1278 | """Print a string, piping through a pager after a certain length. | |
1267 |
|
1279 | |||
1268 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1280 | The screen_lines parameter specifies the number of *usable* lines of your | |
1269 | terminal screen (total lines minus lines you need to reserve to show other |
|
1281 | terminal screen (total lines minus lines you need to reserve to show other | |
1270 | information). |
|
1282 | information). | |
1271 |
|
1283 | |||
1272 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1284 | If you set screen_lines to a number <=0, page() will try to auto-determine | |
1273 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1285 | your screen size and will only use up to (screen_size+screen_lines) for | |
1274 | printing, paging after that. That is, if you want auto-detection but need |
|
1286 | printing, paging after that. That is, if you want auto-detection but need | |
1275 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1287 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for | |
1276 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1288 | auto-detection without any lines reserved simply use screen_lines = 0. | |
1277 |
|
1289 | |||
1278 | If a string won't fit in the allowed lines, it is sent through the |
|
1290 | If a string won't fit in the allowed lines, it is sent through the | |
1279 | specified pager command. If none given, look for PAGER in the environment, |
|
1291 | specified pager command. If none given, look for PAGER in the environment, | |
1280 | and ultimately default to less. |
|
1292 | and ultimately default to less. | |
1281 |
|
1293 | |||
1282 | If no system pager works, the string is sent through a 'dumb pager' |
|
1294 | If no system pager works, the string is sent through a 'dumb pager' | |
1283 | written in python, very simplistic. |
|
1295 | written in python, very simplistic. | |
1284 | """ |
|
1296 | """ | |
1285 |
|
1297 | |||
1286 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1298 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs | |
1287 | TERM = os.environ.get('TERM','dumb') |
|
1299 | TERM = os.environ.get('TERM','dumb') | |
1288 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1300 | if TERM in ['dumb','emacs'] and os.name != 'nt': | |
1289 | print strng |
|
1301 | print strng | |
1290 | return |
|
1302 | return | |
1291 | # chop off the topmost part of the string we don't want to see |
|
1303 | # chop off the topmost part of the string we don't want to see | |
1292 | str_lines = strng.split(os.linesep)[start:] |
|
1304 | str_lines = strng.split(os.linesep)[start:] | |
1293 | str_toprint = os.linesep.join(str_lines) |
|
1305 | str_toprint = os.linesep.join(str_lines) | |
1294 | num_newlines = len(str_lines) |
|
1306 | num_newlines = len(str_lines) | |
1295 | len_str = len(str_toprint) |
|
1307 | len_str = len(str_toprint) | |
1296 |
|
1308 | |||
1297 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1309 | # Dumb heuristics to guesstimate number of on-screen lines the string | |
1298 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1310 | # takes. Very basic, but good enough for docstrings in reasonable | |
1299 | # terminals. If someone later feels like refining it, it's not hard. |
|
1311 | # terminals. If someone later feels like refining it, it's not hard. | |
1300 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1312 | numlines = max(num_newlines,int(len_str/80)+1) | |
1301 |
|
1313 | |||
1302 | if os.name == "nt": |
|
1314 | if os.name == "nt": | |
1303 | screen_lines_def = get_console_size(defaulty=25)[1] |
|
1315 | screen_lines_def = get_console_size(defaulty=25)[1] | |
1304 | else: |
|
1316 | else: | |
1305 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1317 | screen_lines_def = 25 # default value if we can't auto-determine | |
1306 |
|
1318 | |||
1307 | # auto-determine screen size |
|
1319 | # auto-determine screen size | |
1308 | if screen_lines <= 0: |
|
1320 | if screen_lines <= 0: | |
1309 | if TERM=='xterm': |
|
1321 | if TERM=='xterm': | |
1310 | try: |
|
1322 | try: | |
1311 | import curses |
|
1323 | import curses | |
1312 | if hasattr(curses,'initscr'): |
|
1324 | if hasattr(curses,'initscr'): | |
1313 | use_curses = 1 |
|
1325 | use_curses = 1 | |
1314 | else: |
|
1326 | else: | |
1315 | use_curses = 0 |
|
1327 | use_curses = 0 | |
1316 | except ImportError: |
|
1328 | except ImportError: | |
1317 | use_curses = 0 |
|
1329 | use_curses = 0 | |
1318 | else: |
|
1330 | else: | |
1319 | # curses causes problems on many terminals other than xterm. |
|
1331 | # curses causes problems on many terminals other than xterm. | |
1320 | use_curses = 0 |
|
1332 | use_curses = 0 | |
1321 | if use_curses: |
|
1333 | if use_curses: | |
1322 | scr = curses.initscr() |
|
1334 | scr = curses.initscr() | |
1323 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1335 | screen_lines_real,screen_cols = scr.getmaxyx() | |
1324 | curses.endwin() |
|
1336 | curses.endwin() | |
1325 | screen_lines += screen_lines_real |
|
1337 | screen_lines += screen_lines_real | |
1326 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1338 | #print '***Screen size:',screen_lines_real,'lines x',\ | |
1327 | #screen_cols,'columns.' # dbg |
|
1339 | #screen_cols,'columns.' # dbg | |
1328 | else: |
|
1340 | else: | |
1329 | screen_lines += screen_lines_def |
|
1341 | screen_lines += screen_lines_def | |
1330 |
|
1342 | |||
1331 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1343 | #print 'numlines',numlines,'screenlines',screen_lines # dbg | |
1332 | if numlines <= screen_lines : |
|
1344 | if numlines <= screen_lines : | |
1333 | #print '*** normal print' # dbg |
|
1345 | #print '*** normal print' # dbg | |
1334 | print >>Term.cout, str_toprint |
|
1346 | print >>Term.cout, str_toprint | |
1335 | else: |
|
1347 | else: | |
1336 | # Try to open pager and default to internal one if that fails. |
|
1348 | # Try to open pager and default to internal one if that fails. | |
1337 | # All failure modes are tagged as 'retval=1', to match the return |
|
1349 | # All failure modes are tagged as 'retval=1', to match the return | |
1338 | # value of a failed system command. If any intermediate attempt |
|
1350 | # value of a failed system command. If any intermediate attempt | |
1339 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1351 | # sets retval to 1, at the end we resort to our own page_dumb() pager. | |
1340 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1352 | pager_cmd = get_pager_cmd(pager_cmd) | |
1341 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1353 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1342 | if os.name == 'nt': |
|
1354 | if os.name == 'nt': | |
1343 | if pager_cmd.startswith('type'): |
|
1355 | if pager_cmd.startswith('type'): | |
1344 | # The default WinXP 'type' command is failing on complex strings. |
|
1356 | # The default WinXP 'type' command is failing on complex strings. | |
1345 | retval = 1 |
|
1357 | retval = 1 | |
1346 | else: |
|
1358 | else: | |
1347 | tmpname = tempfile.mktemp('.txt') |
|
1359 | tmpname = tempfile.mktemp('.txt') | |
1348 | tmpfile = file(tmpname,'wt') |
|
1360 | tmpfile = file(tmpname,'wt') | |
1349 | tmpfile.write(strng) |
|
1361 | tmpfile.write(strng) | |
1350 | tmpfile.close() |
|
1362 | tmpfile.close() | |
1351 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1363 | cmd = "%s < %s" % (pager_cmd,tmpname) | |
1352 | if os.system(cmd): |
|
1364 | if os.system(cmd): | |
1353 | retval = 1 |
|
1365 | retval = 1 | |
1354 | else: |
|
1366 | else: | |
1355 | retval = None |
|
1367 | retval = None | |
1356 | os.remove(tmpname) |
|
1368 | os.remove(tmpname) | |
1357 | else: |
|
1369 | else: | |
1358 | try: |
|
1370 | try: | |
1359 | retval = None |
|
1371 | retval = None | |
1360 | # if I use popen4, things hang. No idea why. |
|
1372 | # if I use popen4, things hang. No idea why. | |
1361 | #pager,shell_out = os.popen4(pager_cmd) |
|
1373 | #pager,shell_out = os.popen4(pager_cmd) | |
1362 | pager = os.popen(pager_cmd,'w') |
|
1374 | pager = os.popen(pager_cmd,'w') | |
1363 | pager.write(strng) |
|
1375 | pager.write(strng) | |
1364 | pager.close() |
|
1376 | pager.close() | |
1365 | retval = pager.close() # success returns None |
|
1377 | retval = pager.close() # success returns None | |
1366 | except IOError,msg: # broken pipe when user quits |
|
1378 | except IOError,msg: # broken pipe when user quits | |
1367 | if msg.args == (32,'Broken pipe'): |
|
1379 | if msg.args == (32,'Broken pipe'): | |
1368 | retval = None |
|
1380 | retval = None | |
1369 | else: |
|
1381 | else: | |
1370 | retval = 1 |
|
1382 | retval = 1 | |
1371 | except OSError: |
|
1383 | except OSError: | |
1372 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1384 | # Other strange problems, sometimes seen in Win2k/cygwin | |
1373 | retval = 1 |
|
1385 | retval = 1 | |
1374 | if retval is not None: |
|
1386 | if retval is not None: | |
1375 | page_dumb(strng,screen_lines=screen_lines) |
|
1387 | page_dumb(strng,screen_lines=screen_lines) | |
1376 |
|
1388 | |||
1377 | #---------------------------------------------------------------------------- |
|
1389 | #---------------------------------------------------------------------------- | |
1378 | def page_file(fname,start = 0, pager_cmd = None): |
|
1390 | def page_file(fname,start = 0, pager_cmd = None): | |
1379 | """Page a file, using an optional pager command and starting line. |
|
1391 | """Page a file, using an optional pager command and starting line. | |
1380 | """ |
|
1392 | """ | |
1381 |
|
1393 | |||
1382 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1394 | pager_cmd = get_pager_cmd(pager_cmd) | |
1383 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1395 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1384 |
|
1396 | |||
1385 | try: |
|
1397 | try: | |
1386 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1398 | if os.environ['TERM'] in ['emacs','dumb']: | |
1387 | raise EnvironmentError |
|
1399 | raise EnvironmentError | |
1388 | xsys(pager_cmd + ' ' + fname) |
|
1400 | xsys(pager_cmd + ' ' + fname) | |
1389 | except: |
|
1401 | except: | |
1390 | try: |
|
1402 | try: | |
1391 | if start > 0: |
|
1403 | if start > 0: | |
1392 | start -= 1 |
|
1404 | start -= 1 | |
1393 | page(open(fname).read(),start) |
|
1405 | page(open(fname).read(),start) | |
1394 | except: |
|
1406 | except: | |
1395 | print 'Unable to show file',`fname` |
|
1407 | print 'Unable to show file',`fname` | |
1396 |
|
1408 | |||
1397 | #---------------------------------------------------------------------------- |
|
1409 | #---------------------------------------------------------------------------- | |
1398 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1410 | def snip_print(str,width = 75,print_full = 0,header = ''): | |
1399 | """Print a string snipping the midsection to fit in width. |
|
1411 | """Print a string snipping the midsection to fit in width. | |
1400 |
|
1412 | |||
1401 | print_full: mode control: |
|
1413 | print_full: mode control: | |
1402 | - 0: only snip long strings |
|
1414 | - 0: only snip long strings | |
1403 | - 1: send to page() directly. |
|
1415 | - 1: send to page() directly. | |
1404 | - 2: snip long strings and ask for full length viewing with page() |
|
1416 | - 2: snip long strings and ask for full length viewing with page() | |
1405 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1417 | Return 1 if snipping was necessary, 0 otherwise.""" | |
1406 |
|
1418 | |||
1407 | if print_full == 1: |
|
1419 | if print_full == 1: | |
1408 | page(header+str) |
|
1420 | page(header+str) | |
1409 | return 0 |
|
1421 | return 0 | |
1410 |
|
1422 | |||
1411 | print header, |
|
1423 | print header, | |
1412 | if len(str) < width: |
|
1424 | if len(str) < width: | |
1413 | print str |
|
1425 | print str | |
1414 | snip = 0 |
|
1426 | snip = 0 | |
1415 | else: |
|
1427 | else: | |
1416 | whalf = int((width -5)/2) |
|
1428 | whalf = int((width -5)/2) | |
1417 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1429 | print str[:whalf] + ' <...> ' + str[-whalf:] | |
1418 | snip = 1 |
|
1430 | snip = 1 | |
1419 | if snip and print_full == 2: |
|
1431 | if snip and print_full == 2: | |
1420 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1432 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': | |
1421 | page(str) |
|
1433 | page(str) | |
1422 | return snip |
|
1434 | return snip | |
1423 |
|
1435 | |||
1424 | #**************************************************************************** |
|
1436 | #**************************************************************************** | |
1425 | # lists, dicts and structures |
|
1437 | # lists, dicts and structures | |
1426 |
|
1438 | |||
1427 | def belong(candidates,checklist): |
|
1439 | def belong(candidates,checklist): | |
1428 | """Check whether a list of items appear in a given list of options. |
|
1440 | """Check whether a list of items appear in a given list of options. | |
1429 |
|
1441 | |||
1430 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1442 | Returns a list of 1 and 0, one for each candidate given.""" | |
1431 |
|
1443 | |||
1432 | return [x in checklist for x in candidates] |
|
1444 | return [x in checklist for x in candidates] | |
1433 |
|
1445 | |||
1434 | #---------------------------------------------------------------------------- |
|
1446 | #---------------------------------------------------------------------------- | |
1435 | def uniq_stable(elems): |
|
1447 | def uniq_stable(elems): | |
1436 | """uniq_stable(elems) -> list |
|
1448 | """uniq_stable(elems) -> list | |
1437 |
|
1449 | |||
1438 | Return from an iterable, a list of all the unique elements in the input, |
|
1450 | Return from an iterable, a list of all the unique elements in the input, | |
1439 | but maintaining the order in which they first appear. |
|
1451 | but maintaining the order in which they first appear. | |
1440 |
|
1452 | |||
1441 | A naive solution to this problem which just makes a dictionary with the |
|
1453 | A naive solution to this problem which just makes a dictionary with the | |
1442 | elements as keys fails to respect the stability condition, since |
|
1454 | elements as keys fails to respect the stability condition, since | |
1443 | dictionaries are unsorted by nature. |
|
1455 | dictionaries are unsorted by nature. | |
1444 |
|
1456 | |||
1445 | Note: All elements in the input must be valid dictionary keys for this |
|
1457 | Note: All elements in the input must be valid dictionary keys for this | |
1446 | routine to work, as it internally uses a dictionary for efficiency |
|
1458 | routine to work, as it internally uses a dictionary for efficiency | |
1447 | reasons.""" |
|
1459 | reasons.""" | |
1448 |
|
1460 | |||
1449 | unique = [] |
|
1461 | unique = [] | |
1450 | unique_dict = {} |
|
1462 | unique_dict = {} | |
1451 | for nn in elems: |
|
1463 | for nn in elems: | |
1452 | if nn not in unique_dict: |
|
1464 | if nn not in unique_dict: | |
1453 | unique.append(nn) |
|
1465 | unique.append(nn) | |
1454 | unique_dict[nn] = None |
|
1466 | unique_dict[nn] = None | |
1455 | return unique |
|
1467 | return unique | |
1456 |
|
1468 | |||
1457 | #---------------------------------------------------------------------------- |
|
1469 | #---------------------------------------------------------------------------- | |
1458 | class NLprinter: |
|
1470 | class NLprinter: | |
1459 | """Print an arbitrarily nested list, indicating index numbers. |
|
1471 | """Print an arbitrarily nested list, indicating index numbers. | |
1460 |
|
1472 | |||
1461 | An instance of this class called nlprint is available and callable as a |
|
1473 | An instance of this class called nlprint is available and callable as a | |
1462 | function. |
|
1474 | function. | |
1463 |
|
1475 | |||
1464 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1476 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' | |
1465 | and using 'sep' to separate the index from the value. """ |
|
1477 | and using 'sep' to separate the index from the value. """ | |
1466 |
|
1478 | |||
1467 | def __init__(self): |
|
1479 | def __init__(self): | |
1468 | self.depth = 0 |
|
1480 | self.depth = 0 | |
1469 |
|
1481 | |||
1470 | def __call__(self,lst,pos='',**kw): |
|
1482 | def __call__(self,lst,pos='',**kw): | |
1471 | """Prints the nested list numbering levels.""" |
|
1483 | """Prints the nested list numbering levels.""" | |
1472 | kw.setdefault('indent',' ') |
|
1484 | kw.setdefault('indent',' ') | |
1473 | kw.setdefault('sep',': ') |
|
1485 | kw.setdefault('sep',': ') | |
1474 | kw.setdefault('start',0) |
|
1486 | kw.setdefault('start',0) | |
1475 | kw.setdefault('stop',len(lst)) |
|
1487 | kw.setdefault('stop',len(lst)) | |
1476 | # we need to remove start and stop from kw so they don't propagate |
|
1488 | # we need to remove start and stop from kw so they don't propagate | |
1477 | # into a recursive call for a nested list. |
|
1489 | # into a recursive call for a nested list. | |
1478 | start = kw['start']; del kw['start'] |
|
1490 | start = kw['start']; del kw['start'] | |
1479 | stop = kw['stop']; del kw['stop'] |
|
1491 | stop = kw['stop']; del kw['stop'] | |
1480 | if self.depth == 0 and 'header' in kw.keys(): |
|
1492 | if self.depth == 0 and 'header' in kw.keys(): | |
1481 | print kw['header'] |
|
1493 | print kw['header'] | |
1482 |
|
1494 | |||
1483 | for idx in range(start,stop): |
|
1495 | for idx in range(start,stop): | |
1484 | elem = lst[idx] |
|
1496 | elem = lst[idx] | |
1485 | if type(elem)==type([]): |
|
1497 | if type(elem)==type([]): | |
1486 | self.depth += 1 |
|
1498 | self.depth += 1 | |
1487 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1499 | self.__call__(elem,itpl('$pos$idx,'),**kw) | |
1488 | self.depth -= 1 |
|
1500 | self.depth -= 1 | |
1489 | else: |
|
1501 | else: | |
1490 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1502 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') | |
1491 |
|
1503 | |||
1492 | nlprint = NLprinter() |
|
1504 | nlprint = NLprinter() | |
1493 | #---------------------------------------------------------------------------- |
|
1505 | #---------------------------------------------------------------------------- | |
1494 | def all_belong(candidates,checklist): |
|
1506 | def all_belong(candidates,checklist): | |
1495 | """Check whether a list of items ALL appear in a given list of options. |
|
1507 | """Check whether a list of items ALL appear in a given list of options. | |
1496 |
|
1508 | |||
1497 | Returns a single 1 or 0 value.""" |
|
1509 | Returns a single 1 or 0 value.""" | |
1498 |
|
1510 | |||
1499 | return 1-(0 in [x in checklist for x in candidates]) |
|
1511 | return 1-(0 in [x in checklist for x in candidates]) | |
1500 |
|
1512 | |||
1501 | #---------------------------------------------------------------------------- |
|
1513 | #---------------------------------------------------------------------------- | |
1502 | def sort_compare(lst1,lst2,inplace = 1): |
|
1514 | def sort_compare(lst1,lst2,inplace = 1): | |
1503 | """Sort and compare two lists. |
|
1515 | """Sort and compare two lists. | |
1504 |
|
1516 | |||
1505 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1517 | By default it does it in place, thus modifying the lists. Use inplace = 0 | |
1506 | to avoid that (at the cost of temporary copy creation).""" |
|
1518 | to avoid that (at the cost of temporary copy creation).""" | |
1507 | if not inplace: |
|
1519 | if not inplace: | |
1508 | lst1 = lst1[:] |
|
1520 | lst1 = lst1[:] | |
1509 | lst2 = lst2[:] |
|
1521 | lst2 = lst2[:] | |
1510 | lst1.sort(); lst2.sort() |
|
1522 | lst1.sort(); lst2.sort() | |
1511 | return lst1 == lst2 |
|
1523 | return lst1 == lst2 | |
1512 |
|
1524 | |||
1513 | #---------------------------------------------------------------------------- |
|
1525 | #---------------------------------------------------------------------------- | |
1514 | def mkdict(**kwargs): |
|
1526 | def mkdict(**kwargs): | |
1515 | """Return a dict from a keyword list. |
|
1527 | """Return a dict from a keyword list. | |
1516 |
|
1528 | |||
1517 | It's just syntactic sugar for making ditcionary creation more convenient: |
|
1529 | It's just syntactic sugar for making ditcionary creation more convenient: | |
1518 | # the standard way |
|
1530 | # the standard way | |
1519 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } |
|
1531 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } | |
1520 | # a cleaner way |
|
1532 | # a cleaner way | |
1521 | >>>data = dict(red=1, green=2, blue=3) |
|
1533 | >>>data = dict(red=1, green=2, blue=3) | |
1522 |
|
1534 | |||
1523 | If you need more than this, look at the Struct() class.""" |
|
1535 | If you need more than this, look at the Struct() class.""" | |
1524 |
|
1536 | |||
1525 | return kwargs |
|
1537 | return kwargs | |
1526 |
|
1538 | |||
1527 | #---------------------------------------------------------------------------- |
|
1539 | #---------------------------------------------------------------------------- | |
1528 | def list2dict(lst): |
|
1540 | def list2dict(lst): | |
1529 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1541 | """Takes a list of (key,value) pairs and turns it into a dict.""" | |
1530 |
|
1542 | |||
1531 | dic = {} |
|
1543 | dic = {} | |
1532 | for k,v in lst: dic[k] = v |
|
1544 | for k,v in lst: dic[k] = v | |
1533 | return dic |
|
1545 | return dic | |
1534 |
|
1546 | |||
1535 | #---------------------------------------------------------------------------- |
|
1547 | #---------------------------------------------------------------------------- | |
1536 | def list2dict2(lst,default=''): |
|
1548 | def list2dict2(lst,default=''): | |
1537 | """Takes a list and turns it into a dict. |
|
1549 | """Takes a list and turns it into a dict. | |
1538 | Much slower than list2dict, but more versatile. This version can take |
|
1550 | Much slower than list2dict, but more versatile. This version can take | |
1539 | lists with sublists of arbitrary length (including sclars).""" |
|
1551 | lists with sublists of arbitrary length (including sclars).""" | |
1540 |
|
1552 | |||
1541 | dic = {} |
|
1553 | dic = {} | |
1542 | for elem in lst: |
|
1554 | for elem in lst: | |
1543 | if type(elem) in (types.ListType,types.TupleType): |
|
1555 | if type(elem) in (types.ListType,types.TupleType): | |
1544 | size = len(elem) |
|
1556 | size = len(elem) | |
1545 | if size == 0: |
|
1557 | if size == 0: | |
1546 | pass |
|
1558 | pass | |
1547 | elif size == 1: |
|
1559 | elif size == 1: | |
1548 | dic[elem] = default |
|
1560 | dic[elem] = default | |
1549 | else: |
|
1561 | else: | |
1550 | k,v = elem[0], elem[1:] |
|
1562 | k,v = elem[0], elem[1:] | |
1551 | if len(v) == 1: v = v[0] |
|
1563 | if len(v) == 1: v = v[0] | |
1552 | dic[k] = v |
|
1564 | dic[k] = v | |
1553 | else: |
|
1565 | else: | |
1554 | dic[elem] = default |
|
1566 | dic[elem] = default | |
1555 | return dic |
|
1567 | return dic | |
1556 |
|
1568 | |||
1557 | #---------------------------------------------------------------------------- |
|
1569 | #---------------------------------------------------------------------------- | |
1558 | def flatten(seq): |
|
1570 | def flatten(seq): | |
1559 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1571 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" | |
1560 |
|
1572 | |||
1561 | return [x for subseq in seq for x in subseq] |
|
1573 | return [x for subseq in seq for x in subseq] | |
1562 |
|
1574 | |||
1563 | #---------------------------------------------------------------------------- |
|
1575 | #---------------------------------------------------------------------------- | |
1564 | def get_slice(seq,start=0,stop=None,step=1): |
|
1576 | def get_slice(seq,start=0,stop=None,step=1): | |
1565 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1577 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" | |
1566 | if stop == None: |
|
1578 | if stop == None: | |
1567 | stop = len(seq) |
|
1579 | stop = len(seq) | |
1568 | item = lambda i: seq[i] |
|
1580 | item = lambda i: seq[i] | |
1569 | return map(item,xrange(start,stop,step)) |
|
1581 | return map(item,xrange(start,stop,step)) | |
1570 |
|
1582 | |||
1571 | #---------------------------------------------------------------------------- |
|
1583 | #---------------------------------------------------------------------------- | |
1572 | def chop(seq,size): |
|
1584 | def chop(seq,size): | |
1573 | """Chop a sequence into chunks of the given size.""" |
|
1585 | """Chop a sequence into chunks of the given size.""" | |
1574 | chunk = lambda i: seq[i:i+size] |
|
1586 | chunk = lambda i: seq[i:i+size] | |
1575 | return map(chunk,xrange(0,len(seq),size)) |
|
1587 | return map(chunk,xrange(0,len(seq),size)) | |
1576 |
|
1588 | |||
1577 | #---------------------------------------------------------------------------- |
|
1589 | #---------------------------------------------------------------------------- | |
1578 | # with is a keyword as of python 2.5, so this function is renamed to withobj |
|
1590 | # with is a keyword as of python 2.5, so this function is renamed to withobj | |
1579 | # from its old 'with' name. |
|
1591 | # from its old 'with' name. | |
1580 | def with_obj(object, **args): |
|
1592 | def with_obj(object, **args): | |
1581 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1593 | """Set multiple attributes for an object, similar to Pascal's with. | |
1582 |
|
1594 | |||
1583 | Example: |
|
1595 | Example: | |
1584 | with_obj(jim, |
|
1596 | with_obj(jim, | |
1585 | born = 1960, |
|
1597 | born = 1960, | |
1586 | haircolour = 'Brown', |
|
1598 | haircolour = 'Brown', | |
1587 | eyecolour = 'Green') |
|
1599 | eyecolour = 'Green') | |
1588 |
|
1600 | |||
1589 | Credit: Greg Ewing, in |
|
1601 | Credit: Greg Ewing, in | |
1590 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. |
|
1602 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. | |
1591 |
|
1603 | |||
1592 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' |
|
1604 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' | |
1593 | has become a keyword for Python 2.5, so we had to rename it.""" |
|
1605 | has become a keyword for Python 2.5, so we had to rename it.""" | |
1594 |
|
1606 | |||
1595 | object.__dict__.update(args) |
|
1607 | object.__dict__.update(args) | |
1596 |
|
1608 | |||
1597 | #---------------------------------------------------------------------------- |
|
1609 | #---------------------------------------------------------------------------- | |
1598 | def setattr_list(obj,alist,nspace = None): |
|
1610 | def setattr_list(obj,alist,nspace = None): | |
1599 | """Set a list of attributes for an object taken from a namespace. |
|
1611 | """Set a list of attributes for an object taken from a namespace. | |
1600 |
|
1612 | |||
1601 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1613 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in | |
1602 | alist with their values taken from nspace, which must be a dict (something |
|
1614 | alist with their values taken from nspace, which must be a dict (something | |
1603 | like locals() will often do) If nspace isn't given, locals() of the |
|
1615 | like locals() will often do) If nspace isn't given, locals() of the | |
1604 | *caller* is used, so in most cases you can omit it. |
|
1616 | *caller* is used, so in most cases you can omit it. | |
1605 |
|
1617 | |||
1606 | Note that alist can be given as a string, which will be automatically |
|
1618 | Note that alist can be given as a string, which will be automatically | |
1607 | split into a list on whitespace. If given as a list, it must be a list of |
|
1619 | split into a list on whitespace. If given as a list, it must be a list of | |
1608 | *strings* (the variable names themselves), not of variables.""" |
|
1620 | *strings* (the variable names themselves), not of variables.""" | |
1609 |
|
1621 | |||
1610 | # this grabs the local variables from the *previous* call frame -- that is |
|
1622 | # this grabs the local variables from the *previous* call frame -- that is | |
1611 | # the locals from the function that called setattr_list(). |
|
1623 | # the locals from the function that called setattr_list(). | |
1612 | # - snipped from weave.inline() |
|
1624 | # - snipped from weave.inline() | |
1613 | if nspace is None: |
|
1625 | if nspace is None: | |
1614 | call_frame = sys._getframe().f_back |
|
1626 | call_frame = sys._getframe().f_back | |
1615 | nspace = call_frame.f_locals |
|
1627 | nspace = call_frame.f_locals | |
1616 |
|
1628 | |||
1617 | if type(alist) in StringTypes: |
|
1629 | if type(alist) in StringTypes: | |
1618 | alist = alist.split() |
|
1630 | alist = alist.split() | |
1619 | for attr in alist: |
|
1631 | for attr in alist: | |
1620 | val = eval(attr,nspace) |
|
1632 | val = eval(attr,nspace) | |
1621 | setattr(obj,attr,val) |
|
1633 | setattr(obj,attr,val) | |
1622 |
|
1634 | |||
1623 | #---------------------------------------------------------------------------- |
|
1635 | #---------------------------------------------------------------------------- | |
1624 | def getattr_list(obj,alist,*args): |
|
1636 | def getattr_list(obj,alist,*args): | |
1625 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1637 | """getattr_list(obj,alist[, default]) -> attribute list. | |
1626 |
|
1638 | |||
1627 | Get a list of named attributes for an object. When a default argument is |
|
1639 | Get a list of named attributes for an object. When a default argument is | |
1628 | given, it is returned when the attribute doesn't exist; without it, an |
|
1640 | given, it is returned when the attribute doesn't exist; without it, an | |
1629 | exception is raised in that case. |
|
1641 | exception is raised in that case. | |
1630 |
|
1642 | |||
1631 | Note that alist can be given as a string, which will be automatically |
|
1643 | Note that alist can be given as a string, which will be automatically | |
1632 | split into a list on whitespace. If given as a list, it must be a list of |
|
1644 | split into a list on whitespace. If given as a list, it must be a list of | |
1633 | *strings* (the variable names themselves), not of variables.""" |
|
1645 | *strings* (the variable names themselves), not of variables.""" | |
1634 |
|
1646 | |||
1635 | if type(alist) in StringTypes: |
|
1647 | if type(alist) in StringTypes: | |
1636 | alist = alist.split() |
|
1648 | alist = alist.split() | |
1637 | if args: |
|
1649 | if args: | |
1638 | if len(args)==1: |
|
1650 | if len(args)==1: | |
1639 | default = args[0] |
|
1651 | default = args[0] | |
1640 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1652 | return map(lambda attr: getattr(obj,attr,default),alist) | |
1641 | else: |
|
1653 | else: | |
1642 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1654 | raise ValueError,'getattr_list() takes only one optional argument' | |
1643 | else: |
|
1655 | else: | |
1644 | return map(lambda attr: getattr(obj,attr),alist) |
|
1656 | return map(lambda attr: getattr(obj,attr),alist) | |
1645 |
|
1657 | |||
1646 | #---------------------------------------------------------------------------- |
|
1658 | #---------------------------------------------------------------------------- | |
1647 | def map_method(method,object_list,*argseq,**kw): |
|
1659 | def map_method(method,object_list,*argseq,**kw): | |
1648 | """map_method(method,object_list,*args,**kw) -> list |
|
1660 | """map_method(method,object_list,*args,**kw) -> list | |
1649 |
|
1661 | |||
1650 | Return a list of the results of applying the methods to the items of the |
|
1662 | Return a list of the results of applying the methods to the items of the | |
1651 | argument sequence(s). If more than one sequence is given, the method is |
|
1663 | argument sequence(s). If more than one sequence is given, the method is | |
1652 | called with an argument list consisting of the corresponding item of each |
|
1664 | called with an argument list consisting of the corresponding item of each | |
1653 | sequence. All sequences must be of the same length. |
|
1665 | sequence. All sequences must be of the same length. | |
1654 |
|
1666 | |||
1655 | Keyword arguments are passed verbatim to all objects called. |
|
1667 | Keyword arguments are passed verbatim to all objects called. | |
1656 |
|
1668 | |||
1657 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1669 | This is Python code, so it's not nearly as fast as the builtin map().""" | |
1658 |
|
1670 | |||
1659 | out_list = [] |
|
1671 | out_list = [] | |
1660 | idx = 0 |
|
1672 | idx = 0 | |
1661 | for object in object_list: |
|
1673 | for object in object_list: | |
1662 | try: |
|
1674 | try: | |
1663 | handler = getattr(object, method) |
|
1675 | handler = getattr(object, method) | |
1664 | except AttributeError: |
|
1676 | except AttributeError: | |
1665 | out_list.append(None) |
|
1677 | out_list.append(None) | |
1666 | else: |
|
1678 | else: | |
1667 | if argseq: |
|
1679 | if argseq: | |
1668 | args = map(lambda lst:lst[idx],argseq) |
|
1680 | args = map(lambda lst:lst[idx],argseq) | |
1669 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1681 | #print 'ob',object,'hand',handler,'ar',args # dbg | |
1670 | out_list.append(handler(args,**kw)) |
|
1682 | out_list.append(handler(args,**kw)) | |
1671 | else: |
|
1683 | else: | |
1672 | out_list.append(handler(**kw)) |
|
1684 | out_list.append(handler(**kw)) | |
1673 | idx += 1 |
|
1685 | idx += 1 | |
1674 | return out_list |
|
1686 | return out_list | |
1675 |
|
1687 | |||
1676 | #---------------------------------------------------------------------------- |
|
1688 | #---------------------------------------------------------------------------- | |
1677 | def import_fail_info(mod_name,fns=None): |
|
1689 | def import_fail_info(mod_name,fns=None): | |
1678 | """Inform load failure for a module.""" |
|
1690 | """Inform load failure for a module.""" | |
1679 |
|
1691 | |||
1680 | if fns == None: |
|
1692 | if fns == None: | |
1681 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
1693 | warn("Loading of %s failed.\n" % (mod_name,)) | |
1682 | else: |
|
1694 | else: | |
1683 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
1695 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) | |
1684 |
|
1696 | |||
1685 | #---------------------------------------------------------------------------- |
|
1697 | #---------------------------------------------------------------------------- | |
1686 | # Proposed popitem() extension, written as a method |
|
1698 | # Proposed popitem() extension, written as a method | |
1687 |
|
1699 | |||
1688 | class NotGiven: pass |
|
1700 | class NotGiven: pass | |
1689 |
|
1701 | |||
1690 | def popkey(dct,key,default=NotGiven): |
|
1702 | def popkey(dct,key,default=NotGiven): | |
1691 | """Return dct[key] and delete dct[key]. |
|
1703 | """Return dct[key] and delete dct[key]. | |
1692 |
|
1704 | |||
1693 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
1705 | If default is given, return it if dct[key] doesn't exist, otherwise raise | |
1694 | KeyError. """ |
|
1706 | KeyError. """ | |
1695 |
|
1707 | |||
1696 | try: |
|
1708 | try: | |
1697 | val = dct[key] |
|
1709 | val = dct[key] | |
1698 | except KeyError: |
|
1710 | except KeyError: | |
1699 | if default is NotGiven: |
|
1711 | if default is NotGiven: | |
1700 | raise |
|
1712 | raise | |
1701 | else: |
|
1713 | else: | |
1702 | return default |
|
1714 | return default | |
1703 | else: |
|
1715 | else: | |
1704 | del dct[key] |
|
1716 | del dct[key] | |
1705 | return val |
|
1717 | return val | |
1706 | #*************************** end of file <genutils.py> ********************** |
|
1718 | #*************************** end of file <genutils.py> ********************** | |
1707 |
|
1719 |
General Comments 0
You need to be logged in to leave comments.
Login now