Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,2490 +1,2454 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 |
|
4 | $Id: Magic.py 897 2005-09-22 09:32:46Z fperez $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
8 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 |
|
13 | |||
14 | #**************************************************************************** |
|
14 | #**************************************************************************** | |
15 | # Modules and globals |
|
15 | # Modules and globals | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
18 | __author__ = '%s <%s>\n%s <%s>' % \ | |
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
20 | __license__ = Release.license |
|
20 | __license__ = Release.license | |
21 |
|
21 | |||
22 | # Python standard modules |
|
22 | # Python standard modules | |
23 | import __builtin__ |
|
23 | import __builtin__ | |
24 |
import os,sys,inspect,pydoc,re,tempfile, |
|
24 | import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time | |
25 | try: |
|
25 | try: | |
26 | import profile,pstats |
|
26 | import profile,pstats | |
27 | except ImportError: |
|
27 | except ImportError: | |
28 | profile = pstats = None |
|
28 | profile = pstats = None | |
29 | from getopt import getopt |
|
29 | from getopt import getopt | |
30 | from pprint import pprint, pformat |
|
30 | from pprint import pprint, pformat | |
31 | from cStringIO import StringIO |
|
31 | from cStringIO import StringIO | |
32 |
|
32 | |||
33 | # Homebrewed |
|
33 | # Homebrewed | |
34 | from IPython.Struct import Struct |
|
34 | from IPython.Struct import Struct | |
35 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
35 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
36 | from IPython.FakeModule import FakeModule |
|
36 | from IPython.FakeModule import FakeModule | |
37 | from IPython import OInspect |
|
37 | from IPython import OInspect | |
38 | from IPython.genutils import * |
|
38 | from IPython.genutils import * | |
39 |
|
39 | |||
40 | # Globals to be set later by Magic constructor |
|
40 | # Globals to be set later by Magic constructor | |
41 | MAGIC_PREFIX = '' |
|
41 | MAGIC_PREFIX = '' | |
42 | MAGIC_ESCAPE = '' |
|
42 | MAGIC_ESCAPE = '' | |
43 |
|
43 | |||
44 | #*************************************************************************** |
|
44 | #*************************************************************************** | |
45 | # Utility functions |
|
45 | # Utility functions | |
46 | def magic2python(cmd): |
|
46 | def magic2python(cmd): | |
47 | """Convert a command string of magic syntax to valid Python code.""" |
|
47 | """Convert a command string of magic syntax to valid Python code.""" | |
48 |
|
48 | |||
49 | if cmd.startswith('#'+MAGIC_ESCAPE) or \ |
|
49 | if cmd.startswith('#'+MAGIC_ESCAPE) or \ | |
50 | cmd.startswith(MAGIC_ESCAPE): |
|
50 | cmd.startswith(MAGIC_ESCAPE): | |
51 | if cmd[0]=='#': |
|
51 | if cmd[0]=='#': | |
52 | cmd = cmd[1:] |
|
52 | cmd = cmd[1:] | |
53 | # we need to return the proper line end later |
|
53 | # we need to return the proper line end later | |
54 | if cmd[-1] == '\n': |
|
54 | if cmd[-1] == '\n': | |
55 | endl = '\n' |
|
55 | endl = '\n' | |
56 | else: |
|
56 | else: | |
57 | endl = '' |
|
57 | endl = '' | |
58 | try: |
|
58 | try: | |
59 | func,args = cmd[1:].split(' ',1) |
|
59 | func,args = cmd[1:].split(' ',1) | |
60 | except: |
|
60 | except: | |
61 | func,args = cmd[1:].rstrip(),'' |
|
61 | func,args = cmd[1:].rstrip(),'' | |
62 | args = args.replace('"','\\"').replace("'","\\'").rstrip() |
|
62 | args = args.replace('"','\\"').replace("'","\\'").rstrip() | |
63 | return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl) |
|
63 | return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl) | |
64 | else: |
|
64 | else: | |
65 | return cmd |
|
65 | return cmd | |
66 |
|
66 | |||
67 | def on_off(tag): |
|
67 | def on_off(tag): | |
68 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
68 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
69 | return ['OFF','ON'][tag] |
|
69 | return ['OFF','ON'][tag] | |
70 |
|
70 | |||
71 | def get_py_filename(name): |
|
71 | def get_py_filename(name): | |
72 | """Return a valid python filename in the current directory. |
|
72 | """Return a valid python filename in the current directory. | |
73 |
|
73 | |||
74 | If the given name is not a file, it adds '.py' and searches again. |
|
74 | If the given name is not a file, it adds '.py' and searches again. | |
75 | Raises IOError with an informative message if the file isn't found.""" |
|
75 | Raises IOError with an informative message if the file isn't found.""" | |
76 |
|
76 | |||
77 | name = os.path.expanduser(name) |
|
77 | name = os.path.expanduser(name) | |
78 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
78 | if not os.path.isfile(name) and not name.endswith('.py'): | |
79 | name += '.py' |
|
79 | name += '.py' | |
80 | if os.path.isfile(name): |
|
80 | if os.path.isfile(name): | |
81 | return name |
|
81 | return name | |
82 | else: |
|
82 | else: | |
83 | raise IOError,'File `%s` not found.' % name |
|
83 | raise IOError,'File `%s` not found.' % name | |
84 |
|
84 | |||
85 | # Try to use shlex.split for converting an input string into a sys.argv-type |
|
|||
86 | # list. This appeared in Python 2.3, so here's a quick backport for 2.2. |
|
|||
87 | try: |
|
|||
88 | shlex_split = shlex.split |
|
|||
89 | except AttributeError: |
|
|||
90 | _quotesre = re.compile(r'[\'"](.*)[\'"]') |
|
|||
91 | _wordchars = ('abcdfeghijklmnopqrstuvwxyz' |
|
|||
92 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?' |
|
|||
93 | 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' |
|
|||
94 | 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s' |
|
|||
95 | % os.sep) |
|
|||
96 |
|
||||
97 | def shlex_split(s): |
|
|||
98 | """Simplified backport to Python 2.2 of shlex.split(). |
|
|||
99 |
|
||||
100 | This is a quick and dirty hack, since the shlex module under 2.2 lacks |
|
|||
101 | several of the features needed to really match the functionality of |
|
|||
102 | shlex.split() in 2.3.""" |
|
|||
103 |
|
||||
104 | lex = shlex.shlex(StringIO(s)) |
|
|||
105 | # Try to get options, extensions and path separators as characters |
|
|||
106 | lex.wordchars = _wordchars |
|
|||
107 | lex.commenters = '' |
|
|||
108 | # Make a list out of the lexer by hand, since in 2.2 it's not an |
|
|||
109 | # iterator. |
|
|||
110 | lout = [] |
|
|||
111 | while 1: |
|
|||
112 | token = lex.get_token() |
|
|||
113 | if token == '': |
|
|||
114 | break |
|
|||
115 | # Try to handle quoted tokens correctly |
|
|||
116 | quotes = _quotesre.match(token) |
|
|||
117 | if quotes: |
|
|||
118 | token = quotes.group(1) |
|
|||
119 | lout.append(token) |
|
|||
120 | return lout |
|
|||
121 |
|
85 | |||
122 | #**************************************************************************** |
|
86 | #**************************************************************************** | |
123 | # Utility classes |
|
87 | # Utility classes | |
124 | class Macro: |
|
88 | class Macro: | |
125 | """Simple class to store the value of macros as strings. |
|
89 | """Simple class to store the value of macros as strings. | |
126 |
|
90 | |||
127 | This allows us to later exec them by checking when something is an |
|
91 | This allows us to later exec them by checking when something is an | |
128 | instance of this class.""" |
|
92 | instance of this class.""" | |
129 |
|
93 | |||
130 | def __init__(self,cmds): |
|
94 | def __init__(self,cmds): | |
131 | """Build a macro from a list of commands.""" |
|
95 | """Build a macro from a list of commands.""" | |
132 |
|
96 | |||
133 | # Since the list may include multi-line entries, first make sure that |
|
97 | # Since the list may include multi-line entries, first make sure that | |
134 | # they've been all broken up before passing it to magic2python |
|
98 | # they've been all broken up before passing it to magic2python | |
135 | cmdlist = map(magic2python,''.join(cmds).split('\n')) |
|
99 | cmdlist = map(magic2python,''.join(cmds).split('\n')) | |
136 | self.value = '\n'.join(cmdlist) |
|
100 | self.value = '\n'.join(cmdlist) | |
137 |
|
101 | |||
138 | def __str__(self): |
|
102 | def __str__(self): | |
139 | return self.value |
|
103 | return self.value | |
140 |
|
104 | |||
141 | #*************************************************************************** |
|
105 | #*************************************************************************** | |
142 | # Main class implementing Magic functionality |
|
106 | # Main class implementing Magic functionality | |
143 | class Magic: |
|
107 | class Magic: | |
144 | """Magic functions for InteractiveShell. |
|
108 | """Magic functions for InteractiveShell. | |
145 |
|
109 | |||
146 | Shell functions which can be reached as %function_name. All magic |
|
110 | Shell functions which can be reached as %function_name. All magic | |
147 | functions should accept a string, which they can parse for their own |
|
111 | functions should accept a string, which they can parse for their own | |
148 | needs. This can make some functions easier to type, eg `%cd ../` |
|
112 | needs. This can make some functions easier to type, eg `%cd ../` | |
149 | vs. `%cd("../")` |
|
113 | vs. `%cd("../")` | |
150 |
|
114 | |||
151 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
115 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
152 | at the command line, but it is is needed in the definition. """ |
|
116 | at the command line, but it is is needed in the definition. """ | |
153 |
|
117 | |||
154 | # class globals |
|
118 | # class globals | |
155 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
119 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
156 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
120 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
157 |
|
121 | |||
158 | #...................................................................... |
|
122 | #...................................................................... | |
159 | # some utility functions |
|
123 | # some utility functions | |
160 |
|
124 | |||
161 | def __init__(self,shell): |
|
125 | def __init__(self,shell): | |
162 | # XXX This is hackish, clean up later to avoid these messy globals |
|
126 | # XXX This is hackish, clean up later to avoid these messy globals | |
163 | global MAGIC_PREFIX, MAGIC_ESCAPE |
|
127 | global MAGIC_PREFIX, MAGIC_ESCAPE | |
164 |
|
128 | |||
165 | self.options_table = {} |
|
129 | self.options_table = {} | |
166 | MAGIC_PREFIX = shell.name+'.magic_' |
|
130 | MAGIC_PREFIX = shell.name+'.magic_' | |
167 | MAGIC_ESCAPE = shell.ESC_MAGIC |
|
131 | MAGIC_ESCAPE = shell.ESC_MAGIC | |
168 | if profile is None: |
|
132 | if profile is None: | |
169 | self.magic_prun = self.profile_missing_notice |
|
133 | self.magic_prun = self.profile_missing_notice | |
170 |
|
134 | |||
171 | def profile_missing_notice(self, *args, **kwargs): |
|
135 | def profile_missing_notice(self, *args, **kwargs): | |
172 | error("""\ |
|
136 | error("""\ | |
173 | The profile module could not be found. If you are a Debian user, |
|
137 | The profile module could not be found. If you are a Debian user, | |
174 | it has been removed from the standard Debian package because of its non-free |
|
138 | it has been removed from the standard Debian package because of its non-free | |
175 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
139 | license. To use profiling, please install"python2.3-profiler" from non-free.""") | |
176 |
|
140 | |||
177 | def default_option(self,fn,optstr): |
|
141 | def default_option(self,fn,optstr): | |
178 | """Make an entry in the options_table for fn, with value optstr""" |
|
142 | """Make an entry in the options_table for fn, with value optstr""" | |
179 |
|
143 | |||
180 | if fn not in self.lsmagic(): |
|
144 | if fn not in self.lsmagic(): | |
181 | error("%s is not a magic function" % fn) |
|
145 | error("%s is not a magic function" % fn) | |
182 | self.options_table[fn] = optstr |
|
146 | self.options_table[fn] = optstr | |
183 |
|
147 | |||
184 | def lsmagic(self): |
|
148 | def lsmagic(self): | |
185 | """Return a list of currently available magic functions. |
|
149 | """Return a list of currently available magic functions. | |
186 |
|
150 | |||
187 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
151 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
188 | ['magic_ls','magic_cd',...]""" |
|
152 | ['magic_ls','magic_cd',...]""" | |
189 |
|
153 | |||
190 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
154 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
191 |
|
155 | |||
192 | # magics in class definition |
|
156 | # magics in class definition | |
193 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
157 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
194 | callable(Magic.__dict__[fn]) |
|
158 | callable(Magic.__dict__[fn]) | |
195 | # in instance namespace (run-time user additions) |
|
159 | # in instance namespace (run-time user additions) | |
196 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
160 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
197 | callable(self.__dict__[fn]) |
|
161 | callable(self.__dict__[fn]) | |
198 | # and bound magics by user (so they can access self): |
|
162 | # and bound magics by user (so they can access self): | |
199 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
163 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
200 | callable(self.__class__.__dict__[fn]) |
|
164 | callable(self.__class__.__dict__[fn]) | |
201 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
165 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
202 | filter(inst_magic,self.__dict__.keys()) + \ |
|
166 | filter(inst_magic,self.__dict__.keys()) + \ | |
203 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
167 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
204 | out = [] |
|
168 | out = [] | |
205 | for fn in magics: |
|
169 | for fn in magics: | |
206 | out.append(fn.replace('magic_','',1)) |
|
170 | out.append(fn.replace('magic_','',1)) | |
207 | out.sort() |
|
171 | out.sort() | |
208 | return out |
|
172 | return out | |
209 |
|
173 | |||
210 | def set_shell(self,shell): |
|
174 | def set_shell(self,shell): | |
211 | self.shell = shell |
|
175 | self.shell = shell | |
212 | self.alias_table = shell.alias_table |
|
176 | self.alias_table = shell.alias_table | |
213 |
|
177 | |||
214 | def extract_input_slices(self,slices): |
|
178 | def extract_input_slices(self,slices): | |
215 | """Return as a string a set of input history slices. |
|
179 | """Return as a string a set of input history slices. | |
216 |
|
180 | |||
217 | The set of slices is given as a list of strings (like ['1','4:8','9'], |
|
181 | The set of slices is given as a list of strings (like ['1','4:8','9'], | |
218 | since this function is for use by magic functions which get their |
|
182 | since this function is for use by magic functions which get their | |
219 | arguments as strings.""" |
|
183 | arguments as strings.""" | |
220 |
|
184 | |||
221 | cmds = [] |
|
185 | cmds = [] | |
222 | for chunk in slices: |
|
186 | for chunk in slices: | |
223 | if ':' in chunk: |
|
187 | if ':' in chunk: | |
224 | ini,fin = map(int,chunk.split(':')) |
|
188 | ini,fin = map(int,chunk.split(':')) | |
225 | else: |
|
189 | else: | |
226 | ini = int(chunk) |
|
190 | ini = int(chunk) | |
227 | fin = ini+1 |
|
191 | fin = ini+1 | |
228 | cmds.append(self.shell.input_hist[ini:fin]) |
|
192 | cmds.append(self.shell.input_hist[ini:fin]) | |
229 | return cmds |
|
193 | return cmds | |
230 |
|
194 | |||
231 | def _ofind(self,oname): |
|
195 | def _ofind(self,oname): | |
232 | """Find an object in the available namespaces. |
|
196 | """Find an object in the available namespaces. | |
233 |
|
197 | |||
234 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
198 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
235 |
|
199 | |||
236 | Has special code to detect magic functions. |
|
200 | Has special code to detect magic functions. | |
237 | """ |
|
201 | """ | |
238 |
|
202 | |||
239 | oname = oname.strip() |
|
203 | oname = oname.strip() | |
240 |
|
204 | |||
241 | # Namespaces to search in: |
|
205 | # Namespaces to search in: | |
242 | user_ns = self.shell.user_ns |
|
206 | user_ns = self.shell.user_ns | |
243 | internal_ns = self.shell.internal_ns |
|
207 | internal_ns = self.shell.internal_ns | |
244 | builtin_ns = __builtin__.__dict__ |
|
208 | builtin_ns = __builtin__.__dict__ | |
245 | alias_ns = self.shell.alias_table |
|
209 | alias_ns = self.shell.alias_table | |
246 |
|
210 | |||
247 | # Put them in a list. The order is important so that we find things in |
|
211 | # Put them in a list. The order is important so that we find things in | |
248 | # the same order that Python finds them. |
|
212 | # the same order that Python finds them. | |
249 | namespaces = [ ('Interactive',user_ns), |
|
213 | namespaces = [ ('Interactive',user_ns), | |
250 | ('IPython internal',internal_ns), |
|
214 | ('IPython internal',internal_ns), | |
251 | ('Python builtin',builtin_ns), |
|
215 | ('Python builtin',builtin_ns), | |
252 | ('Alias',alias_ns), |
|
216 | ('Alias',alias_ns), | |
253 | ] |
|
217 | ] | |
254 |
|
218 | |||
255 | # initialize results to 'null' |
|
219 | # initialize results to 'null' | |
256 | found = 0; obj = None; ospace = None; ds = None; |
|
220 | found = 0; obj = None; ospace = None; ds = None; | |
257 | ismagic = 0; isalias = 0 |
|
221 | ismagic = 0; isalias = 0 | |
258 |
|
222 | |||
259 | # Look for the given name by splitting it in parts. If the head is |
|
223 | # Look for the given name by splitting it in parts. If the head is | |
260 | # found, then we look for all the remaining parts as members, and only |
|
224 | # found, then we look for all the remaining parts as members, and only | |
261 | # declare success if we can find them all. |
|
225 | # declare success if we can find them all. | |
262 | oname_parts = oname.split('.') |
|
226 | oname_parts = oname.split('.') | |
263 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
227 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
264 | for nsname,ns in namespaces: |
|
228 | for nsname,ns in namespaces: | |
265 | try: |
|
229 | try: | |
266 | obj = ns[oname_head] |
|
230 | obj = ns[oname_head] | |
267 | except KeyError: |
|
231 | except KeyError: | |
268 | continue |
|
232 | continue | |
269 | else: |
|
233 | else: | |
270 | for part in oname_rest: |
|
234 | for part in oname_rest: | |
271 | try: |
|
235 | try: | |
272 | obj = getattr(obj,part) |
|
236 | obj = getattr(obj,part) | |
273 | except: |
|
237 | except: | |
274 | # Blanket except b/c some badly implemented objects |
|
238 | # Blanket except b/c some badly implemented objects | |
275 | # allow __getattr__ to raise exceptions other than |
|
239 | # allow __getattr__ to raise exceptions other than | |
276 | # AttributeError, which then crashes IPython. |
|
240 | # AttributeError, which then crashes IPython. | |
277 | break |
|
241 | break | |
278 | else: |
|
242 | else: | |
279 | # If we finish the for loop (no break), we got all members |
|
243 | # If we finish the for loop (no break), we got all members | |
280 | found = 1 |
|
244 | found = 1 | |
281 | ospace = nsname |
|
245 | ospace = nsname | |
282 | if ns == alias_ns: |
|
246 | if ns == alias_ns: | |
283 | isalias = 1 |
|
247 | isalias = 1 | |
284 | break # namespace loop |
|
248 | break # namespace loop | |
285 |
|
249 | |||
286 | # Try to see if it's magic |
|
250 | # Try to see if it's magic | |
287 | if not found: |
|
251 | if not found: | |
288 | if oname.startswith(self.shell.ESC_MAGIC): |
|
252 | if oname.startswith(self.shell.ESC_MAGIC): | |
289 | oname = oname[1:] |
|
253 | oname = oname[1:] | |
290 | obj = getattr(self,'magic_'+oname,None) |
|
254 | obj = getattr(self,'magic_'+oname,None) | |
291 | if obj is not None: |
|
255 | if obj is not None: | |
292 | found = 1 |
|
256 | found = 1 | |
293 | ospace = 'IPython internal' |
|
257 | ospace = 'IPython internal' | |
294 | ismagic = 1 |
|
258 | ismagic = 1 | |
295 |
|
259 | |||
296 | # Last try: special-case some literals like '', [], {}, etc: |
|
260 | # Last try: special-case some literals like '', [], {}, etc: | |
297 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
261 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
298 | obj = eval(oname_head) |
|
262 | obj = eval(oname_head) | |
299 | found = 1 |
|
263 | found = 1 | |
300 | ospace = 'Interactive' |
|
264 | ospace = 'Interactive' | |
301 |
|
265 | |||
302 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
266 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
303 | 'ismagic':ismagic, 'isalias':isalias} |
|
267 | 'ismagic':ismagic, 'isalias':isalias} | |
304 |
|
268 | |||
305 | def arg_err(self,func): |
|
269 | def arg_err(self,func): | |
306 | """Print docstring if incorrect arguments were passed""" |
|
270 | """Print docstring if incorrect arguments were passed""" | |
307 | print 'Error in arguments:' |
|
271 | print 'Error in arguments:' | |
308 | print OInspect.getdoc(func) |
|
272 | print OInspect.getdoc(func) | |
309 |
|
273 | |||
310 |
|
274 | |||
311 | def format_latex(self,str): |
|
275 | def format_latex(self,str): | |
312 | """Format a string for latex inclusion.""" |
|
276 | """Format a string for latex inclusion.""" | |
313 |
|
277 | |||
314 | # Characters that need to be escaped for latex: |
|
278 | # Characters that need to be escaped for latex: | |
315 | escape_re = re.compile(r'(%|_|\$)',re.MULTILINE) |
|
279 | escape_re = re.compile(r'(%|_|\$)',re.MULTILINE) | |
316 | # Magic command names as headers: |
|
280 | # Magic command names as headers: | |
317 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
281 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
318 | re.MULTILINE) |
|
282 | re.MULTILINE) | |
319 | # Magic commands |
|
283 | # Magic commands | |
320 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
284 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
321 | re.MULTILINE) |
|
285 | re.MULTILINE) | |
322 | # Paragraph continue |
|
286 | # Paragraph continue | |
323 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
287 | par_re = re.compile(r'\\$',re.MULTILINE) | |
324 |
|
288 | |||
325 | str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str) |
|
289 | str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str) | |
326 | str = cmd_re.sub(r'\\texttt{\g<cmd>}',str) |
|
290 | str = cmd_re.sub(r'\\texttt{\g<cmd>}',str) | |
327 | str = par_re.sub(r'\\\\',str) |
|
291 | str = par_re.sub(r'\\\\',str) | |
328 | str = escape_re.sub(r'\\\1',str) |
|
292 | str = escape_re.sub(r'\\\1',str) | |
329 | return str |
|
293 | return str | |
330 |
|
294 | |||
331 | def format_screen(self,str): |
|
295 | def format_screen(self,str): | |
332 | """Format a string for screen printing. |
|
296 | """Format a string for screen printing. | |
333 |
|
297 | |||
334 | This removes some latex-type format codes.""" |
|
298 | This removes some latex-type format codes.""" | |
335 | # Paragraph continue |
|
299 | # Paragraph continue | |
336 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
300 | par_re = re.compile(r'\\$',re.MULTILINE) | |
337 | str = par_re.sub('',str) |
|
301 | str = par_re.sub('',str) | |
338 | return str |
|
302 | return str | |
339 |
|
303 | |||
340 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
304 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
341 | """Parse options passed to an argument string. |
|
305 | """Parse options passed to an argument string. | |
342 |
|
306 | |||
343 | The interface is similar to that of getopt(), but it returns back a |
|
307 | The interface is similar to that of getopt(), but it returns back a | |
344 | Struct with the options as keys and the stripped argument string still |
|
308 | Struct with the options as keys and the stripped argument string still | |
345 | as a string. |
|
309 | as a string. | |
346 |
|
310 | |||
347 | arg_str is quoted as a true sys.argv vector by calling on the fly a |
|
311 | arg_str is quoted as a true sys.argv vector by calling on the fly a | |
348 | python process in a subshell. This allows us to easily expand |
|
312 | python process in a subshell. This allows us to easily expand | |
349 | variables, glob files, quote arguments, etc, with all the power and |
|
313 | variables, glob files, quote arguments, etc, with all the power and | |
350 | correctness of the underlying system shell. |
|
314 | correctness of the underlying system shell. | |
351 |
|
315 | |||
352 | Options: |
|
316 | Options: | |
353 | -mode: default 'string'. If given as 'list', the argument string is |
|
317 | -mode: default 'string'. If given as 'list', the argument string is | |
354 | returned as a list (split on whitespace) instead of a string. |
|
318 | returned as a list (split on whitespace) instead of a string. | |
355 |
|
319 | |||
356 | -list_all: put all option values in lists. Normally only options |
|
320 | -list_all: put all option values in lists. Normally only options | |
357 | appearing more than once are put in a list.""" |
|
321 | appearing more than once are put in a list.""" | |
358 |
|
322 | |||
359 | # inject default options at the beginning of the input line |
|
323 | # inject default options at the beginning of the input line | |
360 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
324 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
361 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
325 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
362 |
|
326 | |||
363 | mode = kw.get('mode','string') |
|
327 | mode = kw.get('mode','string') | |
364 | if mode not in ['string','list']: |
|
328 | if mode not in ['string','list']: | |
365 | raise ValueError,'incorrect mode given: %s' % mode |
|
329 | raise ValueError,'incorrect mode given: %s' % mode | |
366 | # Get options |
|
330 | # Get options | |
367 | list_all = kw.get('list_all',0) |
|
331 | list_all = kw.get('list_all',0) | |
368 |
|
332 | |||
369 | # Check if we have more than one argument to warrant extra processing: |
|
333 | # Check if we have more than one argument to warrant extra processing: | |
370 | odict = {} # Dictionary with options |
|
334 | odict = {} # Dictionary with options | |
371 | args = arg_str.split() |
|
335 | args = arg_str.split() | |
372 | if len(args) >= 1: |
|
336 | if len(args) >= 1: | |
373 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
337 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
374 | # need to look for options |
|
338 | # need to look for options | |
375 | argv = shlex_split(arg_str) |
|
339 | argv = shlex_split(arg_str) | |
376 | # Do regular option processing |
|
340 | # Do regular option processing | |
377 | opts,args = getopt(argv,opt_str,*long_opts) |
|
341 | opts,args = getopt(argv,opt_str,*long_opts) | |
378 | for o,a in opts: |
|
342 | for o,a in opts: | |
379 | if o.startswith('--'): |
|
343 | if o.startswith('--'): | |
380 | o = o[2:] |
|
344 | o = o[2:] | |
381 | else: |
|
345 | else: | |
382 | o = o[1:] |
|
346 | o = o[1:] | |
383 | try: |
|
347 | try: | |
384 | odict[o].append(a) |
|
348 | odict[o].append(a) | |
385 | except AttributeError: |
|
349 | except AttributeError: | |
386 | odict[o] = [odict[o],a] |
|
350 | odict[o] = [odict[o],a] | |
387 | except KeyError: |
|
351 | except KeyError: | |
388 | if list_all: |
|
352 | if list_all: | |
389 | odict[o] = [a] |
|
353 | odict[o] = [a] | |
390 | else: |
|
354 | else: | |
391 | odict[o] = a |
|
355 | odict[o] = a | |
392 |
|
356 | |||
393 | # Prepare opts,args for return |
|
357 | # Prepare opts,args for return | |
394 | opts = Struct(odict) |
|
358 | opts = Struct(odict) | |
395 | if mode == 'string': |
|
359 | if mode == 'string': | |
396 | args = ' '.join(args) |
|
360 | args = ' '.join(args) | |
397 |
|
361 | |||
398 | return opts,args |
|
362 | return opts,args | |
399 |
|
363 | |||
400 | #...................................................................... |
|
364 | #...................................................................... | |
401 | # And now the actual magic functions |
|
365 | # And now the actual magic functions | |
402 |
|
366 | |||
403 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
367 | # Functions for IPython shell work (vars,funcs, config, etc) | |
404 | def magic_lsmagic(self, parameter_s = ''): |
|
368 | def magic_lsmagic(self, parameter_s = ''): | |
405 | """List currently available magic functions.""" |
|
369 | """List currently available magic functions.""" | |
406 | mesc = self.shell.ESC_MAGIC |
|
370 | mesc = self.shell.ESC_MAGIC | |
407 | print 'Available magic functions:\n'+mesc+\ |
|
371 | print 'Available magic functions:\n'+mesc+\ | |
408 | (' '+mesc).join(self.lsmagic()) |
|
372 | (' '+mesc).join(self.lsmagic()) | |
409 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
373 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
410 | return None |
|
374 | return None | |
411 |
|
375 | |||
412 | def magic_magic(self, parameter_s = ''): |
|
376 | def magic_magic(self, parameter_s = ''): | |
413 | """Print information about the magic function system.""" |
|
377 | """Print information about the magic function system.""" | |
414 |
|
378 | |||
415 | mode = '' |
|
379 | mode = '' | |
416 | try: |
|
380 | try: | |
417 | if parameter_s.split()[0] == '-latex': |
|
381 | if parameter_s.split()[0] == '-latex': | |
418 | mode = 'latex' |
|
382 | mode = 'latex' | |
419 | except: |
|
383 | except: | |
420 | pass |
|
384 | pass | |
421 |
|
385 | |||
422 | magic_docs = [] |
|
386 | magic_docs = [] | |
423 | for fname in self.lsmagic(): |
|
387 | for fname in self.lsmagic(): | |
424 | mname = 'magic_' + fname |
|
388 | mname = 'magic_' + fname | |
425 | for space in (Magic,self,self.__class__): |
|
389 | for space in (Magic,self,self.__class__): | |
426 | try: |
|
390 | try: | |
427 | fn = space.__dict__[mname] |
|
391 | fn = space.__dict__[mname] | |
428 | except KeyError: |
|
392 | except KeyError: | |
429 | pass |
|
393 | pass | |
430 | else: |
|
394 | else: | |
431 | break |
|
395 | break | |
432 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
396 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
433 | fname,fn.__doc__)) |
|
397 | fname,fn.__doc__)) | |
434 | magic_docs = ''.join(magic_docs) |
|
398 | magic_docs = ''.join(magic_docs) | |
435 |
|
399 | |||
436 | if mode == 'latex': |
|
400 | if mode == 'latex': | |
437 | print self.format_latex(magic_docs) |
|
401 | print self.format_latex(magic_docs) | |
438 | return |
|
402 | return | |
439 | else: |
|
403 | else: | |
440 | magic_docs = self.format_screen(magic_docs) |
|
404 | magic_docs = self.format_screen(magic_docs) | |
441 |
|
405 | |||
442 | outmsg = """ |
|
406 | outmsg = """ | |
443 | IPython's 'magic' functions |
|
407 | IPython's 'magic' functions | |
444 | =========================== |
|
408 | =========================== | |
445 |
|
409 | |||
446 | The magic function system provides a series of functions which allow you to |
|
410 | The magic function system provides a series of functions which allow you to | |
447 | control the behavior of IPython itself, plus a lot of system-type |
|
411 | control the behavior of IPython itself, plus a lot of system-type | |
448 | features. All these functions are prefixed with a % character, but parameters |
|
412 | features. All these functions are prefixed with a % character, but parameters | |
449 | are given without parentheses or quotes. |
|
413 | are given without parentheses or quotes. | |
450 |
|
414 | |||
451 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
415 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
452 | %automagic function), you don't need to type in the % explicitly. By default, |
|
416 | %automagic function), you don't need to type in the % explicitly. By default, | |
453 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
417 | IPython ships with automagic on, so you should only rarely need the % escape. | |
454 |
|
418 | |||
455 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
419 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
456 | to 'mydir', if it exists. |
|
420 | to 'mydir', if it exists. | |
457 |
|
421 | |||
458 | You can define your own magic functions to extend the system. See the supplied |
|
422 | You can define your own magic functions to extend the system. See the supplied | |
459 | ipythonrc and example-magic.py files for details (in your ipython |
|
423 | ipythonrc and example-magic.py files for details (in your ipython | |
460 | configuration directory, typically $HOME/.ipython/). |
|
424 | configuration directory, typically $HOME/.ipython/). | |
461 |
|
425 | |||
462 | You can also define your own aliased names for magic functions. In your |
|
426 | You can also define your own aliased names for magic functions. In your | |
463 | ipythonrc file, placing a line like: |
|
427 | ipythonrc file, placing a line like: | |
464 |
|
428 | |||
465 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
429 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
466 |
|
430 | |||
467 | will define %pf as a new name for %profile. |
|
431 | will define %pf as a new name for %profile. | |
468 |
|
432 | |||
469 | You can also call magics in code using the ipmagic() function, which IPython |
|
433 | You can also call magics in code using the ipmagic() function, which IPython | |
470 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
434 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
471 |
|
435 | |||
472 | For a list of the available magic functions, use %lsmagic. For a description |
|
436 | For a list of the available magic functions, use %lsmagic. For a description | |
473 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
437 | of any of them, type %magic_name?, e.g. '%cd?'. | |
474 |
|
438 | |||
475 | Currently the magic system has the following functions:\n""" |
|
439 | Currently the magic system has the following functions:\n""" | |
476 |
|
440 | |||
477 | mesc = self.shell.ESC_MAGIC |
|
441 | mesc = self.shell.ESC_MAGIC | |
478 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
442 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
479 | "\n\n%s%s\n\n%s" % (outmsg, |
|
443 | "\n\n%s%s\n\n%s" % (outmsg, | |
480 | magic_docs,mesc,mesc, |
|
444 | magic_docs,mesc,mesc, | |
481 | (' '+mesc).join(self.lsmagic()), |
|
445 | (' '+mesc).join(self.lsmagic()), | |
482 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
446 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
483 |
|
447 | |||
484 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
448 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
485 |
|
449 | |||
486 | def magic_automagic(self, parameter_s = ''): |
|
450 | def magic_automagic(self, parameter_s = ''): | |
487 | """Make magic functions callable without having to type the initial %. |
|
451 | """Make magic functions callable without having to type the initial %. | |
488 |
|
452 | |||
489 | Toggles on/off (when off, you must call it as %automagic, of |
|
453 | Toggles on/off (when off, you must call it as %automagic, of | |
490 | course). Note that magic functions have lowest priority, so if there's |
|
454 | course). Note that magic functions have lowest priority, so if there's | |
491 | a variable whose name collides with that of a magic fn, automagic |
|
455 | a variable whose name collides with that of a magic fn, automagic | |
492 | won't work for that function (you get the variable instead). However, |
|
456 | won't work for that function (you get the variable instead). However, | |
493 | if you delete the variable (del var), the previously shadowed magic |
|
457 | if you delete the variable (del var), the previously shadowed magic | |
494 | function becomes visible to automagic again.""" |
|
458 | function becomes visible to automagic again.""" | |
495 |
|
459 | |||
496 | rc = self.shell.rc |
|
460 | rc = self.shell.rc | |
497 | rc.automagic = not rc.automagic |
|
461 | rc.automagic = not rc.automagic | |
498 | print '\n' + Magic.auto_status[rc.automagic] |
|
462 | print '\n' + Magic.auto_status[rc.automagic] | |
499 |
|
463 | |||
500 | def magic_autocall(self, parameter_s = ''): |
|
464 | def magic_autocall(self, parameter_s = ''): | |
501 | """Make functions callable without having to type parentheses. |
|
465 | """Make functions callable without having to type parentheses. | |
502 |
|
466 | |||
503 | This toggles the autocall command line option on and off.""" |
|
467 | This toggles the autocall command line option on and off.""" | |
504 |
|
468 | |||
505 | rc = self.shell.rc |
|
469 | rc = self.shell.rc | |
506 | rc.autocall = not rc.autocall |
|
470 | rc.autocall = not rc.autocall | |
507 | print "Automatic calling is:",['OFF','ON'][rc.autocall] |
|
471 | print "Automatic calling is:",['OFF','ON'][rc.autocall] | |
508 |
|
472 | |||
509 | def magic_autoindent(self, parameter_s = ''): |
|
473 | def magic_autoindent(self, parameter_s = ''): | |
510 | """Toggle autoindent on/off (if available).""" |
|
474 | """Toggle autoindent on/off (if available).""" | |
511 |
|
475 | |||
512 | self.shell.set_autoindent() |
|
476 | self.shell.set_autoindent() | |
513 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
477 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
514 |
|
478 | |||
515 | def magic_system_verbose(self, parameter_s = ''): |
|
479 | def magic_system_verbose(self, parameter_s = ''): | |
516 | """Toggle verbose printing of system calls on/off.""" |
|
480 | """Toggle verbose printing of system calls on/off.""" | |
517 |
|
481 | |||
518 | self.shell.rc_set_toggle('system_verbose') |
|
482 | self.shell.rc_set_toggle('system_verbose') | |
519 | print "System verbose printing is:",\ |
|
483 | print "System verbose printing is:",\ | |
520 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
484 | ['OFF','ON'][self.shell.rc.system_verbose] | |
521 |
|
485 | |||
522 | def magic_history(self, parameter_s = ''): |
|
486 | def magic_history(self, parameter_s = ''): | |
523 | """Print input history (_i<n> variables), with most recent last. |
|
487 | """Print input history (_i<n> variables), with most recent last. | |
524 |
|
488 | |||
525 | %history [-n] -> print at most 40 inputs (some may be multi-line)\\ |
|
489 | %history [-n] -> print at most 40 inputs (some may be multi-line)\\ | |
526 | %history [-n] n -> print at most n inputs\\ |
|
490 | %history [-n] n -> print at most n inputs\\ | |
527 | %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
491 | %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
528 |
|
492 | |||
529 | Each input's number <n> is shown, and is accessible as the |
|
493 | Each input's number <n> is shown, and is accessible as the | |
530 | automatically generated variable _i<n>. Multi-line statements are |
|
494 | automatically generated variable _i<n>. Multi-line statements are | |
531 | printed starting at a new line for easy copy/paste. |
|
495 | printed starting at a new line for easy copy/paste. | |
532 |
|
496 | |||
533 | If option -n is used, input numbers are not printed. This is useful if |
|
497 | If option -n is used, input numbers are not printed. This is useful if | |
534 | you want to get a printout of many lines which can be directly pasted |
|
498 | you want to get a printout of many lines which can be directly pasted | |
535 | into a text editor. |
|
499 | into a text editor. | |
536 |
|
500 | |||
537 | This feature is only available if numbered prompts are in use.""" |
|
501 | This feature is only available if numbered prompts are in use.""" | |
538 |
|
502 | |||
539 | if not self.do_full_cache: |
|
503 | if not self.do_full_cache: | |
540 | print 'This feature is only available if numbered prompts are in use.' |
|
504 | print 'This feature is only available if numbered prompts are in use.' | |
541 | return |
|
505 | return | |
542 | opts,args = self.parse_options(parameter_s,'n',mode='list') |
|
506 | opts,args = self.parse_options(parameter_s,'n',mode='list') | |
543 |
|
507 | |||
544 | default_length = 40 |
|
508 | default_length = 40 | |
545 | if len(args) == 0: |
|
509 | if len(args) == 0: | |
546 | final = self.outputcache.prompt_count |
|
510 | final = self.outputcache.prompt_count | |
547 | init = max(1,final-default_length) |
|
511 | init = max(1,final-default_length) | |
548 | elif len(args) == 1: |
|
512 | elif len(args) == 1: | |
549 | final = self.outputcache.prompt_count |
|
513 | final = self.outputcache.prompt_count | |
550 | init = max(1,final-int(args[0])) |
|
514 | init = max(1,final-int(args[0])) | |
551 | elif len(args) == 2: |
|
515 | elif len(args) == 2: | |
552 | init,final = map(int,args) |
|
516 | init,final = map(int,args) | |
553 | else: |
|
517 | else: | |
554 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
518 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
555 | print self.magic_hist.__doc__ |
|
519 | print self.magic_hist.__doc__ | |
556 | return |
|
520 | return | |
557 | width = len(str(final)) |
|
521 | width = len(str(final)) | |
558 | line_sep = ['','\n'] |
|
522 | line_sep = ['','\n'] | |
559 | input_hist = self.shell.input_hist |
|
523 | input_hist = self.shell.input_hist | |
560 | print_nums = not opts.has_key('n') |
|
524 | print_nums = not opts.has_key('n') | |
561 | for in_num in range(init,final): |
|
525 | for in_num in range(init,final): | |
562 | inline = input_hist[in_num] |
|
526 | inline = input_hist[in_num] | |
563 | multiline = inline.count('\n') > 1 |
|
527 | multiline = inline.count('\n') > 1 | |
564 | if print_nums: |
|
528 | if print_nums: | |
565 | print str(in_num).ljust(width)+':'+ line_sep[multiline], |
|
529 | print str(in_num).ljust(width)+':'+ line_sep[multiline], | |
566 | if inline.startswith('#'+self.shell.ESC_MAGIC) or \ |
|
530 | if inline.startswith('#'+self.shell.ESC_MAGIC) or \ | |
567 | inline.startswith('#!'): |
|
531 | inline.startswith('#!'): | |
568 | print inline[1:], |
|
532 | print inline[1:], | |
569 | else: |
|
533 | else: | |
570 | print inline, |
|
534 | print inline, | |
571 |
|
535 | |||
572 | def magic_hist(self, parameter_s=''): |
|
536 | def magic_hist(self, parameter_s=''): | |
573 | """Alternate name for %history.""" |
|
537 | """Alternate name for %history.""" | |
574 | return self.magic_history(parameter_s) |
|
538 | return self.magic_history(parameter_s) | |
575 |
|
539 | |||
576 | def magic_p(self, parameter_s=''): |
|
540 | def magic_p(self, parameter_s=''): | |
577 | """Just a short alias for Python's 'print'.""" |
|
541 | """Just a short alias for Python's 'print'.""" | |
578 | exec 'print ' + parameter_s in self.shell.user_ns |
|
542 | exec 'print ' + parameter_s in self.shell.user_ns | |
579 |
|
543 | |||
580 | def magic_r(self, parameter_s=''): |
|
544 | def magic_r(self, parameter_s=''): | |
581 | """Repeat previous input. |
|
545 | """Repeat previous input. | |
582 |
|
546 | |||
583 | If given an argument, repeats the previous command which starts with |
|
547 | If given an argument, repeats the previous command which starts with | |
584 | the same string, otherwise it just repeats the previous input. |
|
548 | the same string, otherwise it just repeats the previous input. | |
585 |
|
549 | |||
586 | Shell escaped commands (with ! as first character) are not recognized |
|
550 | Shell escaped commands (with ! as first character) are not recognized | |
587 | by this system, only pure python code and magic commands. |
|
551 | by this system, only pure python code and magic commands. | |
588 | """ |
|
552 | """ | |
589 |
|
553 | |||
590 | start = parameter_s.strip() |
|
554 | start = parameter_s.strip() | |
591 | esc_magic = self.shell.ESC_MAGIC |
|
555 | esc_magic = self.shell.ESC_MAGIC | |
592 | # Identify magic commands even if automagic is on (which means |
|
556 | # Identify magic commands even if automagic is on (which means | |
593 | # the in-memory version is different from that typed by the user). |
|
557 | # the in-memory version is different from that typed by the user). | |
594 | if self.shell.rc.automagic: |
|
558 | if self.shell.rc.automagic: | |
595 | start_magic = esc_magic+start |
|
559 | start_magic = esc_magic+start | |
596 | else: |
|
560 | else: | |
597 | start_magic = start |
|
561 | start_magic = start | |
598 | # Look through the input history in reverse |
|
562 | # Look through the input history in reverse | |
599 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
563 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
600 | input = self.shell.input_hist[n] |
|
564 | input = self.shell.input_hist[n] | |
601 | # skip plain 'r' lines so we don't recurse to infinity |
|
565 | # skip plain 'r' lines so we don't recurse to infinity | |
602 | if input != 'ipmagic("r")\n' and \ |
|
566 | if input != 'ipmagic("r")\n' and \ | |
603 | (input.startswith(start) or input.startswith(start_magic)): |
|
567 | (input.startswith(start) or input.startswith(start_magic)): | |
604 | #print 'match',`input` # dbg |
|
568 | #print 'match',`input` # dbg | |
605 | if input.startswith(esc_magic): |
|
569 | if input.startswith(esc_magic): | |
606 | input = magic2python(input) |
|
570 | input = magic2python(input) | |
607 | #print 'modified',`input` # dbg |
|
571 | #print 'modified',`input` # dbg | |
608 | print 'Executing:',input, |
|
572 | print 'Executing:',input, | |
609 | exec input in self.shell.user_ns |
|
573 | exec input in self.shell.user_ns | |
610 | return |
|
574 | return | |
611 | print 'No previous input matching `%s` found.' % start |
|
575 | print 'No previous input matching `%s` found.' % start | |
612 |
|
576 | |||
613 | def magic_page(self, parameter_s=''): |
|
577 | def magic_page(self, parameter_s=''): | |
614 | """Pretty print the object and display it through a pager. |
|
578 | """Pretty print the object and display it through a pager. | |
615 |
|
579 | |||
616 | If no parameter is given, use _ (last output).""" |
|
580 | If no parameter is given, use _ (last output).""" | |
617 | # After a function contributed by Olivier Aubert, slightly modified. |
|
581 | # After a function contributed by Olivier Aubert, slightly modified. | |
618 |
|
582 | |||
619 | oname = parameter_s and parameter_s or '_' |
|
583 | oname = parameter_s and parameter_s or '_' | |
620 | info = self._ofind(oname) |
|
584 | info = self._ofind(oname) | |
621 | if info['found']: |
|
585 | if info['found']: | |
622 | page(pformat(info['obj'])) |
|
586 | page(pformat(info['obj'])) | |
623 | else: |
|
587 | else: | |
624 | print 'Object `%s` not found' % oname |
|
588 | print 'Object `%s` not found' % oname | |
625 |
|
589 | |||
626 | def magic_profile(self, parameter_s=''): |
|
590 | def magic_profile(self, parameter_s=''): | |
627 | """Print your currently active IPyhton profile.""" |
|
591 | """Print your currently active IPyhton profile.""" | |
628 | if self.shell.rc.profile: |
|
592 | if self.shell.rc.profile: | |
629 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
593 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
630 | else: |
|
594 | else: | |
631 | print 'No profile active.' |
|
595 | print 'No profile active.' | |
632 |
|
596 | |||
633 | def _inspect(self,meth,oname,**kw): |
|
597 | def _inspect(self,meth,oname,**kw): | |
634 | """Generic interface to the inspector system. |
|
598 | """Generic interface to the inspector system. | |
635 |
|
599 | |||
636 | This function is meant to be called by pdef, pdoc & friends.""" |
|
600 | This function is meant to be called by pdef, pdoc & friends.""" | |
637 |
|
601 | |||
638 | oname = oname.strip() |
|
602 | oname = oname.strip() | |
639 | info = Struct(self._ofind(oname)) |
|
603 | info = Struct(self._ofind(oname)) | |
640 | if info.found: |
|
604 | if info.found: | |
641 | pmethod = getattr(self.shell.inspector,meth) |
|
605 | pmethod = getattr(self.shell.inspector,meth) | |
642 | formatter = info.ismagic and self.format_screen or None |
|
606 | formatter = info.ismagic and self.format_screen or None | |
643 | if meth == 'pdoc': |
|
607 | if meth == 'pdoc': | |
644 | pmethod(info.obj,oname,formatter) |
|
608 | pmethod(info.obj,oname,formatter) | |
645 | elif meth == 'pinfo': |
|
609 | elif meth == 'pinfo': | |
646 | pmethod(info.obj,oname,formatter,info,**kw) |
|
610 | pmethod(info.obj,oname,formatter,info,**kw) | |
647 | else: |
|
611 | else: | |
648 | pmethod(info.obj,oname) |
|
612 | pmethod(info.obj,oname) | |
649 | else: |
|
613 | else: | |
650 | print 'Object `%s` not found.' % oname |
|
614 | print 'Object `%s` not found.' % oname | |
651 | return 'not found' # so callers can take other action |
|
615 | return 'not found' # so callers can take other action | |
652 |
|
616 | |||
653 | def magic_pdef(self, parameter_s=''): |
|
617 | def magic_pdef(self, parameter_s=''): | |
654 | """Print the definition header for any callable object. |
|
618 | """Print the definition header for any callable object. | |
655 |
|
619 | |||
656 | If the object is a class, print the constructor information.""" |
|
620 | If the object is a class, print the constructor information.""" | |
657 | self._inspect('pdef',parameter_s) |
|
621 | self._inspect('pdef',parameter_s) | |
658 |
|
622 | |||
659 | def magic_pdoc(self, parameter_s=''): |
|
623 | def magic_pdoc(self, parameter_s=''): | |
660 | """Print the docstring for an object. |
|
624 | """Print the docstring for an object. | |
661 |
|
625 | |||
662 | If the given object is a class, it will print both the class and the |
|
626 | If the given object is a class, it will print both the class and the | |
663 | constructor docstrings.""" |
|
627 | constructor docstrings.""" | |
664 | self._inspect('pdoc',parameter_s) |
|
628 | self._inspect('pdoc',parameter_s) | |
665 |
|
629 | |||
666 | def magic_psource(self, parameter_s=''): |
|
630 | def magic_psource(self, parameter_s=''): | |
667 | """Print (or run through pager) the source code for an object.""" |
|
631 | """Print (or run through pager) the source code for an object.""" | |
668 | self._inspect('psource',parameter_s) |
|
632 | self._inspect('psource',parameter_s) | |
669 |
|
633 | |||
670 | def magic_pfile(self, parameter_s=''): |
|
634 | def magic_pfile(self, parameter_s=''): | |
671 | """Print (or run through pager) the file where an object is defined. |
|
635 | """Print (or run through pager) the file where an object is defined. | |
672 |
|
636 | |||
673 | The file opens at the line where the object definition begins. IPython |
|
637 | The file opens at the line where the object definition begins. IPython | |
674 | will honor the environment variable PAGER if set, and otherwise will |
|
638 | will honor the environment variable PAGER if set, and otherwise will | |
675 | do its best to print the file in a convenient form. |
|
639 | do its best to print the file in a convenient form. | |
676 |
|
640 | |||
677 | If the given argument is not an object currently defined, IPython will |
|
641 | If the given argument is not an object currently defined, IPython will | |
678 | try to interpret it as a filename (automatically adding a .py extension |
|
642 | try to interpret it as a filename (automatically adding a .py extension | |
679 | if needed). You can thus use %pfile as a syntax highlighting code |
|
643 | if needed). You can thus use %pfile as a syntax highlighting code | |
680 | viewer.""" |
|
644 | viewer.""" | |
681 |
|
645 | |||
682 | # first interpret argument as an object name |
|
646 | # first interpret argument as an object name | |
683 | out = self._inspect('pfile',parameter_s) |
|
647 | out = self._inspect('pfile',parameter_s) | |
684 | # if not, try the input as a filename |
|
648 | # if not, try the input as a filename | |
685 | if out == 'not found': |
|
649 | if out == 'not found': | |
686 | try: |
|
650 | try: | |
687 | filename = get_py_filename(parameter_s) |
|
651 | filename = get_py_filename(parameter_s) | |
688 | except IOError,msg: |
|
652 | except IOError,msg: | |
689 | print msg |
|
653 | print msg | |
690 | return |
|
654 | return | |
691 | page(self.shell.inspector.format(file(filename).read())) |
|
655 | page(self.shell.inspector.format(file(filename).read())) | |
692 |
|
656 | |||
693 | def magic_pinfo(self, parameter_s=''): |
|
657 | def magic_pinfo(self, parameter_s=''): | |
694 | """Provide detailed information about an object. |
|
658 | """Provide detailed information about an object. | |
695 |
|
659 | |||
696 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
660 | '%pinfo object' is just a synonym for object? or ?object.""" | |
697 |
|
661 | |||
698 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
662 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
699 |
|
663 | |||
700 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
664 | # detail_level: 0 -> obj? , 1 -> obj?? | |
701 | detail_level = 0 |
|
665 | detail_level = 0 | |
702 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
666 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
703 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
667 | # happen if the user types 'pinfo foo?' at the cmd line. | |
704 | pinfo,qmark1,oname,qmark2 = \ |
|
668 | pinfo,qmark1,oname,qmark2 = \ | |
705 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
669 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
706 | if pinfo or qmark1 or qmark2: |
|
670 | if pinfo or qmark1 or qmark2: | |
707 | detail_level = 1 |
|
671 | detail_level = 1 | |
708 | self._inspect('pinfo',oname,detail_level=detail_level) |
|
672 | self._inspect('pinfo',oname,detail_level=detail_level) | |
709 |
|
673 | |||
710 | def magic_who_ls(self, parameter_s=''): |
|
674 | def magic_who_ls(self, parameter_s=''): | |
711 | """Return a sorted list of all interactive variables. |
|
675 | """Return a sorted list of all interactive variables. | |
712 |
|
676 | |||
713 | If arguments are given, only variables of types matching these |
|
677 | If arguments are given, only variables of types matching these | |
714 | arguments are returned.""" |
|
678 | arguments are returned.""" | |
715 |
|
679 | |||
716 | user_ns = self.shell.user_ns |
|
680 | user_ns = self.shell.user_ns | |
717 | out = [] |
|
681 | out = [] | |
718 | typelist = parameter_s.split() |
|
682 | typelist = parameter_s.split() | |
719 | for i in self.shell.user_ns.keys(): |
|
683 | for i in self.shell.user_ns.keys(): | |
720 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
684 | if not (i.startswith('_') or i.startswith('_i')) \ | |
721 | and not (self.internal_ns.has_key(i) or |
|
685 | and not (self.internal_ns.has_key(i) or | |
722 | self.user_config_ns.has_key(i)): |
|
686 | self.user_config_ns.has_key(i)): | |
723 | if typelist: |
|
687 | if typelist: | |
724 | if type(user_ns[i]).__name__ in typelist: |
|
688 | if type(user_ns[i]).__name__ in typelist: | |
725 | out.append(i) |
|
689 | out.append(i) | |
726 | else: |
|
690 | else: | |
727 | out.append(i) |
|
691 | out.append(i) | |
728 | out.sort() |
|
692 | out.sort() | |
729 | return out |
|
693 | return out | |
730 |
|
694 | |||
731 | def magic_who(self, parameter_s=''): |
|
695 | def magic_who(self, parameter_s=''): | |
732 | """Print all interactive variables, with some minimal formatting. |
|
696 | """Print all interactive variables, with some minimal formatting. | |
733 |
|
697 | |||
734 | If any arguments are given, only variables whose type matches one of |
|
698 | If any arguments are given, only variables whose type matches one of | |
735 | these are printed. For example: |
|
699 | these are printed. For example: | |
736 |
|
700 | |||
737 | %who function str |
|
701 | %who function str | |
738 |
|
702 | |||
739 | will only list functions and strings, excluding all other types of |
|
703 | will only list functions and strings, excluding all other types of | |
740 | variables. To find the proper type names, simply use type(var) at a |
|
704 | variables. To find the proper type names, simply use type(var) at a | |
741 | command line to see how python prints type names. For example: |
|
705 | command line to see how python prints type names. For example: | |
742 |
|
706 | |||
743 | In [1]: type('hello')\\ |
|
707 | In [1]: type('hello')\\ | |
744 | Out[1]: <type 'str'> |
|
708 | Out[1]: <type 'str'> | |
745 |
|
709 | |||
746 | indicates that the type name for strings is 'str'. |
|
710 | indicates that the type name for strings is 'str'. | |
747 |
|
711 | |||
748 | %who always excludes executed names loaded through your configuration |
|
712 | %who always excludes executed names loaded through your configuration | |
749 | file and things which are internal to IPython. |
|
713 | file and things which are internal to IPython. | |
750 |
|
714 | |||
751 | This is deliberate, as typically you may load many modules and the |
|
715 | This is deliberate, as typically you may load many modules and the | |
752 | purpose of %who is to show you only what you've manually defined.""" |
|
716 | purpose of %who is to show you only what you've manually defined.""" | |
753 |
|
717 | |||
754 | varlist = self.magic_who_ls(parameter_s) |
|
718 | varlist = self.magic_who_ls(parameter_s) | |
755 | if not varlist: |
|
719 | if not varlist: | |
756 | print 'Interactive namespace is empty.' |
|
720 | print 'Interactive namespace is empty.' | |
757 | return |
|
721 | return | |
758 |
|
722 | |||
759 | # if we have variables, move on... |
|
723 | # if we have variables, move on... | |
760 |
|
724 | |||
761 | # stupid flushing problem: when prompts have no separators, stdout is |
|
725 | # stupid flushing problem: when prompts have no separators, stdout is | |
762 | # getting lost. I'm starting to think this is a python bug. I'm having |
|
726 | # getting lost. I'm starting to think this is a python bug. I'm having | |
763 | # to force a flush with a print because even a sys.stdout.flush |
|
727 | # to force a flush with a print because even a sys.stdout.flush | |
764 | # doesn't seem to do anything! |
|
728 | # doesn't seem to do anything! | |
765 |
|
729 | |||
766 | count = 0 |
|
730 | count = 0 | |
767 | for i in varlist: |
|
731 | for i in varlist: | |
768 | print i+'\t', |
|
732 | print i+'\t', | |
769 | count += 1 |
|
733 | count += 1 | |
770 | if count > 8: |
|
734 | if count > 8: | |
771 | count = 0 |
|
735 | count = 0 | |
772 |
|
736 | |||
773 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? |
|
737 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? | |
774 |
|
738 | |||
775 | print # well, this does force a flush at the expense of an extra \n |
|
739 | print # well, this does force a flush at the expense of an extra \n | |
776 |
|
740 | |||
777 | def magic_whos(self, parameter_s=''): |
|
741 | def magic_whos(self, parameter_s=''): | |
778 | """Like %who, but gives some extra information about each variable. |
|
742 | """Like %who, but gives some extra information about each variable. | |
779 |
|
743 | |||
780 | The same type filtering of %who can be applied here. |
|
744 | The same type filtering of %who can be applied here. | |
781 |
|
745 | |||
782 | For all variables, the type is printed. Additionally it prints: |
|
746 | For all variables, the type is printed. Additionally it prints: | |
783 |
|
747 | |||
784 | - For {},[],(): their length. |
|
748 | - For {},[],(): their length. | |
785 |
|
749 | |||
786 | - For Numeric arrays, a summary with shape, number of elements, |
|
750 | - For Numeric arrays, a summary with shape, number of elements, | |
787 | typecode and size in memory. |
|
751 | typecode and size in memory. | |
788 |
|
752 | |||
789 | - Everything else: a string representation, snipping their middle if |
|
753 | - Everything else: a string representation, snipping their middle if | |
790 | too long.""" |
|
754 | too long.""" | |
791 |
|
755 | |||
792 | varnames = self.magic_who_ls(parameter_s) |
|
756 | varnames = self.magic_who_ls(parameter_s) | |
793 | if not varnames: |
|
757 | if not varnames: | |
794 | print 'Interactive namespace is empty.' |
|
758 | print 'Interactive namespace is empty.' | |
795 | return |
|
759 | return | |
796 |
|
760 | |||
797 | # if we have variables, move on... |
|
761 | # if we have variables, move on... | |
798 |
|
762 | |||
799 | # for these types, show len() instead of data: |
|
763 | # for these types, show len() instead of data: | |
800 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
764 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
801 |
|
765 | |||
802 | # for Numeric arrays, display summary info |
|
766 | # for Numeric arrays, display summary info | |
803 | try: |
|
767 | try: | |
804 | import Numeric |
|
768 | import Numeric | |
805 | except ImportError: |
|
769 | except ImportError: | |
806 | array_type = None |
|
770 | array_type = None | |
807 | else: |
|
771 | else: | |
808 | array_type = Numeric.ArrayType.__name__ |
|
772 | array_type = Numeric.ArrayType.__name__ | |
809 |
|
773 | |||
810 | # Find all variable names and types so we can figure out column sizes |
|
774 | # Find all variable names and types so we can figure out column sizes | |
811 | get_vars = lambda i: self.locals[i] |
|
775 | get_vars = lambda i: self.locals[i] | |
812 | type_name = lambda v: type(v).__name__ |
|
776 | type_name = lambda v: type(v).__name__ | |
813 | varlist = map(get_vars,varnames) |
|
777 | varlist = map(get_vars,varnames) | |
814 | typelist = map(type_name,varlist) |
|
778 | typelist = map(type_name,varlist) | |
815 | # column labels and # of spaces as separator |
|
779 | # column labels and # of spaces as separator | |
816 | varlabel = 'Variable' |
|
780 | varlabel = 'Variable' | |
817 | typelabel = 'Type' |
|
781 | typelabel = 'Type' | |
818 | datalabel = 'Data/Info' |
|
782 | datalabel = 'Data/Info' | |
819 | colsep = 3 |
|
783 | colsep = 3 | |
820 | # variable format strings |
|
784 | # variable format strings | |
821 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
785 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
822 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
786 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
823 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
787 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
824 | # find the size of the columns to format the output nicely |
|
788 | # find the size of the columns to format the output nicely | |
825 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
789 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
826 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
790 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
827 | # table header |
|
791 | # table header | |
828 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
792 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
829 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
793 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
830 | # and the table itself |
|
794 | # and the table itself | |
831 | kb = 1024 |
|
795 | kb = 1024 | |
832 | Mb = 1048576 # kb**2 |
|
796 | Mb = 1048576 # kb**2 | |
833 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
797 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
834 | print itpl(vformat), |
|
798 | print itpl(vformat), | |
835 | if vtype in seq_types: |
|
799 | if vtype in seq_types: | |
836 | print len(var) |
|
800 | print len(var) | |
837 | elif vtype==array_type: |
|
801 | elif vtype==array_type: | |
838 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
802 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
839 | vsize = Numeric.size(var) |
|
803 | vsize = Numeric.size(var) | |
840 | vbytes = vsize*var.itemsize() |
|
804 | vbytes = vsize*var.itemsize() | |
841 | if vbytes < 100000: |
|
805 | if vbytes < 100000: | |
842 | print aformat % (vshape,vsize,var.typecode(),vbytes) |
|
806 | print aformat % (vshape,vsize,var.typecode(),vbytes) | |
843 | else: |
|
807 | else: | |
844 | print aformat % (vshape,vsize,var.typecode(),vbytes), |
|
808 | print aformat % (vshape,vsize,var.typecode(),vbytes), | |
845 | if vbytes < Mb: |
|
809 | if vbytes < Mb: | |
846 | print '(%s kb)' % (vbytes/kb,) |
|
810 | print '(%s kb)' % (vbytes/kb,) | |
847 | else: |
|
811 | else: | |
848 | print '(%s Mb)' % (vbytes/Mb,) |
|
812 | print '(%s Mb)' % (vbytes/Mb,) | |
849 | else: |
|
813 | else: | |
850 | vstr = str(var) |
|
814 | vstr = str(var) | |
851 | if len(vstr) < 50: |
|
815 | if len(vstr) < 50: | |
852 | print vstr |
|
816 | print vstr | |
853 | else: |
|
817 | else: | |
854 | printpl(vfmt_short) |
|
818 | printpl(vfmt_short) | |
855 |
|
819 | |||
856 | def magic_reset(self, parameter_s=''): |
|
820 | def magic_reset(self, parameter_s=''): | |
857 | """Resets the namespace by removing all names defined by the user. |
|
821 | """Resets the namespace by removing all names defined by the user. | |
858 |
|
822 | |||
859 | Input/Output history are left around in case you need them.""" |
|
823 | Input/Output history are left around in case you need them.""" | |
860 |
|
824 | |||
861 | ans = raw_input( |
|
825 | ans = raw_input( | |
862 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") |
|
826 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") | |
863 | if not ans.lower() == 'y': |
|
827 | if not ans.lower() == 'y': | |
864 | print 'Nothing done.' |
|
828 | print 'Nothing done.' | |
865 | return |
|
829 | return | |
866 | for i in self.magic_who_ls(): |
|
830 | for i in self.magic_who_ls(): | |
867 | del(self.locals[i]) |
|
831 | del(self.locals[i]) | |
868 |
|
832 | |||
869 | def magic_config(self,parameter_s=''): |
|
833 | def magic_config(self,parameter_s=''): | |
870 | """Show IPython's internal configuration.""" |
|
834 | """Show IPython's internal configuration.""" | |
871 |
|
835 | |||
872 | page('Current configuration structure:\n'+ |
|
836 | page('Current configuration structure:\n'+ | |
873 | pformat(self.shell.rc.dict())) |
|
837 | pformat(self.shell.rc.dict())) | |
874 |
|
838 | |||
875 | def magic_logstart(self,parameter_s=''): |
|
839 | def magic_logstart(self,parameter_s=''): | |
876 | """Start logging anywhere in a session. |
|
840 | """Start logging anywhere in a session. | |
877 |
|
841 | |||
878 | %logstart [log_name [log_mode]] |
|
842 | %logstart [log_name [log_mode]] | |
879 |
|
843 | |||
880 | If no name is given, it defaults to a file named 'ipython.log' in your |
|
844 | If no name is given, it defaults to a file named 'ipython.log' in your | |
881 | current directory, in 'rotate' mode (see below). |
|
845 | current directory, in 'rotate' mode (see below). | |
882 |
|
846 | |||
883 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
847 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
884 | history up to that point and then continues logging. |
|
848 | history up to that point and then continues logging. | |
885 |
|
849 | |||
886 | %logstart takes a second optional parameter: logging mode. This can be one |
|
850 | %logstart takes a second optional parameter: logging mode. This can be one | |
887 | of (note that the modes are given unquoted):\\ |
|
851 | of (note that the modes are given unquoted):\\ | |
888 | over: overwrite existing log.\\ |
|
852 | over: overwrite existing log.\\ | |
889 | backup: rename (if exists) to name~ and start name.\\ |
|
853 | backup: rename (if exists) to name~ and start name.\\ | |
890 | append: well, that says it.\\ |
|
854 | append: well, that says it.\\ | |
891 | rotate: create rotating logs name.1~, name.2~, etc. |
|
855 | rotate: create rotating logs name.1~, name.2~, etc. | |
892 | """ |
|
856 | """ | |
893 |
|
857 | |||
894 | #FIXME. This function should all be moved to the Logger class. |
|
858 | #FIXME. This function should all be moved to the Logger class. | |
895 |
|
859 | |||
896 | valid_modes = qw('over backup append rotate') |
|
860 | valid_modes = qw('over backup append rotate') | |
897 | if self.LOG: |
|
861 | if self.LOG: | |
898 | print 'Logging is already in place. Logfile:',self.LOG |
|
862 | print 'Logging is already in place. Logfile:',self.LOG | |
899 | return |
|
863 | return | |
900 |
|
864 | |||
901 | par = parameter_s.strip() |
|
865 | par = parameter_s.strip() | |
902 | if not par: |
|
866 | if not par: | |
903 | logname = self.LOGDEF |
|
867 | logname = self.LOGDEF | |
904 | logmode = 'rotate' # use rotate for the auto-generated logs |
|
868 | logmode = 'rotate' # use rotate for the auto-generated logs | |
905 | else: |
|
869 | else: | |
906 | try: |
|
870 | try: | |
907 | logname,logmode = par.split() |
|
871 | logname,logmode = par.split() | |
908 | except: |
|
872 | except: | |
909 | try: |
|
873 | try: | |
910 | logname = par |
|
874 | logname = par | |
911 | logmode = 'backup' |
|
875 | logmode = 'backup' | |
912 | except: |
|
876 | except: | |
913 | warn('Usage: %log [log_name [log_mode]]') |
|
877 | warn('Usage: %log [log_name [log_mode]]') | |
914 | return |
|
878 | return | |
915 | if not logmode in valid_modes: |
|
879 | if not logmode in valid_modes: | |
916 | warn('Logging NOT activated.\n' |
|
880 | warn('Logging NOT activated.\n' | |
917 | 'Usage: %log [log_name [log_mode]]\n' |
|
881 | 'Usage: %log [log_name [log_mode]]\n' | |
918 | 'Valid modes: '+str(valid_modes)) |
|
882 | 'Valid modes: '+str(valid_modes)) | |
919 | return |
|
883 | return | |
920 |
|
884 | |||
921 | # If we made it this far, I think we're ok: |
|
885 | # If we made it this far, I think we're ok: | |
922 | print 'Activating auto-logging.' |
|
886 | print 'Activating auto-logging.' | |
923 | print 'Current session state plus future input saved to:',logname |
|
887 | print 'Current session state plus future input saved to:',logname | |
924 | print 'Logging mode: ',logmode |
|
888 | print 'Logging mode: ',logmode | |
925 | # put logname into rc struct as if it had been called on the command line, |
|
889 | # put logname into rc struct as if it had been called on the command line, | |
926 | # so it ends up saved in the log header |
|
890 | # so it ends up saved in the log header | |
927 | # Save it in case we need to restore it... |
|
891 | # Save it in case we need to restore it... | |
928 | old_logfile = self.shell.rc.opts.get('logfile','') |
|
892 | old_logfile = self.shell.rc.opts.get('logfile','') | |
929 | logname = os.path.expanduser(logname) |
|
893 | logname = os.path.expanduser(logname) | |
930 | self.shell.rc.opts.logfile = logname |
|
894 | self.shell.rc.opts.logfile = logname | |
931 | self.LOGMODE = logmode # FIXME: this should be set through a function. |
|
895 | self.LOGMODE = logmode # FIXME: this should be set through a function. | |
932 | try: |
|
896 | try: | |
933 | header = str(self.LOGHEAD) |
|
897 | header = str(self.LOGHEAD) | |
934 | self.create_log(header,logname) |
|
898 | self.create_log(header,logname) | |
935 | self.logstart(header,logname) |
|
899 | self.logstart(header,logname) | |
936 | except: |
|
900 | except: | |
937 | self.LOG = '' # we are NOT logging, something went wrong |
|
901 | self.LOG = '' # we are NOT logging, something went wrong | |
938 | self.shell.rc.opts.logfile = old_logfile |
|
902 | self.shell.rc.opts.logfile = old_logfile | |
939 | warn("Couldn't start log: "+str(sys.exc_info()[1])) |
|
903 | warn("Couldn't start log: "+str(sys.exc_info()[1])) | |
940 | else: # log input history up to this point |
|
904 | else: # log input history up to this point | |
941 | self.logfile.write(self.shell.user_ns['_ih'][1:]) |
|
905 | self.logfile.write(self.shell.user_ns['_ih'][1:]) | |
942 | self.logfile.flush() |
|
906 | self.logfile.flush() | |
943 |
|
907 | |||
944 | def magic_logoff(self,parameter_s=''): |
|
908 | def magic_logoff(self,parameter_s=''): | |
945 | """Temporarily stop logging. |
|
909 | """Temporarily stop logging. | |
946 |
|
910 | |||
947 | You must have previously started logging.""" |
|
911 | You must have previously started logging.""" | |
948 | self.switch_log(0) |
|
912 | self.switch_log(0) | |
949 |
|
913 | |||
950 | def magic_logon(self,parameter_s=''): |
|
914 | def magic_logon(self,parameter_s=''): | |
951 | """Restart logging. |
|
915 | """Restart logging. | |
952 |
|
916 | |||
953 | This function is for restarting logging which you've temporarily |
|
917 | This function is for restarting logging which you've temporarily | |
954 | stopped with %logoff. For starting logging for the first time, you |
|
918 | stopped with %logoff. For starting logging for the first time, you | |
955 | must use the %logstart function, which allows you to specify an |
|
919 | must use the %logstart function, which allows you to specify an | |
956 | optional log filename.""" |
|
920 | optional log filename.""" | |
957 |
|
921 | |||
958 | self.switch_log(1) |
|
922 | self.switch_log(1) | |
959 |
|
923 | |||
960 | def magic_logstate(self,parameter_s=''): |
|
924 | def magic_logstate(self,parameter_s=''): | |
961 | """Print the status of the logging system.""" |
|
925 | """Print the status of the logging system.""" | |
962 |
|
926 | |||
963 | self.logstate() |
|
927 | self.logstate() | |
964 |
|
928 | |||
965 | def magic_pdb(self, parameter_s=''): |
|
929 | def magic_pdb(self, parameter_s=''): | |
966 | """Control the calling of the pdb interactive debugger. |
|
930 | """Control the calling of the pdb interactive debugger. | |
967 |
|
931 | |||
968 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
932 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
969 | argument it works as a toggle. |
|
933 | argument it works as a toggle. | |
970 |
|
934 | |||
971 | When an exception is triggered, IPython can optionally call the |
|
935 | When an exception is triggered, IPython can optionally call the | |
972 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
936 | interactive pdb debugger after the traceback printout. %pdb toggles | |
973 | this feature on and off.""" |
|
937 | this feature on and off.""" | |
974 |
|
938 | |||
975 | par = parameter_s.strip().lower() |
|
939 | par = parameter_s.strip().lower() | |
976 |
|
940 | |||
977 | if par: |
|
941 | if par: | |
978 | try: |
|
942 | try: | |
979 | pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
943 | pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
980 | except KeyError: |
|
944 | except KeyError: | |
981 | print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.' |
|
945 | print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.' | |
982 | return |
|
946 | return | |
983 | else: |
|
947 | else: | |
984 | self.shell.InteractiveTB.call_pdb = pdb |
|
948 | self.shell.InteractiveTB.call_pdb = pdb | |
985 | else: |
|
949 | else: | |
986 | self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb |
|
950 | self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb | |
987 | print 'Automatic pdb calling has been turned',\ |
|
951 | print 'Automatic pdb calling has been turned',\ | |
988 | on_off(self.shell.InteractiveTB.call_pdb) |
|
952 | on_off(self.shell.InteractiveTB.call_pdb) | |
989 |
|
953 | |||
990 |
|
954 | |||
991 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
955 | def magic_prun(self, parameter_s ='',user_mode=1, | |
992 | opts=None,arg_lst=None,prog_ns=None): |
|
956 | opts=None,arg_lst=None,prog_ns=None): | |
993 |
|
957 | |||
994 | """Run a statement through the python code profiler. |
|
958 | """Run a statement through the python code profiler. | |
995 |
|
959 | |||
996 | Usage:\\ |
|
960 | Usage:\\ | |
997 | %prun [options] statement |
|
961 | %prun [options] statement | |
998 |
|
962 | |||
999 | The given statement (which doesn't require quote marks) is run via the |
|
963 | The given statement (which doesn't require quote marks) is run via the | |
1000 | python profiler in a manner similar to the profile.run() function. |
|
964 | python profiler in a manner similar to the profile.run() function. | |
1001 | Namespaces are internally managed to work correctly; profile.run |
|
965 | Namespaces are internally managed to work correctly; profile.run | |
1002 | cannot be used in IPython because it makes certain assumptions about |
|
966 | cannot be used in IPython because it makes certain assumptions about | |
1003 | namespaces which do not hold under IPython. |
|
967 | namespaces which do not hold under IPython. | |
1004 |
|
968 | |||
1005 | Options: |
|
969 | Options: | |
1006 |
|
970 | |||
1007 | -l <limit>: you can place restrictions on what or how much of the |
|
971 | -l <limit>: you can place restrictions on what or how much of the | |
1008 | profile gets printed. The limit value can be: |
|
972 | profile gets printed. The limit value can be: | |
1009 |
|
973 | |||
1010 | * A string: only information for function names containing this string |
|
974 | * A string: only information for function names containing this string | |
1011 | is printed. |
|
975 | is printed. | |
1012 |
|
976 | |||
1013 | * An integer: only these many lines are printed. |
|
977 | * An integer: only these many lines are printed. | |
1014 |
|
978 | |||
1015 | * A float (between 0 and 1): this fraction of the report is printed |
|
979 | * A float (between 0 and 1): this fraction of the report is printed | |
1016 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
980 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1017 |
|
981 | |||
1018 | You can combine several limits with repeated use of the option. For |
|
982 | You can combine several limits with repeated use of the option. For | |
1019 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
983 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1020 | information about class constructors. |
|
984 | information about class constructors. | |
1021 |
|
985 | |||
1022 | -r: return the pstats.Stats object generated by the profiling. This |
|
986 | -r: return the pstats.Stats object generated by the profiling. This | |
1023 | object has all the information about the profile in it, and you can |
|
987 | object has all the information about the profile in it, and you can | |
1024 | later use it for further analysis or in other functions. |
|
988 | later use it for further analysis or in other functions. | |
1025 |
|
989 | |||
1026 | Since magic functions have a particular form of calling which prevents |
|
990 | Since magic functions have a particular form of calling which prevents | |
1027 | you from writing something like:\\ |
|
991 | you from writing something like:\\ | |
1028 | In [1]: p = %prun -r print 4 # invalid!\\ |
|
992 | In [1]: p = %prun -r print 4 # invalid!\\ | |
1029 | you must instead use IPython's automatic variables to assign this:\\ |
|
993 | you must instead use IPython's automatic variables to assign this:\\ | |
1030 | In [1]: %prun -r print 4 \\ |
|
994 | In [1]: %prun -r print 4 \\ | |
1031 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ |
|
995 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ | |
1032 | In [2]: stats = _ |
|
996 | In [2]: stats = _ | |
1033 |
|
997 | |||
1034 | If you really need to assign this value via an explicit function call, |
|
998 | If you really need to assign this value via an explicit function call, | |
1035 | you can always tap directly into the true name of the magic function |
|
999 | you can always tap directly into the true name of the magic function | |
1036 | by using the ipmagic function (which IPython automatically adds to the |
|
1000 | by using the ipmagic function (which IPython automatically adds to the | |
1037 | builtins):\\ |
|
1001 | builtins):\\ | |
1038 | In [3]: stats = ipmagic('prun','-r print 4') |
|
1002 | In [3]: stats = ipmagic('prun','-r print 4') | |
1039 |
|
1003 | |||
1040 | You can type ipmagic? for more details on ipmagic. |
|
1004 | You can type ipmagic? for more details on ipmagic. | |
1041 |
|
1005 | |||
1042 | -s <key>: sort profile by given key. You can provide more than one key |
|
1006 | -s <key>: sort profile by given key. You can provide more than one key | |
1043 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1007 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1044 | default sorting key is 'time'. |
|
1008 | default sorting key is 'time'. | |
1045 |
|
1009 | |||
1046 | The following is copied verbatim from the profile documentation |
|
1010 | The following is copied verbatim from the profile documentation | |
1047 | referenced below: |
|
1011 | referenced below: | |
1048 |
|
1012 | |||
1049 | When more than one key is provided, additional keys are used as |
|
1013 | When more than one key is provided, additional keys are used as | |
1050 | secondary criteria when the there is equality in all keys selected |
|
1014 | secondary criteria when the there is equality in all keys selected | |
1051 | before them. |
|
1015 | before them. | |
1052 |
|
1016 | |||
1053 | Abbreviations can be used for any key names, as long as the |
|
1017 | Abbreviations can be used for any key names, as long as the | |
1054 | abbreviation is unambiguous. The following are the keys currently |
|
1018 | abbreviation is unambiguous. The following are the keys currently | |
1055 | defined: |
|
1019 | defined: | |
1056 |
|
1020 | |||
1057 | Valid Arg Meaning\\ |
|
1021 | Valid Arg Meaning\\ | |
1058 | "calls" call count\\ |
|
1022 | "calls" call count\\ | |
1059 | "cumulative" cumulative time\\ |
|
1023 | "cumulative" cumulative time\\ | |
1060 | "file" file name\\ |
|
1024 | "file" file name\\ | |
1061 | "module" file name\\ |
|
1025 | "module" file name\\ | |
1062 | "pcalls" primitive call count\\ |
|
1026 | "pcalls" primitive call count\\ | |
1063 | "line" line number\\ |
|
1027 | "line" line number\\ | |
1064 | "name" function name\\ |
|
1028 | "name" function name\\ | |
1065 | "nfl" name/file/line\\ |
|
1029 | "nfl" name/file/line\\ | |
1066 | "stdname" standard name\\ |
|
1030 | "stdname" standard name\\ | |
1067 | "time" internal time |
|
1031 | "time" internal time | |
1068 |
|
1032 | |||
1069 | Note that all sorts on statistics are in descending order (placing |
|
1033 | Note that all sorts on statistics are in descending order (placing | |
1070 | most time consuming items first), where as name, file, and line number |
|
1034 | most time consuming items first), where as name, file, and line number | |
1071 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1035 | searches are in ascending order (i.e., alphabetical). The subtle | |
1072 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1036 | distinction between "nfl" and "stdname" is that the standard name is a | |
1073 | sort of the name as printed, which means that the embedded line |
|
1037 | sort of the name as printed, which means that the embedded line | |
1074 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1038 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1075 | would (if the file names were the same) appear in the string order |
|
1039 | would (if the file names were the same) appear in the string order | |
1076 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1040 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1077 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1041 | line numbers. In fact, sort_stats("nfl") is the same as | |
1078 | sort_stats("name", "file", "line"). |
|
1042 | sort_stats("name", "file", "line"). | |
1079 |
|
1043 | |||
1080 | -T <filename>: save profile results as shown on screen to a text |
|
1044 | -T <filename>: save profile results as shown on screen to a text | |
1081 | file. The profile is still shown on screen. |
|
1045 | file. The profile is still shown on screen. | |
1082 |
|
1046 | |||
1083 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1047 | -D <filename>: save (via dump_stats) profile statistics to given | |
1084 | filename. This data is in a format understod by the pstats module, and |
|
1048 | filename. This data is in a format understod by the pstats module, and | |
1085 | is generated by a call to the dump_stats() method of profile |
|
1049 | is generated by a call to the dump_stats() method of profile | |
1086 | objects. The profile is still shown on screen. |
|
1050 | objects. The profile is still shown on screen. | |
1087 |
|
1051 | |||
1088 | If you want to run complete programs under the profiler's control, use |
|
1052 | If you want to run complete programs under the profiler's control, use | |
1089 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1053 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1090 | contains profiler specific options as described here. |
|
1054 | contains profiler specific options as described here. | |
1091 |
|
1055 | |||
1092 | You can read the complete documentation for the profile module with:\\ |
|
1056 | You can read the complete documentation for the profile module with:\\ | |
1093 | In [1]: import profile; profile.help() """ |
|
1057 | In [1]: import profile; profile.help() """ | |
1094 |
|
1058 | |||
1095 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1059 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1096 | # protect user quote marks |
|
1060 | # protect user quote marks | |
1097 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1061 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1098 |
|
1062 | |||
1099 | if user_mode: # regular user call |
|
1063 | if user_mode: # regular user call | |
1100 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1064 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1101 | list_all=1) |
|
1065 | list_all=1) | |
1102 | namespace = self.shell.user_ns |
|
1066 | namespace = self.shell.user_ns | |
1103 | else: # called to run a program by %run -p |
|
1067 | else: # called to run a program by %run -p | |
1104 | try: |
|
1068 | try: | |
1105 | filename = get_py_filename(arg_lst[0]) |
|
1069 | filename = get_py_filename(arg_lst[0]) | |
1106 | except IOError,msg: |
|
1070 | except IOError,msg: | |
1107 | error(msg) |
|
1071 | error(msg) | |
1108 | return |
|
1072 | return | |
1109 |
|
1073 | |||
1110 | arg_str = 'execfile(filename,prog_ns)' |
|
1074 | arg_str = 'execfile(filename,prog_ns)' | |
1111 | namespace = locals() |
|
1075 | namespace = locals() | |
1112 |
|
1076 | |||
1113 | opts.merge(opts_def) |
|
1077 | opts.merge(opts_def) | |
1114 |
|
1078 | |||
1115 | prof = profile.Profile() |
|
1079 | prof = profile.Profile() | |
1116 | try: |
|
1080 | try: | |
1117 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1081 | prof = prof.runctx(arg_str,namespace,namespace) | |
1118 | sys_exit = '' |
|
1082 | sys_exit = '' | |
1119 | except SystemExit: |
|
1083 | except SystemExit: | |
1120 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1084 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1121 |
|
1085 | |||
1122 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1086 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1123 |
|
1087 | |||
1124 | lims = opts.l |
|
1088 | lims = opts.l | |
1125 | if lims: |
|
1089 | if lims: | |
1126 | lims = [] # rebuild lims with ints/floats/strings |
|
1090 | lims = [] # rebuild lims with ints/floats/strings | |
1127 | for lim in opts.l: |
|
1091 | for lim in opts.l: | |
1128 | try: |
|
1092 | try: | |
1129 | lims.append(int(lim)) |
|
1093 | lims.append(int(lim)) | |
1130 | except ValueError: |
|
1094 | except ValueError: | |
1131 | try: |
|
1095 | try: | |
1132 | lims.append(float(lim)) |
|
1096 | lims.append(float(lim)) | |
1133 | except ValueError: |
|
1097 | except ValueError: | |
1134 | lims.append(lim) |
|
1098 | lims.append(lim) | |
1135 |
|
1099 | |||
1136 | # trap output |
|
1100 | # trap output | |
1137 | sys_stdout = sys.stdout |
|
1101 | sys_stdout = sys.stdout | |
1138 | stdout_trap = StringIO() |
|
1102 | stdout_trap = StringIO() | |
1139 | try: |
|
1103 | try: | |
1140 | sys.stdout = stdout_trap |
|
1104 | sys.stdout = stdout_trap | |
1141 | stats.print_stats(*lims) |
|
1105 | stats.print_stats(*lims) | |
1142 | finally: |
|
1106 | finally: | |
1143 | sys.stdout = sys_stdout |
|
1107 | sys.stdout = sys_stdout | |
1144 | output = stdout_trap.getvalue() |
|
1108 | output = stdout_trap.getvalue() | |
1145 | output = output.rstrip() |
|
1109 | output = output.rstrip() | |
1146 |
|
1110 | |||
1147 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1111 | page(output,screen_lines=self.shell.rc.screen_length) | |
1148 | print sys_exit, |
|
1112 | print sys_exit, | |
1149 |
|
1113 | |||
1150 | dump_file = opts.D[0] |
|
1114 | dump_file = opts.D[0] | |
1151 | text_file = opts.T[0] |
|
1115 | text_file = opts.T[0] | |
1152 | if dump_file: |
|
1116 | if dump_file: | |
1153 | prof.dump_stats(dump_file) |
|
1117 | prof.dump_stats(dump_file) | |
1154 | print '\n*** Profile stats marshalled to file',\ |
|
1118 | print '\n*** Profile stats marshalled to file',\ | |
1155 | `dump_file`+'.',sys_exit |
|
1119 | `dump_file`+'.',sys_exit | |
1156 | if text_file: |
|
1120 | if text_file: | |
1157 | file(text_file,'w').write(output) |
|
1121 | file(text_file,'w').write(output) | |
1158 | print '\n*** Profile printout saved to text file',\ |
|
1122 | print '\n*** Profile printout saved to text file',\ | |
1159 | `text_file`+'.',sys_exit |
|
1123 | `text_file`+'.',sys_exit | |
1160 |
|
1124 | |||
1161 | if opts.has_key('r'): |
|
1125 | if opts.has_key('r'): | |
1162 | return stats |
|
1126 | return stats | |
1163 | else: |
|
1127 | else: | |
1164 | return None |
|
1128 | return None | |
1165 |
|
1129 | |||
1166 | def magic_run(self, parameter_s ='',runner=None): |
|
1130 | def magic_run(self, parameter_s ='',runner=None): | |
1167 | """Run the named file inside IPython as a program. |
|
1131 | """Run the named file inside IPython as a program. | |
1168 |
|
1132 | |||
1169 | Usage:\\ |
|
1133 | Usage:\\ | |
1170 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1134 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1171 |
|
1135 | |||
1172 | Parameters after the filename are passed as command-line arguments to |
|
1136 | Parameters after the filename are passed as command-line arguments to | |
1173 | the program (put in sys.argv). Then, control returns to IPython's |
|
1137 | the program (put in sys.argv). Then, control returns to IPython's | |
1174 | prompt. |
|
1138 | prompt. | |
1175 |
|
1139 | |||
1176 | This is similar to running at a system prompt:\\ |
|
1140 | This is similar to running at a system prompt:\\ | |
1177 | $ python file args\\ |
|
1141 | $ python file args\\ | |
1178 | but with the advantage of giving you IPython's tracebacks, and of |
|
1142 | but with the advantage of giving you IPython's tracebacks, and of | |
1179 | loading all variables into your interactive namespace for further use |
|
1143 | loading all variables into your interactive namespace for further use | |
1180 | (unless -p is used, see below). |
|
1144 | (unless -p is used, see below). | |
1181 |
|
1145 | |||
1182 | The file is executed in a namespace initially consisting only of |
|
1146 | The file is executed in a namespace initially consisting only of | |
1183 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1147 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1184 | sees its environment as if it were being run as a stand-alone |
|
1148 | sees its environment as if it were being run as a stand-alone | |
1185 | program. But after execution, the IPython interactive namespace gets |
|
1149 | program. But after execution, the IPython interactive namespace gets | |
1186 | updated with all variables defined in the program (except for __name__ |
|
1150 | updated with all variables defined in the program (except for __name__ | |
1187 | and sys.argv). This allows for very convenient loading of code for |
|
1151 | and sys.argv). This allows for very convenient loading of code for | |
1188 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1152 | interactive work, while giving each program a 'clean sheet' to run in. | |
1189 |
|
1153 | |||
1190 | Options: |
|
1154 | Options: | |
1191 |
|
1155 | |||
1192 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1156 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1193 | without extension (as python does under import). This allows running |
|
1157 | without extension (as python does under import). This allows running | |
1194 | scripts and reloading the definitions in them without calling code |
|
1158 | scripts and reloading the definitions in them without calling code | |
1195 | protected by an ' if __name__ == "__main__" ' clause. |
|
1159 | protected by an ' if __name__ == "__main__" ' clause. | |
1196 |
|
1160 | |||
1197 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1161 | -i: run the file in IPython's namespace instead of an empty one. This | |
1198 | is useful if you are experimenting with code written in a text editor |
|
1162 | is useful if you are experimenting with code written in a text editor | |
1199 | which depends on variables defined interactively. |
|
1163 | which depends on variables defined interactively. | |
1200 |
|
1164 | |||
1201 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1165 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1202 | being run. This is particularly useful if IPython is being used to |
|
1166 | being run. This is particularly useful if IPython is being used to | |
1203 | run unittests, which always exit with a sys.exit() call. In such |
|
1167 | run unittests, which always exit with a sys.exit() call. In such | |
1204 | cases you are interested in the output of the test results, not in |
|
1168 | cases you are interested in the output of the test results, not in | |
1205 | seeing a traceback of the unittest module. |
|
1169 | seeing a traceback of the unittest module. | |
1206 |
|
1170 | |||
1207 | -t: print timing information at the end of the run. IPython will give |
|
1171 | -t: print timing information at the end of the run. IPython will give | |
1208 | you an estimated CPU time consumption for your script, which under |
|
1172 | you an estimated CPU time consumption for your script, which under | |
1209 | Unix uses the resource module to avoid the wraparound problems of |
|
1173 | Unix uses the resource module to avoid the wraparound problems of | |
1210 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1174 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1211 | is also given (for Windows platforms this is reported as 0.0). |
|
1175 | is also given (for Windows platforms this is reported as 0.0). | |
1212 |
|
1176 | |||
1213 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1177 | If -t is given, an additional -N<N> option can be given, where <N> | |
1214 | must be an integer indicating how many times you want the script to |
|
1178 | must be an integer indicating how many times you want the script to | |
1215 | run. The final timing report will include total and per run results. |
|
1179 | run. The final timing report will include total and per run results. | |
1216 |
|
1180 | |||
1217 | For example (testing the script uniq_stable.py): |
|
1181 | For example (testing the script uniq_stable.py): | |
1218 |
|
1182 | |||
1219 | In [1]: run -t uniq_stable |
|
1183 | In [1]: run -t uniq_stable | |
1220 |
|
1184 | |||
1221 | IPython CPU timings (estimated):\\ |
|
1185 | IPython CPU timings (estimated):\\ | |
1222 | User : 0.19597 s.\\ |
|
1186 | User : 0.19597 s.\\ | |
1223 | System: 0.0 s.\\ |
|
1187 | System: 0.0 s.\\ | |
1224 |
|
1188 | |||
1225 | In [2]: run -t -N5 uniq_stable |
|
1189 | In [2]: run -t -N5 uniq_stable | |
1226 |
|
1190 | |||
1227 | IPython CPU timings (estimated):\\ |
|
1191 | IPython CPU timings (estimated):\\ | |
1228 | Total runs performed: 5\\ |
|
1192 | Total runs performed: 5\\ | |
1229 | Times : Total Per run\\ |
|
1193 | Times : Total Per run\\ | |
1230 | User : 0.910862 s, 0.1821724 s.\\ |
|
1194 | User : 0.910862 s, 0.1821724 s.\\ | |
1231 | System: 0.0 s, 0.0 s. |
|
1195 | System: 0.0 s, 0.0 s. | |
1232 |
|
1196 | |||
1233 | -d: run your program under the control of pdb, the Python debugger. |
|
1197 | -d: run your program under the control of pdb, the Python debugger. | |
1234 | This allows you to execute your program step by step, watch variables, |
|
1198 | This allows you to execute your program step by step, watch variables, | |
1235 | etc. Internally, what IPython does is similar to calling: |
|
1199 | etc. Internally, what IPython does is similar to calling: | |
1236 |
|
1200 | |||
1237 | pdb.run('execfile("YOURFILENAME")') |
|
1201 | pdb.run('execfile("YOURFILENAME")') | |
1238 |
|
1202 | |||
1239 | with a breakpoint set on line 1 of your file. You can change the line |
|
1203 | with a breakpoint set on line 1 of your file. You can change the line | |
1240 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1204 | number for this automatic breakpoint to be <N> by using the -bN option | |
1241 | (where N must be an integer). For example: |
|
1205 | (where N must be an integer). For example: | |
1242 |
|
1206 | |||
1243 | %run -d -b40 myscript |
|
1207 | %run -d -b40 myscript | |
1244 |
|
1208 | |||
1245 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1209 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1246 | the first breakpoint must be set on a line which actually does |
|
1210 | the first breakpoint must be set on a line which actually does | |
1247 | something (not a comment or docstring) for it to stop execution. |
|
1211 | something (not a comment or docstring) for it to stop execution. | |
1248 |
|
1212 | |||
1249 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1213 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1250 | first enter 'c' (without qoutes) to start execution up to the first |
|
1214 | first enter 'c' (without qoutes) to start execution up to the first | |
1251 | breakpoint. |
|
1215 | breakpoint. | |
1252 |
|
1216 | |||
1253 | Entering 'help' gives information about the use of the debugger. You |
|
1217 | Entering 'help' gives information about the use of the debugger. You | |
1254 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1218 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1255 | at a prompt. |
|
1219 | at a prompt. | |
1256 |
|
1220 | |||
1257 | -p: run program under the control of the Python profiler module (which |
|
1221 | -p: run program under the control of the Python profiler module (which | |
1258 | prints a detailed report of execution times, function calls, etc). |
|
1222 | prints a detailed report of execution times, function calls, etc). | |
1259 |
|
1223 | |||
1260 | You can pass other options after -p which affect the behavior of the |
|
1224 | You can pass other options after -p which affect the behavior of the | |
1261 | profiler itself. See the docs for %prun for details. |
|
1225 | profiler itself. See the docs for %prun for details. | |
1262 |
|
1226 | |||
1263 | In this mode, the program's variables do NOT propagate back to the |
|
1227 | In this mode, the program's variables do NOT propagate back to the | |
1264 | IPython interactive namespace (because they remain in the namespace |
|
1228 | IPython interactive namespace (because they remain in the namespace | |
1265 | where the profiler executes them). |
|
1229 | where the profiler executes them). | |
1266 |
|
1230 | |||
1267 | Internally this triggers a call to %prun, see its documentation for |
|
1231 | Internally this triggers a call to %prun, see its documentation for | |
1268 | details on the options available specifically for profiling.""" |
|
1232 | details on the options available specifically for profiling.""" | |
1269 |
|
1233 | |||
1270 | # get arguments and set sys.argv for program to be run. |
|
1234 | # get arguments and set sys.argv for program to be run. | |
1271 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1235 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1272 | mode='list',list_all=1) |
|
1236 | mode='list',list_all=1) | |
1273 |
|
1237 | |||
1274 | try: |
|
1238 | try: | |
1275 | filename = get_py_filename(arg_lst[0]) |
|
1239 | filename = get_py_filename(arg_lst[0]) | |
1276 | except IndexError: |
|
1240 | except IndexError: | |
1277 | warn('you must provide at least a filename.') |
|
1241 | warn('you must provide at least a filename.') | |
1278 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1242 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1279 | return |
|
1243 | return | |
1280 | except IOError,msg: |
|
1244 | except IOError,msg: | |
1281 | error(msg) |
|
1245 | error(msg) | |
1282 | return |
|
1246 | return | |
1283 |
|
1247 | |||
1284 | # Control the response to exit() calls made by the script being run |
|
1248 | # Control the response to exit() calls made by the script being run | |
1285 | exit_ignore = opts.has_key('e') |
|
1249 | exit_ignore = opts.has_key('e') | |
1286 |
|
1250 | |||
1287 | # Make sure that the running script gets a proper sys.argv as if it |
|
1251 | # Make sure that the running script gets a proper sys.argv as if it | |
1288 | # were run from a system shell. |
|
1252 | # were run from a system shell. | |
1289 | save_argv = sys.argv # save it for later restoring |
|
1253 | save_argv = sys.argv # save it for later restoring | |
1290 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1254 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1291 |
|
1255 | |||
1292 | if opts.has_key('i'): |
|
1256 | if opts.has_key('i'): | |
1293 | prog_ns = self.shell.user_ns |
|
1257 | prog_ns = self.shell.user_ns | |
1294 | __name__save = self.shell.user_ns['__name__'] |
|
1258 | __name__save = self.shell.user_ns['__name__'] | |
1295 | prog_ns['__name__'] = '__main__' |
|
1259 | prog_ns['__name__'] = '__main__' | |
1296 | else: |
|
1260 | else: | |
1297 | if opts.has_key('n'): |
|
1261 | if opts.has_key('n'): | |
1298 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1262 | name = os.path.splitext(os.path.basename(filename))[0] | |
1299 | else: |
|
1263 | else: | |
1300 | name = '__main__' |
|
1264 | name = '__main__' | |
1301 | prog_ns = {'__name__':name} |
|
1265 | prog_ns = {'__name__':name} | |
1302 |
|
1266 | |||
1303 | # pickle fix. See iplib for an explanation |
|
1267 | # pickle fix. See iplib for an explanation | |
1304 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1268 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) | |
1305 |
|
1269 | |||
1306 | stats = None |
|
1270 | stats = None | |
1307 | try: |
|
1271 | try: | |
1308 | if opts.has_key('p'): |
|
1272 | if opts.has_key('p'): | |
1309 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1273 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1310 | else: |
|
1274 | else: | |
1311 | if opts.has_key('d'): |
|
1275 | if opts.has_key('d'): | |
1312 | deb = pdb.Pdb() |
|
1276 | deb = pdb.Pdb() | |
1313 | # reset Breakpoint state, which is moronically kept |
|
1277 | # reset Breakpoint state, which is moronically kept | |
1314 | # in a class |
|
1278 | # in a class | |
1315 | bdb.Breakpoint.next = 1 |
|
1279 | bdb.Breakpoint.next = 1 | |
1316 | bdb.Breakpoint.bplist = {} |
|
1280 | bdb.Breakpoint.bplist = {} | |
1317 | bdb.Breakpoint.bpbynumber = [None] |
|
1281 | bdb.Breakpoint.bpbynumber = [None] | |
1318 | # Set an initial breakpoint to stop execution |
|
1282 | # Set an initial breakpoint to stop execution | |
1319 | maxtries = 10 |
|
1283 | maxtries = 10 | |
1320 | bp = int(opts.get('b',[1])[0]) |
|
1284 | bp = int(opts.get('b',[1])[0]) | |
1321 | checkline = deb.checkline(filename,bp) |
|
1285 | checkline = deb.checkline(filename,bp) | |
1322 | if not checkline: |
|
1286 | if not checkline: | |
1323 | for bp in range(bp+1,bp+maxtries+1): |
|
1287 | for bp in range(bp+1,bp+maxtries+1): | |
1324 | if deb.checkline(filename,bp): |
|
1288 | if deb.checkline(filename,bp): | |
1325 | break |
|
1289 | break | |
1326 | else: |
|
1290 | else: | |
1327 | msg = ("\nI failed to find a valid line to set " |
|
1291 | msg = ("\nI failed to find a valid line to set " | |
1328 | "a breakpoint\n" |
|
1292 | "a breakpoint\n" | |
1329 | "after trying up to line: %s.\n" |
|
1293 | "after trying up to line: %s.\n" | |
1330 | "Please set a valid breakpoint manually " |
|
1294 | "Please set a valid breakpoint manually " | |
1331 | "with the -b option." % bp) |
|
1295 | "with the -b option." % bp) | |
1332 | error(msg) |
|
1296 | error(msg) | |
1333 | return |
|
1297 | return | |
1334 | # if we find a good linenumber, set the breakpoint |
|
1298 | # if we find a good linenumber, set the breakpoint | |
1335 | deb.do_break('%s:%s' % (filename,bp)) |
|
1299 | deb.do_break('%s:%s' % (filename,bp)) | |
1336 | # Start file run |
|
1300 | # Start file run | |
1337 | print "NOTE: Enter 'c' at the", |
|
1301 | print "NOTE: Enter 'c' at the", | |
1338 | print "(Pdb) prompt to start your script." |
|
1302 | print "(Pdb) prompt to start your script." | |
1339 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1303 | deb.run('execfile("%s")' % filename,prog_ns) | |
1340 | else: |
|
1304 | else: | |
1341 | if runner is None: |
|
1305 | if runner is None: | |
1342 | runner = self.shell.safe_execfile |
|
1306 | runner = self.shell.safe_execfile | |
1343 | if opts.has_key('t'): |
|
1307 | if opts.has_key('t'): | |
1344 | try: |
|
1308 | try: | |
1345 | nruns = int(opts['N'][0]) |
|
1309 | nruns = int(opts['N'][0]) | |
1346 | if nruns < 1: |
|
1310 | if nruns < 1: | |
1347 | error('Number of runs must be >=1') |
|
1311 | error('Number of runs must be >=1') | |
1348 | return |
|
1312 | return | |
1349 | except (KeyError): |
|
1313 | except (KeyError): | |
1350 | nruns = 1 |
|
1314 | nruns = 1 | |
1351 | if nruns == 1: |
|
1315 | if nruns == 1: | |
1352 | t0 = clock2() |
|
1316 | t0 = clock2() | |
1353 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1317 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1354 | t1 = clock2() |
|
1318 | t1 = clock2() | |
1355 | t_usr = t1[0]-t0[0] |
|
1319 | t_usr = t1[0]-t0[0] | |
1356 | t_sys = t1[1]-t1[1] |
|
1320 | t_sys = t1[1]-t1[1] | |
1357 | print "\nIPython CPU timings (estimated):" |
|
1321 | print "\nIPython CPU timings (estimated):" | |
1358 | print " User : %10s s." % t_usr |
|
1322 | print " User : %10s s." % t_usr | |
1359 | print " System: %10s s." % t_sys |
|
1323 | print " System: %10s s." % t_sys | |
1360 | else: |
|
1324 | else: | |
1361 | runs = range(nruns) |
|
1325 | runs = range(nruns) | |
1362 | t0 = clock2() |
|
1326 | t0 = clock2() | |
1363 | for nr in runs: |
|
1327 | for nr in runs: | |
1364 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1328 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1365 | t1 = clock2() |
|
1329 | t1 = clock2() | |
1366 | t_usr = t1[0]-t0[0] |
|
1330 | t_usr = t1[0]-t0[0] | |
1367 | t_sys = t1[1]-t1[1] |
|
1331 | t_sys = t1[1]-t1[1] | |
1368 | print "\nIPython CPU timings (estimated):" |
|
1332 | print "\nIPython CPU timings (estimated):" | |
1369 | print "Total runs performed:",nruns |
|
1333 | print "Total runs performed:",nruns | |
1370 | print " Times : %10s %10s" % ('Total','Per run') |
|
1334 | print " Times : %10s %10s" % ('Total','Per run') | |
1371 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1335 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1372 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1336 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1373 |
|
1337 | |||
1374 | else: |
|
1338 | else: | |
1375 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1339 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1376 | if opts.has_key('i'): |
|
1340 | if opts.has_key('i'): | |
1377 | self.shell.user_ns['__name__'] = __name__save |
|
1341 | self.shell.user_ns['__name__'] = __name__save | |
1378 | else: |
|
1342 | else: | |
1379 | # update IPython interactive namespace |
|
1343 | # update IPython interactive namespace | |
1380 | del prog_ns['__name__'] |
|
1344 | del prog_ns['__name__'] | |
1381 | self.shell.user_ns.update(prog_ns) |
|
1345 | self.shell.user_ns.update(prog_ns) | |
1382 | finally: |
|
1346 | finally: | |
1383 | sys.argv = save_argv |
|
1347 | sys.argv = save_argv | |
1384 | return stats |
|
1348 | return stats | |
1385 |
|
1349 | |||
1386 | def magic_runlog(self, parameter_s =''): |
|
1350 | def magic_runlog(self, parameter_s =''): | |
1387 | """Run files as logs. |
|
1351 | """Run files as logs. | |
1388 |
|
1352 | |||
1389 | Usage:\\ |
|
1353 | Usage:\\ | |
1390 | %runlog file1 file2 ... |
|
1354 | %runlog file1 file2 ... | |
1391 |
|
1355 | |||
1392 | Run the named files (treating them as log files) in sequence inside |
|
1356 | Run the named files (treating them as log files) in sequence inside | |
1393 | the interpreter, and return to the prompt. This is much slower than |
|
1357 | the interpreter, and return to the prompt. This is much slower than | |
1394 | %run because each line is executed in a try/except block, but it |
|
1358 | %run because each line is executed in a try/except block, but it | |
1395 | allows running files with syntax errors in them. |
|
1359 | allows running files with syntax errors in them. | |
1396 |
|
1360 | |||
1397 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1361 | Normally IPython will guess when a file is one of its own logfiles, so | |
1398 | you can typically use %run even for logs. This shorthand allows you to |
|
1362 | you can typically use %run even for logs. This shorthand allows you to | |
1399 | force any file to be treated as a log file.""" |
|
1363 | force any file to be treated as a log file.""" | |
1400 |
|
1364 | |||
1401 | for f in parameter_s.split(): |
|
1365 | for f in parameter_s.split(): | |
1402 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1366 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1403 | self.shell.user_ns,islog=1) |
|
1367 | self.shell.user_ns,islog=1) | |
1404 |
|
1368 | |||
1405 | def magic_time(self,parameter_s = ''): |
|
1369 | def magic_time(self,parameter_s = ''): | |
1406 | """Time execution of a Python statement or expression. |
|
1370 | """Time execution of a Python statement or expression. | |
1407 |
|
1371 | |||
1408 | The CPU and wall clock times are printed, and the value of the |
|
1372 | The CPU and wall clock times are printed, and the value of the | |
1409 | expression (if any) is returned. Note that under Win32, system time |
|
1373 | expression (if any) is returned. Note that under Win32, system time | |
1410 | is always reported as 0, since it can not be measured. |
|
1374 | is always reported as 0, since it can not be measured. | |
1411 |
|
1375 | |||
1412 | This function provides very basic timing functionality. In Python |
|
1376 | This function provides very basic timing functionality. In Python | |
1413 | 2.3, the timeit module offers more control and sophistication, but for |
|
1377 | 2.3, the timeit module offers more control and sophistication, but for | |
1414 | now IPython supports Python 2.2, so we can not rely on timeit being |
|
1378 | now IPython supports Python 2.2, so we can not rely on timeit being | |
1415 | present. |
|
1379 | present. | |
1416 |
|
1380 | |||
1417 | Some examples: |
|
1381 | Some examples: | |
1418 |
|
1382 | |||
1419 | In [1]: time 2**128 |
|
1383 | In [1]: time 2**128 | |
1420 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1384 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1421 | Wall time: 0.00 |
|
1385 | Wall time: 0.00 | |
1422 | Out[1]: 340282366920938463463374607431768211456L |
|
1386 | Out[1]: 340282366920938463463374607431768211456L | |
1423 |
|
1387 | |||
1424 | In [2]: n = 1000000 |
|
1388 | In [2]: n = 1000000 | |
1425 |
|
1389 | |||
1426 | In [3]: time sum(range(n)) |
|
1390 | In [3]: time sum(range(n)) | |
1427 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1391 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1428 | Wall time: 1.37 |
|
1392 | Wall time: 1.37 | |
1429 | Out[3]: 499999500000L |
|
1393 | Out[3]: 499999500000L | |
1430 |
|
1394 | |||
1431 | In [4]: time print 'hello world' |
|
1395 | In [4]: time print 'hello world' | |
1432 | hello world |
|
1396 | hello world | |
1433 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1397 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1434 | Wall time: 0.00 |
|
1398 | Wall time: 0.00 | |
1435 | """ |
|
1399 | """ | |
1436 |
|
1400 | |||
1437 | # fail immediately if the given expression can't be compiled |
|
1401 | # fail immediately if the given expression can't be compiled | |
1438 | try: |
|
1402 | try: | |
1439 | mode = 'eval' |
|
1403 | mode = 'eval' | |
1440 | code = compile(parameter_s,'<timed eval>',mode) |
|
1404 | code = compile(parameter_s,'<timed eval>',mode) | |
1441 | except SyntaxError: |
|
1405 | except SyntaxError: | |
1442 | mode = 'exec' |
|
1406 | mode = 'exec' | |
1443 | code = compile(parameter_s,'<timed exec>',mode) |
|
1407 | code = compile(parameter_s,'<timed exec>',mode) | |
1444 | # skew measurement as little as possible |
|
1408 | # skew measurement as little as possible | |
1445 | glob = self.shell.user_ns |
|
1409 | glob = self.shell.user_ns | |
1446 | clk = clock2 |
|
1410 | clk = clock2 | |
1447 | wtime = time.time |
|
1411 | wtime = time.time | |
1448 | # time execution |
|
1412 | # time execution | |
1449 | wall_st = wtime() |
|
1413 | wall_st = wtime() | |
1450 | if mode=='eval': |
|
1414 | if mode=='eval': | |
1451 | st = clk() |
|
1415 | st = clk() | |
1452 | out = eval(code,glob) |
|
1416 | out = eval(code,glob) | |
1453 | end = clk() |
|
1417 | end = clk() | |
1454 | else: |
|
1418 | else: | |
1455 | st = clk() |
|
1419 | st = clk() | |
1456 | exec code in glob |
|
1420 | exec code in glob | |
1457 | end = clk() |
|
1421 | end = clk() | |
1458 | out = None |
|
1422 | out = None | |
1459 | wall_end = wtime() |
|
1423 | wall_end = wtime() | |
1460 | # Compute actual times and report |
|
1424 | # Compute actual times and report | |
1461 | wall_time = wall_end-wall_st |
|
1425 | wall_time = wall_end-wall_st | |
1462 | cpu_user = end[0]-st[0] |
|
1426 | cpu_user = end[0]-st[0] | |
1463 | cpu_sys = end[1]-st[1] |
|
1427 | cpu_sys = end[1]-st[1] | |
1464 | cpu_tot = cpu_user+cpu_sys |
|
1428 | cpu_tot = cpu_user+cpu_sys | |
1465 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1429 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1466 | (cpu_user,cpu_sys,cpu_tot) |
|
1430 | (cpu_user,cpu_sys,cpu_tot) | |
1467 | print "Wall time: %.2f" % wall_time |
|
1431 | print "Wall time: %.2f" % wall_time | |
1468 | return out |
|
1432 | return out | |
1469 |
|
1433 | |||
1470 | def magic_macro(self,parameter_s = ''): |
|
1434 | def magic_macro(self,parameter_s = ''): | |
1471 | """Define a set of input lines as a macro for future re-execution. |
|
1435 | """Define a set of input lines as a macro for future re-execution. | |
1472 |
|
1436 | |||
1473 | Usage:\\ |
|
1437 | Usage:\\ | |
1474 | %macro name n1:n2 n3:n4 ... n5 .. n6 ... |
|
1438 | %macro name n1:n2 n3:n4 ... n5 .. n6 ... | |
1475 |
|
1439 | |||
1476 | This will define a global variable called `name` which is a string |
|
1440 | This will define a global variable called `name` which is a string | |
1477 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1441 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1478 | above) from your input history into a single string. This variable |
|
1442 | above) from your input history into a single string. This variable | |
1479 | acts like an automatic function which re-executes those lines as if |
|
1443 | acts like an automatic function which re-executes those lines as if | |
1480 | you had typed them. You just type 'name' at the prompt and the code |
|
1444 | you had typed them. You just type 'name' at the prompt and the code | |
1481 | executes. |
|
1445 | executes. | |
1482 |
|
1446 | |||
1483 | Note that the slices use the standard Python slicing notation (5:8 |
|
1447 | Note that the slices use the standard Python slicing notation (5:8 | |
1484 | means include lines numbered 5,6,7). |
|
1448 | means include lines numbered 5,6,7). | |
1485 |
|
1449 | |||
1486 | For example, if your history contains (%hist prints it): |
|
1450 | For example, if your history contains (%hist prints it): | |
1487 |
|
1451 | |||
1488 | 44: x=1\\ |
|
1452 | 44: x=1\\ | |
1489 | 45: y=3\\ |
|
1453 | 45: y=3\\ | |
1490 | 46: z=x+y\\ |
|
1454 | 46: z=x+y\\ | |
1491 | 47: print x\\ |
|
1455 | 47: print x\\ | |
1492 | 48: a=5\\ |
|
1456 | 48: a=5\\ | |
1493 | 49: print 'x',x,'y',y\\ |
|
1457 | 49: print 'x',x,'y',y\\ | |
1494 |
|
1458 | |||
1495 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1459 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1496 | called my_macro with: |
|
1460 | called my_macro with: | |
1497 |
|
1461 | |||
1498 | In [51]: %macro my_macro 44:48 49 |
|
1462 | In [51]: %macro my_macro 44:48 49 | |
1499 |
|
1463 | |||
1500 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1464 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1501 | in one pass. |
|
1465 | in one pass. | |
1502 |
|
1466 | |||
1503 | You don't need to give the line-numbers in order, and any given line |
|
1467 | You don't need to give the line-numbers in order, and any given line | |
1504 | number can appear multiple times. You can assemble macros with any |
|
1468 | number can appear multiple times. You can assemble macros with any | |
1505 | lines from your input history in any order. |
|
1469 | lines from your input history in any order. | |
1506 |
|
1470 | |||
1507 | The macro is a simple object which holds its value in an attribute, |
|
1471 | The macro is a simple object which holds its value in an attribute, | |
1508 | but IPython's display system checks for macros and executes them as |
|
1472 | but IPython's display system checks for macros and executes them as | |
1509 | code instead of printing them when you type their name. |
|
1473 | code instead of printing them when you type their name. | |
1510 |
|
1474 | |||
1511 | You can view a macro's contents by explicitly printing it with: |
|
1475 | You can view a macro's contents by explicitly printing it with: | |
1512 |
|
1476 | |||
1513 | 'print macro_name'. |
|
1477 | 'print macro_name'. | |
1514 |
|
1478 | |||
1515 | For one-off cases which DON'T contain magic function calls in them you |
|
1479 | For one-off cases which DON'T contain magic function calls in them you | |
1516 | can obtain similar results by explicitly executing slices from your |
|
1480 | can obtain similar results by explicitly executing slices from your | |
1517 | input history with: |
|
1481 | input history with: | |
1518 |
|
1482 | |||
1519 | In [60]: exec In[44:48]+In[49]""" |
|
1483 | In [60]: exec In[44:48]+In[49]""" | |
1520 |
|
1484 | |||
1521 | args = parameter_s.split() |
|
1485 | args = parameter_s.split() | |
1522 | name,ranges = args[0], args[1:] |
|
1486 | name,ranges = args[0], args[1:] | |
1523 | #print 'rng',ranges # dbg |
|
1487 | #print 'rng',ranges # dbg | |
1524 | cmds = self.extract_input_slices(ranges) |
|
1488 | cmds = self.extract_input_slices(ranges) | |
1525 | macro = Macro(cmds) |
|
1489 | macro = Macro(cmds) | |
1526 | self.shell.user_ns.update({name:macro}) |
|
1490 | self.shell.user_ns.update({name:macro}) | |
1527 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1491 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1528 | print 'Macro contents:' |
|
1492 | print 'Macro contents:' | |
1529 | print str(macro).rstrip(), |
|
1493 | print str(macro).rstrip(), | |
1530 |
|
1494 | |||
1531 | def magic_save(self,parameter_s = ''): |
|
1495 | def magic_save(self,parameter_s = ''): | |
1532 | """Save a set of lines to a given filename. |
|
1496 | """Save a set of lines to a given filename. | |
1533 |
|
1497 | |||
1534 | Usage:\\ |
|
1498 | Usage:\\ | |
1535 | %save filename n1:n2 n3:n4 ... n5 .. n6 ... |
|
1499 | %save filename n1:n2 n3:n4 ... n5 .. n6 ... | |
1536 |
|
1500 | |||
1537 | This function uses the same syntax as %macro for line extraction, but |
|
1501 | This function uses the same syntax as %macro for line extraction, but | |
1538 | instead of creating a macro it saves the resulting string to the |
|
1502 | instead of creating a macro it saves the resulting string to the | |
1539 | filename you specify. |
|
1503 | filename you specify. | |
1540 |
|
1504 | |||
1541 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1505 | It adds a '.py' extension to the file if you don't do so yourself, and | |
1542 | it asks for confirmation before overwriting existing files.""" |
|
1506 | it asks for confirmation before overwriting existing files.""" | |
1543 |
|
1507 | |||
1544 | args = parameter_s.split() |
|
1508 | args = parameter_s.split() | |
1545 | fname,ranges = args[0], args[1:] |
|
1509 | fname,ranges = args[0], args[1:] | |
1546 | if not fname.endswith('.py'): |
|
1510 | if not fname.endswith('.py'): | |
1547 | fname += '.py' |
|
1511 | fname += '.py' | |
1548 | if os.path.isfile(fname): |
|
1512 | if os.path.isfile(fname): | |
1549 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1513 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
1550 | if ans.lower() not in ['y','yes']: |
|
1514 | if ans.lower() not in ['y','yes']: | |
1551 | print 'Operation cancelled.' |
|
1515 | print 'Operation cancelled.' | |
1552 | return |
|
1516 | return | |
1553 | cmds = ''.join(self.extract_input_slices(ranges)) |
|
1517 | cmds = ''.join(self.extract_input_slices(ranges)) | |
1554 | f = file(fname,'w') |
|
1518 | f = file(fname,'w') | |
1555 | f.write(cmds) |
|
1519 | f.write(cmds) | |
1556 | f.close() |
|
1520 | f.close() | |
1557 | print 'The following commands were written to file `%s`:' % fname |
|
1521 | print 'The following commands were written to file `%s`:' % fname | |
1558 | print cmds |
|
1522 | print cmds | |
1559 |
|
1523 | |||
1560 | def magic_ed(self,parameter_s = ''): |
|
1524 | def magic_ed(self,parameter_s = ''): | |
1561 | """Alias to %edit.""" |
|
1525 | """Alias to %edit.""" | |
1562 | return self.magic_edit(parameter_s) |
|
1526 | return self.magic_edit(parameter_s) | |
1563 |
|
1527 | |||
1564 | def magic_edit(self,parameter_s = '',last_call=['','']): |
|
1528 | def magic_edit(self,parameter_s = '',last_call=['','']): | |
1565 | """Bring up an editor and execute the resulting code. |
|
1529 | """Bring up an editor and execute the resulting code. | |
1566 |
|
1530 | |||
1567 | Usage: |
|
1531 | Usage: | |
1568 | %edit [options] [args] |
|
1532 | %edit [options] [args] | |
1569 |
|
1533 | |||
1570 | %edit runs IPython's editor hook. The default version of this hook is |
|
1534 | %edit runs IPython's editor hook. The default version of this hook is | |
1571 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1535 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
1572 | environment variable $EDITOR. If this isn't found, it will default to |
|
1536 | environment variable $EDITOR. If this isn't found, it will default to | |
1573 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1537 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
1574 | docstring for how to change the editor hook. |
|
1538 | docstring for how to change the editor hook. | |
1575 |
|
1539 | |||
1576 | You can also set the value of this editor via the command line option |
|
1540 | You can also set the value of this editor via the command line option | |
1577 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
1541 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
1578 | specifically for IPython an editor different from your typical default |
|
1542 | specifically for IPython an editor different from your typical default | |
1579 | (and for Windows users who typically don't set environment variables). |
|
1543 | (and for Windows users who typically don't set environment variables). | |
1580 |
|
1544 | |||
1581 | This command allows you to conveniently edit multi-line code right in |
|
1545 | This command allows you to conveniently edit multi-line code right in | |
1582 | your IPython session. |
|
1546 | your IPython session. | |
1583 |
|
1547 | |||
1584 | If called without arguments, %edit opens up an empty editor with a |
|
1548 | If called without arguments, %edit opens up an empty editor with a | |
1585 | temporary file and will execute the contents of this file when you |
|
1549 | temporary file and will execute the contents of this file when you | |
1586 | close it (don't forget to save it!). |
|
1550 | close it (don't forget to save it!). | |
1587 |
|
1551 | |||
1588 | Options: |
|
1552 | Options: | |
1589 |
|
1553 | |||
1590 | -p: this will call the editor with the same data as the previous time |
|
1554 | -p: this will call the editor with the same data as the previous time | |
1591 | it was used, regardless of how long ago (in your current session) it |
|
1555 | it was used, regardless of how long ago (in your current session) it | |
1592 | was. |
|
1556 | was. | |
1593 |
|
1557 | |||
1594 | -x: do not execute the edited code immediately upon exit. This is |
|
1558 | -x: do not execute the edited code immediately upon exit. This is | |
1595 | mainly useful if you are editing programs which need to be called with |
|
1559 | mainly useful if you are editing programs which need to be called with | |
1596 | command line arguments, which you can then do using %run. |
|
1560 | command line arguments, which you can then do using %run. | |
1597 |
|
1561 | |||
1598 | Arguments: |
|
1562 | Arguments: | |
1599 |
|
1563 | |||
1600 | If arguments are given, the following possibilites exist: |
|
1564 | If arguments are given, the following possibilites exist: | |
1601 |
|
1565 | |||
1602 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
1566 | - The arguments are numbers or pairs of colon-separated numbers (like | |
1603 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
1567 | 1 4:8 9). These are interpreted as lines of previous input to be | |
1604 | loaded into the editor. The syntax is the same of the %macro command. |
|
1568 | loaded into the editor. The syntax is the same of the %macro command. | |
1605 |
|
1569 | |||
1606 | - If the argument doesn't start with a number, it is evaluated as a |
|
1570 | - If the argument doesn't start with a number, it is evaluated as a | |
1607 | variable and its contents loaded into the editor. You can thus edit |
|
1571 | variable and its contents loaded into the editor. You can thus edit | |
1608 | any string which contains python code (including the result of |
|
1572 | any string which contains python code (including the result of | |
1609 | previous edits). |
|
1573 | previous edits). | |
1610 |
|
1574 | |||
1611 | - If the argument is the name of an object (other than a string), |
|
1575 | - If the argument is the name of an object (other than a string), | |
1612 | IPython will try to locate the file where it was defined and open the |
|
1576 | IPython will try to locate the file where it was defined and open the | |
1613 | editor at the point where it is defined. You can use `%edit function` |
|
1577 | editor at the point where it is defined. You can use `%edit function` | |
1614 | to load an editor exactly at the point where 'function' is defined, |
|
1578 | to load an editor exactly at the point where 'function' is defined, | |
1615 | edit it and have the file be executed automatically. |
|
1579 | edit it and have the file be executed automatically. | |
1616 |
|
1580 | |||
1617 | Note: opening at an exact line is only supported under Unix, and some |
|
1581 | Note: opening at an exact line is only supported under Unix, and some | |
1618 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
1582 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
1619 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
1583 | '+NUMBER' parameter necessary for this feature. Good editors like | |
1620 | (X)Emacs, vi, jed, pico and joe all do. |
|
1584 | (X)Emacs, vi, jed, pico and joe all do. | |
1621 |
|
1585 | |||
1622 | - If the argument is not found as a variable, IPython will look for a |
|
1586 | - If the argument is not found as a variable, IPython will look for a | |
1623 | file with that name (adding .py if necessary) and load it into the |
|
1587 | file with that name (adding .py if necessary) and load it into the | |
1624 | editor. It will execute its contents with execfile() when you exit, |
|
1588 | editor. It will execute its contents with execfile() when you exit, | |
1625 | loading any code in the file into your interactive namespace. |
|
1589 | loading any code in the file into your interactive namespace. | |
1626 |
|
1590 | |||
1627 | After executing your code, %edit will return as output the code you |
|
1591 | After executing your code, %edit will return as output the code you | |
1628 | typed in the editor (except when it was an existing file). This way |
|
1592 | typed in the editor (except when it was an existing file). This way | |
1629 | you can reload the code in further invocations of %edit as a variable, |
|
1593 | you can reload the code in further invocations of %edit as a variable, | |
1630 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
1594 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
1631 | the output. |
|
1595 | the output. | |
1632 |
|
1596 | |||
1633 | Note that %edit is also available through the alias %ed. |
|
1597 | Note that %edit is also available through the alias %ed. | |
1634 |
|
1598 | |||
1635 | This is an example of creating a simple function inside the editor and |
|
1599 | This is an example of creating a simple function inside the editor and | |
1636 | then modifying it. First, start up the editor: |
|
1600 | then modifying it. First, start up the editor: | |
1637 |
|
1601 | |||
1638 | In [1]: ed\\ |
|
1602 | In [1]: ed\\ | |
1639 | Editing... done. Executing edited code...\\ |
|
1603 | Editing... done. Executing edited code...\\ | |
1640 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
1604 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' | |
1641 |
|
1605 | |||
1642 | We can then call the function foo(): |
|
1606 | We can then call the function foo(): | |
1643 |
|
1607 | |||
1644 | In [2]: foo()\\ |
|
1608 | In [2]: foo()\\ | |
1645 | foo() was defined in an editing session |
|
1609 | foo() was defined in an editing session | |
1646 |
|
1610 | |||
1647 | Now we edit foo. IPython automatically loads the editor with the |
|
1611 | Now we edit foo. IPython automatically loads the editor with the | |
1648 | (temporary) file where foo() was previously defined: |
|
1612 | (temporary) file where foo() was previously defined: | |
1649 |
|
1613 | |||
1650 | In [3]: ed foo\\ |
|
1614 | In [3]: ed foo\\ | |
1651 | Editing... done. Executing edited code... |
|
1615 | Editing... done. Executing edited code... | |
1652 |
|
1616 | |||
1653 | And if we call foo() again we get the modified version: |
|
1617 | And if we call foo() again we get the modified version: | |
1654 |
|
1618 | |||
1655 | In [4]: foo()\\ |
|
1619 | In [4]: foo()\\ | |
1656 | foo() has now been changed! |
|
1620 | foo() has now been changed! | |
1657 |
|
1621 | |||
1658 | Here is an example of how to edit a code snippet successive |
|
1622 | Here is an example of how to edit a code snippet successive | |
1659 | times. First we call the editor: |
|
1623 | times. First we call the editor: | |
1660 |
|
1624 | |||
1661 | In [8]: ed\\ |
|
1625 | In [8]: ed\\ | |
1662 | Editing... done. Executing edited code...\\ |
|
1626 | Editing... done. Executing edited code...\\ | |
1663 | hello\\ |
|
1627 | hello\\ | |
1664 | Out[8]: "print 'hello'\\n" |
|
1628 | Out[8]: "print 'hello'\\n" | |
1665 |
|
1629 | |||
1666 | Now we call it again with the previous output (stored in _): |
|
1630 | Now we call it again with the previous output (stored in _): | |
1667 |
|
1631 | |||
1668 | In [9]: ed _\\ |
|
1632 | In [9]: ed _\\ | |
1669 | Editing... done. Executing edited code...\\ |
|
1633 | Editing... done. Executing edited code...\\ | |
1670 | hello world\\ |
|
1634 | hello world\\ | |
1671 | Out[9]: "print 'hello world'\\n" |
|
1635 | Out[9]: "print 'hello world'\\n" | |
1672 |
|
1636 | |||
1673 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
1637 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
1674 |
|
1638 | |||
1675 | In [10]: ed _8\\ |
|
1639 | In [10]: ed _8\\ | |
1676 | Editing... done. Executing edited code...\\ |
|
1640 | Editing... done. Executing edited code...\\ | |
1677 | hello again\\ |
|
1641 | hello again\\ | |
1678 | Out[10]: "print 'hello again'\\n" |
|
1642 | Out[10]: "print 'hello again'\\n" | |
1679 |
|
1643 | |||
1680 |
|
1644 | |||
1681 | Changing the default editor hook: |
|
1645 | Changing the default editor hook: | |
1682 |
|
1646 | |||
1683 | If you wish to write your own editor hook, you can put it in a |
|
1647 | If you wish to write your own editor hook, you can put it in a | |
1684 | configuration file which you load at startup time. The default hook |
|
1648 | configuration file which you load at startup time. The default hook | |
1685 | is defined in the IPython.hooks module, and you can use that as a |
|
1649 | is defined in the IPython.hooks module, and you can use that as a | |
1686 | starting example for further modifications. That file also has |
|
1650 | starting example for further modifications. That file also has | |
1687 | general instructions on how to set a new hook for use once you've |
|
1651 | general instructions on how to set a new hook for use once you've | |
1688 | defined it.""" |
|
1652 | defined it.""" | |
1689 |
|
1653 | |||
1690 | # FIXME: This function has become a convoluted mess. It needs a |
|
1654 | # FIXME: This function has become a convoluted mess. It needs a | |
1691 | # ground-up rewrite with clean, simple logic. |
|
1655 | # ground-up rewrite with clean, simple logic. | |
1692 |
|
1656 | |||
1693 | def make_filename(arg): |
|
1657 | def make_filename(arg): | |
1694 | "Make a filename from the given args" |
|
1658 | "Make a filename from the given args" | |
1695 | try: |
|
1659 | try: | |
1696 | filename = get_py_filename(arg) |
|
1660 | filename = get_py_filename(arg) | |
1697 | except IOError: |
|
1661 | except IOError: | |
1698 | if args.endswith('.py'): |
|
1662 | if args.endswith('.py'): | |
1699 | filename = arg |
|
1663 | filename = arg | |
1700 | else: |
|
1664 | else: | |
1701 | filename = None |
|
1665 | filename = None | |
1702 | return filename |
|
1666 | return filename | |
1703 |
|
1667 | |||
1704 | # custom exceptions |
|
1668 | # custom exceptions | |
1705 | class DataIsObject(Exception): pass |
|
1669 | class DataIsObject(Exception): pass | |
1706 |
|
1670 | |||
1707 | opts,args = self.parse_options(parameter_s,'px') |
|
1671 | opts,args = self.parse_options(parameter_s,'px') | |
1708 |
|
1672 | |||
1709 | # Default line number value |
|
1673 | # Default line number value | |
1710 | lineno = None |
|
1674 | lineno = None | |
1711 | if opts.has_key('p'): |
|
1675 | if opts.has_key('p'): | |
1712 | args = '_%s' % last_call[0] |
|
1676 | args = '_%s' % last_call[0] | |
1713 | if not self.shell.user_ns.has_key(args): |
|
1677 | if not self.shell.user_ns.has_key(args): | |
1714 | args = last_call[1] |
|
1678 | args = last_call[1] | |
1715 |
|
1679 | |||
1716 | # use last_call to remember the state of the previous call, but don't |
|
1680 | # use last_call to remember the state of the previous call, but don't | |
1717 | # let it be clobbered by successive '-p' calls. |
|
1681 | # let it be clobbered by successive '-p' calls. | |
1718 | try: |
|
1682 | try: | |
1719 | last_call[0] = self.shell.outputcache.prompt_count |
|
1683 | last_call[0] = self.shell.outputcache.prompt_count | |
1720 | if not opts.has_key('p'): |
|
1684 | if not opts.has_key('p'): | |
1721 | last_call[1] = parameter_s |
|
1685 | last_call[1] = parameter_s | |
1722 | except: |
|
1686 | except: | |
1723 | pass |
|
1687 | pass | |
1724 |
|
1688 | |||
1725 | # by default this is done with temp files, except when the given |
|
1689 | # by default this is done with temp files, except when the given | |
1726 | # arg is a filename |
|
1690 | # arg is a filename | |
1727 | use_temp = 1 |
|
1691 | use_temp = 1 | |
1728 |
|
1692 | |||
1729 | if re.match(r'\d',args): |
|
1693 | if re.match(r'\d',args): | |
1730 | # Mode where user specifies ranges of lines, like in %macro. |
|
1694 | # Mode where user specifies ranges of lines, like in %macro. | |
1731 | # This means that you can't edit files whose names begin with |
|
1695 | # This means that you can't edit files whose names begin with | |
1732 | # numbers this way. Tough. |
|
1696 | # numbers this way. Tough. | |
1733 | ranges = args.split() |
|
1697 | ranges = args.split() | |
1734 | data = ''.join(self.extract_input_slices(ranges)) |
|
1698 | data = ''.join(self.extract_input_slices(ranges)) | |
1735 | elif args.endswith('.py'): |
|
1699 | elif args.endswith('.py'): | |
1736 | filename = make_filename(args) |
|
1700 | filename = make_filename(args) | |
1737 | data = '' |
|
1701 | data = '' | |
1738 | use_temp = 0 |
|
1702 | use_temp = 0 | |
1739 | elif args: |
|
1703 | elif args: | |
1740 | try: |
|
1704 | try: | |
1741 | # Load the parameter given as a variable. If not a string, |
|
1705 | # Load the parameter given as a variable. If not a string, | |
1742 | # process it as an object instead (below) |
|
1706 | # process it as an object instead (below) | |
1743 |
|
1707 | |||
1744 | #print '*** args',args,'type',type(args) # dbg |
|
1708 | #print '*** args',args,'type',type(args) # dbg | |
1745 | data = eval(args,self.shell.user_ns) |
|
1709 | data = eval(args,self.shell.user_ns) | |
1746 | if not type(data) in StringTypes: |
|
1710 | if not type(data) in StringTypes: | |
1747 | raise DataIsObject |
|
1711 | raise DataIsObject | |
1748 | except (NameError,SyntaxError): |
|
1712 | except (NameError,SyntaxError): | |
1749 | # given argument is not a variable, try as a filename |
|
1713 | # given argument is not a variable, try as a filename | |
1750 | filename = make_filename(args) |
|
1714 | filename = make_filename(args) | |
1751 | if filename is None: |
|
1715 | if filename is None: | |
1752 | warn("Argument given (%s) can't be found as a variable " |
|
1716 | warn("Argument given (%s) can't be found as a variable " | |
1753 | "or as a filename." % args) |
|
1717 | "or as a filename." % args) | |
1754 | return |
|
1718 | return | |
1755 | data = '' |
|
1719 | data = '' | |
1756 | use_temp = 0 |
|
1720 | use_temp = 0 | |
1757 | except DataIsObject: |
|
1721 | except DataIsObject: | |
1758 | # For objects, try to edit the file where they are defined |
|
1722 | # For objects, try to edit the file where they are defined | |
1759 | try: |
|
1723 | try: | |
1760 | filename = inspect.getabsfile(data) |
|
1724 | filename = inspect.getabsfile(data) | |
1761 | datafile = 1 |
|
1725 | datafile = 1 | |
1762 | except TypeError: |
|
1726 | except TypeError: | |
1763 | filename = make_filename(args) |
|
1727 | filename = make_filename(args) | |
1764 | datafile = 1 |
|
1728 | datafile = 1 | |
1765 | warn('Could not find file where `%s` is defined.\n' |
|
1729 | warn('Could not find file where `%s` is defined.\n' | |
1766 | 'Opening a file named `%s`' % (args,filename)) |
|
1730 | 'Opening a file named `%s`' % (args,filename)) | |
1767 | # Now, make sure we can actually read the source (if it was in |
|
1731 | # Now, make sure we can actually read the source (if it was in | |
1768 | # a temp file it's gone by now). |
|
1732 | # a temp file it's gone by now). | |
1769 | if datafile: |
|
1733 | if datafile: | |
1770 | try: |
|
1734 | try: | |
1771 | lineno = inspect.getsourcelines(data)[1] |
|
1735 | lineno = inspect.getsourcelines(data)[1] | |
1772 | except IOError: |
|
1736 | except IOError: | |
1773 | filename = make_filename(args) |
|
1737 | filename = make_filename(args) | |
1774 | if filename is None: |
|
1738 | if filename is None: | |
1775 | warn('The file `%s` where `%s` was defined cannot ' |
|
1739 | warn('The file `%s` where `%s` was defined cannot ' | |
1776 | 'be read.' % (filename,data)) |
|
1740 | 'be read.' % (filename,data)) | |
1777 | return |
|
1741 | return | |
1778 | use_temp = 0 |
|
1742 | use_temp = 0 | |
1779 | else: |
|
1743 | else: | |
1780 | data = '' |
|
1744 | data = '' | |
1781 |
|
1745 | |||
1782 | if use_temp: |
|
1746 | if use_temp: | |
1783 | filename = tempfile.mktemp('.py') |
|
1747 | filename = tempfile.mktemp('.py') | |
1784 | self.shell.tempfiles.append(filename) |
|
1748 | self.shell.tempfiles.append(filename) | |
1785 |
|
1749 | |||
1786 | if data and use_temp: |
|
1750 | if data and use_temp: | |
1787 | tmp_file = open(filename,'w') |
|
1751 | tmp_file = open(filename,'w') | |
1788 | tmp_file.write(data) |
|
1752 | tmp_file.write(data) | |
1789 | tmp_file.close() |
|
1753 | tmp_file.close() | |
1790 |
|
1754 | |||
1791 | # do actual editing here |
|
1755 | # do actual editing here | |
1792 | print 'Editing...', |
|
1756 | print 'Editing...', | |
1793 | sys.stdout.flush() |
|
1757 | sys.stdout.flush() | |
1794 | self.shell.hooks.editor(filename,lineno) |
|
1758 | self.shell.hooks.editor(filename,lineno) | |
1795 | if opts.has_key('x'): # -x prevents actual execution |
|
1759 | if opts.has_key('x'): # -x prevents actual execution | |
1796 |
|
1760 | |||
1797 | else: |
|
1761 | else: | |
1798 | print 'done. Executing edited code...' |
|
1762 | print 'done. Executing edited code...' | |
1799 | try: |
|
1763 | try: | |
1800 | execfile(filename,self.shell.user_ns) |
|
1764 | execfile(filename,self.shell.user_ns) | |
1801 | except IOError,msg: |
|
1765 | except IOError,msg: | |
1802 | if msg.filename == filename: |
|
1766 | if msg.filename == filename: | |
1803 | warn('File not found. Did you forget to save?') |
|
1767 | warn('File not found. Did you forget to save?') | |
1804 | return |
|
1768 | return | |
1805 | else: |
|
1769 | else: | |
1806 | self.shell.showtraceback() |
|
1770 | self.shell.showtraceback() | |
1807 | except: |
|
1771 | except: | |
1808 | self.shell.showtraceback() |
|
1772 | self.shell.showtraceback() | |
1809 | if use_temp: |
|
1773 | if use_temp: | |
1810 | contents = open(filename).read() |
|
1774 | contents = open(filename).read() | |
1811 | return contents |
|
1775 | return contents | |
1812 |
|
1776 | |||
1813 | def magic_xmode(self,parameter_s = ''): |
|
1777 | def magic_xmode(self,parameter_s = ''): | |
1814 | """Switch modes for the exception handlers. |
|
1778 | """Switch modes for the exception handlers. | |
1815 |
|
1779 | |||
1816 | Valid modes: Plain, Context and Verbose. |
|
1780 | Valid modes: Plain, Context and Verbose. | |
1817 |
|
1781 | |||
1818 | If called without arguments, acts as a toggle.""" |
|
1782 | If called without arguments, acts as a toggle.""" | |
1819 |
|
1783 | |||
1820 | new_mode = parameter_s.strip().capitalize() |
|
1784 | new_mode = parameter_s.strip().capitalize() | |
1821 | try: |
|
1785 | try: | |
1822 | self.InteractiveTB.set_mode(mode = new_mode) |
|
1786 | self.InteractiveTB.set_mode(mode = new_mode) | |
1823 | print 'Exception reporting mode:',self.InteractiveTB.mode |
|
1787 | print 'Exception reporting mode:',self.InteractiveTB.mode | |
1824 | except: |
|
1788 | except: | |
1825 | warn('Error changing exception modes.\n' + str(sys.exc_info()[1])) |
|
1789 | warn('Error changing exception modes.\n' + str(sys.exc_info()[1])) | |
1826 |
|
1790 | |||
1827 | def magic_colors(self,parameter_s = ''): |
|
1791 | def magic_colors(self,parameter_s = ''): | |
1828 | """Switch color scheme for prompts, info system and exception handlers. |
|
1792 | """Switch color scheme for prompts, info system and exception handlers. | |
1829 |
|
1793 | |||
1830 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
1794 | Currently implemented schemes: NoColor, Linux, LightBG. | |
1831 |
|
1795 | |||
1832 | Color scheme names are not case-sensitive.""" |
|
1796 | Color scheme names are not case-sensitive.""" | |
1833 |
|
1797 | |||
1834 | new_scheme = parameter_s.strip() |
|
1798 | new_scheme = parameter_s.strip() | |
1835 | if not new_scheme: |
|
1799 | if not new_scheme: | |
1836 | print 'You must specify a color scheme.' |
|
1800 | print 'You must specify a color scheme.' | |
1837 | return |
|
1801 | return | |
1838 | # Under Windows, check for Gary Bishop's readline, which is necessary |
|
1802 | # Under Windows, check for Gary Bishop's readline, which is necessary | |
1839 | # for ANSI coloring |
|
1803 | # for ANSI coloring | |
1840 | if os.name in ['nt','dos']: |
|
1804 | if os.name in ['nt','dos']: | |
1841 | try: |
|
1805 | try: | |
1842 | import readline |
|
1806 | import readline | |
1843 | except ImportError: |
|
1807 | except ImportError: | |
1844 | has_readline = 0 |
|
1808 | has_readline = 0 | |
1845 | else: |
|
1809 | else: | |
1846 | try: |
|
1810 | try: | |
1847 | readline.GetOutputFile() |
|
1811 | readline.GetOutputFile() | |
1848 | except AttributeError: |
|
1812 | except AttributeError: | |
1849 | has_readline = 0 |
|
1813 | has_readline = 0 | |
1850 | else: |
|
1814 | else: | |
1851 | has_readline = 1 |
|
1815 | has_readline = 1 | |
1852 | if not has_readline: |
|
1816 | if not has_readline: | |
1853 | msg = """\ |
|
1817 | msg = """\ | |
1854 | Proper color support under MS Windows requires Gary Bishop's readline library. |
|
1818 | Proper color support under MS Windows requires Gary Bishop's readline library. | |
1855 | You can find it at: |
|
1819 | You can find it at: | |
1856 | http://sourceforge.net/projects/uncpythontools |
|
1820 | http://sourceforge.net/projects/uncpythontools | |
1857 | Gary's readline needs the ctypes module, from: |
|
1821 | Gary's readline needs the ctypes module, from: | |
1858 | http://starship.python.net/crew/theller/ctypes |
|
1822 | http://starship.python.net/crew/theller/ctypes | |
1859 |
|
1823 | |||
1860 | Defaulting color scheme to 'NoColor'""" |
|
1824 | Defaulting color scheme to 'NoColor'""" | |
1861 | new_scheme = 'NoColor' |
|
1825 | new_scheme = 'NoColor' | |
1862 | warn(msg) |
|
1826 | warn(msg) | |
1863 |
|
1827 | |||
1864 | # Set prompt colors |
|
1828 | # Set prompt colors | |
1865 | try: |
|
1829 | try: | |
1866 | self.shell.outputcache.set_colors(new_scheme) |
|
1830 | self.shell.outputcache.set_colors(new_scheme) | |
1867 | except: |
|
1831 | except: | |
1868 | warn('Error changing prompt color schemes.\n' |
|
1832 | warn('Error changing prompt color schemes.\n' | |
1869 | + str(sys.exc_info()[1])) |
|
1833 | + str(sys.exc_info()[1])) | |
1870 | else: |
|
1834 | else: | |
1871 | self.shell.rc.colors = \ |
|
1835 | self.shell.rc.colors = \ | |
1872 | self.shell.outputcache.color_table.active_scheme_name |
|
1836 | self.shell.outputcache.color_table.active_scheme_name | |
1873 | # Set exception colors |
|
1837 | # Set exception colors | |
1874 | try: |
|
1838 | try: | |
1875 | self.shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
1839 | self.shell.InteractiveTB.set_colors(scheme = new_scheme) | |
1876 | self.shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
1840 | self.shell.SyntaxTB.set_colors(scheme = new_scheme) | |
1877 | except: |
|
1841 | except: | |
1878 | warn('Error changing exception color schemes.\n' |
|
1842 | warn('Error changing exception color schemes.\n' | |
1879 | + str(sys.exc_info()[1])) |
|
1843 | + str(sys.exc_info()[1])) | |
1880 | # Set info (for 'object?') colors |
|
1844 | # Set info (for 'object?') colors | |
1881 | if self.shell.rc.color_info: |
|
1845 | if self.shell.rc.color_info: | |
1882 | try: |
|
1846 | try: | |
1883 | self.shell.inspector.set_active_scheme(new_scheme) |
|
1847 | self.shell.inspector.set_active_scheme(new_scheme) | |
1884 | except: |
|
1848 | except: | |
1885 | warn('Error changing object inspector color schemes.\n' |
|
1849 | warn('Error changing object inspector color schemes.\n' | |
1886 | + str(sys.exc_info()[1])) |
|
1850 | + str(sys.exc_info()[1])) | |
1887 | else: |
|
1851 | else: | |
1888 | self.shell.inspector.set_active_scheme('NoColor') |
|
1852 | self.shell.inspector.set_active_scheme('NoColor') | |
1889 |
|
1853 | |||
1890 | def magic_color_info(self,parameter_s = ''): |
|
1854 | def magic_color_info(self,parameter_s = ''): | |
1891 | """Toggle color_info. |
|
1855 | """Toggle color_info. | |
1892 |
|
1856 | |||
1893 | The color_info configuration parameter controls whether colors are |
|
1857 | The color_info configuration parameter controls whether colors are | |
1894 | used for displaying object details (by things like %psource, %pfile or |
|
1858 | used for displaying object details (by things like %psource, %pfile or | |
1895 | the '?' system). This function toggles this value with each call. |
|
1859 | the '?' system). This function toggles this value with each call. | |
1896 |
|
1860 | |||
1897 | Note that unless you have a fairly recent pager (less works better |
|
1861 | Note that unless you have a fairly recent pager (less works better | |
1898 | than more) in your system, using colored object information displays |
|
1862 | than more) in your system, using colored object information displays | |
1899 | will not work properly. Test it and see.""" |
|
1863 | will not work properly. Test it and see.""" | |
1900 |
|
1864 | |||
1901 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
1865 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
1902 | self.magic_colors(self.shell.rc.colors) |
|
1866 | self.magic_colors(self.shell.rc.colors) | |
1903 | print 'Object introspection functions have now coloring:', |
|
1867 | print 'Object introspection functions have now coloring:', | |
1904 | print ['OFF','ON'][self.shell.rc.color_info] |
|
1868 | print ['OFF','ON'][self.shell.rc.color_info] | |
1905 |
|
1869 | |||
1906 | def magic_Pprint(self, parameter_s=''): |
|
1870 | def magic_Pprint(self, parameter_s=''): | |
1907 | """Toggle pretty printing on/off.""" |
|
1871 | """Toggle pretty printing on/off.""" | |
1908 |
|
1872 | |||
1909 | self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint |
|
1873 | self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint | |
1910 | print 'Pretty printing has been turned', \ |
|
1874 | print 'Pretty printing has been turned', \ | |
1911 | ['OFF','ON'][self.shell.outputcache.Pprint] |
|
1875 | ['OFF','ON'][self.shell.outputcache.Pprint] | |
1912 |
|
1876 | |||
1913 | def magic_Exit(self, parameter_s=''): |
|
1877 | def magic_Exit(self, parameter_s=''): | |
1914 | """Exit IPython without confirmation.""" |
|
1878 | """Exit IPython without confirmation.""" | |
1915 |
|
1879 | |||
1916 | self.shell.exit_now = True |
|
1880 | self.shell.exit_now = True | |
1917 |
|
1881 | |||
1918 | def magic_Quit(self, parameter_s=''): |
|
1882 | def magic_Quit(self, parameter_s=''): | |
1919 | """Exit IPython without confirmation (like %Exit).""" |
|
1883 | """Exit IPython without confirmation (like %Exit).""" | |
1920 |
|
1884 | |||
1921 | self.shell.exit_now = True |
|
1885 | self.shell.exit_now = True | |
1922 |
|
1886 | |||
1923 | #...................................................................... |
|
1887 | #...................................................................... | |
1924 | # Functions to implement unix shell-type things |
|
1888 | # Functions to implement unix shell-type things | |
1925 |
|
1889 | |||
1926 | def magic_alias(self, parameter_s = ''): |
|
1890 | def magic_alias(self, parameter_s = ''): | |
1927 | """Define an alias for a system command. |
|
1891 | """Define an alias for a system command. | |
1928 |
|
1892 | |||
1929 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
1893 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
1930 |
|
1894 | |||
1931 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
1895 | Then, typing 'alias_name params' will execute the system command 'cmd | |
1932 | params' (from your underlying operating system). |
|
1896 | params' (from your underlying operating system). | |
1933 |
|
1897 | |||
1934 | Aliases have lower precedence than magic functions and Python normal |
|
1898 | Aliases have lower precedence than magic functions and Python normal | |
1935 | variables, so if 'foo' is both a Python variable and an alias, the |
|
1899 | variables, so if 'foo' is both a Python variable and an alias, the | |
1936 | alias can not be executed until 'del foo' removes the Python variable. |
|
1900 | alias can not be executed until 'del foo' removes the Python variable. | |
1937 |
|
1901 | |||
1938 | You can use the %l specifier in an alias definition to represent the |
|
1902 | You can use the %l specifier in an alias definition to represent the | |
1939 | whole line when the alias is called. For example: |
|
1903 | whole line when the alias is called. For example: | |
1940 |
|
1904 | |||
1941 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
1905 | In [2]: alias all echo "Input in brackets: <%l>"\\ | |
1942 | In [3]: all hello world\\ |
|
1906 | In [3]: all hello world\\ | |
1943 | Input in brackets: <hello world> |
|
1907 | Input in brackets: <hello world> | |
1944 |
|
1908 | |||
1945 | You can also define aliases with parameters using %s specifiers (one |
|
1909 | You can also define aliases with parameters using %s specifiers (one | |
1946 | per parameter): |
|
1910 | per parameter): | |
1947 |
|
1911 | |||
1948 | In [1]: alias parts echo first %s second %s\\ |
|
1912 | In [1]: alias parts echo first %s second %s\\ | |
1949 | In [2]: %parts A B\\ |
|
1913 | In [2]: %parts A B\\ | |
1950 | first A second B\\ |
|
1914 | first A second B\\ | |
1951 | In [3]: %parts A\\ |
|
1915 | In [3]: %parts A\\ | |
1952 | Incorrect number of arguments: 2 expected.\\ |
|
1916 | Incorrect number of arguments: 2 expected.\\ | |
1953 | parts is an alias to: 'echo first %s second %s' |
|
1917 | parts is an alias to: 'echo first %s second %s' | |
1954 |
|
1918 | |||
1955 | Note that %l and %s are mutually exclusive. You can only use one or |
|
1919 | Note that %l and %s are mutually exclusive. You can only use one or | |
1956 | the other in your aliases. |
|
1920 | the other in your aliases. | |
1957 |
|
1921 | |||
1958 | Aliases expand Python variables just like system calls using ! or !! |
|
1922 | Aliases expand Python variables just like system calls using ! or !! | |
1959 | do: all expressions prefixed with '$' get expanded. For details of |
|
1923 | do: all expressions prefixed with '$' get expanded. For details of | |
1960 | the semantic rules, see PEP-215: |
|
1924 | the semantic rules, see PEP-215: | |
1961 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
1925 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
1962 | IPython for variable expansion. If you want to access a true shell |
|
1926 | IPython for variable expansion. If you want to access a true shell | |
1963 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
1927 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
1964 |
|
1928 | |||
1965 | In [6]: alias show echo\\ |
|
1929 | In [6]: alias show echo\\ | |
1966 | In [7]: PATH='A Python string'\\ |
|
1930 | In [7]: PATH='A Python string'\\ | |
1967 | In [8]: show $PATH\\ |
|
1931 | In [8]: show $PATH\\ | |
1968 | A Python string\\ |
|
1932 | A Python string\\ | |
1969 | In [9]: show $$PATH\\ |
|
1933 | In [9]: show $$PATH\\ | |
1970 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
1934 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
1971 |
|
1935 | |||
1972 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
1936 | You can use the alias facility to acess all of $PATH. See the %rehash | |
1973 | and %rehashx functions, which automatically create aliases for the |
|
1937 | and %rehashx functions, which automatically create aliases for the | |
1974 | contents of your $PATH. |
|
1938 | contents of your $PATH. | |
1975 |
|
1939 | |||
1976 | If called with no parameters, %alias prints the current alias table.""" |
|
1940 | If called with no parameters, %alias prints the current alias table.""" | |
1977 |
|
1941 | |||
1978 | par = parameter_s.strip() |
|
1942 | par = parameter_s.strip() | |
1979 | if not par: |
|
1943 | if not par: | |
1980 | if self.shell.rc.automagic: |
|
1944 | if self.shell.rc.automagic: | |
1981 | prechar = '' |
|
1945 | prechar = '' | |
1982 | else: |
|
1946 | else: | |
1983 | prechar = self.shell.ESC_MAGIC |
|
1947 | prechar = self.shell.ESC_MAGIC | |
1984 | print 'Alias\t\tSystem Command\n'+'-'*30 |
|
1948 | print 'Alias\t\tSystem Command\n'+'-'*30 | |
1985 | atab = self.shell.alias_table |
|
1949 | atab = self.shell.alias_table | |
1986 | aliases = atab.keys() |
|
1950 | aliases = atab.keys() | |
1987 | aliases.sort() |
|
1951 | aliases.sort() | |
1988 | for alias in aliases: |
|
1952 | for alias in aliases: | |
1989 | print prechar+alias+'\t\t'+atab[alias][1] |
|
1953 | print prechar+alias+'\t\t'+atab[alias][1] | |
1990 | print '-'*30+'\nTotal number of aliases:',len(aliases) |
|
1954 | print '-'*30+'\nTotal number of aliases:',len(aliases) | |
1991 | return |
|
1955 | return | |
1992 | try: |
|
1956 | try: | |
1993 | alias,cmd = par.split(None,1) |
|
1957 | alias,cmd = par.split(None,1) | |
1994 | except: |
|
1958 | except: | |
1995 | print OInspect.getdoc(self.magic_alias) |
|
1959 | print OInspect.getdoc(self.magic_alias) | |
1996 | else: |
|
1960 | else: | |
1997 | nargs = cmd.count('%s') |
|
1961 | nargs = cmd.count('%s') | |
1998 | if nargs>0 and cmd.find('%l')>=0: |
|
1962 | if nargs>0 and cmd.find('%l')>=0: | |
1999 | error('The %s and %l specifiers are mutually exclusive ' |
|
1963 | error('The %s and %l specifiers are mutually exclusive ' | |
2000 | 'in alias definitions.') |
|
1964 | 'in alias definitions.') | |
2001 | else: # all looks OK |
|
1965 | else: # all looks OK | |
2002 | self.shell.alias_table[alias] = (nargs,cmd) |
|
1966 | self.shell.alias_table[alias] = (nargs,cmd) | |
2003 | self.shell.alias_table_validate(verbose=1) |
|
1967 | self.shell.alias_table_validate(verbose=1) | |
2004 | # end magic_alias |
|
1968 | # end magic_alias | |
2005 |
|
1969 | |||
2006 | def magic_unalias(self, parameter_s = ''): |
|
1970 | def magic_unalias(self, parameter_s = ''): | |
2007 | """Remove an alias""" |
|
1971 | """Remove an alias""" | |
2008 |
|
1972 | |||
2009 | aname = parameter_s.strip() |
|
1973 | aname = parameter_s.strip() | |
2010 | if aname in self.shell.alias_table: |
|
1974 | if aname in self.shell.alias_table: | |
2011 | del self.shell.alias_table[aname] |
|
1975 | del self.shell.alias_table[aname] | |
2012 |
|
1976 | |||
2013 | def magic_rehash(self, parameter_s = ''): |
|
1977 | def magic_rehash(self, parameter_s = ''): | |
2014 | """Update the alias table with all entries in $PATH. |
|
1978 | """Update the alias table with all entries in $PATH. | |
2015 |
|
1979 | |||
2016 | This version does no checks on execute permissions or whether the |
|
1980 | This version does no checks on execute permissions or whether the | |
2017 | contents of $PATH are truly files (instead of directories or something |
|
1981 | contents of $PATH are truly files (instead of directories or something | |
2018 | else). For such a safer (but slower) version, use %rehashx.""" |
|
1982 | else). For such a safer (but slower) version, use %rehashx.""" | |
2019 |
|
1983 | |||
2020 | # This function (and rehashx) manipulate the alias_table directly |
|
1984 | # This function (and rehashx) manipulate the alias_table directly | |
2021 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
1985 | # rather than calling magic_alias, for speed reasons. A rehash on a | |
2022 | # typical Linux box involves several thousand entries, so efficiency |
|
1986 | # typical Linux box involves several thousand entries, so efficiency | |
2023 | # here is a top concern. |
|
1987 | # here is a top concern. | |
2024 |
|
1988 | |||
2025 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
1989 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) | |
2026 | alias_table = self.shell.alias_table |
|
1990 | alias_table = self.shell.alias_table | |
2027 | for pdir in path: |
|
1991 | for pdir in path: | |
2028 | for ff in os.listdir(pdir): |
|
1992 | for ff in os.listdir(pdir): | |
2029 | # each entry in the alias table must be (N,name), where |
|
1993 | # each entry in the alias table must be (N,name), where | |
2030 | # N is the number of positional arguments of the alias. |
|
1994 | # N is the number of positional arguments of the alias. | |
2031 | alias_table[ff] = (0,ff) |
|
1995 | alias_table[ff] = (0,ff) | |
2032 | # Make sure the alias table doesn't contain keywords or builtins |
|
1996 | # Make sure the alias table doesn't contain keywords or builtins | |
2033 | self.shell.alias_table_validate() |
|
1997 | self.shell.alias_table_validate() | |
2034 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
1998 | # Call again init_auto_alias() so we get 'rm -i' and other modified | |
2035 | # aliases since %rehash will probably clobber them |
|
1999 | # aliases since %rehash will probably clobber them | |
2036 | self.shell.init_auto_alias() |
|
2000 | self.shell.init_auto_alias() | |
2037 |
|
2001 | |||
2038 | def magic_rehashx(self, parameter_s = ''): |
|
2002 | def magic_rehashx(self, parameter_s = ''): | |
2039 | """Update the alias table with all executable files in $PATH. |
|
2003 | """Update the alias table with all executable files in $PATH. | |
2040 |
|
2004 | |||
2041 | This version explicitly checks that every entry in $PATH is a file |
|
2005 | This version explicitly checks that every entry in $PATH is a file | |
2042 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2006 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2043 |
|
2007 | |||
2044 | Under Windows, it checks executability as a match agains a |
|
2008 | Under Windows, it checks executability as a match agains a | |
2045 | '|'-separated string of extensions, stored in the IPython config |
|
2009 | '|'-separated string of extensions, stored in the IPython config | |
2046 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ |
|
2010 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ | |
2047 |
|
2011 | |||
2048 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
2012 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) | |
2049 | alias_table = self.shell.alias_table |
|
2013 | alias_table = self.shell.alias_table | |
2050 |
|
2014 | |||
2051 | if os.name == 'posix': |
|
2015 | if os.name == 'posix': | |
2052 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2016 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2053 | os.access(fname,os.X_OK) |
|
2017 | os.access(fname,os.X_OK) | |
2054 | else: |
|
2018 | else: | |
2055 |
|
2019 | |||
2056 | try: |
|
2020 | try: | |
2057 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2021 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2058 | except KeyError: |
|
2022 | except KeyError: | |
2059 | winext = 'exe|com|bat' |
|
2023 | winext = 'exe|com|bat' | |
2060 |
|
2024 | |||
2061 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2025 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2062 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2026 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2063 | savedir = os.getcwd() |
|
2027 | savedir = os.getcwd() | |
2064 | try: |
|
2028 | try: | |
2065 | # write the whole loop for posix/Windows so we don't have an if in |
|
2029 | # write the whole loop for posix/Windows so we don't have an if in | |
2066 | # the innermost part |
|
2030 | # the innermost part | |
2067 | if os.name == 'posix': |
|
2031 | if os.name == 'posix': | |
2068 | for pdir in path: |
|
2032 | for pdir in path: | |
2069 | os.chdir(pdir) |
|
2033 | os.chdir(pdir) | |
2070 | for ff in os.listdir(pdir): |
|
2034 | for ff in os.listdir(pdir): | |
2071 | if isexec(ff): |
|
2035 | if isexec(ff): | |
2072 | # each entry in the alias table must be (N,name), |
|
2036 | # each entry in the alias table must be (N,name), | |
2073 | # where N is the number of positional arguments of the |
|
2037 | # where N is the number of positional arguments of the | |
2074 | # alias. |
|
2038 | # alias. | |
2075 | alias_table[ff] = (0,ff) |
|
2039 | alias_table[ff] = (0,ff) | |
2076 | else: |
|
2040 | else: | |
2077 | for pdir in path: |
|
2041 | for pdir in path: | |
2078 | os.chdir(pdir) |
|
2042 | os.chdir(pdir) | |
2079 | for ff in os.listdir(pdir): |
|
2043 | for ff in os.listdir(pdir): | |
2080 | if isexec(ff): |
|
2044 | if isexec(ff): | |
2081 | alias_table[execre.sub(r'\1',ff)] = (0,ff) |
|
2045 | alias_table[execre.sub(r'\1',ff)] = (0,ff) | |
2082 | # Make sure the alias table doesn't contain keywords or builtins |
|
2046 | # Make sure the alias table doesn't contain keywords or builtins | |
2083 | self.shell.alias_table_validate() |
|
2047 | self.shell.alias_table_validate() | |
2084 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2048 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2085 | # modified aliases since %rehashx will probably clobber them |
|
2049 | # modified aliases since %rehashx will probably clobber them | |
2086 | self.shell.init_auto_alias() |
|
2050 | self.shell.init_auto_alias() | |
2087 | finally: |
|
2051 | finally: | |
2088 | os.chdir(savedir) |
|
2052 | os.chdir(savedir) | |
2089 |
|
2053 | |||
2090 | def magic_pwd(self, parameter_s = ''): |
|
2054 | def magic_pwd(self, parameter_s = ''): | |
2091 | """Return the current working directory path.""" |
|
2055 | """Return the current working directory path.""" | |
2092 | return os.getcwd() |
|
2056 | return os.getcwd() | |
2093 |
|
2057 | |||
2094 | def magic_cd(self, parameter_s=''): |
|
2058 | def magic_cd(self, parameter_s=''): | |
2095 | """Change the current working directory. |
|
2059 | """Change the current working directory. | |
2096 |
|
2060 | |||
2097 | This command automatically maintains an internal list of directories |
|
2061 | This command automatically maintains an internal list of directories | |
2098 | you visit during your IPython session, in the variable _dh. The |
|
2062 | you visit during your IPython session, in the variable _dh. The | |
2099 | command %dhist shows this history nicely formatted. |
|
2063 | command %dhist shows this history nicely formatted. | |
2100 |
|
2064 | |||
2101 | Usage: |
|
2065 | Usage: | |
2102 |
|
2066 | |||
2103 | cd 'dir': changes to directory 'dir'. |
|
2067 | cd 'dir': changes to directory 'dir'. | |
2104 |
|
2068 | |||
2105 | cd -: changes to the last visited directory. |
|
2069 | cd -: changes to the last visited directory. | |
2106 |
|
2070 | |||
2107 | cd -<n>: changes to the n-th directory in the directory history. |
|
2071 | cd -<n>: changes to the n-th directory in the directory history. | |
2108 |
|
2072 | |||
2109 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2073 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2110 | (note: cd <bookmark_name> is enough if there is no |
|
2074 | (note: cd <bookmark_name> is enough if there is no | |
2111 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2075 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2112 |
|
2076 | |||
2113 | Options: |
|
2077 | Options: | |
2114 |
|
2078 | |||
2115 | -q: quiet. Do not print the working directory after the cd command is |
|
2079 | -q: quiet. Do not print the working directory after the cd command is | |
2116 | executed. By default IPython's cd command does print this directory, |
|
2080 | executed. By default IPython's cd command does print this directory, | |
2117 | since the default prompts do not display path information. |
|
2081 | since the default prompts do not display path information. | |
2118 |
|
2082 | |||
2119 | Note that !cd doesn't work for this purpose because the shell where |
|
2083 | Note that !cd doesn't work for this purpose because the shell where | |
2120 | !command runs is immediately discarded after executing 'command'.""" |
|
2084 | !command runs is immediately discarded after executing 'command'.""" | |
2121 |
|
2085 | |||
2122 | parameter_s = parameter_s.strip() |
|
2086 | parameter_s = parameter_s.strip() | |
2123 | bkms = self.shell.persist.get("bookmarks",{}) |
|
2087 | bkms = self.shell.persist.get("bookmarks",{}) | |
2124 |
|
2088 | |||
2125 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2089 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2126 | # jump in directory history by number |
|
2090 | # jump in directory history by number | |
2127 | if numcd: |
|
2091 | if numcd: | |
2128 | nn = int(numcd.group(2)) |
|
2092 | nn = int(numcd.group(2)) | |
2129 | try: |
|
2093 | try: | |
2130 | ps = self.shell.user_ns['_dh'][nn] |
|
2094 | ps = self.shell.user_ns['_dh'][nn] | |
2131 | except IndexError: |
|
2095 | except IndexError: | |
2132 | print 'The requested directory does not exist in history.' |
|
2096 | print 'The requested directory does not exist in history.' | |
2133 | return |
|
2097 | return | |
2134 | else: |
|
2098 | else: | |
2135 | opts = {} |
|
2099 | opts = {} | |
2136 | else: |
|
2100 | else: | |
2137 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2101 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2138 | # jump to previous |
|
2102 | # jump to previous | |
2139 | if ps == '-': |
|
2103 | if ps == '-': | |
2140 | try: |
|
2104 | try: | |
2141 | ps = self.shell.user_ns['_dh'][-2] |
|
2105 | ps = self.shell.user_ns['_dh'][-2] | |
2142 | except IndexError: |
|
2106 | except IndexError: | |
2143 | print 'No previous directory to change to.' |
|
2107 | print 'No previous directory to change to.' | |
2144 | return |
|
2108 | return | |
2145 | # jump to bookmark |
|
2109 | # jump to bookmark | |
2146 | elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)): |
|
2110 | elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)): | |
2147 | if bkms.has_key(ps): |
|
2111 | if bkms.has_key(ps): | |
2148 | target = bkms[ps] |
|
2112 | target = bkms[ps] | |
2149 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2113 | print '(bookmark:%s) -> %s' % (ps,target) | |
2150 | ps = target |
|
2114 | ps = target | |
2151 | else: |
|
2115 | else: | |
2152 | if bkms: |
|
2116 | if bkms: | |
2153 | error("Bookmark '%s' not found. " |
|
2117 | error("Bookmark '%s' not found. " | |
2154 | "Use '%bookmark -l' to see your bookmarks." % ps) |
|
2118 | "Use '%bookmark -l' to see your bookmarks." % ps) | |
2155 | else: |
|
2119 | else: | |
2156 | print "Bookmarks not set - use %bookmark <bookmarkname>" |
|
2120 | print "Bookmarks not set - use %bookmark <bookmarkname>" | |
2157 | return |
|
2121 | return | |
2158 |
|
2122 | |||
2159 | # at this point ps should point to the target dir |
|
2123 | # at this point ps should point to the target dir | |
2160 | if ps: |
|
2124 | if ps: | |
2161 | try: |
|
2125 | try: | |
2162 | os.chdir(os.path.expanduser(ps)) |
|
2126 | os.chdir(os.path.expanduser(ps)) | |
2163 | except OSError: |
|
2127 | except OSError: | |
2164 | print sys.exc_info()[1] |
|
2128 | print sys.exc_info()[1] | |
2165 | else: |
|
2129 | else: | |
2166 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2130 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2167 | else: |
|
2131 | else: | |
2168 | os.chdir(self.home_dir) |
|
2132 | os.chdir(self.home_dir) | |
2169 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2133 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2170 | if not 'q' in opts: |
|
2134 | if not 'q' in opts: | |
2171 | print self.shell.user_ns['_dh'][-1] |
|
2135 | print self.shell.user_ns['_dh'][-1] | |
2172 |
|
2136 | |||
2173 | def magic_dhist(self, parameter_s=''): |
|
2137 | def magic_dhist(self, parameter_s=''): | |
2174 | """Print your history of visited directories. |
|
2138 | """Print your history of visited directories. | |
2175 |
|
2139 | |||
2176 | %dhist -> print full history\\ |
|
2140 | %dhist -> print full history\\ | |
2177 | %dhist n -> print last n entries only\\ |
|
2141 | %dhist n -> print last n entries only\\ | |
2178 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2142 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2179 |
|
2143 | |||
2180 | This history is automatically maintained by the %cd command, and |
|
2144 | This history is automatically maintained by the %cd command, and | |
2181 | always available as the global list variable _dh. You can use %cd -<n> |
|
2145 | always available as the global list variable _dh. You can use %cd -<n> | |
2182 | to go to directory number <n>.""" |
|
2146 | to go to directory number <n>.""" | |
2183 |
|
2147 | |||
2184 | dh = self.shell.user_ns['_dh'] |
|
2148 | dh = self.shell.user_ns['_dh'] | |
2185 | if parameter_s: |
|
2149 | if parameter_s: | |
2186 | try: |
|
2150 | try: | |
2187 | args = map(int,parameter_s.split()) |
|
2151 | args = map(int,parameter_s.split()) | |
2188 | except: |
|
2152 | except: | |
2189 | self.arg_err(Magic.magic_dhist) |
|
2153 | self.arg_err(Magic.magic_dhist) | |
2190 | return |
|
2154 | return | |
2191 | if len(args) == 1: |
|
2155 | if len(args) == 1: | |
2192 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2156 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2193 | elif len(args) == 2: |
|
2157 | elif len(args) == 2: | |
2194 | ini,fin = args |
|
2158 | ini,fin = args | |
2195 | else: |
|
2159 | else: | |
2196 | self.arg_err(Magic.magic_dhist) |
|
2160 | self.arg_err(Magic.magic_dhist) | |
2197 | return |
|
2161 | return | |
2198 | else: |
|
2162 | else: | |
2199 | ini,fin = 0,len(dh) |
|
2163 | ini,fin = 0,len(dh) | |
2200 | nlprint(dh, |
|
2164 | nlprint(dh, | |
2201 | header = 'Directory history (kept in _dh)', |
|
2165 | header = 'Directory history (kept in _dh)', | |
2202 | start=ini,stop=fin) |
|
2166 | start=ini,stop=fin) | |
2203 |
|
2167 | |||
2204 | def magic_env(self, parameter_s=''): |
|
2168 | def magic_env(self, parameter_s=''): | |
2205 | """List environment variables.""" |
|
2169 | """List environment variables.""" | |
2206 |
|
2170 | |||
2207 | # environ is an instance of UserDict |
|
2171 | # environ is an instance of UserDict | |
2208 | return os.environ.data |
|
2172 | return os.environ.data | |
2209 |
|
2173 | |||
2210 | def magic_pushd(self, parameter_s=''): |
|
2174 | def magic_pushd(self, parameter_s=''): | |
2211 | """Place the current dir on stack and change directory. |
|
2175 | """Place the current dir on stack and change directory. | |
2212 |
|
2176 | |||
2213 | Usage:\\ |
|
2177 | Usage:\\ | |
2214 | %pushd ['dirname'] |
|
2178 | %pushd ['dirname'] | |
2215 |
|
2179 | |||
2216 | %pushd with no arguments does a %pushd to your home directory. |
|
2180 | %pushd with no arguments does a %pushd to your home directory. | |
2217 | """ |
|
2181 | """ | |
2218 | if parameter_s == '': parameter_s = '~' |
|
2182 | if parameter_s == '': parameter_s = '~' | |
2219 | if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \ |
|
2183 | if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \ | |
2220 | os.path.expanduser(self.dir_stack[0]): |
|
2184 | os.path.expanduser(self.dir_stack[0]): | |
2221 | try: |
|
2185 | try: | |
2222 | self.magic_cd(parameter_s) |
|
2186 | self.magic_cd(parameter_s) | |
2223 | self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2187 | self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~')) | |
2224 | self.magic_dirs() |
|
2188 | self.magic_dirs() | |
2225 | except: |
|
2189 | except: | |
2226 | print 'Invalid directory' |
|
2190 | print 'Invalid directory' | |
2227 | else: |
|
2191 | else: | |
2228 | print 'You are already there!' |
|
2192 | print 'You are already there!' | |
2229 |
|
2193 | |||
2230 | def magic_popd(self, parameter_s=''): |
|
2194 | def magic_popd(self, parameter_s=''): | |
2231 | """Change to directory popped off the top of the stack. |
|
2195 | """Change to directory popped off the top of the stack. | |
2232 | """ |
|
2196 | """ | |
2233 | if len (self.dir_stack) > 1: |
|
2197 | if len (self.dir_stack) > 1: | |
2234 | self.dir_stack.pop(0) |
|
2198 | self.dir_stack.pop(0) | |
2235 | self.magic_cd(self.dir_stack[0]) |
|
2199 | self.magic_cd(self.dir_stack[0]) | |
2236 | print self.dir_stack[0] |
|
2200 | print self.dir_stack[0] | |
2237 | else: |
|
2201 | else: | |
2238 | print "You can't remove the starting directory from the stack:",\ |
|
2202 | print "You can't remove the starting directory from the stack:",\ | |
2239 | self.dir_stack |
|
2203 | self.dir_stack | |
2240 |
|
2204 | |||
2241 | def magic_dirs(self, parameter_s=''): |
|
2205 | def magic_dirs(self, parameter_s=''): | |
2242 | """Return the current directory stack.""" |
|
2206 | """Return the current directory stack.""" | |
2243 |
|
2207 | |||
2244 | return self.dir_stack[:] |
|
2208 | return self.dir_stack[:] | |
2245 |
|
2209 | |||
2246 | def magic_sc(self, parameter_s=''): |
|
2210 | def magic_sc(self, parameter_s=''): | |
2247 | """Shell capture - execute a shell command and capture its output. |
|
2211 | """Shell capture - execute a shell command and capture its output. | |
2248 |
|
2212 | |||
2249 | %sc [options] varname=command |
|
2213 | %sc [options] varname=command | |
2250 |
|
2214 | |||
2251 | IPython will run the given command using commands.getoutput(), and |
|
2215 | IPython will run the given command using commands.getoutput(), and | |
2252 | will then update the user's interactive namespace with a variable |
|
2216 | will then update the user's interactive namespace with a variable | |
2253 | called varname, containing the value of the call. Your command can |
|
2217 | called varname, containing the value of the call. Your command can | |
2254 | contain shell wildcards, pipes, etc. |
|
2218 | contain shell wildcards, pipes, etc. | |
2255 |
|
2219 | |||
2256 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2220 | The '=' sign in the syntax is mandatory, and the variable name you | |
2257 | supply must follow Python's standard conventions for valid names. |
|
2221 | supply must follow Python's standard conventions for valid names. | |
2258 |
|
2222 | |||
2259 | Options: |
|
2223 | Options: | |
2260 |
|
2224 | |||
2261 | -l: list output. Split the output on newlines into a list before |
|
2225 | -l: list output. Split the output on newlines into a list before | |
2262 | assigning it to the given variable. By default the output is stored |
|
2226 | assigning it to the given variable. By default the output is stored | |
2263 | as a single string. |
|
2227 | as a single string. | |
2264 |
|
2228 | |||
2265 | -v: verbose. Print the contents of the variable. |
|
2229 | -v: verbose. Print the contents of the variable. | |
2266 |
|
2230 | |||
2267 | In most cases you should not need to split as a list, because the |
|
2231 | In most cases you should not need to split as a list, because the | |
2268 | returned value is a special type of string which can automatically |
|
2232 | returned value is a special type of string which can automatically | |
2269 | provide its contents either as a list (split on newlines) or as a |
|
2233 | provide its contents either as a list (split on newlines) or as a | |
2270 | space-separated string. These are convenient, respectively, either |
|
2234 | space-separated string. These are convenient, respectively, either | |
2271 | for sequential processing or to be passed to a shell command. |
|
2235 | for sequential processing or to be passed to a shell command. | |
2272 |
|
2236 | |||
2273 | For example: |
|
2237 | For example: | |
2274 |
|
2238 | |||
2275 | # Capture into variable a |
|
2239 | # Capture into variable a | |
2276 | In [9]: sc a=ls *py |
|
2240 | In [9]: sc a=ls *py | |
2277 |
|
2241 | |||
2278 | # a is a string with embedded newlines |
|
2242 | # a is a string with embedded newlines | |
2279 | In [10]: a |
|
2243 | In [10]: a | |
2280 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2244 | Out[10]: 'setup.py\nwin32_manual_post_install.py' | |
2281 |
|
2245 | |||
2282 | # which can be seen as a list: |
|
2246 | # which can be seen as a list: | |
2283 | In [11]: a.l |
|
2247 | In [11]: a.l | |
2284 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2248 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] | |
2285 |
|
2249 | |||
2286 | # or as a whitespace-separated string: |
|
2250 | # or as a whitespace-separated string: | |
2287 | In [12]: a.s |
|
2251 | In [12]: a.s | |
2288 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2252 | Out[12]: 'setup.py win32_manual_post_install.py' | |
2289 |
|
2253 | |||
2290 | # a.s is useful to pass as a single command line: |
|
2254 | # a.s is useful to pass as a single command line: | |
2291 | In [13]: !wc -l $a.s |
|
2255 | In [13]: !wc -l $a.s | |
2292 | 146 setup.py |
|
2256 | 146 setup.py | |
2293 | 130 win32_manual_post_install.py |
|
2257 | 130 win32_manual_post_install.py | |
2294 | 276 total |
|
2258 | 276 total | |
2295 |
|
2259 | |||
2296 | # while the list form is useful to loop over: |
|
2260 | # while the list form is useful to loop over: | |
2297 | In [14]: for f in a.l: |
|
2261 | In [14]: for f in a.l: | |
2298 | ....: !wc -l $f |
|
2262 | ....: !wc -l $f | |
2299 | ....: |
|
2263 | ....: | |
2300 | 146 setup.py |
|
2264 | 146 setup.py | |
2301 | 130 win32_manual_post_install.py |
|
2265 | 130 win32_manual_post_install.py | |
2302 |
|
2266 | |||
2303 | Similiarly, the lists returned by the -l option are also special, in |
|
2267 | Similiarly, the lists returned by the -l option are also special, in | |
2304 | the sense that you can equally invoke the .s attribute on them to |
|
2268 | the sense that you can equally invoke the .s attribute on them to | |
2305 | automatically get a whitespace-separated string from their contents: |
|
2269 | automatically get a whitespace-separated string from their contents: | |
2306 |
|
2270 | |||
2307 | In [1]: sc -l b=ls *py |
|
2271 | In [1]: sc -l b=ls *py | |
2308 |
|
2272 | |||
2309 | In [2]: b |
|
2273 | In [2]: b | |
2310 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2274 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] | |
2311 |
|
2275 | |||
2312 | In [3]: b.s |
|
2276 | In [3]: b.s | |
2313 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2277 | Out[3]: 'setup.py win32_manual_post_install.py' | |
2314 |
|
2278 | |||
2315 | In summary, both the lists and strings used for ouptut capture have |
|
2279 | In summary, both the lists and strings used for ouptut capture have | |
2316 | the following special attributes: |
|
2280 | the following special attributes: | |
2317 |
|
2281 | |||
2318 | .l (or .list) : value as list. |
|
2282 | .l (or .list) : value as list. | |
2319 | .n (or .nlstr): value as newline-separated string. |
|
2283 | .n (or .nlstr): value as newline-separated string. | |
2320 | .s (or .spstr): value as space-separated string. |
|
2284 | .s (or .spstr): value as space-separated string. | |
2321 | """ |
|
2285 | """ | |
2322 |
|
2286 | |||
2323 | opts,args = self.parse_options(parameter_s,'lv') |
|
2287 | opts,args = self.parse_options(parameter_s,'lv') | |
2324 | # Try to get a variable name and command to run |
|
2288 | # Try to get a variable name and command to run | |
2325 | try: |
|
2289 | try: | |
2326 | # the variable name must be obtained from the parse_options |
|
2290 | # the variable name must be obtained from the parse_options | |
2327 | # output, which uses shlex.split to strip options out. |
|
2291 | # output, which uses shlex.split to strip options out. | |
2328 | var,_ = args.split('=',1) |
|
2292 | var,_ = args.split('=',1) | |
2329 | var = var.strip() |
|
2293 | var = var.strip() | |
2330 | # But the the command has to be extracted from the original input |
|
2294 | # But the the command has to be extracted from the original input | |
2331 | # parameter_s, not on what parse_options returns, to avoid the |
|
2295 | # parameter_s, not on what parse_options returns, to avoid the | |
2332 | # quote stripping which shlex.split performs on it. |
|
2296 | # quote stripping which shlex.split performs on it. | |
2333 | _,cmd = parameter_s.split('=',1) |
|
2297 | _,cmd = parameter_s.split('=',1) | |
2334 | except ValueError: |
|
2298 | except ValueError: | |
2335 | var,cmd = '','' |
|
2299 | var,cmd = '','' | |
2336 | if not var: |
|
2300 | if not var: | |
2337 | error('you must specify a variable to assign the command to.') |
|
2301 | error('you must specify a variable to assign the command to.') | |
2338 | return |
|
2302 | return | |
2339 | # If all looks ok, proceed |
|
2303 | # If all looks ok, proceed | |
2340 | out,err = self.shell.getoutputerror(cmd) |
|
2304 | out,err = self.shell.getoutputerror(cmd) | |
2341 | if err: |
|
2305 | if err: | |
2342 | print >> Term.cerr,err |
|
2306 | print >> Term.cerr,err | |
2343 | if opts.has_key('l'): |
|
2307 | if opts.has_key('l'): | |
2344 | out = SList(out.split('\n')) |
|
2308 | out = SList(out.split('\n')) | |
2345 | else: |
|
2309 | else: | |
2346 | out = LSString(out) |
|
2310 | out = LSString(out) | |
2347 | if opts.has_key('v'): |
|
2311 | if opts.has_key('v'): | |
2348 | print '%s ==\n%s' % (var,pformat(out)) |
|
2312 | print '%s ==\n%s' % (var,pformat(out)) | |
2349 | self.shell.user_ns.update({var:out}) |
|
2313 | self.shell.user_ns.update({var:out}) | |
2350 |
|
2314 | |||
2351 | def magic_sx(self, parameter_s=''): |
|
2315 | def magic_sx(self, parameter_s=''): | |
2352 | """Shell execute - run a shell command and capture its output. |
|
2316 | """Shell execute - run a shell command and capture its output. | |
2353 |
|
2317 | |||
2354 | %sx command |
|
2318 | %sx command | |
2355 |
|
2319 | |||
2356 | IPython will run the given command using commands.getoutput(), and |
|
2320 | IPython will run the given command using commands.getoutput(), and | |
2357 | return the result formatted as a list (split on '\\n'). Since the |
|
2321 | return the result formatted as a list (split on '\\n'). Since the | |
2358 | output is _returned_, it will be stored in ipython's regular output |
|
2322 | output is _returned_, it will be stored in ipython's regular output | |
2359 | cache Out[N] and in the '_N' automatic variables. |
|
2323 | cache Out[N] and in the '_N' automatic variables. | |
2360 |
|
2324 | |||
2361 | Notes: |
|
2325 | Notes: | |
2362 |
|
2326 | |||
2363 | 1) If an input line begins with '!!', then %sx is automatically |
|
2327 | 1) If an input line begins with '!!', then %sx is automatically | |
2364 | invoked. That is, while: |
|
2328 | invoked. That is, while: | |
2365 | !ls |
|
2329 | !ls | |
2366 | causes ipython to simply issue system('ls'), typing |
|
2330 | causes ipython to simply issue system('ls'), typing | |
2367 | !!ls |
|
2331 | !!ls | |
2368 | is a shorthand equivalent to: |
|
2332 | is a shorthand equivalent to: | |
2369 | %sx ls |
|
2333 | %sx ls | |
2370 |
|
2334 | |||
2371 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2335 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2372 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2336 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2373 | to process line-oriented shell output via further python commands. |
|
2337 | to process line-oriented shell output via further python commands. | |
2374 | %sc is meant to provide much finer control, but requires more |
|
2338 | %sc is meant to provide much finer control, but requires more | |
2375 | typing. |
|
2339 | typing. | |
2376 |
|
2340 | |||
2377 | 3) Just like %sc -l, this is a list with special attributes: |
|
2341 | 3) Just like %sc -l, this is a list with special attributes: | |
2378 |
|
2342 | |||
2379 | .l (or .list) : value as list. |
|
2343 | .l (or .list) : value as list. | |
2380 | .n (or .nlstr): value as newline-separated string. |
|
2344 | .n (or .nlstr): value as newline-separated string. | |
2381 | .s (or .spstr): value as whitespace-separated string. |
|
2345 | .s (or .spstr): value as whitespace-separated string. | |
2382 |
|
2346 | |||
2383 | This is very useful when trying to use such lists as arguments to |
|
2347 | This is very useful when trying to use such lists as arguments to | |
2384 | system commands.""" |
|
2348 | system commands.""" | |
2385 |
|
2349 | |||
2386 | if parameter_s: |
|
2350 | if parameter_s: | |
2387 | out,err = self.shell.getoutputerror(parameter_s) |
|
2351 | out,err = self.shell.getoutputerror(parameter_s) | |
2388 | if err: |
|
2352 | if err: | |
2389 | print >> Term.cerr,err |
|
2353 | print >> Term.cerr,err | |
2390 | return SList(out.split('\n')) |
|
2354 | return SList(out.split('\n')) | |
2391 |
|
2355 | |||
2392 | def magic_bg(self, parameter_s=''): |
|
2356 | def magic_bg(self, parameter_s=''): | |
2393 | """Run a job in the background, in a separate thread. |
|
2357 | """Run a job in the background, in a separate thread. | |
2394 |
|
2358 | |||
2395 | For example, |
|
2359 | For example, | |
2396 |
|
2360 | |||
2397 | %bg myfunc(x,y,z=1) |
|
2361 | %bg myfunc(x,y,z=1) | |
2398 |
|
2362 | |||
2399 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2363 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
2400 | execution starts, a message will be printed indicating the job |
|
2364 | execution starts, a message will be printed indicating the job | |
2401 | number. If your job number is 5, you can use |
|
2365 | number. If your job number is 5, you can use | |
2402 |
|
2366 | |||
2403 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2367 | myvar = jobs.result(5) or myvar = jobs[5].result | |
2404 |
|
2368 | |||
2405 | to assign this result to variable 'myvar'. |
|
2369 | to assign this result to variable 'myvar'. | |
2406 |
|
2370 | |||
2407 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2371 | IPython has a job manager, accessible via the 'jobs' object. You can | |
2408 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2372 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
2409 | its attributes. All attributes not starting with an underscore are |
|
2373 | its attributes. All attributes not starting with an underscore are | |
2410 | meant for public use. |
|
2374 | meant for public use. | |
2411 |
|
2375 | |||
2412 | In particular, look at the jobs.new() method, which is used to create |
|
2376 | In particular, look at the jobs.new() method, which is used to create | |
2413 | new jobs. This magic %bg function is just a convenience wrapper |
|
2377 | new jobs. This magic %bg function is just a convenience wrapper | |
2414 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2378 | around jobs.new(), for expression-based jobs. If you want to create a | |
2415 | new job with an explicit function object and arguments, you must call |
|
2379 | new job with an explicit function object and arguments, you must call | |
2416 | jobs.new() directly. |
|
2380 | jobs.new() directly. | |
2417 |
|
2381 | |||
2418 | The jobs.new docstring also describes in detail several important |
|
2382 | The jobs.new docstring also describes in detail several important | |
2419 | caveats associated with a thread-based model for background job |
|
2383 | caveats associated with a thread-based model for background job | |
2420 | execution. Type jobs.new? for details. |
|
2384 | execution. Type jobs.new? for details. | |
2421 |
|
2385 | |||
2422 | You can check the status of all jobs with jobs.status(). |
|
2386 | You can check the status of all jobs with jobs.status(). | |
2423 |
|
2387 | |||
2424 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2388 | The jobs variable is set by IPython into the Python builtin namespace. | |
2425 | If you ever declare a variable named 'jobs', you will shadow this |
|
2389 | If you ever declare a variable named 'jobs', you will shadow this | |
2426 | name. You can either delete your global jobs variable to regain |
|
2390 | name. You can either delete your global jobs variable to regain | |
2427 | access to the job manager, or make a new name and assign it manually |
|
2391 | access to the job manager, or make a new name and assign it manually | |
2428 | to the manager (stored in IPython's namespace). For example, to |
|
2392 | to the manager (stored in IPython's namespace). For example, to | |
2429 | assign the job manager to the Jobs name, use: |
|
2393 | assign the job manager to the Jobs name, use: | |
2430 |
|
2394 | |||
2431 | Jobs = __builtins__.jobs""" |
|
2395 | Jobs = __builtins__.jobs""" | |
2432 |
|
2396 | |||
2433 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2397 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
2434 |
|
2398 | |||
2435 | def magic_bookmark(self, parameter_s=''): |
|
2399 | def magic_bookmark(self, parameter_s=''): | |
2436 | """Manage IPython's bookmark system. |
|
2400 | """Manage IPython's bookmark system. | |
2437 |
|
2401 | |||
2438 | %bookmark <name> - set bookmark to current dir |
|
2402 | %bookmark <name> - set bookmark to current dir | |
2439 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2403 | %bookmark <name> <dir> - set bookmark to <dir> | |
2440 | %bookmark -l - list all bookmarks |
|
2404 | %bookmark -l - list all bookmarks | |
2441 | %bookmark -d <name> - remove bookmark |
|
2405 | %bookmark -d <name> - remove bookmark | |
2442 | %bookmark -r - remove all bookmarks |
|
2406 | %bookmark -r - remove all bookmarks | |
2443 |
|
2407 | |||
2444 | You can later on access a bookmarked folder with: |
|
2408 | You can later on access a bookmarked folder with: | |
2445 | %cd -b <name> |
|
2409 | %cd -b <name> | |
2446 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2410 | or simply '%cd <name>' if there is no directory called <name> AND | |
2447 | there is such a bookmark defined. |
|
2411 | there is such a bookmark defined. | |
2448 |
|
2412 | |||
2449 | Your bookmarks persist through IPython sessions, but they are |
|
2413 | Your bookmarks persist through IPython sessions, but they are | |
2450 | associated with each profile.""" |
|
2414 | associated with each profile.""" | |
2451 |
|
2415 | |||
2452 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2416 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
2453 | if len(args) > 2: |
|
2417 | if len(args) > 2: | |
2454 | error('You can only give at most two arguments') |
|
2418 | error('You can only give at most two arguments') | |
2455 | return |
|
2419 | return | |
2456 |
|
2420 | |||
2457 | bkms = self.shell.persist.get('bookmarks',{}) |
|
2421 | bkms = self.shell.persist.get('bookmarks',{}) | |
2458 |
|
2422 | |||
2459 | if opts.has_key('d'): |
|
2423 | if opts.has_key('d'): | |
2460 | try: |
|
2424 | try: | |
2461 | todel = args[0] |
|
2425 | todel = args[0] | |
2462 | except IndexError: |
|
2426 | except IndexError: | |
2463 | error('You must provide a bookmark to delete') |
|
2427 | error('You must provide a bookmark to delete') | |
2464 | else: |
|
2428 | else: | |
2465 | try: |
|
2429 | try: | |
2466 | del bkms[todel] |
|
2430 | del bkms[todel] | |
2467 | except: |
|
2431 | except: | |
2468 | error("Can't delete bookmark '%s'" % todel) |
|
2432 | error("Can't delete bookmark '%s'" % todel) | |
2469 | elif opts.has_key('r'): |
|
2433 | elif opts.has_key('r'): | |
2470 | bkms = {} |
|
2434 | bkms = {} | |
2471 | elif opts.has_key('l'): |
|
2435 | elif opts.has_key('l'): | |
2472 | bks = bkms.keys() |
|
2436 | bks = bkms.keys() | |
2473 | bks.sort() |
|
2437 | bks.sort() | |
2474 | if bks: |
|
2438 | if bks: | |
2475 | size = max(map(len,bks)) |
|
2439 | size = max(map(len,bks)) | |
2476 | else: |
|
2440 | else: | |
2477 | size = 0 |
|
2441 | size = 0 | |
2478 | fmt = '%-'+str(size)+'s -> %s' |
|
2442 | fmt = '%-'+str(size)+'s -> %s' | |
2479 | print 'Current bookmarks:' |
|
2443 | print 'Current bookmarks:' | |
2480 | for bk in bks: |
|
2444 | for bk in bks: | |
2481 | print fmt % (bk,bkms[bk]) |
|
2445 | print fmt % (bk,bkms[bk]) | |
2482 | else: |
|
2446 | else: | |
2483 | if not args: |
|
2447 | if not args: | |
2484 | error("You must specify the bookmark name") |
|
2448 | error("You must specify the bookmark name") | |
2485 | elif len(args)==1: |
|
2449 | elif len(args)==1: | |
2486 | bkms[args[0]] = os.getcwd() |
|
2450 | bkms[args[0]] = os.getcwd() | |
2487 | elif len(args)==2: |
|
2451 | elif len(args)==2: | |
2488 | bkms[args[0]] = args[1] |
|
2452 | bkms[args[0]] = args[1] | |
2489 | self.persist['bookmarks'] = bkms |
|
2453 | self.persist['bookmarks'] = bkms | |
2490 | # end Magic |
|
2454 | # end Magic |
@@ -1,149 +1,175 b'' | |||||
1 | """Module for interactive demos using IPython. |
|
1 | """Module for interactive demos using IPython. | |
2 |
|
2 | |||
3 | Sorry, but this uses Python 2.3 features, so it won't work in 2.2 environments. |
|
3 | Sorry, but this uses Python 2.3 features, so it won't work in 2.2 environments. | |
4 | """ |
|
4 | """ | |
5 | #***************************************************************************** |
|
5 | #***************************************************************************** | |
6 | # Copyright (C) 2005 Fernando Perez. <Fernando.Perez@colorado.edu> |
|
6 | # Copyright (C) 2005 Fernando Perez. <Fernando.Perez@colorado.edu> | |
7 | # |
|
7 | # | |
8 | # Distributed under the terms of the BSD License. The full license is in |
|
8 | # Distributed under the terms of the BSD License. The full license is in | |
9 | # the file COPYING, distributed as part of this software. |
|
9 | # the file COPYING, distributed as part of this software. | |
10 | # |
|
10 | # | |
11 | #***************************************************************************** |
|
11 | #***************************************************************************** | |
12 |
|
12 | |||
|
13 | import sys | |||
13 | import exceptions |
|
14 | import exceptions | |
14 | import re |
|
15 | import re | |
15 |
|
16 | |||
16 | from IPython.PyColorize import Parser |
|
17 | from IPython.PyColorize import Parser | |
17 | from IPython.genutils import marquee |
|
18 | from IPython.genutils import marquee, shlex_split | |
18 |
|
19 | |||
19 | class DemoError(exceptions.Exception): pass |
|
20 | class DemoError(exceptions.Exception): pass | |
20 |
|
21 | |||
21 | class Demo: |
|
22 | class Demo: | |
22 |
def __init__(self,fname,mark_pause='# pause', |
|
23 | def __init__(self,fname,arg_str='',mark_pause='# pause', | |
23 | auto=False): |
|
24 | mark_silent='# silent',auto=False): | |
24 | """The marks are turned into regexps which match them as standalone in |
|
25 | """Make a new demo object. To run the demo, simply call the object. | |
25 | a line, with all leading/trailing whitespace ignored.""" |
|
26 | ||
|
27 | Inputs: | |||
|
28 | ||||
|
29 | - fname = filename. | |||
|
30 | ||||
|
31 | Optional inputs: | |||
|
32 | ||||
|
33 | - arg_str(''): a string of arguments, internally converted to a list | |||
|
34 | just like sys.argv, so the demo script can see a similar | |||
|
35 | environment. | |||
|
36 | ||||
|
37 | - mark_pause ('# pause'), mark_silent('# silent'): marks for pausing | |||
|
38 | (block boundaries) and to tag blocks as silent. The marks are | |||
|
39 | turned into regexps which match them as standalone in a line, with | |||
|
40 | all leading/trailing whitespace ignored. | |||
|
41 | ||||
|
42 | - auto(False): flag to run each block automatically without | |||
|
43 | confirmation. Note that silent blocks are always automatically | |||
|
44 | executed. This flag is an attribute of the object, and can be | |||
|
45 | changed at runtime simply by reassigning it. | |||
|
46 | """ | |||
26 |
|
47 | |||
27 | self.fname = fname |
|
48 | self.fname = fname | |
28 | self.mark_pause = mark_pause |
|
49 | self.mark_pause = mark_pause | |
29 | self.re_pause = re.compile(r'^\s*%s\s*$' % mark_pause,re.MULTILINE) |
|
50 | self.re_pause = re.compile(r'^\s*%s\s*$' % mark_pause,re.MULTILINE) | |
30 | self.mark_silent = mark_silent |
|
51 | self.mark_silent = mark_silent | |
31 | self.re_silent = re.compile(r'^\s*%s\s*$' % mark_silent,re.MULTILINE) |
|
52 | self.re_silent = re.compile(r'^\s*%s\s*$' % mark_silent,re.MULTILINE) | |
32 | self.auto = auto |
|
53 | self.auto = auto | |
|
54 | self.sys_argv = shlex_split(arg_str) | |||
33 |
|
55 | |||
34 | # get a few things from ipython. While it's a bit ugly design-wise, |
|
56 | # get a few things from ipython. While it's a bit ugly design-wise, | |
35 | # it ensures that things like color scheme and the like are always in |
|
57 | # it ensures that things like color scheme and the like are always in | |
36 | # sync with the ipython mode being used. This class is only meant to |
|
58 | # sync with the ipython mode being used. This class is only meant to | |
37 | # be used inside ipython anyways, so it's OK. |
|
59 | # be used inside ipython anyways, so it's OK. | |
38 | self.ip_showtraceback = __IPYTHON__.showtraceback |
|
60 | self.ip_showtraceback = __IPYTHON__.showtraceback | |
39 | self.ip_ns = __IPYTHON__.user_ns |
|
61 | self.ip_ns = __IPYTHON__.user_ns | |
40 | self.ip_colors = __IPYTHON__.rc['colors'] |
|
62 | self.ip_colors = __IPYTHON__.rc['colors'] | |
41 |
|
63 | |||
42 | # read data and parse into blocks |
|
64 | # read data and parse into blocks | |
43 | fobj = file(fname,'r') |
|
65 | fobj = file(fname,'r') | |
44 | self.src = fobj.read() |
|
66 | self.src = fobj.read() | |
45 | fobj.close() |
|
67 | fobj.close() | |
46 | self.src_blocks = [b.strip() for b in self.re_pause.split(self.src) if b] |
|
68 | self.src_blocks = [b.strip() for b in self.re_pause.split(self.src) if b] | |
47 | self.silent = [bool(self.re_silent.findall(b)) for b in self.src_blocks] |
|
69 | self.silent = [bool(self.re_silent.findall(b)) for b in self.src_blocks] | |
48 | self.nblocks = len(self.src_blocks) |
|
70 | self.nblocks = len(self.src_blocks) | |
49 |
|
71 | |||
50 | # try to colorize blocks |
|
72 | # try to colorize blocks | |
51 | colorize = Parser().format |
|
73 | colorize = Parser().format | |
52 | col_scheme = self.ip_colors |
|
74 | col_scheme = self.ip_colors | |
53 | self.src_blocks_colored = [colorize(s_blk,'str',col_scheme) |
|
75 | self.src_blocks_colored = [colorize(s_blk,'str',col_scheme) | |
54 | for s_blk in self.src_blocks] |
|
76 | for s_blk in self.src_blocks] | |
55 |
|
77 | |||
56 | # finish initialization |
|
78 | # finish initialization | |
57 | self.reset() |
|
79 | self.reset() | |
58 |
|
80 | |||
59 | def reset(self): |
|
81 | def reset(self): | |
60 | """Reset the namespace and seek pointer to restart the demo""" |
|
82 | """Reset the namespace and seek pointer to restart the demo""" | |
61 | self.user_ns = {} |
|
83 | self.user_ns = {} | |
62 | self.finished = False |
|
84 | self.finished = False | |
63 | self.block_index = 0 |
|
85 | self.block_index = 0 | |
64 |
|
86 | |||
65 | def again(self): |
|
87 | def again(self): | |
66 | """Repeat the last block""" |
|
88 | """Repeat the last block""" | |
67 | self.block_index -= 1 |
|
89 | self.block_index -= 1 | |
68 | self() |
|
90 | self() | |
69 |
|
91 | |||
70 | def _validate_index(self,index): |
|
92 | def _validate_index(self,index): | |
71 | if index<0 or index>=self.nblocks: |
|
93 | if index<0 or index>=self.nblocks: | |
72 | raise ValueError('invalid block index %s' % index) |
|
94 | raise ValueError('invalid block index %s' % index) | |
73 |
|
95 | |||
74 | def seek(self,index): |
|
96 | def seek(self,index): | |
75 | """Move the current seek pointer to the given block""" |
|
97 | """Move the current seek pointer to the given block""" | |
76 | self._validate_index(index) |
|
98 | self._validate_index(index) | |
77 | self.block_index = index-1 |
|
99 | self.block_index = index-1 | |
78 | self.finished = False |
|
100 | self.finished = False | |
79 |
|
101 | |||
80 | def show_block(self,index=None): |
|
102 | def show_block(self,index=None): | |
81 | """Show a single block on screen""" |
|
103 | """Show a single block on screen""" | |
82 | if index is None: |
|
104 | if index is None: | |
83 | if self.finished: |
|
105 | if self.finished: | |
84 | print 'Demo finished. Use reset() if you want to rerun it.' |
|
106 | print 'Demo finished. Use reset() if you want to rerun it.' | |
85 | return |
|
107 | return | |
86 | index = self.block_index |
|
108 | index = self.block_index | |
87 | else: |
|
109 | else: | |
88 | self._validate_index(index) |
|
110 | self._validate_index(index) | |
89 | print marquee('<%s> block # %s (%s/%s)' % |
|
111 | print marquee('<%s> block # %s (%s/%s)' % | |
90 | (self.fname,index,index+1,self.nblocks)) |
|
112 | (self.fname,index,index+1,self.nblocks)) | |
91 | print self.src_blocks_colored[index], |
|
113 | print self.src_blocks_colored[index], | |
92 |
|
114 | |||
93 | def show(self): |
|
115 | def show(self): | |
94 | """Show entire demo on screen, block by block""" |
|
116 | """Show entire demo on screen, block by block""" | |
95 |
|
117 | |||
96 | fname = self.fname |
|
118 | fname = self.fname | |
97 | nblocks = self.nblocks |
|
119 | nblocks = self.nblocks | |
98 | silent = self.silent |
|
120 | silent = self.silent | |
99 | for index,block in enumerate(self.src_blocks_colored): |
|
121 | for index,block in enumerate(self.src_blocks_colored): | |
100 | if silent[index]: |
|
122 | if silent[index]: | |
101 | print marquee('<%s> SILENT block # %s (%s/%s)' % |
|
123 | print marquee('<%s> SILENT block # %s (%s/%s)' % | |
102 | (fname,index,index+1,nblocks)) |
|
124 | (fname,index,index+1,nblocks)) | |
103 | else: |
|
125 | else: | |
104 | print marquee('<%s> block # %s (%s/%s)' % |
|
126 | print marquee('<%s> block # %s (%s/%s)' % | |
105 | (fname,index,index+1,nblocks)) |
|
127 | (fname,index,index+1,nblocks)) | |
106 | print block, |
|
128 | print block, | |
107 |
|
129 | |||
108 | def __call__(self,index=None): |
|
130 | def __call__(self,index=None): | |
109 | """run a block of the demo. |
|
131 | """run a block of the demo. | |
110 |
|
132 | |||
111 | If index is given, it should be an integer >=1 and <= nblocks. This |
|
133 | If index is given, it should be an integer >=1 and <= nblocks. This | |
112 | means that the calling convention is one off from typical Python |
|
134 | means that the calling convention is one off from typical Python | |
113 | lists. The reason for the inconsistency is that the demo always |
|
135 | lists. The reason for the inconsistency is that the demo always | |
114 | prints 'Block n/N, and N is the total, so it would be very odd to use |
|
136 | prints 'Block n/N, and N is the total, so it would be very odd to use | |
115 | zero-indexing here.""" |
|
137 | zero-indexing here.""" | |
116 |
|
138 | |||
117 | if index is None and self.finished: |
|
139 | if index is None and self.finished: | |
118 | print 'Demo finished. Use reset() if you want to rerun it.' |
|
140 | print 'Demo finished. Use reset() if you want to rerun it.' | |
119 | return |
|
141 | return | |
120 | if index is None: |
|
142 | if index is None: | |
121 | index = self.block_index |
|
143 | index = self.block_index | |
122 | self._validate_index(index) |
|
144 | self._validate_index(index) | |
123 | try: |
|
145 | try: | |
124 | next_block = self.src_blocks[index] |
|
146 | next_block = self.src_blocks[index] | |
125 | self.block_index += 1 |
|
147 | self.block_index += 1 | |
126 | if self.silent[index]: |
|
148 | if self.silent[index]: | |
127 | print marquee('Executing silent block # %s (%s/%s)' % |
|
149 | print marquee('Executing silent block # %s (%s/%s)' % | |
128 | (index,index+1,self.nblocks)) |
|
150 | (index,index+1,self.nblocks)) | |
129 | else: |
|
151 | else: | |
130 | self.show_block(index) |
|
152 | self.show_block(index) | |
131 | if not self.auto: |
|
153 | if not self.auto: | |
132 | print marquee('Press <q> to quit, <Enter> to execute...'), |
|
154 | print marquee('Press <q> to quit, <Enter> to execute...'), | |
133 | ans = raw_input().strip() |
|
155 | ans = raw_input().strip() | |
134 | if ans: |
|
156 | if ans: | |
135 | print marquee('Block NOT executed') |
|
157 | print marquee('Block NOT executed') | |
136 | return |
|
158 | return | |
137 |
|
159 | try: | ||
138 | exec next_block in self.user_ns |
|
160 | save_argv = sys.argv | |
|
161 | sys.argv = self.sys_argv | |||
|
162 | exec next_block in self.user_ns | |||
|
163 | finally: | |||
|
164 | sys.argv = save_argv | |||
139 |
|
165 | |||
140 | except: |
|
166 | except: | |
141 | self.ip_showtraceback(filename=self.fname) |
|
167 | self.ip_showtraceback(filename=self.fname) | |
142 | else: |
|
168 | else: | |
143 | self.ip_ns.update(self.user_ns) |
|
169 | self.ip_ns.update(self.user_ns) | |
144 |
|
170 | |||
145 | if self.block_index == self.nblocks: |
|
171 | if self.block_index == self.nblocks: | |
146 |
|
172 | |||
147 | print marquee(' END OF DEMO ') |
|
173 | print marquee(' END OF DEMO ') | |
148 | print marquee('Use reset() if you want to rerun it.') |
|
174 | print marquee('Use reset() if you want to rerun it.') | |
149 | self.finished = True |
|
175 | self.finished = True |
@@ -1,1540 +1,1578 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 89 |
|
8 | $Id: genutils.py 897 2005-09-22 09:32:46Z fperez $""" | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> |
|
11 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | from __future__ import generators # 2.2 compatibility |
|
17 | from __future__ import generators # 2.2 compatibility | |
18 |
|
18 | |||
19 | from IPython import Release |
|
19 | from IPython import Release | |
20 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
20 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
21 | __license__ = Release.license |
|
21 | __license__ = Release.license | |
22 |
|
22 | |||
23 | #**************************************************************************** |
|
23 | #**************************************************************************** | |
24 | # required modules |
|
24 | # required modules | |
25 | import __main__ |
|
25 | import __main__ | |
26 | import types,commands,time,sys,os,re,shutil |
|
26 | import types,commands,time,sys,os,re,shutil | |
|
27 | import shlex | |||
27 | import tempfile |
|
28 | import tempfile | |
28 | from IPython.Itpl import Itpl,itpl,printpl |
|
29 | from IPython.Itpl import Itpl,itpl,printpl | |
29 | from IPython import DPyGetOpt |
|
30 | from IPython import DPyGetOpt | |
30 |
|
31 | |||
31 | # Build objects which appeared in Python 2.3 for 2.2, to make ipython |
|
32 | # Build objects which appeared in Python 2.3 for 2.2, to make ipython | |
32 | # 2.2-friendly |
|
33 | # 2.2-friendly | |
33 | try: |
|
34 | try: | |
34 | basestring |
|
35 | basestring | |
35 | except NameError: |
|
36 | except NameError: | |
36 | import types |
|
37 | import types | |
37 | basestring = (types.StringType, types.UnicodeType) |
|
38 | basestring = (types.StringType, types.UnicodeType) | |
38 | True = 1==1 |
|
39 | True = 1==1 | |
39 | False = 1==0 |
|
40 | False = 1==0 | |
40 |
|
41 | |||
41 | def enumerate(obj): |
|
42 | def enumerate(obj): | |
42 | i = -1 |
|
43 | i = -1 | |
43 | for item in obj: |
|
44 | for item in obj: | |
44 | i += 1 |
|
45 | i += 1 | |
45 | yield i, item |
|
46 | yield i, item | |
46 |
|
47 | |||
47 | # add these to the builtin namespace, so that all modules find them |
|
48 | # add these to the builtin namespace, so that all modules find them | |
48 | import __builtin__ |
|
49 | import __builtin__ | |
49 | __builtin__.basestring = basestring |
|
50 | __builtin__.basestring = basestring | |
50 | __builtin__.True = True |
|
51 | __builtin__.True = True | |
51 | __builtin__.False = False |
|
52 | __builtin__.False = False | |
52 | __builtin__.enumerate = enumerate |
|
53 | __builtin__.enumerate = enumerate | |
53 |
|
54 | |||
|
55 | # Try to use shlex.split for converting an input string into a sys.argv-type | |||
|
56 | # list. This appeared in Python 2.3, so here's a quick backport for 2.2. | |||
|
57 | try: | |||
|
58 | shlex_split = shlex.split | |||
|
59 | except AttributeError: | |||
|
60 | _quotesre = re.compile(r'[\'"](.*)[\'"]') | |||
|
61 | _wordchars = ('abcdfeghijklmnopqrstuvwxyz' | |||
|
62 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?' | |||
|
63 | 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' | |||
|
64 | 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s' | |||
|
65 | % os.sep) | |||
|
66 | ||||
|
67 | def shlex_split(s): | |||
|
68 | """Simplified backport to Python 2.2 of shlex.split(). | |||
|
69 | ||||
|
70 | This is a quick and dirty hack, since the shlex module under 2.2 lacks | |||
|
71 | several of the features needed to really match the functionality of | |||
|
72 | shlex.split() in 2.3.""" | |||
|
73 | ||||
|
74 | lex = shlex.shlex(StringIO(s)) | |||
|
75 | # Try to get options, extensions and path separators as characters | |||
|
76 | lex.wordchars = _wordchars | |||
|
77 | lex.commenters = '' | |||
|
78 | # Make a list out of the lexer by hand, since in 2.2 it's not an | |||
|
79 | # iterator. | |||
|
80 | lout = [] | |||
|
81 | while 1: | |||
|
82 | token = lex.get_token() | |||
|
83 | if token == '': | |||
|
84 | break | |||
|
85 | # Try to handle quoted tokens correctly | |||
|
86 | quotes = _quotesre.match(token) | |||
|
87 | if quotes: | |||
|
88 | token = quotes.group(1) | |||
|
89 | lout.append(token) | |||
|
90 | return lout | |||
|
91 | ||||
54 | #**************************************************************************** |
|
92 | #**************************************************************************** | |
55 | # Exceptions |
|
93 | # Exceptions | |
56 | class Error(Exception): |
|
94 | class Error(Exception): | |
57 | """Base class for exceptions in this module.""" |
|
95 | """Base class for exceptions in this module.""" | |
58 | pass |
|
96 | pass | |
59 |
|
97 | |||
60 | #---------------------------------------------------------------------------- |
|
98 | #---------------------------------------------------------------------------- | |
61 | class IOStream: |
|
99 | class IOStream: | |
62 | def __init__(self,stream,fallback): |
|
100 | def __init__(self,stream,fallback): | |
63 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
101 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): | |
64 | stream = fallback |
|
102 | stream = fallback | |
65 | self.stream = stream |
|
103 | self.stream = stream | |
66 | self._swrite = stream.write |
|
104 | self._swrite = stream.write | |
67 | self.flush = stream.flush |
|
105 | self.flush = stream.flush | |
68 |
|
106 | |||
69 | def write(self,data): |
|
107 | def write(self,data): | |
70 | try: |
|
108 | try: | |
71 | self._swrite(data) |
|
109 | self._swrite(data) | |
72 | except: |
|
110 | except: | |
73 | try: |
|
111 | try: | |
74 | # print handles some unicode issues which may trip a plain |
|
112 | # print handles some unicode issues which may trip a plain | |
75 | # write() call. Attempt to emulate write() by using a |
|
113 | # write() call. Attempt to emulate write() by using a | |
76 | # trailing comma |
|
114 | # trailing comma | |
77 | print >> self.stream, data, |
|
115 | print >> self.stream, data, | |
78 | except: |
|
116 | except: | |
79 | # if we get here, something is seriously broken. |
|
117 | # if we get here, something is seriously broken. | |
80 | print >> sys.stderr, \ |
|
118 | print >> sys.stderr, \ | |
81 | 'ERROR - failed to write data to stream:', stream |
|
119 | 'ERROR - failed to write data to stream:', stream | |
82 |
|
120 | |||
83 | class IOTerm: |
|
121 | class IOTerm: | |
84 | """ Term holds the file or file-like objects for handling I/O operations. |
|
122 | """ Term holds the file or file-like objects for handling I/O operations. | |
85 |
|
123 | |||
86 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
124 | These are normally just sys.stdin, sys.stdout and sys.stderr but for | |
87 | Windows they can can replaced to allow editing the strings before they are |
|
125 | Windows they can can replaced to allow editing the strings before they are | |
88 | displayed.""" |
|
126 | displayed.""" | |
89 |
|
127 | |||
90 | # In the future, having IPython channel all its I/O operations through |
|
128 | # In the future, having IPython channel all its I/O operations through | |
91 | # this class will make it easier to embed it into other environments which |
|
129 | # this class will make it easier to embed it into other environments which | |
92 | # are not a normal terminal (such as a GUI-based shell) |
|
130 | # are not a normal terminal (such as a GUI-based shell) | |
93 | def __init__(self,cin=None,cout=None,cerr=None): |
|
131 | def __init__(self,cin=None,cout=None,cerr=None): | |
94 | self.cin = IOStream(cin,sys.stdin) |
|
132 | self.cin = IOStream(cin,sys.stdin) | |
95 | self.cout = IOStream(cout,sys.stdout) |
|
133 | self.cout = IOStream(cout,sys.stdout) | |
96 | self.cerr = IOStream(cerr,sys.stderr) |
|
134 | self.cerr = IOStream(cerr,sys.stderr) | |
97 |
|
135 | |||
98 | # Global variable to be used for all I/O |
|
136 | # Global variable to be used for all I/O | |
99 | Term = IOTerm() |
|
137 | Term = IOTerm() | |
100 |
|
138 | |||
101 | # Windows-specific code to load Gary Bishop's readline and configure it |
|
139 | # Windows-specific code to load Gary Bishop's readline and configure it | |
102 | # automatically for the users |
|
140 | # automatically for the users | |
103 | # Note: os.name on cygwin returns posix, so this should only pick up 'native' |
|
141 | # Note: os.name on cygwin returns posix, so this should only pick up 'native' | |
104 | # windows. Cygwin returns 'cygwin' for sys.platform. |
|
142 | # windows. Cygwin returns 'cygwin' for sys.platform. | |
105 | if os.name == 'nt': |
|
143 | if os.name == 'nt': | |
106 | try: |
|
144 | try: | |
107 | import readline |
|
145 | import readline | |
108 | except ImportError: |
|
146 | except ImportError: | |
109 | pass |
|
147 | pass | |
110 | else: |
|
148 | else: | |
111 | try: |
|
149 | try: | |
112 | _out = readline.GetOutputFile() |
|
150 | _out = readline.GetOutputFile() | |
113 | except AttributeError: |
|
151 | except AttributeError: | |
114 | pass |
|
152 | pass | |
115 | else: |
|
153 | else: | |
116 | # Remake Term to use the readline i/o facilities |
|
154 | # Remake Term to use the readline i/o facilities | |
117 | Term = IOTerm(cout=_out,cerr=_out) |
|
155 | Term = IOTerm(cout=_out,cerr=_out) | |
118 | del _out |
|
156 | del _out | |
119 |
|
157 | |||
120 | #**************************************************************************** |
|
158 | #**************************************************************************** | |
121 | # Generic warning/error printer, used by everything else |
|
159 | # Generic warning/error printer, used by everything else | |
122 | def warn(msg,level=2,exit_val=1): |
|
160 | def warn(msg,level=2,exit_val=1): | |
123 | """Standard warning printer. Gives formatting consistency. |
|
161 | """Standard warning printer. Gives formatting consistency. | |
124 |
|
162 | |||
125 | Output is sent to Term.cerr (sys.stderr by default). |
|
163 | Output is sent to Term.cerr (sys.stderr by default). | |
126 |
|
164 | |||
127 | Options: |
|
165 | Options: | |
128 |
|
166 | |||
129 | -level(2): allows finer control: |
|
167 | -level(2): allows finer control: | |
130 | 0 -> Do nothing, dummy function. |
|
168 | 0 -> Do nothing, dummy function. | |
131 | 1 -> Print message. |
|
169 | 1 -> Print message. | |
132 | 2 -> Print 'WARNING:' + message. (Default level). |
|
170 | 2 -> Print 'WARNING:' + message. (Default level). | |
133 | 3 -> Print 'ERROR:' + message. |
|
171 | 3 -> Print 'ERROR:' + message. | |
134 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
172 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). | |
135 |
|
173 | |||
136 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
174 | -exit_val (1): exit value returned by sys.exit() for a level 4 | |
137 | warning. Ignored for all other levels.""" |
|
175 | warning. Ignored for all other levels.""" | |
138 |
|
176 | |||
139 | if level>0: |
|
177 | if level>0: | |
140 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
178 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] | |
141 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
179 | print >> Term.cerr, '%s%s' % (header[level],msg) | |
142 | if level == 4: |
|
180 | if level == 4: | |
143 | print >> Term.cerr,'Exiting.\n' |
|
181 | print >> Term.cerr,'Exiting.\n' | |
144 | sys.exit(exit_val) |
|
182 | sys.exit(exit_val) | |
145 |
|
183 | |||
146 | def info(msg): |
|
184 | def info(msg): | |
147 | """Equivalent to warn(msg,level=1).""" |
|
185 | """Equivalent to warn(msg,level=1).""" | |
148 |
|
186 | |||
149 | warn(msg,level=1) |
|
187 | warn(msg,level=1) | |
150 |
|
188 | |||
151 | def error(msg): |
|
189 | def error(msg): | |
152 | """Equivalent to warn(msg,level=3).""" |
|
190 | """Equivalent to warn(msg,level=3).""" | |
153 |
|
191 | |||
154 | warn(msg,level=3) |
|
192 | warn(msg,level=3) | |
155 |
|
193 | |||
156 | def fatal(msg,exit_val=1): |
|
194 | def fatal(msg,exit_val=1): | |
157 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
195 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" | |
158 |
|
196 | |||
159 | warn(msg,exit_val=exit_val,level=4) |
|
197 | warn(msg,exit_val=exit_val,level=4) | |
160 |
|
198 | |||
161 | #---------------------------------------------------------------------------- |
|
199 | #---------------------------------------------------------------------------- | |
162 | StringTypes = types.StringTypes |
|
200 | StringTypes = types.StringTypes | |
163 |
|
201 | |||
164 | # Basic timing functionality |
|
202 | # Basic timing functionality | |
165 |
|
203 | |||
166 | # If possible (Unix), use the resource module instead of time.clock() |
|
204 | # If possible (Unix), use the resource module instead of time.clock() | |
167 | try: |
|
205 | try: | |
168 | import resource |
|
206 | import resource | |
169 | def clock(): |
|
207 | def clock(): | |
170 | """clock() -> floating point number |
|
208 | """clock() -> floating point number | |
171 |
|
209 | |||
172 | Return the CPU time in seconds (user time only, system time is |
|
210 | Return the CPU time in seconds (user time only, system time is | |
173 | ignored) since the start of the process. This is done via a call to |
|
211 | ignored) since the start of the process. This is done via a call to | |
174 | resource.getrusage, so it avoids the wraparound problems in |
|
212 | resource.getrusage, so it avoids the wraparound problems in | |
175 | time.clock().""" |
|
213 | time.clock().""" | |
176 |
|
214 | |||
177 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
215 | return resource.getrusage(resource.RUSAGE_SELF)[0] | |
178 |
|
216 | |||
179 | def clock2(): |
|
217 | def clock2(): | |
180 | """clock2() -> (t_user,t_system) |
|
218 | """clock2() -> (t_user,t_system) | |
181 |
|
219 | |||
182 | Similar to clock(), but return a tuple of user/system times.""" |
|
220 | Similar to clock(), but return a tuple of user/system times.""" | |
183 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
221 | return resource.getrusage(resource.RUSAGE_SELF)[:2] | |
184 |
|
222 | |||
185 | except ImportError: |
|
223 | except ImportError: | |
186 | clock = time.clock |
|
224 | clock = time.clock | |
187 | def clock2(): |
|
225 | def clock2(): | |
188 | """Under windows, system CPU time can't be measured. |
|
226 | """Under windows, system CPU time can't be measured. | |
189 |
|
227 | |||
190 | This just returns clock() and zero.""" |
|
228 | This just returns clock() and zero.""" | |
191 | return time.clock(),0.0 |
|
229 | return time.clock(),0.0 | |
192 |
|
230 | |||
193 | def timings_out(reps,func,*args,**kw): |
|
231 | def timings_out(reps,func,*args,**kw): | |
194 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
232 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) | |
195 |
|
233 | |||
196 | Execute a function reps times, return a tuple with the elapsed total |
|
234 | Execute a function reps times, return a tuple with the elapsed total | |
197 | CPU time in seconds, the time per call and the function's output. |
|
235 | CPU time in seconds, the time per call and the function's output. | |
198 |
|
236 | |||
199 | Under Unix, the return value is the sum of user+system time consumed by |
|
237 | Under Unix, the return value is the sum of user+system time consumed by | |
200 | the process, computed via the resource module. This prevents problems |
|
238 | the process, computed via the resource module. This prevents problems | |
201 | related to the wraparound effect which the time.clock() function has. |
|
239 | related to the wraparound effect which the time.clock() function has. | |
202 |
|
240 | |||
203 | Under Windows the return value is in wall clock seconds. See the |
|
241 | Under Windows the return value is in wall clock seconds. See the | |
204 | documentation for the time module for more details.""" |
|
242 | documentation for the time module for more details.""" | |
205 |
|
243 | |||
206 | reps = int(reps) |
|
244 | reps = int(reps) | |
207 | assert reps >=1, 'reps must be >= 1' |
|
245 | assert reps >=1, 'reps must be >= 1' | |
208 | if reps==1: |
|
246 | if reps==1: | |
209 | start = clock() |
|
247 | start = clock() | |
210 | out = func(*args,**kw) |
|
248 | out = func(*args,**kw) | |
211 | tot_time = clock()-start |
|
249 | tot_time = clock()-start | |
212 | else: |
|
250 | else: | |
213 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
251 | rng = xrange(reps-1) # the last time is executed separately to store output | |
214 | start = clock() |
|
252 | start = clock() | |
215 | for dummy in rng: func(*args,**kw) |
|
253 | for dummy in rng: func(*args,**kw) | |
216 | out = func(*args,**kw) # one last time |
|
254 | out = func(*args,**kw) # one last time | |
217 | tot_time = clock()-start |
|
255 | tot_time = clock()-start | |
218 | av_time = tot_time / reps |
|
256 | av_time = tot_time / reps | |
219 | return tot_time,av_time,out |
|
257 | return tot_time,av_time,out | |
220 |
|
258 | |||
221 | def timings(reps,func,*args,**kw): |
|
259 | def timings(reps,func,*args,**kw): | |
222 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
260 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) | |
223 |
|
261 | |||
224 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
262 | Execute a function reps times, return a tuple with the elapsed total CPU | |
225 | time in seconds and the time per call. These are just the first two values |
|
263 | time in seconds and the time per call. These are just the first two values | |
226 | in timings_out().""" |
|
264 | in timings_out().""" | |
227 |
|
265 | |||
228 | return timings_out(reps,func,*args,**kw)[0:2] |
|
266 | return timings_out(reps,func,*args,**kw)[0:2] | |
229 |
|
267 | |||
230 | def timing(func,*args,**kw): |
|
268 | def timing(func,*args,**kw): | |
231 | """timing(func,*args,**kw) -> t_total |
|
269 | """timing(func,*args,**kw) -> t_total | |
232 |
|
270 | |||
233 | Execute a function once, return the elapsed total CPU time in |
|
271 | Execute a function once, return the elapsed total CPU time in | |
234 | seconds. This is just the first value in timings_out().""" |
|
272 | seconds. This is just the first value in timings_out().""" | |
235 |
|
273 | |||
236 | return timings_out(1,func,*args,**kw)[0] |
|
274 | return timings_out(1,func,*args,**kw)[0] | |
237 |
|
275 | |||
238 | #**************************************************************************** |
|
276 | #**************************************************************************** | |
239 | # file and system |
|
277 | # file and system | |
240 |
|
278 | |||
241 | def system(cmd,verbose=0,debug=0,header=''): |
|
279 | def system(cmd,verbose=0,debug=0,header=''): | |
242 | """Execute a system command, return its exit status. |
|
280 | """Execute a system command, return its exit status. | |
243 |
|
281 | |||
244 | Options: |
|
282 | Options: | |
245 |
|
283 | |||
246 | - verbose (0): print the command to be executed. |
|
284 | - verbose (0): print the command to be executed. | |
247 |
|
285 | |||
248 | - debug (0): only print, do not actually execute. |
|
286 | - debug (0): only print, do not actually execute. | |
249 |
|
287 | |||
250 | - header (''): Header to print on screen prior to the executed command (it |
|
288 | - header (''): Header to print on screen prior to the executed command (it | |
251 | is only prepended to the command, no newlines are added). |
|
289 | is only prepended to the command, no newlines are added). | |
252 |
|
290 | |||
253 | Note: a stateful version of this function is available through the |
|
291 | Note: a stateful version of this function is available through the | |
254 | SystemExec class.""" |
|
292 | SystemExec class.""" | |
255 |
|
293 | |||
256 | stat = 0 |
|
294 | stat = 0 | |
257 | if verbose or debug: print header+cmd |
|
295 | if verbose or debug: print header+cmd | |
258 | sys.stdout.flush() |
|
296 | sys.stdout.flush() | |
259 | if not debug: stat = os.system(cmd) |
|
297 | if not debug: stat = os.system(cmd) | |
260 | return stat |
|
298 | return stat | |
261 |
|
299 | |||
262 | def shell(cmd,verbose=0,debug=0,header=''): |
|
300 | def shell(cmd,verbose=0,debug=0,header=''): | |
263 | """Execute a command in the system shell, always return None. |
|
301 | """Execute a command in the system shell, always return None. | |
264 |
|
302 | |||
265 | Options: |
|
303 | Options: | |
266 |
|
304 | |||
267 | - verbose (0): print the command to be executed. |
|
305 | - verbose (0): print the command to be executed. | |
268 |
|
306 | |||
269 | - debug (0): only print, do not actually execute. |
|
307 | - debug (0): only print, do not actually execute. | |
270 |
|
308 | |||
271 | - header (''): Header to print on screen prior to the executed command (it |
|
309 | - header (''): Header to print on screen prior to the executed command (it | |
272 | is only prepended to the command, no newlines are added). |
|
310 | is only prepended to the command, no newlines are added). | |
273 |
|
311 | |||
274 | Note: this is similar to genutils.system(), but it returns None so it can |
|
312 | Note: this is similar to genutils.system(), but it returns None so it can | |
275 | be conveniently used in interactive loops without getting the return value |
|
313 | be conveniently used in interactive loops without getting the return value | |
276 | (typically 0) printed many times.""" |
|
314 | (typically 0) printed many times.""" | |
277 |
|
315 | |||
278 | stat = 0 |
|
316 | stat = 0 | |
279 | if verbose or debug: print header+cmd |
|
317 | if verbose or debug: print header+cmd | |
280 | # flush stdout so we don't mangle python's buffering |
|
318 | # flush stdout so we don't mangle python's buffering | |
281 | sys.stdout.flush() |
|
319 | sys.stdout.flush() | |
282 | if not debug: |
|
320 | if not debug: | |
283 | os.system(cmd) |
|
321 | os.system(cmd) | |
284 |
|
322 | |||
285 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
323 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): | |
286 | """Dummy substitute for perl's backquotes. |
|
324 | """Dummy substitute for perl's backquotes. | |
287 |
|
325 | |||
288 | Executes a command and returns the output. |
|
326 | Executes a command and returns the output. | |
289 |
|
327 | |||
290 | Accepts the same arguments as system(), plus: |
|
328 | Accepts the same arguments as system(), plus: | |
291 |
|
329 | |||
292 | - split(0): if true, the output is returned as a list split on newlines. |
|
330 | - split(0): if true, the output is returned as a list split on newlines. | |
293 |
|
331 | |||
294 | Note: a stateful version of this function is available through the |
|
332 | Note: a stateful version of this function is available through the | |
295 | SystemExec class.""" |
|
333 | SystemExec class.""" | |
296 |
|
334 | |||
297 | if verbose or debug: print header+cmd |
|
335 | if verbose or debug: print header+cmd | |
298 | if not debug: |
|
336 | if not debug: | |
299 | output = commands.getoutput(cmd) |
|
337 | output = commands.getoutput(cmd) | |
300 | if split: |
|
338 | if split: | |
301 | return output.split('\n') |
|
339 | return output.split('\n') | |
302 | else: |
|
340 | else: | |
303 | return output |
|
341 | return output | |
304 |
|
342 | |||
305 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
343 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): | |
306 | """Return (standard output,standard error) of executing cmd in a shell. |
|
344 | """Return (standard output,standard error) of executing cmd in a shell. | |
307 |
|
345 | |||
308 | Accepts the same arguments as system(), plus: |
|
346 | Accepts the same arguments as system(), plus: | |
309 |
|
347 | |||
310 | - split(0): if true, each of stdout/err is returned as a list split on |
|
348 | - split(0): if true, each of stdout/err is returned as a list split on | |
311 | newlines. |
|
349 | newlines. | |
312 |
|
350 | |||
313 | Note: a stateful version of this function is available through the |
|
351 | Note: a stateful version of this function is available through the | |
314 | SystemExec class.""" |
|
352 | SystemExec class.""" | |
315 |
|
353 | |||
316 | if verbose or debug: print header+cmd |
|
354 | if verbose or debug: print header+cmd | |
317 | if not cmd: |
|
355 | if not cmd: | |
318 | if split: |
|
356 | if split: | |
319 | return [],[] |
|
357 | return [],[] | |
320 | else: |
|
358 | else: | |
321 | return '','' |
|
359 | return '','' | |
322 | if not debug: |
|
360 | if not debug: | |
323 | pin,pout,perr = os.popen3(cmd) |
|
361 | pin,pout,perr = os.popen3(cmd) | |
324 | tout = pout.read().rstrip() |
|
362 | tout = pout.read().rstrip() | |
325 | terr = perr.read().rstrip() |
|
363 | terr = perr.read().rstrip() | |
326 | pin.close() |
|
364 | pin.close() | |
327 | pout.close() |
|
365 | pout.close() | |
328 | perr.close() |
|
366 | perr.close() | |
329 | if split: |
|
367 | if split: | |
330 | return tout.split('\n'),terr.split('\n') |
|
368 | return tout.split('\n'),terr.split('\n') | |
331 | else: |
|
369 | else: | |
332 | return tout,terr |
|
370 | return tout,terr | |
333 |
|
371 | |||
334 | # for compatibility with older naming conventions |
|
372 | # for compatibility with older naming conventions | |
335 | xsys = system |
|
373 | xsys = system | |
336 | bq = getoutput |
|
374 | bq = getoutput | |
337 |
|
375 | |||
338 | class SystemExec: |
|
376 | class SystemExec: | |
339 | """Access the system and getoutput functions through a stateful interface. |
|
377 | """Access the system and getoutput functions through a stateful interface. | |
340 |
|
378 | |||
341 | Note: here we refer to the system and getoutput functions from this |
|
379 | Note: here we refer to the system and getoutput functions from this | |
342 | library, not the ones from the standard python library. |
|
380 | library, not the ones from the standard python library. | |
343 |
|
381 | |||
344 | This class offers the system and getoutput functions as methods, but the |
|
382 | This class offers the system and getoutput functions as methods, but the | |
345 | verbose, debug and header parameters can be set for the instance (at |
|
383 | verbose, debug and header parameters can be set for the instance (at | |
346 | creation time or later) so that they don't need to be specified on each |
|
384 | creation time or later) so that they don't need to be specified on each | |
347 | call. |
|
385 | call. | |
348 |
|
386 | |||
349 | For efficiency reasons, there's no way to override the parameters on a |
|
387 | For efficiency reasons, there's no way to override the parameters on a | |
350 | per-call basis other than by setting instance attributes. If you need |
|
388 | per-call basis other than by setting instance attributes. If you need | |
351 | local overrides, it's best to directly call system() or getoutput(). |
|
389 | local overrides, it's best to directly call system() or getoutput(). | |
352 |
|
390 | |||
353 | The following names are provided as alternate options: |
|
391 | The following names are provided as alternate options: | |
354 | - xsys: alias to system |
|
392 | - xsys: alias to system | |
355 | - bq: alias to getoutput |
|
393 | - bq: alias to getoutput | |
356 |
|
394 | |||
357 | An instance can then be created as: |
|
395 | An instance can then be created as: | |
358 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
396 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') | |
359 |
|
397 | |||
360 | And used as: |
|
398 | And used as: | |
361 | >>> sysexec.xsys('pwd') |
|
399 | >>> sysexec.xsys('pwd') | |
362 | >>> dirlist = sysexec.bq('ls -l') |
|
400 | >>> dirlist = sysexec.bq('ls -l') | |
363 | """ |
|
401 | """ | |
364 |
|
402 | |||
365 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
403 | def __init__(self,verbose=0,debug=0,header='',split=0): | |
366 | """Specify the instance's values for verbose, debug and header.""" |
|
404 | """Specify the instance's values for verbose, debug and header.""" | |
367 | setattr_list(self,'verbose debug header split') |
|
405 | setattr_list(self,'verbose debug header split') | |
368 |
|
406 | |||
369 | def system(self,cmd): |
|
407 | def system(self,cmd): | |
370 | """Stateful interface to system(), with the same keyword parameters.""" |
|
408 | """Stateful interface to system(), with the same keyword parameters.""" | |
371 |
|
409 | |||
372 | system(cmd,self.verbose,self.debug,self.header) |
|
410 | system(cmd,self.verbose,self.debug,self.header) | |
373 |
|
411 | |||
374 | def shell(self,cmd): |
|
412 | def shell(self,cmd): | |
375 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
413 | """Stateful interface to shell(), with the same keyword parameters.""" | |
376 |
|
414 | |||
377 | shell(cmd,self.verbose,self.debug,self.header) |
|
415 | shell(cmd,self.verbose,self.debug,self.header) | |
378 |
|
416 | |||
379 | xsys = system # alias |
|
417 | xsys = system # alias | |
380 |
|
418 | |||
381 | def getoutput(self,cmd): |
|
419 | def getoutput(self,cmd): | |
382 | """Stateful interface to getoutput().""" |
|
420 | """Stateful interface to getoutput().""" | |
383 |
|
421 | |||
384 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
422 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) | |
385 |
|
423 | |||
386 | def getoutputerror(self,cmd): |
|
424 | def getoutputerror(self,cmd): | |
387 | """Stateful interface to getoutputerror().""" |
|
425 | """Stateful interface to getoutputerror().""" | |
388 |
|
426 | |||
389 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
427 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) | |
390 |
|
428 | |||
391 | bq = getoutput # alias |
|
429 | bq = getoutput # alias | |
392 |
|
430 | |||
393 | #----------------------------------------------------------------------------- |
|
431 | #----------------------------------------------------------------------------- | |
394 | def mutex_opts(dict,ex_op): |
|
432 | def mutex_opts(dict,ex_op): | |
395 | """Check for presence of mutually exclusive keys in a dict. |
|
433 | """Check for presence of mutually exclusive keys in a dict. | |
396 |
|
434 | |||
397 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
435 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" | |
398 | for op1,op2 in ex_op: |
|
436 | for op1,op2 in ex_op: | |
399 | if op1 in dict and op2 in dict: |
|
437 | if op1 in dict and op2 in dict: | |
400 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
438 | raise ValueError,'\n*** ERROR in Arguments *** '\ | |
401 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
439 | 'Options '+op1+' and '+op2+' are mutually exclusive.' | |
402 |
|
440 | |||
403 | #----------------------------------------------------------------------------- |
|
441 | #----------------------------------------------------------------------------- | |
404 | def filefind(fname,alt_dirs = None): |
|
442 | def filefind(fname,alt_dirs = None): | |
405 | """Return the given filename either in the current directory, if it |
|
443 | """Return the given filename either in the current directory, if it | |
406 | exists, or in a specified list of directories. |
|
444 | exists, or in a specified list of directories. | |
407 |
|
445 | |||
408 | ~ expansion is done on all file and directory names. |
|
446 | ~ expansion is done on all file and directory names. | |
409 |
|
447 | |||
410 | Upon an unsuccessful search, raise an IOError exception.""" |
|
448 | Upon an unsuccessful search, raise an IOError exception.""" | |
411 |
|
449 | |||
412 | if alt_dirs is None: |
|
450 | if alt_dirs is None: | |
413 | try: |
|
451 | try: | |
414 | alt_dirs = get_home_dir() |
|
452 | alt_dirs = get_home_dir() | |
415 | except HomeDirError: |
|
453 | except HomeDirError: | |
416 | alt_dirs = os.getcwd() |
|
454 | alt_dirs = os.getcwd() | |
417 | search = [fname] + list_strings(alt_dirs) |
|
455 | search = [fname] + list_strings(alt_dirs) | |
418 | search = map(os.path.expanduser,search) |
|
456 | search = map(os.path.expanduser,search) | |
419 | #print 'search list for',fname,'list:',search # dbg |
|
457 | #print 'search list for',fname,'list:',search # dbg | |
420 | fname = search[0] |
|
458 | fname = search[0] | |
421 | if os.path.isfile(fname): |
|
459 | if os.path.isfile(fname): | |
422 | return fname |
|
460 | return fname | |
423 | for direc in search[1:]: |
|
461 | for direc in search[1:]: | |
424 | testname = os.path.join(direc,fname) |
|
462 | testname = os.path.join(direc,fname) | |
425 | #print 'testname',testname # dbg |
|
463 | #print 'testname',testname # dbg | |
426 | if os.path.isfile(testname): |
|
464 | if os.path.isfile(testname): | |
427 | return testname |
|
465 | return testname | |
428 | raise IOError,'File' + `fname` + \ |
|
466 | raise IOError,'File' + `fname` + \ | |
429 | ' not found in current or supplied directories:' + `alt_dirs` |
|
467 | ' not found in current or supplied directories:' + `alt_dirs` | |
430 |
|
468 | |||
431 | #---------------------------------------------------------------------------- |
|
469 | #---------------------------------------------------------------------------- | |
432 | def target_outdated(target,deps): |
|
470 | def target_outdated(target,deps): | |
433 | """Determine whether a target is out of date. |
|
471 | """Determine whether a target is out of date. | |
434 |
|
472 | |||
435 | target_outdated(target,deps) -> 1/0 |
|
473 | target_outdated(target,deps) -> 1/0 | |
436 |
|
474 | |||
437 | deps: list of filenames which MUST exist. |
|
475 | deps: list of filenames which MUST exist. | |
438 | target: single filename which may or may not exist. |
|
476 | target: single filename which may or may not exist. | |
439 |
|
477 | |||
440 | If target doesn't exist or is older than any file listed in deps, return |
|
478 | If target doesn't exist or is older than any file listed in deps, return | |
441 | true, otherwise return false. |
|
479 | true, otherwise return false. | |
442 | """ |
|
480 | """ | |
443 | try: |
|
481 | try: | |
444 | target_time = os.path.getmtime(target) |
|
482 | target_time = os.path.getmtime(target) | |
445 | except os.error: |
|
483 | except os.error: | |
446 | return 1 |
|
484 | return 1 | |
447 | for dep in deps: |
|
485 | for dep in deps: | |
448 | dep_time = os.path.getmtime(dep) |
|
486 | dep_time = os.path.getmtime(dep) | |
449 | if dep_time > target_time: |
|
487 | if dep_time > target_time: | |
450 | #print "For target",target,"Dep failed:",dep # dbg |
|
488 | #print "For target",target,"Dep failed:",dep # dbg | |
451 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
489 | #print "times (dep,tar):",dep_time,target_time # dbg | |
452 | return 1 |
|
490 | return 1 | |
453 | return 0 |
|
491 | return 0 | |
454 |
|
492 | |||
455 | #----------------------------------------------------------------------------- |
|
493 | #----------------------------------------------------------------------------- | |
456 | def target_update(target,deps,cmd): |
|
494 | def target_update(target,deps,cmd): | |
457 | """Update a target with a given command given a list of dependencies. |
|
495 | """Update a target with a given command given a list of dependencies. | |
458 |
|
496 | |||
459 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
497 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
460 |
|
498 | |||
461 | This is just a wrapper around target_outdated() which calls the given |
|
499 | This is just a wrapper around target_outdated() which calls the given | |
462 | command if target is outdated.""" |
|
500 | command if target is outdated.""" | |
463 |
|
501 | |||
464 | if target_outdated(target,deps): |
|
502 | if target_outdated(target,deps): | |
465 | xsys(cmd) |
|
503 | xsys(cmd) | |
466 |
|
504 | |||
467 | #---------------------------------------------------------------------------- |
|
505 | #---------------------------------------------------------------------------- | |
468 | def unquote_ends(istr): |
|
506 | def unquote_ends(istr): | |
469 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
507 | """Remove a single pair of quotes from the endpoints of a string.""" | |
470 |
|
508 | |||
471 | if not istr: |
|
509 | if not istr: | |
472 | return istr |
|
510 | return istr | |
473 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
511 | if (istr[0]=="'" and istr[-1]=="'") or \ | |
474 | (istr[0]=='"' and istr[-1]=='"'): |
|
512 | (istr[0]=='"' and istr[-1]=='"'): | |
475 | return istr[1:-1] |
|
513 | return istr[1:-1] | |
476 | else: |
|
514 | else: | |
477 | return istr |
|
515 | return istr | |
478 |
|
516 | |||
479 | #---------------------------------------------------------------------------- |
|
517 | #---------------------------------------------------------------------------- | |
480 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
518 | def process_cmdline(argv,names=[],defaults={},usage=''): | |
481 | """ Process command-line options and arguments. |
|
519 | """ Process command-line options and arguments. | |
482 |
|
520 | |||
483 | Arguments: |
|
521 | Arguments: | |
484 |
|
522 | |||
485 | - argv: list of arguments, typically sys.argv. |
|
523 | - argv: list of arguments, typically sys.argv. | |
486 |
|
524 | |||
487 | - names: list of option names. See DPyGetOpt docs for details on options |
|
525 | - names: list of option names. See DPyGetOpt docs for details on options | |
488 | syntax. |
|
526 | syntax. | |
489 |
|
527 | |||
490 | - defaults: dict of default values. |
|
528 | - defaults: dict of default values. | |
491 |
|
529 | |||
492 | - usage: optional usage notice to print if a wrong argument is passed. |
|
530 | - usage: optional usage notice to print if a wrong argument is passed. | |
493 |
|
531 | |||
494 | Return a dict of options and a list of free arguments.""" |
|
532 | Return a dict of options and a list of free arguments.""" | |
495 |
|
533 | |||
496 | getopt = DPyGetOpt.DPyGetOpt() |
|
534 | getopt = DPyGetOpt.DPyGetOpt() | |
497 | getopt.setIgnoreCase(0) |
|
535 | getopt.setIgnoreCase(0) | |
498 | getopt.parseConfiguration(names) |
|
536 | getopt.parseConfiguration(names) | |
499 |
|
537 | |||
500 | try: |
|
538 | try: | |
501 | getopt.processArguments(argv) |
|
539 | getopt.processArguments(argv) | |
502 | except: |
|
540 | except: | |
503 | print usage |
|
541 | print usage | |
504 | warn(`sys.exc_value`,level=4) |
|
542 | warn(`sys.exc_value`,level=4) | |
505 |
|
543 | |||
506 | defaults.update(getopt.optionValues) |
|
544 | defaults.update(getopt.optionValues) | |
507 | args = getopt.freeValues |
|
545 | args = getopt.freeValues | |
508 |
|
546 | |||
509 | return defaults,args |
|
547 | return defaults,args | |
510 |
|
548 | |||
511 | #---------------------------------------------------------------------------- |
|
549 | #---------------------------------------------------------------------------- | |
512 | def optstr2types(ostr): |
|
550 | def optstr2types(ostr): | |
513 | """Convert a string of option names to a dict of type mappings. |
|
551 | """Convert a string of option names to a dict of type mappings. | |
514 |
|
552 | |||
515 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
553 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} | |
516 |
|
554 | |||
517 | This is used to get the types of all the options in a string formatted |
|
555 | This is used to get the types of all the options in a string formatted | |
518 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
556 | with the conventions of DPyGetOpt. The 'type' None is used for options | |
519 | which are strings (they need no further conversion). This function's main |
|
557 | which are strings (they need no further conversion). This function's main | |
520 | use is to get a typemap for use with read_dict(). |
|
558 | use is to get a typemap for use with read_dict(). | |
521 | """ |
|
559 | """ | |
522 |
|
560 | |||
523 | typeconv = {None:'',int:'',float:''} |
|
561 | typeconv = {None:'',int:'',float:''} | |
524 | typemap = {'s':None,'i':int,'f':float} |
|
562 | typemap = {'s':None,'i':int,'f':float} | |
525 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
563 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') | |
526 |
|
564 | |||
527 | for w in ostr.split(): |
|
565 | for w in ostr.split(): | |
528 | oname,alias,otype = opt_re.match(w).groups() |
|
566 | oname,alias,otype = opt_re.match(w).groups() | |
529 | if otype == '' or alias == '!': # simple switches are integers too |
|
567 | if otype == '' or alias == '!': # simple switches are integers too | |
530 | otype = 'i' |
|
568 | otype = 'i' | |
531 | typeconv[typemap[otype]] += oname + ' ' |
|
569 | typeconv[typemap[otype]] += oname + ' ' | |
532 | return typeconv |
|
570 | return typeconv | |
533 |
|
571 | |||
534 | #---------------------------------------------------------------------------- |
|
572 | #---------------------------------------------------------------------------- | |
535 | def read_dict(filename,type_conv=None,**opt): |
|
573 | def read_dict(filename,type_conv=None,**opt): | |
536 |
|
574 | |||
537 | """Read a dictionary of key=value pairs from an input file, optionally |
|
575 | """Read a dictionary of key=value pairs from an input file, optionally | |
538 | performing conversions on the resulting values. |
|
576 | performing conversions on the resulting values. | |
539 |
|
577 | |||
540 | read_dict(filename,type_conv,**opt) -> dict |
|
578 | read_dict(filename,type_conv,**opt) -> dict | |
541 |
|
579 | |||
542 | Only one value per line is accepted, the format should be |
|
580 | Only one value per line is accepted, the format should be | |
543 | # optional comments are ignored |
|
581 | # optional comments are ignored | |
544 | key value\n |
|
582 | key value\n | |
545 |
|
583 | |||
546 | Args: |
|
584 | Args: | |
547 |
|
585 | |||
548 | - type_conv: A dictionary specifying which keys need to be converted to |
|
586 | - type_conv: A dictionary specifying which keys need to be converted to | |
549 | which types. By default all keys are read as strings. This dictionary |
|
587 | which types. By default all keys are read as strings. This dictionary | |
550 | should have as its keys valid conversion functions for strings |
|
588 | should have as its keys valid conversion functions for strings | |
551 | (int,long,float,complex, or your own). The value for each key |
|
589 | (int,long,float,complex, or your own). The value for each key | |
552 | (converter) should be a whitespace separated string containing the names |
|
590 | (converter) should be a whitespace separated string containing the names | |
553 | of all the entries in the file to be converted using that function. For |
|
591 | of all the entries in the file to be converted using that function. For | |
554 | keys to be left alone, use None as the conversion function (only needed |
|
592 | keys to be left alone, use None as the conversion function (only needed | |
555 | with purge=1, see below). |
|
593 | with purge=1, see below). | |
556 |
|
594 | |||
557 | - opt: dictionary with extra options as below (default in parens) |
|
595 | - opt: dictionary with extra options as below (default in parens) | |
558 |
|
596 | |||
559 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
597 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out | |
560 | of the dictionary to be returned. If purge is going to be used, the |
|
598 | of the dictionary to be returned. If purge is going to be used, the | |
561 | set of keys to be left as strings also has to be explicitly specified |
|
599 | set of keys to be left as strings also has to be explicitly specified | |
562 | using the (non-existent) conversion function None. |
|
600 | using the (non-existent) conversion function None. | |
563 |
|
601 | |||
564 | fs(None): field separator. This is the key/value separator to be used |
|
602 | fs(None): field separator. This is the key/value separator to be used | |
565 | when parsing the file. The None default means any whitespace [behavior |
|
603 | when parsing the file. The None default means any whitespace [behavior | |
566 | of string.split()]. |
|
604 | of string.split()]. | |
567 |
|
605 | |||
568 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
606 | strip(0): if 1, strip string values of leading/trailinig whitespace. | |
569 |
|
607 | |||
570 | warn(1): warning level if requested keys are not found in file. |
|
608 | warn(1): warning level if requested keys are not found in file. | |
571 | - 0: silently ignore. |
|
609 | - 0: silently ignore. | |
572 | - 1: inform but proceed. |
|
610 | - 1: inform but proceed. | |
573 | - 2: raise KeyError exception. |
|
611 | - 2: raise KeyError exception. | |
574 |
|
612 | |||
575 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
613 | no_empty(0): if 1, remove keys with whitespace strings as a value. | |
576 |
|
614 | |||
577 | unique([]): list of keys (or space separated string) which can't be |
|
615 | unique([]): list of keys (or space separated string) which can't be | |
578 | repeated. If one such key is found in the file, each new instance |
|
616 | repeated. If one such key is found in the file, each new instance | |
579 | overwrites the previous one. For keys not listed here, the behavior is |
|
617 | overwrites the previous one. For keys not listed here, the behavior is | |
580 | to make a list of all appearances. |
|
618 | to make a list of all appearances. | |
581 |
|
619 | |||
582 | Example: |
|
620 | Example: | |
583 | If the input file test.ini has: |
|
621 | If the input file test.ini has: | |
584 | i 3 |
|
622 | i 3 | |
585 | x 4.5 |
|
623 | x 4.5 | |
586 | y 5.5 |
|
624 | y 5.5 | |
587 | s hi ho |
|
625 | s hi ho | |
588 | Then: |
|
626 | Then: | |
589 |
|
627 | |||
590 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
628 | >>> type_conv={int:'i',float:'x',None:'s'} | |
591 | >>> read_dict('test.ini') |
|
629 | >>> read_dict('test.ini') | |
592 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} |
|
630 | {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'} | |
593 | >>> read_dict('test.ini',type_conv) |
|
631 | >>> read_dict('test.ini',type_conv) | |
594 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} |
|
632 | {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'} | |
595 | >>> read_dict('test.ini',type_conv,purge=1) |
|
633 | >>> read_dict('test.ini',type_conv,purge=1) | |
596 | {'i': 3, 's': 'hi ho', 'x': 4.5} |
|
634 | {'i': 3, 's': 'hi ho', 'x': 4.5} | |
597 | """ |
|
635 | """ | |
598 |
|
636 | |||
599 | # starting config |
|
637 | # starting config | |
600 | opt.setdefault('purge',0) |
|
638 | opt.setdefault('purge',0) | |
601 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
639 | opt.setdefault('fs',None) # field sep defaults to any whitespace | |
602 | opt.setdefault('strip',0) |
|
640 | opt.setdefault('strip',0) | |
603 | opt.setdefault('warn',1) |
|
641 | opt.setdefault('warn',1) | |
604 | opt.setdefault('no_empty',0) |
|
642 | opt.setdefault('no_empty',0) | |
605 | opt.setdefault('unique','') |
|
643 | opt.setdefault('unique','') | |
606 | if type(opt['unique']) in StringTypes: |
|
644 | if type(opt['unique']) in StringTypes: | |
607 | unique_keys = qw(opt['unique']) |
|
645 | unique_keys = qw(opt['unique']) | |
608 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
646 | elif type(opt['unique']) in (types.TupleType,types.ListType): | |
609 | unique_keys = opt['unique'] |
|
647 | unique_keys = opt['unique'] | |
610 | else: |
|
648 | else: | |
611 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
649 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' | |
612 |
|
650 | |||
613 | dict = {} |
|
651 | dict = {} | |
614 | # first read in table of values as strings |
|
652 | # first read in table of values as strings | |
615 | file = open(filename,'r') |
|
653 | file = open(filename,'r') | |
616 | for line in file.readlines(): |
|
654 | for line in file.readlines(): | |
617 | line = line.strip() |
|
655 | line = line.strip() | |
618 | if len(line) and line[0]=='#': continue |
|
656 | if len(line) and line[0]=='#': continue | |
619 | if len(line)>0: |
|
657 | if len(line)>0: | |
620 | lsplit = line.split(opt['fs'],1) |
|
658 | lsplit = line.split(opt['fs'],1) | |
621 | try: |
|
659 | try: | |
622 | key,val = lsplit |
|
660 | key,val = lsplit | |
623 | except ValueError: |
|
661 | except ValueError: | |
624 | key,val = lsplit[0],'' |
|
662 | key,val = lsplit[0],'' | |
625 | key = key.strip() |
|
663 | key = key.strip() | |
626 | if opt['strip']: val = val.strip() |
|
664 | if opt['strip']: val = val.strip() | |
627 | if val == "''" or val == '""': val = '' |
|
665 | if val == "''" or val == '""': val = '' | |
628 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
666 | if opt['no_empty'] and (val=='' or val.isspace()): | |
629 | continue |
|
667 | continue | |
630 | # if a key is found more than once in the file, build a list |
|
668 | # if a key is found more than once in the file, build a list | |
631 | # unless it's in the 'unique' list. In that case, last found in file |
|
669 | # unless it's in the 'unique' list. In that case, last found in file | |
632 | # takes precedence. User beware. |
|
670 | # takes precedence. User beware. | |
633 | try: |
|
671 | try: | |
634 | if dict[key] and key in unique_keys: |
|
672 | if dict[key] and key in unique_keys: | |
635 | dict[key] = val |
|
673 | dict[key] = val | |
636 | elif type(dict[key]) is types.ListType: |
|
674 | elif type(dict[key]) is types.ListType: | |
637 | dict[key].append(val) |
|
675 | dict[key].append(val) | |
638 | else: |
|
676 | else: | |
639 | dict[key] = [dict[key],val] |
|
677 | dict[key] = [dict[key],val] | |
640 | except KeyError: |
|
678 | except KeyError: | |
641 | dict[key] = val |
|
679 | dict[key] = val | |
642 | # purge if requested |
|
680 | # purge if requested | |
643 | if opt['purge']: |
|
681 | if opt['purge']: | |
644 | accepted_keys = qwflat(type_conv.values()) |
|
682 | accepted_keys = qwflat(type_conv.values()) | |
645 | for key in dict.keys(): |
|
683 | for key in dict.keys(): | |
646 | if key in accepted_keys: continue |
|
684 | if key in accepted_keys: continue | |
647 | del(dict[key]) |
|
685 | del(dict[key]) | |
648 | # now convert if requested |
|
686 | # now convert if requested | |
649 | if type_conv==None: return dict |
|
687 | if type_conv==None: return dict | |
650 | conversions = type_conv.keys() |
|
688 | conversions = type_conv.keys() | |
651 | try: conversions.remove(None) |
|
689 | try: conversions.remove(None) | |
652 | except: pass |
|
690 | except: pass | |
653 | for convert in conversions: |
|
691 | for convert in conversions: | |
654 | for val in qw(type_conv[convert]): |
|
692 | for val in qw(type_conv[convert]): | |
655 | try: |
|
693 | try: | |
656 | dict[val] = convert(dict[val]) |
|
694 | dict[val] = convert(dict[val]) | |
657 | except KeyError,e: |
|
695 | except KeyError,e: | |
658 | if opt['warn'] == 0: |
|
696 | if opt['warn'] == 0: | |
659 | pass |
|
697 | pass | |
660 | elif opt['warn'] == 1: |
|
698 | elif opt['warn'] == 1: | |
661 | print >>sys.stderr, 'Warning: key',val,\ |
|
699 | print >>sys.stderr, 'Warning: key',val,\ | |
662 | 'not found in file',filename |
|
700 | 'not found in file',filename | |
663 | elif opt['warn'] == 2: |
|
701 | elif opt['warn'] == 2: | |
664 | raise KeyError,e |
|
702 | raise KeyError,e | |
665 | else: |
|
703 | else: | |
666 | raise ValueError,'Warning level must be 0,1 or 2' |
|
704 | raise ValueError,'Warning level must be 0,1 or 2' | |
667 |
|
705 | |||
668 | return dict |
|
706 | return dict | |
669 |
|
707 | |||
670 | #---------------------------------------------------------------------------- |
|
708 | #---------------------------------------------------------------------------- | |
671 | def flag_calls(func): |
|
709 | def flag_calls(func): | |
672 | """Wrap a function to detect and flag when it gets called. |
|
710 | """Wrap a function to detect and flag when it gets called. | |
673 |
|
711 | |||
674 | This is a decorator which takes a function and wraps it in a function with |
|
712 | This is a decorator which takes a function and wraps it in a function with | |
675 | a 'called' attribute. wrapper.called is initialized to False. |
|
713 | a 'called' attribute. wrapper.called is initialized to False. | |
676 |
|
714 | |||
677 | The wrapper.called attribute is set to False right before each call to the |
|
715 | The wrapper.called attribute is set to False right before each call to the | |
678 | wrapped function, so if the call fails it remains False. After the call |
|
716 | wrapped function, so if the call fails it remains False. After the call | |
679 | completes, wrapper.called is set to True and the output is returned. |
|
717 | completes, wrapper.called is set to True and the output is returned. | |
680 |
|
718 | |||
681 | Testing for truth in wrapper.called allows you to determine if a call to |
|
719 | Testing for truth in wrapper.called allows you to determine if a call to | |
682 | func() was attempted and succeeded.""" |
|
720 | func() was attempted and succeeded.""" | |
683 |
|
721 | |||
684 | def wrapper(*args,**kw): |
|
722 | def wrapper(*args,**kw): | |
685 | wrapper.called = False |
|
723 | wrapper.called = False | |
686 | out = func(*args,**kw) |
|
724 | out = func(*args,**kw) | |
687 | wrapper.called = True |
|
725 | wrapper.called = True | |
688 | return out |
|
726 | return out | |
689 |
|
727 | |||
690 | wrapper.called = False |
|
728 | wrapper.called = False | |
691 | wrapper.__doc__ = func.__doc__ |
|
729 | wrapper.__doc__ = func.__doc__ | |
692 | return wrapper |
|
730 | return wrapper | |
693 |
|
731 | |||
694 | #---------------------------------------------------------------------------- |
|
732 | #---------------------------------------------------------------------------- | |
695 | class HomeDirError(Error): |
|
733 | class HomeDirError(Error): | |
696 | pass |
|
734 | pass | |
697 |
|
735 | |||
698 | def get_home_dir(): |
|
736 | def get_home_dir(): | |
699 | """Return the closest possible equivalent to a 'home' directory. |
|
737 | """Return the closest possible equivalent to a 'home' directory. | |
700 |
|
738 | |||
701 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
739 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. | |
702 |
|
740 | |||
703 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
741 | Currently only Posix and NT are implemented, a HomeDirError exception is | |
704 | raised for all other OSes. """ |
|
742 | raised for all other OSes. """ | |
705 |
|
743 | |||
706 | isdir = os.path.isdir |
|
744 | isdir = os.path.isdir | |
707 | env = os.environ |
|
745 | env = os.environ | |
708 | try: |
|
746 | try: | |
709 | homedir = env['HOME'] |
|
747 | homedir = env['HOME'] | |
710 | if not isdir(homedir): |
|
748 | if not isdir(homedir): | |
711 | # in case a user stuck some string which does NOT resolve to a |
|
749 | # in case a user stuck some string which does NOT resolve to a | |
712 | # valid path, it's as good as if we hadn't foud it |
|
750 | # valid path, it's as good as if we hadn't foud it | |
713 | raise KeyError |
|
751 | raise KeyError | |
714 | return homedir |
|
752 | return homedir | |
715 | except KeyError: |
|
753 | except KeyError: | |
716 | if os.name == 'posix': |
|
754 | if os.name == 'posix': | |
717 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
755 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' | |
718 | elif os.name == 'nt': |
|
756 | elif os.name == 'nt': | |
719 | # For some strange reason, win9x returns 'nt' for os.name. |
|
757 | # For some strange reason, win9x returns 'nt' for os.name. | |
720 | try: |
|
758 | try: | |
721 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
759 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) | |
722 | if not isdir(homedir): |
|
760 | if not isdir(homedir): | |
723 | homedir = os.path.join(env['USERPROFILE']) |
|
761 | homedir = os.path.join(env['USERPROFILE']) | |
724 | if not isdir(homedir): |
|
762 | if not isdir(homedir): | |
725 | raise HomeDirError |
|
763 | raise HomeDirError | |
726 | return homedir |
|
764 | return homedir | |
727 | except: |
|
765 | except: | |
728 | try: |
|
766 | try: | |
729 | # Use the registry to get the 'My Documents' folder. |
|
767 | # Use the registry to get the 'My Documents' folder. | |
730 | import _winreg as wreg |
|
768 | import _winreg as wreg | |
731 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
769 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, | |
732 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
770 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") | |
733 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
771 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
734 | key.Close() |
|
772 | key.Close() | |
735 | if not isdir(homedir): |
|
773 | if not isdir(homedir): | |
736 | e = ('Invalid "Personal" folder registry key ' |
|
774 | e = ('Invalid "Personal" folder registry key ' | |
737 | 'typically "My Documents".\n' |
|
775 | 'typically "My Documents".\n' | |
738 | 'Value: %s\n' |
|
776 | 'Value: %s\n' | |
739 | 'This is not a valid directory on your system.' % |
|
777 | 'This is not a valid directory on your system.' % | |
740 | homedir) |
|
778 | homedir) | |
741 | raise HomeDirError(e) |
|
779 | raise HomeDirError(e) | |
742 | return homedir |
|
780 | return homedir | |
743 | except HomeDirError: |
|
781 | except HomeDirError: | |
744 | raise |
|
782 | raise | |
745 | except: |
|
783 | except: | |
746 | return 'C:\\' |
|
784 | return 'C:\\' | |
747 | elif os.name == 'dos': |
|
785 | elif os.name == 'dos': | |
748 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
786 | # Desperate, may do absurd things in classic MacOS. May work under DOS. | |
749 | return 'C:\\' |
|
787 | return 'C:\\' | |
750 | else: |
|
788 | else: | |
751 | raise HomeDirError,'support for your operating system not implemented.' |
|
789 | raise HomeDirError,'support for your operating system not implemented.' | |
752 |
|
790 | |||
753 | #**************************************************************************** |
|
791 | #**************************************************************************** | |
754 | # strings and text |
|
792 | # strings and text | |
755 |
|
793 | |||
756 | class LSString(str): |
|
794 | class LSString(str): | |
757 | """String derivative with a special access attributes. |
|
795 | """String derivative with a special access attributes. | |
758 |
|
796 | |||
759 | These are normal strings, but with the special attributes: |
|
797 | These are normal strings, but with the special attributes: | |
760 |
|
798 | |||
761 | .l (or .list) : value as list (split on newlines). |
|
799 | .l (or .list) : value as list (split on newlines). | |
762 | .n (or .nlstr): original value (the string itself). |
|
800 | .n (or .nlstr): original value (the string itself). | |
763 | .s (or .spstr): value as whitespace-separated string. |
|
801 | .s (or .spstr): value as whitespace-separated string. | |
764 |
|
802 | |||
765 | Any values which require transformations are computed only once and |
|
803 | Any values which require transformations are computed only once and | |
766 | cached. |
|
804 | cached. | |
767 |
|
805 | |||
768 | Such strings are very useful to efficiently interact with the shell, which |
|
806 | Such strings are very useful to efficiently interact with the shell, which | |
769 | typically only understands whitespace-separated options for commands.""" |
|
807 | typically only understands whitespace-separated options for commands.""" | |
770 |
|
808 | |||
771 | def get_list(self): |
|
809 | def get_list(self): | |
772 | try: |
|
810 | try: | |
773 | return self.__list |
|
811 | return self.__list | |
774 | except AttributeError: |
|
812 | except AttributeError: | |
775 | self.__list = self.split('\n') |
|
813 | self.__list = self.split('\n') | |
776 | return self.__list |
|
814 | return self.__list | |
777 |
|
815 | |||
778 | l = list = property(get_list) |
|
816 | l = list = property(get_list) | |
779 |
|
817 | |||
780 | def get_spstr(self): |
|
818 | def get_spstr(self): | |
781 | try: |
|
819 | try: | |
782 | return self.__spstr |
|
820 | return self.__spstr | |
783 | except AttributeError: |
|
821 | except AttributeError: | |
784 | self.__spstr = self.replace('\n',' ') |
|
822 | self.__spstr = self.replace('\n',' ') | |
785 | return self.__spstr |
|
823 | return self.__spstr | |
786 |
|
824 | |||
787 | s = spstr = property(get_spstr) |
|
825 | s = spstr = property(get_spstr) | |
788 |
|
826 | |||
789 | def get_nlstr(self): |
|
827 | def get_nlstr(self): | |
790 | return self |
|
828 | return self | |
791 |
|
829 | |||
792 | n = nlstr = property(get_nlstr) |
|
830 | n = nlstr = property(get_nlstr) | |
793 |
|
831 | |||
794 | class SList(list): |
|
832 | class SList(list): | |
795 | """List derivative with a special access attributes. |
|
833 | """List derivative with a special access attributes. | |
796 |
|
834 | |||
797 | These are normal lists, but with the special attributes: |
|
835 | These are normal lists, but with the special attributes: | |
798 |
|
836 | |||
799 | .l (or .list) : value as list (the list itself). |
|
837 | .l (or .list) : value as list (the list itself). | |
800 | .n (or .nlstr): value as a string, joined on newlines. |
|
838 | .n (or .nlstr): value as a string, joined on newlines. | |
801 | .s (or .spstr): value as a string, joined on spaces. |
|
839 | .s (or .spstr): value as a string, joined on spaces. | |
802 |
|
840 | |||
803 | Any values which require transformations are computed only once and |
|
841 | Any values which require transformations are computed only once and | |
804 | cached.""" |
|
842 | cached.""" | |
805 |
|
843 | |||
806 | def get_list(self): |
|
844 | def get_list(self): | |
807 | return self |
|
845 | return self | |
808 |
|
846 | |||
809 | l = list = property(get_list) |
|
847 | l = list = property(get_list) | |
810 |
|
848 | |||
811 | def get_spstr(self): |
|
849 | def get_spstr(self): | |
812 | try: |
|
850 | try: | |
813 | return self.__spstr |
|
851 | return self.__spstr | |
814 | except AttributeError: |
|
852 | except AttributeError: | |
815 | self.__spstr = ' '.join(self) |
|
853 | self.__spstr = ' '.join(self) | |
816 | return self.__spstr |
|
854 | return self.__spstr | |
817 |
|
855 | |||
818 | s = spstr = property(get_spstr) |
|
856 | s = spstr = property(get_spstr) | |
819 |
|
857 | |||
820 | def get_nlstr(self): |
|
858 | def get_nlstr(self): | |
821 | try: |
|
859 | try: | |
822 | return self.__nlstr |
|
860 | return self.__nlstr | |
823 | except AttributeError: |
|
861 | except AttributeError: | |
824 | self.__nlstr = '\n'.join(self) |
|
862 | self.__nlstr = '\n'.join(self) | |
825 | return self.__nlstr |
|
863 | return self.__nlstr | |
826 |
|
864 | |||
827 | n = nlstr = property(get_nlstr) |
|
865 | n = nlstr = property(get_nlstr) | |
828 |
|
866 | |||
829 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
867 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): | |
830 | """Take multiple lines of input. |
|
868 | """Take multiple lines of input. | |
831 |
|
869 | |||
832 | A list with each line of input as a separate element is returned when a |
|
870 | A list with each line of input as a separate element is returned when a | |
833 | termination string is entered (defaults to a single '.'). Input can also |
|
871 | termination string is entered (defaults to a single '.'). Input can also | |
834 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
872 | terminate via EOF (^D in Unix, ^Z-RET in Windows). | |
835 |
|
873 | |||
836 | Lines of input which end in \\ are joined into single entries (and a |
|
874 | Lines of input which end in \\ are joined into single entries (and a | |
837 | secondary continuation prompt is issued as long as the user terminates |
|
875 | secondary continuation prompt is issued as long as the user terminates | |
838 | lines with \\). This allows entering very long strings which are still |
|
876 | lines with \\). This allows entering very long strings which are still | |
839 | meant to be treated as single entities. |
|
877 | meant to be treated as single entities. | |
840 | """ |
|
878 | """ | |
841 |
|
879 | |||
842 | try: |
|
880 | try: | |
843 | if header: |
|
881 | if header: | |
844 | header += '\n' |
|
882 | header += '\n' | |
845 | lines = [raw_input(header + ps1)] |
|
883 | lines = [raw_input(header + ps1)] | |
846 | except EOFError: |
|
884 | except EOFError: | |
847 | return [] |
|
885 | return [] | |
848 | terminate = [terminate_str] |
|
886 | terminate = [terminate_str] | |
849 | try: |
|
887 | try: | |
850 | while lines[-1:] != terminate: |
|
888 | while lines[-1:] != terminate: | |
851 | new_line = raw_input(ps1) |
|
889 | new_line = raw_input(ps1) | |
852 | while new_line.endswith('\\'): |
|
890 | while new_line.endswith('\\'): | |
853 | new_line = new_line[:-1] + raw_input(ps2) |
|
891 | new_line = new_line[:-1] + raw_input(ps2) | |
854 | lines.append(new_line) |
|
892 | lines.append(new_line) | |
855 |
|
893 | |||
856 | return lines[:-1] # don't return the termination command |
|
894 | return lines[:-1] # don't return the termination command | |
857 | except EOFError: |
|
895 | except EOFError: | |
858 |
|
896 | |||
859 | return lines |
|
897 | return lines | |
860 |
|
898 | |||
861 | #---------------------------------------------------------------------------- |
|
899 | #---------------------------------------------------------------------------- | |
862 | def raw_input_ext(prompt='', ps2='... '): |
|
900 | def raw_input_ext(prompt='', ps2='... '): | |
863 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
901 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" | |
864 |
|
902 | |||
865 | line = raw_input(prompt) |
|
903 | line = raw_input(prompt) | |
866 | while line.endswith('\\'): |
|
904 | while line.endswith('\\'): | |
867 | line = line[:-1] + raw_input(ps2) |
|
905 | line = line[:-1] + raw_input(ps2) | |
868 | return line |
|
906 | return line | |
869 |
|
907 | |||
870 | #---------------------------------------------------------------------------- |
|
908 | #---------------------------------------------------------------------------- | |
871 | def ask_yes_no(prompt,default=None): |
|
909 | def ask_yes_no(prompt,default=None): | |
872 | """Asks a question and returns an integer 1/0 (y/n) answer. |
|
910 | """Asks a question and returns an integer 1/0 (y/n) answer. | |
873 |
|
911 | |||
874 | If default is given (one of 'y','n'), it is used if the user input is |
|
912 | If default is given (one of 'y','n'), it is used if the user input is | |
875 | empty. Otherwise the question is repeated until an answer is given. |
|
913 | empty. Otherwise the question is repeated until an answer is given. | |
876 | If EOF occurs 20 times consecutively, the default answer is assumed, |
|
914 | If EOF occurs 20 times consecutively, the default answer is assumed, | |
877 | or if there is no default, an exception is raised to prevent infinite |
|
915 | or if there is no default, an exception is raised to prevent infinite | |
878 | loops. |
|
916 | loops. | |
879 |
|
917 | |||
880 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
918 | Valid answers are: y/yes/n/no (match is not case sensitive).""" | |
881 |
|
919 | |||
882 | answers = {'y':1,'n':0,'yes':1,'no':0} |
|
920 | answers = {'y':1,'n':0,'yes':1,'no':0} | |
883 | ans = None |
|
921 | ans = None | |
884 | eofs, max_eofs = 0, 20 |
|
922 | eofs, max_eofs = 0, 20 | |
885 | while ans not in answers.keys(): |
|
923 | while ans not in answers.keys(): | |
886 | try: |
|
924 | try: | |
887 | ans = raw_input(prompt+' ').lower() |
|
925 | ans = raw_input(prompt+' ').lower() | |
888 | if not ans: # response was an empty string |
|
926 | if not ans: # response was an empty string | |
889 | ans = default |
|
927 | ans = default | |
890 | eofs = 0 |
|
928 | eofs = 0 | |
891 | except (EOFError,KeyboardInterrupt): |
|
929 | except (EOFError,KeyboardInterrupt): | |
892 | eofs = eofs + 1 |
|
930 | eofs = eofs + 1 | |
893 | if eofs >= max_eofs: |
|
931 | if eofs >= max_eofs: | |
894 | if default in answers.keys(): |
|
932 | if default in answers.keys(): | |
895 | ans = default |
|
933 | ans = default | |
896 | else: |
|
934 | else: | |
897 | raise |
|
935 | raise | |
898 |
|
936 | |||
899 | return answers[ans] |
|
937 | return answers[ans] | |
900 |
|
938 | |||
901 | #---------------------------------------------------------------------------- |
|
939 | #---------------------------------------------------------------------------- | |
902 | def marquee(txt='',width=80,mark='*'): |
|
940 | def marquee(txt='',width=80,mark='*'): | |
903 | """Return the input string centered in a 'marquee'.""" |
|
941 | """Return the input string centered in a 'marquee'.""" | |
904 | if not txt: |
|
942 | if not txt: | |
905 | return (mark*width)[:width] |
|
943 | return (mark*width)[:width] | |
906 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
944 | nmark = (width-len(txt)-2)/len(mark)/2 | |
907 | if nmark < 0: nmark =0 |
|
945 | if nmark < 0: nmark =0 | |
908 | marks = mark*nmark |
|
946 | marks = mark*nmark | |
909 | return '%s %s %s' % (marks,txt,marks) |
|
947 | return '%s %s %s' % (marks,txt,marks) | |
910 |
|
948 | |||
911 | #---------------------------------------------------------------------------- |
|
949 | #---------------------------------------------------------------------------- | |
912 | class EvalDict: |
|
950 | class EvalDict: | |
913 | """ |
|
951 | """ | |
914 | Emulate a dict which evaluates its contents in the caller's frame. |
|
952 | Emulate a dict which evaluates its contents in the caller's frame. | |
915 |
|
953 | |||
916 | Usage: |
|
954 | Usage: | |
917 | >>>number = 19 |
|
955 | >>>number = 19 | |
918 | >>>text = "python" |
|
956 | >>>text = "python" | |
919 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
957 | >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() | |
920 | """ |
|
958 | """ | |
921 |
|
959 | |||
922 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
960 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a | |
923 | # modified (shorter) version of: |
|
961 | # modified (shorter) version of: | |
924 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
962 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by | |
925 | # Skip Montanaro (skip@pobox.com). |
|
963 | # Skip Montanaro (skip@pobox.com). | |
926 |
|
964 | |||
927 | def __getitem__(self, name): |
|
965 | def __getitem__(self, name): | |
928 | frame = sys._getframe(1) |
|
966 | frame = sys._getframe(1) | |
929 | return eval(name, frame.f_globals, frame.f_locals) |
|
967 | return eval(name, frame.f_globals, frame.f_locals) | |
930 |
|
968 | |||
931 | EvalString = EvalDict # for backwards compatibility |
|
969 | EvalString = EvalDict # for backwards compatibility | |
932 | #---------------------------------------------------------------------------- |
|
970 | #---------------------------------------------------------------------------- | |
933 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
971 | def qw(words,flat=0,sep=None,maxsplit=-1): | |
934 | """Similar to Perl's qw() operator, but with some more options. |
|
972 | """Similar to Perl's qw() operator, but with some more options. | |
935 |
|
973 | |||
936 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
974 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) | |
937 |
|
975 | |||
938 | words can also be a list itself, and with flat=1, the output will be |
|
976 | words can also be a list itself, and with flat=1, the output will be | |
939 | recursively flattened. Examples: |
|
977 | recursively flattened. Examples: | |
940 |
|
978 | |||
941 | >>> qw('1 2') |
|
979 | >>> qw('1 2') | |
942 | ['1', '2'] |
|
980 | ['1', '2'] | |
943 | >>> qw(['a b','1 2',['m n','p q']]) |
|
981 | >>> qw(['a b','1 2',['m n','p q']]) | |
944 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
982 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] | |
945 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
983 | >>> qw(['a b','1 2',['m n','p q']],flat=1) | |
946 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ |
|
984 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ | |
947 |
|
985 | |||
948 | if type(words) in StringTypes: |
|
986 | if type(words) in StringTypes: | |
949 | return [word.strip() for word in words.split(sep,maxsplit) |
|
987 | return [word.strip() for word in words.split(sep,maxsplit) | |
950 | if word and not word.isspace() ] |
|
988 | if word and not word.isspace() ] | |
951 | if flat: |
|
989 | if flat: | |
952 | return flatten(map(qw,words,[1]*len(words))) |
|
990 | return flatten(map(qw,words,[1]*len(words))) | |
953 | return map(qw,words) |
|
991 | return map(qw,words) | |
954 |
|
992 | |||
955 | #---------------------------------------------------------------------------- |
|
993 | #---------------------------------------------------------------------------- | |
956 | def qwflat(words,sep=None,maxsplit=-1): |
|
994 | def qwflat(words,sep=None,maxsplit=-1): | |
957 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
995 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" | |
958 | return qw(words,1,sep,maxsplit) |
|
996 | return qw(words,1,sep,maxsplit) | |
959 |
|
997 | |||
960 | #----------------------------------------------------------------------------- |
|
998 | #----------------------------------------------------------------------------- | |
961 | def list_strings(arg): |
|
999 | def list_strings(arg): | |
962 | """Always return a list of strings, given a string or list of strings |
|
1000 | """Always return a list of strings, given a string or list of strings | |
963 | as input.""" |
|
1001 | as input.""" | |
964 |
|
1002 | |||
965 | if type(arg) in StringTypes: return [arg] |
|
1003 | if type(arg) in StringTypes: return [arg] | |
966 | else: return arg |
|
1004 | else: return arg | |
967 |
|
1005 | |||
968 | #---------------------------------------------------------------------------- |
|
1006 | #---------------------------------------------------------------------------- | |
969 | def grep(pat,list,case=1): |
|
1007 | def grep(pat,list,case=1): | |
970 | """Simple minded grep-like function. |
|
1008 | """Simple minded grep-like function. | |
971 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1009 | grep(pat,list) returns occurrences of pat in list, None on failure. | |
972 |
|
1010 | |||
973 | It only does simple string matching, with no support for regexps. Use the |
|
1011 | It only does simple string matching, with no support for regexps. Use the | |
974 | option case=0 for case-insensitive matching.""" |
|
1012 | option case=0 for case-insensitive matching.""" | |
975 |
|
1013 | |||
976 | # This is pretty crude. At least it should implement copying only references |
|
1014 | # This is pretty crude. At least it should implement copying only references | |
977 | # to the original data in case it's big. Now it copies the data for output. |
|
1015 | # to the original data in case it's big. Now it copies the data for output. | |
978 | out=[] |
|
1016 | out=[] | |
979 | if case: |
|
1017 | if case: | |
980 | for term in list: |
|
1018 | for term in list: | |
981 | if term.find(pat)>-1: out.append(term) |
|
1019 | if term.find(pat)>-1: out.append(term) | |
982 | else: |
|
1020 | else: | |
983 | lpat=pat.lower() |
|
1021 | lpat=pat.lower() | |
984 | for term in list: |
|
1022 | for term in list: | |
985 | if term.lower().find(lpat)>-1: out.append(term) |
|
1023 | if term.lower().find(lpat)>-1: out.append(term) | |
986 |
|
1024 | |||
987 | if len(out): return out |
|
1025 | if len(out): return out | |
988 | else: return None |
|
1026 | else: return None | |
989 |
|
1027 | |||
990 | #---------------------------------------------------------------------------- |
|
1028 | #---------------------------------------------------------------------------- | |
991 | def dgrep(pat,*opts): |
|
1029 | def dgrep(pat,*opts): | |
992 | """Return grep() on dir()+dir(__builtins__). |
|
1030 | """Return grep() on dir()+dir(__builtins__). | |
993 |
|
1031 | |||
994 | A very common use of grep() when working interactively.""" |
|
1032 | A very common use of grep() when working interactively.""" | |
995 |
|
1033 | |||
996 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1034 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) | |
997 |
|
1035 | |||
998 | #---------------------------------------------------------------------------- |
|
1036 | #---------------------------------------------------------------------------- | |
999 | def idgrep(pat): |
|
1037 | def idgrep(pat): | |
1000 | """Case-insensitive dgrep()""" |
|
1038 | """Case-insensitive dgrep()""" | |
1001 |
|
1039 | |||
1002 | return dgrep(pat,0) |
|
1040 | return dgrep(pat,0) | |
1003 |
|
1041 | |||
1004 | #---------------------------------------------------------------------------- |
|
1042 | #---------------------------------------------------------------------------- | |
1005 | def igrep(pat,list): |
|
1043 | def igrep(pat,list): | |
1006 | """Synonym for case-insensitive grep.""" |
|
1044 | """Synonym for case-insensitive grep.""" | |
1007 |
|
1045 | |||
1008 | return grep(pat,list,case=0) |
|
1046 | return grep(pat,list,case=0) | |
1009 |
|
1047 | |||
1010 | #---------------------------------------------------------------------------- |
|
1048 | #---------------------------------------------------------------------------- | |
1011 | def indent(str,nspaces=4,ntabs=0): |
|
1049 | def indent(str,nspaces=4,ntabs=0): | |
1012 | """Indent a string a given number of spaces or tabstops. |
|
1050 | """Indent a string a given number of spaces or tabstops. | |
1013 |
|
1051 | |||
1014 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1052 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. | |
1015 | """ |
|
1053 | """ | |
1016 | if str is None: |
|
1054 | if str is None: | |
1017 | return |
|
1055 | return | |
1018 | ind = '\t'*ntabs+' '*nspaces |
|
1056 | ind = '\t'*ntabs+' '*nspaces | |
1019 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1057 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) | |
1020 | if outstr.endswith(os.linesep+ind): |
|
1058 | if outstr.endswith(os.linesep+ind): | |
1021 | return outstr[:-len(ind)] |
|
1059 | return outstr[:-len(ind)] | |
1022 | else: |
|
1060 | else: | |
1023 | return outstr |
|
1061 | return outstr | |
1024 |
|
1062 | |||
1025 | #----------------------------------------------------------------------------- |
|
1063 | #----------------------------------------------------------------------------- | |
1026 | def native_line_ends(filename,backup=1): |
|
1064 | def native_line_ends(filename,backup=1): | |
1027 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1065 | """Convert (in-place) a file to line-ends native to the current OS. | |
1028 |
|
1066 | |||
1029 | If the optional backup argument is given as false, no backup of the |
|
1067 | If the optional backup argument is given as false, no backup of the | |
1030 | original file is left. """ |
|
1068 | original file is left. """ | |
1031 |
|
1069 | |||
1032 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1070 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} | |
1033 |
|
1071 | |||
1034 | bak_filename = filename + backup_suffixes[os.name] |
|
1072 | bak_filename = filename + backup_suffixes[os.name] | |
1035 |
|
1073 | |||
1036 | original = open(filename).read() |
|
1074 | original = open(filename).read() | |
1037 | shutil.copy2(filename,bak_filename) |
|
1075 | shutil.copy2(filename,bak_filename) | |
1038 | try: |
|
1076 | try: | |
1039 | new = open(filename,'wb') |
|
1077 | new = open(filename,'wb') | |
1040 | new.write(os.linesep.join(original.splitlines())) |
|
1078 | new.write(os.linesep.join(original.splitlines())) | |
1041 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1079 | new.write(os.linesep) # ALWAYS put an eol at the end of the file | |
1042 | new.close() |
|
1080 | new.close() | |
1043 | except: |
|
1081 | except: | |
1044 | os.rename(bak_filename,filename) |
|
1082 | os.rename(bak_filename,filename) | |
1045 | if not backup: |
|
1083 | if not backup: | |
1046 | try: |
|
1084 | try: | |
1047 | os.remove(bak_filename) |
|
1085 | os.remove(bak_filename) | |
1048 | except: |
|
1086 | except: | |
1049 | pass |
|
1087 | pass | |
1050 |
|
1088 | |||
1051 | #---------------------------------------------------------------------------- |
|
1089 | #---------------------------------------------------------------------------- | |
1052 | def get_pager_cmd(pager_cmd = None): |
|
1090 | def get_pager_cmd(pager_cmd = None): | |
1053 | """Return a pager command. |
|
1091 | """Return a pager command. | |
1054 |
|
1092 | |||
1055 | Makes some attempts at finding an OS-correct one.""" |
|
1093 | Makes some attempts at finding an OS-correct one.""" | |
1056 |
|
1094 | |||
1057 | if os.name == 'posix': |
|
1095 | if os.name == 'posix': | |
1058 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1096 | default_pager_cmd = 'less -r' # -r for color control sequences | |
1059 | elif os.name in ['nt','dos']: |
|
1097 | elif os.name in ['nt','dos']: | |
1060 | default_pager_cmd = 'type' |
|
1098 | default_pager_cmd = 'type' | |
1061 |
|
1099 | |||
1062 | if pager_cmd is None: |
|
1100 | if pager_cmd is None: | |
1063 | try: |
|
1101 | try: | |
1064 | pager_cmd = os.environ['PAGER'] |
|
1102 | pager_cmd = os.environ['PAGER'] | |
1065 | except: |
|
1103 | except: | |
1066 | pager_cmd = default_pager_cmd |
|
1104 | pager_cmd = default_pager_cmd | |
1067 | return pager_cmd |
|
1105 | return pager_cmd | |
1068 |
|
1106 | |||
1069 | #----------------------------------------------------------------------------- |
|
1107 | #----------------------------------------------------------------------------- | |
1070 | def get_pager_start(pager,start): |
|
1108 | def get_pager_start(pager,start): | |
1071 | """Return the string for paging files with an offset. |
|
1109 | """Return the string for paging files with an offset. | |
1072 |
|
1110 | |||
1073 | This is the '+N' argument which less and more (under Unix) accept. |
|
1111 | This is the '+N' argument which less and more (under Unix) accept. | |
1074 | """ |
|
1112 | """ | |
1075 |
|
1113 | |||
1076 | if pager in ['less','more']: |
|
1114 | if pager in ['less','more']: | |
1077 | if start: |
|
1115 | if start: | |
1078 | start_string = '+' + str(start) |
|
1116 | start_string = '+' + str(start) | |
1079 | else: |
|
1117 | else: | |
1080 | start_string = '' |
|
1118 | start_string = '' | |
1081 | else: |
|
1119 | else: | |
1082 | start_string = '' |
|
1120 | start_string = '' | |
1083 | return start_string |
|
1121 | return start_string | |
1084 |
|
1122 | |||
1085 | #---------------------------------------------------------------------------- |
|
1123 | #---------------------------------------------------------------------------- | |
1086 | def page_dumb(strng,start=0,screen_lines=25): |
|
1124 | def page_dumb(strng,start=0,screen_lines=25): | |
1087 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1125 | """Very dumb 'pager' in Python, for when nothing else works. | |
1088 |
|
1126 | |||
1089 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1127 | Only moves forward, same interface as page(), except for pager_cmd and | |
1090 | mode.""" |
|
1128 | mode.""" | |
1091 |
|
1129 | |||
1092 | out_ln = strng.splitlines()[start:] |
|
1130 | out_ln = strng.splitlines()[start:] | |
1093 | screens = chop(out_ln,screen_lines-1) |
|
1131 | screens = chop(out_ln,screen_lines-1) | |
1094 | if len(screens) == 1: |
|
1132 | if len(screens) == 1: | |
1095 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1133 | print >>Term.cout, os.linesep.join(screens[0]) | |
1096 | else: |
|
1134 | else: | |
1097 | for scr in screens[0:-1]: |
|
1135 | for scr in screens[0:-1]: | |
1098 | print >>Term.cout, os.linesep.join(scr) |
|
1136 | print >>Term.cout, os.linesep.join(scr) | |
1099 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1137 | ans = raw_input('---Return to continue, q to quit--- ') | |
1100 | if ans.lower().startswith('q'): |
|
1138 | if ans.lower().startswith('q'): | |
1101 | return |
|
1139 | return | |
1102 | print >>Term.cout, os.linesep.join(screens[-1]) |
|
1140 | print >>Term.cout, os.linesep.join(screens[-1]) | |
1103 |
|
1141 | |||
1104 | #---------------------------------------------------------------------------- |
|
1142 | #---------------------------------------------------------------------------- | |
1105 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1143 | def page(strng,start=0,screen_lines=0,pager_cmd = None): | |
1106 | """Print a string, piping through a pager after a certain length. |
|
1144 | """Print a string, piping through a pager after a certain length. | |
1107 |
|
1145 | |||
1108 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1146 | The screen_lines parameter specifies the number of *usable* lines of your | |
1109 | terminal screen (total lines minus lines you need to reserve to show other |
|
1147 | terminal screen (total lines minus lines you need to reserve to show other | |
1110 | information). |
|
1148 | information). | |
1111 |
|
1149 | |||
1112 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1150 | If you set screen_lines to a number <=0, page() will try to auto-determine | |
1113 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1151 | your screen size and will only use up to (screen_size+screen_lines) for | |
1114 | printing, paging after that. That is, if you want auto-detection but need |
|
1152 | printing, paging after that. That is, if you want auto-detection but need | |
1115 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1153 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for | |
1116 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1154 | auto-detection without any lines reserved simply use screen_lines = 0. | |
1117 |
|
1155 | |||
1118 | If a string won't fit in the allowed lines, it is sent through the |
|
1156 | If a string won't fit in the allowed lines, it is sent through the | |
1119 | specified pager command. If none given, look for PAGER in the environment, |
|
1157 | specified pager command. If none given, look for PAGER in the environment, | |
1120 | and ultimately default to less. |
|
1158 | and ultimately default to less. | |
1121 |
|
1159 | |||
1122 | If no system pager works, the string is sent through a 'dumb pager' |
|
1160 | If no system pager works, the string is sent through a 'dumb pager' | |
1123 | written in python, very simplistic. |
|
1161 | written in python, very simplistic. | |
1124 | """ |
|
1162 | """ | |
1125 |
|
1163 | |||
1126 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1164 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs | |
1127 | TERM = os.environ.get('TERM','dumb') |
|
1165 | TERM = os.environ.get('TERM','dumb') | |
1128 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1166 | if TERM in ['dumb','emacs'] and os.name != 'nt': | |
1129 | print strng |
|
1167 | print strng | |
1130 | return |
|
1168 | return | |
1131 | # chop off the topmost part of the string we don't want to see |
|
1169 | # chop off the topmost part of the string we don't want to see | |
1132 | str_lines = strng.split(os.linesep)[start:] |
|
1170 | str_lines = strng.split(os.linesep)[start:] | |
1133 | str_toprint = os.linesep.join(str_lines) |
|
1171 | str_toprint = os.linesep.join(str_lines) | |
1134 | num_newlines = len(str_lines) |
|
1172 | num_newlines = len(str_lines) | |
1135 | len_str = len(str_toprint) |
|
1173 | len_str = len(str_toprint) | |
1136 |
|
1174 | |||
1137 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1175 | # Dumb heuristics to guesstimate number of on-screen lines the string | |
1138 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1176 | # takes. Very basic, but good enough for docstrings in reasonable | |
1139 | # terminals. If someone later feels like refining it, it's not hard. |
|
1177 | # terminals. If someone later feels like refining it, it's not hard. | |
1140 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1178 | numlines = max(num_newlines,int(len_str/80)+1) | |
1141 |
|
1179 | |||
1142 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1180 | screen_lines_def = 25 # default value if we can't auto-determine | |
1143 |
|
1181 | |||
1144 | # auto-determine screen size |
|
1182 | # auto-determine screen size | |
1145 | if screen_lines <= 0: |
|
1183 | if screen_lines <= 0: | |
1146 | if TERM=='xterm': |
|
1184 | if TERM=='xterm': | |
1147 | try: |
|
1185 | try: | |
1148 | import curses |
|
1186 | import curses | |
1149 | if hasattr(curses,'initscr'): |
|
1187 | if hasattr(curses,'initscr'): | |
1150 | use_curses = 1 |
|
1188 | use_curses = 1 | |
1151 | else: |
|
1189 | else: | |
1152 | use_curses = 0 |
|
1190 | use_curses = 0 | |
1153 | except ImportError: |
|
1191 | except ImportError: | |
1154 | use_curses = 0 |
|
1192 | use_curses = 0 | |
1155 | else: |
|
1193 | else: | |
1156 | # curses causes problems on many terminals other than xterm. |
|
1194 | # curses causes problems on many terminals other than xterm. | |
1157 | use_curses = 0 |
|
1195 | use_curses = 0 | |
1158 | if use_curses: |
|
1196 | if use_curses: | |
1159 | scr = curses.initscr() |
|
1197 | scr = curses.initscr() | |
1160 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1198 | screen_lines_real,screen_cols = scr.getmaxyx() | |
1161 | curses.endwin() |
|
1199 | curses.endwin() | |
1162 | screen_lines += screen_lines_real |
|
1200 | screen_lines += screen_lines_real | |
1163 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1201 | #print '***Screen size:',screen_lines_real,'lines x',\ | |
1164 | #screen_cols,'columns.' # dbg |
|
1202 | #screen_cols,'columns.' # dbg | |
1165 | else: |
|
1203 | else: | |
1166 | screen_lines += screen_lines_def |
|
1204 | screen_lines += screen_lines_def | |
1167 |
|
1205 | |||
1168 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1206 | #print 'numlines',numlines,'screenlines',screen_lines # dbg | |
1169 | if numlines <= screen_lines : |
|
1207 | if numlines <= screen_lines : | |
1170 | #print '*** normal print' # dbg |
|
1208 | #print '*** normal print' # dbg | |
1171 | print >>Term.cout, str_toprint |
|
1209 | print >>Term.cout, str_toprint | |
1172 | else: |
|
1210 | else: | |
1173 | # Try to open pager and default to internal one if that fails. |
|
1211 | # Try to open pager and default to internal one if that fails. | |
1174 | # All failure modes are tagged as 'retval=1', to match the return |
|
1212 | # All failure modes are tagged as 'retval=1', to match the return | |
1175 | # value of a failed system command. If any intermediate attempt |
|
1213 | # value of a failed system command. If any intermediate attempt | |
1176 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1214 | # sets retval to 1, at the end we resort to our own page_dumb() pager. | |
1177 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1215 | pager_cmd = get_pager_cmd(pager_cmd) | |
1178 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1216 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1179 | if os.name == 'nt': |
|
1217 | if os.name == 'nt': | |
1180 | if pager_cmd.startswith('type'): |
|
1218 | if pager_cmd.startswith('type'): | |
1181 | # The default WinXP 'type' command is failing on complex strings. |
|
1219 | # The default WinXP 'type' command is failing on complex strings. | |
1182 | retval = 1 |
|
1220 | retval = 1 | |
1183 | else: |
|
1221 | else: | |
1184 | tmpname = tempfile.mktemp('.txt') |
|
1222 | tmpname = tempfile.mktemp('.txt') | |
1185 | tmpfile = file(tmpname,'wt') |
|
1223 | tmpfile = file(tmpname,'wt') | |
1186 | tmpfile.write(strng) |
|
1224 | tmpfile.write(strng) | |
1187 | tmpfile.close() |
|
1225 | tmpfile.close() | |
1188 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1226 | cmd = "%s < %s" % (pager_cmd,tmpname) | |
1189 | if os.system(cmd): |
|
1227 | if os.system(cmd): | |
1190 | retval = 1 |
|
1228 | retval = 1 | |
1191 | else: |
|
1229 | else: | |
1192 | retval = None |
|
1230 | retval = None | |
1193 | os.remove(tmpname) |
|
1231 | os.remove(tmpname) | |
1194 | else: |
|
1232 | else: | |
1195 | try: |
|
1233 | try: | |
1196 | retval = None |
|
1234 | retval = None | |
1197 | # if I use popen4, things hang. No idea why. |
|
1235 | # if I use popen4, things hang. No idea why. | |
1198 | #pager,shell_out = os.popen4(pager_cmd) |
|
1236 | #pager,shell_out = os.popen4(pager_cmd) | |
1199 | pager = os.popen(pager_cmd,'w') |
|
1237 | pager = os.popen(pager_cmd,'w') | |
1200 | pager.write(strng) |
|
1238 | pager.write(strng) | |
1201 | pager.close() |
|
1239 | pager.close() | |
1202 | retval = pager.close() # success returns None |
|
1240 | retval = pager.close() # success returns None | |
1203 | except IOError,msg: # broken pipe when user quits |
|
1241 | except IOError,msg: # broken pipe when user quits | |
1204 | if msg.args == (32,'Broken pipe'): |
|
1242 | if msg.args == (32,'Broken pipe'): | |
1205 | retval = None |
|
1243 | retval = None | |
1206 | else: |
|
1244 | else: | |
1207 | retval = 1 |
|
1245 | retval = 1 | |
1208 | except OSError: |
|
1246 | except OSError: | |
1209 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1247 | # Other strange problems, sometimes seen in Win2k/cygwin | |
1210 | retval = 1 |
|
1248 | retval = 1 | |
1211 | if retval is not None: |
|
1249 | if retval is not None: | |
1212 | page_dumb(strng,screen_lines=screen_lines) |
|
1250 | page_dumb(strng,screen_lines=screen_lines) | |
1213 |
|
1251 | |||
1214 | #---------------------------------------------------------------------------- |
|
1252 | #---------------------------------------------------------------------------- | |
1215 | def page_file(fname,start = 0, pager_cmd = None): |
|
1253 | def page_file(fname,start = 0, pager_cmd = None): | |
1216 | """Page a file, using an optional pager command and starting line. |
|
1254 | """Page a file, using an optional pager command and starting line. | |
1217 | """ |
|
1255 | """ | |
1218 |
|
1256 | |||
1219 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1257 | pager_cmd = get_pager_cmd(pager_cmd) | |
1220 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1258 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1221 |
|
1259 | |||
1222 | try: |
|
1260 | try: | |
1223 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1261 | if os.environ['TERM'] in ['emacs','dumb']: | |
1224 | raise EnvironmentError |
|
1262 | raise EnvironmentError | |
1225 | xsys(pager_cmd + ' ' + fname) |
|
1263 | xsys(pager_cmd + ' ' + fname) | |
1226 | except: |
|
1264 | except: | |
1227 | try: |
|
1265 | try: | |
1228 | if start > 0: |
|
1266 | if start > 0: | |
1229 | start -= 1 |
|
1267 | start -= 1 | |
1230 | page(open(fname).read(),start) |
|
1268 | page(open(fname).read(),start) | |
1231 | except: |
|
1269 | except: | |
1232 | print 'Unable to show file',`fname` |
|
1270 | print 'Unable to show file',`fname` | |
1233 |
|
1271 | |||
1234 | #---------------------------------------------------------------------------- |
|
1272 | #---------------------------------------------------------------------------- | |
1235 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1273 | def snip_print(str,width = 75,print_full = 0,header = ''): | |
1236 | """Print a string snipping the midsection to fit in width. |
|
1274 | """Print a string snipping the midsection to fit in width. | |
1237 |
|
1275 | |||
1238 | print_full: mode control: |
|
1276 | print_full: mode control: | |
1239 | - 0: only snip long strings |
|
1277 | - 0: only snip long strings | |
1240 | - 1: send to page() directly. |
|
1278 | - 1: send to page() directly. | |
1241 | - 2: snip long strings and ask for full length viewing with page() |
|
1279 | - 2: snip long strings and ask for full length viewing with page() | |
1242 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1280 | Return 1 if snipping was necessary, 0 otherwise.""" | |
1243 |
|
1281 | |||
1244 | if print_full == 1: |
|
1282 | if print_full == 1: | |
1245 | page(header+str) |
|
1283 | page(header+str) | |
1246 | return 0 |
|
1284 | return 0 | |
1247 |
|
1285 | |||
1248 | print header, |
|
1286 | print header, | |
1249 | if len(str) < width: |
|
1287 | if len(str) < width: | |
1250 | print str |
|
1288 | print str | |
1251 | snip = 0 |
|
1289 | snip = 0 | |
1252 | else: |
|
1290 | else: | |
1253 | whalf = int((width -5)/2) |
|
1291 | whalf = int((width -5)/2) | |
1254 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1292 | print str[:whalf] + ' <...> ' + str[-whalf:] | |
1255 | snip = 1 |
|
1293 | snip = 1 | |
1256 | if snip and print_full == 2: |
|
1294 | if snip and print_full == 2: | |
1257 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1295 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': | |
1258 | page(str) |
|
1296 | page(str) | |
1259 | return snip |
|
1297 | return snip | |
1260 |
|
1298 | |||
1261 | #**************************************************************************** |
|
1299 | #**************************************************************************** | |
1262 | # lists, dicts and structures |
|
1300 | # lists, dicts and structures | |
1263 |
|
1301 | |||
1264 | def belong(candidates,checklist): |
|
1302 | def belong(candidates,checklist): | |
1265 | """Check whether a list of items appear in a given list of options. |
|
1303 | """Check whether a list of items appear in a given list of options. | |
1266 |
|
1304 | |||
1267 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1305 | Returns a list of 1 and 0, one for each candidate given.""" | |
1268 |
|
1306 | |||
1269 | return [x in checklist for x in candidates] |
|
1307 | return [x in checklist for x in candidates] | |
1270 |
|
1308 | |||
1271 | #---------------------------------------------------------------------------- |
|
1309 | #---------------------------------------------------------------------------- | |
1272 | def uniq_stable(elems): |
|
1310 | def uniq_stable(elems): | |
1273 | """uniq_stable(elems) -> list |
|
1311 | """uniq_stable(elems) -> list | |
1274 |
|
1312 | |||
1275 | Return from an iterable, a list of all the unique elements in the input, |
|
1313 | Return from an iterable, a list of all the unique elements in the input, | |
1276 | but maintaining the order in which they first appear. |
|
1314 | but maintaining the order in which they first appear. | |
1277 |
|
1315 | |||
1278 | A naive solution to this problem which just makes a dictionary with the |
|
1316 | A naive solution to this problem which just makes a dictionary with the | |
1279 | elements as keys fails to respect the stability condition, since |
|
1317 | elements as keys fails to respect the stability condition, since | |
1280 | dictionaries are unsorted by nature. |
|
1318 | dictionaries are unsorted by nature. | |
1281 |
|
1319 | |||
1282 | Note: All elements in the input must be valid dictionary keys for this |
|
1320 | Note: All elements in the input must be valid dictionary keys for this | |
1283 | routine to work, as it internally uses a dictionary for efficiency |
|
1321 | routine to work, as it internally uses a dictionary for efficiency | |
1284 | reasons.""" |
|
1322 | reasons.""" | |
1285 |
|
1323 | |||
1286 | unique = [] |
|
1324 | unique = [] | |
1287 | unique_dict = {} |
|
1325 | unique_dict = {} | |
1288 | for nn in elems: |
|
1326 | for nn in elems: | |
1289 | if nn not in unique_dict: |
|
1327 | if nn not in unique_dict: | |
1290 | unique.append(nn) |
|
1328 | unique.append(nn) | |
1291 | unique_dict[nn] = None |
|
1329 | unique_dict[nn] = None | |
1292 | return unique |
|
1330 | return unique | |
1293 |
|
1331 | |||
1294 | #---------------------------------------------------------------------------- |
|
1332 | #---------------------------------------------------------------------------- | |
1295 | class NLprinter: |
|
1333 | class NLprinter: | |
1296 | """Print an arbitrarily nested list, indicating index numbers. |
|
1334 | """Print an arbitrarily nested list, indicating index numbers. | |
1297 |
|
1335 | |||
1298 | An instance of this class called nlprint is available and callable as a |
|
1336 | An instance of this class called nlprint is available and callable as a | |
1299 | function. |
|
1337 | function. | |
1300 |
|
1338 | |||
1301 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1339 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' | |
1302 | and using 'sep' to separate the index from the value. """ |
|
1340 | and using 'sep' to separate the index from the value. """ | |
1303 |
|
1341 | |||
1304 | def __init__(self): |
|
1342 | def __init__(self): | |
1305 | self.depth = 0 |
|
1343 | self.depth = 0 | |
1306 |
|
1344 | |||
1307 | def __call__(self,lst,pos='',**kw): |
|
1345 | def __call__(self,lst,pos='',**kw): | |
1308 | """Prints the nested list numbering levels.""" |
|
1346 | """Prints the nested list numbering levels.""" | |
1309 | kw.setdefault('indent',' ') |
|
1347 | kw.setdefault('indent',' ') | |
1310 | kw.setdefault('sep',': ') |
|
1348 | kw.setdefault('sep',': ') | |
1311 | kw.setdefault('start',0) |
|
1349 | kw.setdefault('start',0) | |
1312 | kw.setdefault('stop',len(lst)) |
|
1350 | kw.setdefault('stop',len(lst)) | |
1313 | # we need to remove start and stop from kw so they don't propagate |
|
1351 | # we need to remove start and stop from kw so they don't propagate | |
1314 | # into a recursive call for a nested list. |
|
1352 | # into a recursive call for a nested list. | |
1315 | start = kw['start']; del kw['start'] |
|
1353 | start = kw['start']; del kw['start'] | |
1316 | stop = kw['stop']; del kw['stop'] |
|
1354 | stop = kw['stop']; del kw['stop'] | |
1317 | if self.depth == 0 and 'header' in kw.keys(): |
|
1355 | if self.depth == 0 and 'header' in kw.keys(): | |
1318 | print kw['header'] |
|
1356 | print kw['header'] | |
1319 |
|
1357 | |||
1320 | for idx in range(start,stop): |
|
1358 | for idx in range(start,stop): | |
1321 | elem = lst[idx] |
|
1359 | elem = lst[idx] | |
1322 | if type(elem)==type([]): |
|
1360 | if type(elem)==type([]): | |
1323 | self.depth += 1 |
|
1361 | self.depth += 1 | |
1324 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1362 | self.__call__(elem,itpl('$pos$idx,'),**kw) | |
1325 | self.depth -= 1 |
|
1363 | self.depth -= 1 | |
1326 | else: |
|
1364 | else: | |
1327 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1365 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') | |
1328 |
|
1366 | |||
1329 | nlprint = NLprinter() |
|
1367 | nlprint = NLprinter() | |
1330 | #---------------------------------------------------------------------------- |
|
1368 | #---------------------------------------------------------------------------- | |
1331 | def all_belong(candidates,checklist): |
|
1369 | def all_belong(candidates,checklist): | |
1332 | """Check whether a list of items ALL appear in a given list of options. |
|
1370 | """Check whether a list of items ALL appear in a given list of options. | |
1333 |
|
1371 | |||
1334 | Returns a single 1 or 0 value.""" |
|
1372 | Returns a single 1 or 0 value.""" | |
1335 |
|
1373 | |||
1336 | return 1-(0 in [x in checklist for x in candidates]) |
|
1374 | return 1-(0 in [x in checklist for x in candidates]) | |
1337 |
|
1375 | |||
1338 | #---------------------------------------------------------------------------- |
|
1376 | #---------------------------------------------------------------------------- | |
1339 | def sort_compare(lst1,lst2,inplace = 1): |
|
1377 | def sort_compare(lst1,lst2,inplace = 1): | |
1340 | """Sort and compare two lists. |
|
1378 | """Sort and compare two lists. | |
1341 |
|
1379 | |||
1342 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1380 | By default it does it in place, thus modifying the lists. Use inplace = 0 | |
1343 | to avoid that (at the cost of temporary copy creation).""" |
|
1381 | to avoid that (at the cost of temporary copy creation).""" | |
1344 | if not inplace: |
|
1382 | if not inplace: | |
1345 | lst1 = lst1[:] |
|
1383 | lst1 = lst1[:] | |
1346 | lst2 = lst2[:] |
|
1384 | lst2 = lst2[:] | |
1347 | lst1.sort(); lst2.sort() |
|
1385 | lst1.sort(); lst2.sort() | |
1348 | return lst1 == lst2 |
|
1386 | return lst1 == lst2 | |
1349 |
|
1387 | |||
1350 | #---------------------------------------------------------------------------- |
|
1388 | #---------------------------------------------------------------------------- | |
1351 | def mkdict(**kwargs): |
|
1389 | def mkdict(**kwargs): | |
1352 | """Return a dict from a keyword list. |
|
1390 | """Return a dict from a keyword list. | |
1353 |
|
1391 | |||
1354 | It's just syntactic sugar for making ditcionary creation more convenient: |
|
1392 | It's just syntactic sugar for making ditcionary creation more convenient: | |
1355 | # the standard way |
|
1393 | # the standard way | |
1356 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } |
|
1394 | >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 } | |
1357 | # a cleaner way |
|
1395 | # a cleaner way | |
1358 | >>>data = dict(red=1, green=2, blue=3) |
|
1396 | >>>data = dict(red=1, green=2, blue=3) | |
1359 |
|
1397 | |||
1360 | If you need more than this, look at the Struct() class.""" |
|
1398 | If you need more than this, look at the Struct() class.""" | |
1361 |
|
1399 | |||
1362 | return kwargs |
|
1400 | return kwargs | |
1363 |
|
1401 | |||
1364 | #---------------------------------------------------------------------------- |
|
1402 | #---------------------------------------------------------------------------- | |
1365 | def list2dict(lst): |
|
1403 | def list2dict(lst): | |
1366 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1404 | """Takes a list of (key,value) pairs and turns it into a dict.""" | |
1367 |
|
1405 | |||
1368 | dic = {} |
|
1406 | dic = {} | |
1369 | for k,v in lst: dic[k] = v |
|
1407 | for k,v in lst: dic[k] = v | |
1370 | return dic |
|
1408 | return dic | |
1371 |
|
1409 | |||
1372 | #---------------------------------------------------------------------------- |
|
1410 | #---------------------------------------------------------------------------- | |
1373 | def list2dict2(lst,default=''): |
|
1411 | def list2dict2(lst,default=''): | |
1374 | """Takes a list and turns it into a dict. |
|
1412 | """Takes a list and turns it into a dict. | |
1375 | Much slower than list2dict, but more versatile. This version can take |
|
1413 | Much slower than list2dict, but more versatile. This version can take | |
1376 | lists with sublists of arbitrary length (including sclars).""" |
|
1414 | lists with sublists of arbitrary length (including sclars).""" | |
1377 |
|
1415 | |||
1378 | dic = {} |
|
1416 | dic = {} | |
1379 | for elem in lst: |
|
1417 | for elem in lst: | |
1380 | if type(elem) in (types.ListType,types.TupleType): |
|
1418 | if type(elem) in (types.ListType,types.TupleType): | |
1381 | size = len(elem) |
|
1419 | size = len(elem) | |
1382 | if size == 0: |
|
1420 | if size == 0: | |
1383 | pass |
|
1421 | pass | |
1384 | elif size == 1: |
|
1422 | elif size == 1: | |
1385 | dic[elem] = default |
|
1423 | dic[elem] = default | |
1386 | else: |
|
1424 | else: | |
1387 | k,v = elem[0], elem[1:] |
|
1425 | k,v = elem[0], elem[1:] | |
1388 | if len(v) == 1: v = v[0] |
|
1426 | if len(v) == 1: v = v[0] | |
1389 | dic[k] = v |
|
1427 | dic[k] = v | |
1390 | else: |
|
1428 | else: | |
1391 | dic[elem] = default |
|
1429 | dic[elem] = default | |
1392 | return dic |
|
1430 | return dic | |
1393 |
|
1431 | |||
1394 | #---------------------------------------------------------------------------- |
|
1432 | #---------------------------------------------------------------------------- | |
1395 | def flatten(seq): |
|
1433 | def flatten(seq): | |
1396 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1434 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" | |
1397 |
|
1435 | |||
1398 | # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in). |
|
1436 | # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in). | |
1399 |
|
1437 | |||
1400 | # if the x=0 isn't made, a *global* variable x is left over after calling |
|
1438 | # if the x=0 isn't made, a *global* variable x is left over after calling | |
1401 | # this function, with the value of the last element in the return |
|
1439 | # this function, with the value of the last element in the return | |
1402 | # list. This does seem like a bug big time to me. |
|
1440 | # list. This does seem like a bug big time to me. | |
1403 |
|
1441 | |||
1404 | # the problem is fixed with the x=0, which seems to force the creation of |
|
1442 | # the problem is fixed with the x=0, which seems to force the creation of | |
1405 | # a local name |
|
1443 | # a local name | |
1406 |
|
1444 | |||
1407 | x = 0 |
|
1445 | x = 0 | |
1408 | return [x for subseq in seq for x in subseq] |
|
1446 | return [x for subseq in seq for x in subseq] | |
1409 |
|
1447 | |||
1410 | #---------------------------------------------------------------------------- |
|
1448 | #---------------------------------------------------------------------------- | |
1411 | def get_slice(seq,start=0,stop=None,step=1): |
|
1449 | def get_slice(seq,start=0,stop=None,step=1): | |
1412 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1450 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" | |
1413 | if stop == None: |
|
1451 | if stop == None: | |
1414 | stop = len(seq) |
|
1452 | stop = len(seq) | |
1415 | item = lambda i: seq[i] |
|
1453 | item = lambda i: seq[i] | |
1416 | return map(item,xrange(start,stop,step)) |
|
1454 | return map(item,xrange(start,stop,step)) | |
1417 |
|
1455 | |||
1418 | #---------------------------------------------------------------------------- |
|
1456 | #---------------------------------------------------------------------------- | |
1419 | def chop(seq,size): |
|
1457 | def chop(seq,size): | |
1420 | """Chop a sequence into chunks of the given size.""" |
|
1458 | """Chop a sequence into chunks of the given size.""" | |
1421 | chunk = lambda i: seq[i:i+size] |
|
1459 | chunk = lambda i: seq[i:i+size] | |
1422 | return map(chunk,xrange(0,len(seq),size)) |
|
1460 | return map(chunk,xrange(0,len(seq),size)) | |
1423 |
|
1461 | |||
1424 | #---------------------------------------------------------------------------- |
|
1462 | #---------------------------------------------------------------------------- | |
1425 | def with(object, **args): |
|
1463 | def with(object, **args): | |
1426 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1464 | """Set multiple attributes for an object, similar to Pascal's with. | |
1427 |
|
1465 | |||
1428 | Example: |
|
1466 | Example: | |
1429 | with(jim, |
|
1467 | with(jim, | |
1430 | born = 1960, |
|
1468 | born = 1960, | |
1431 | haircolour = 'Brown', |
|
1469 | haircolour = 'Brown', | |
1432 | eyecolour = 'Green') |
|
1470 | eyecolour = 'Green') | |
1433 |
|
1471 | |||
1434 | Credit: Greg Ewing, in |
|
1472 | Credit: Greg Ewing, in | |
1435 | http://mail.python.org/pipermail/python-list/2001-May/040703.html""" |
|
1473 | http://mail.python.org/pipermail/python-list/2001-May/040703.html""" | |
1436 |
|
1474 | |||
1437 | object.__dict__.update(args) |
|
1475 | object.__dict__.update(args) | |
1438 |
|
1476 | |||
1439 | #---------------------------------------------------------------------------- |
|
1477 | #---------------------------------------------------------------------------- | |
1440 | def setattr_list(obj,alist,nspace = None): |
|
1478 | def setattr_list(obj,alist,nspace = None): | |
1441 | """Set a list of attributes for an object taken from a namespace. |
|
1479 | """Set a list of attributes for an object taken from a namespace. | |
1442 |
|
1480 | |||
1443 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1481 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in | |
1444 | alist with their values taken from nspace, which must be a dict (something |
|
1482 | alist with their values taken from nspace, which must be a dict (something | |
1445 | like locals() will often do) If nspace isn't given, locals() of the |
|
1483 | like locals() will often do) If nspace isn't given, locals() of the | |
1446 | *caller* is used, so in most cases you can omit it. |
|
1484 | *caller* is used, so in most cases you can omit it. | |
1447 |
|
1485 | |||
1448 | Note that alist can be given as a string, which will be automatically |
|
1486 | Note that alist can be given as a string, which will be automatically | |
1449 | split into a list on whitespace. If given as a list, it must be a list of |
|
1487 | split into a list on whitespace. If given as a list, it must be a list of | |
1450 | *strings* (the variable names themselves), not of variables.""" |
|
1488 | *strings* (the variable names themselves), not of variables.""" | |
1451 |
|
1489 | |||
1452 | # this grabs the local variables from the *previous* call frame -- that is |
|
1490 | # this grabs the local variables from the *previous* call frame -- that is | |
1453 | # the locals from the function that called setattr_list(). |
|
1491 | # the locals from the function that called setattr_list(). | |
1454 | # - snipped from weave.inline() |
|
1492 | # - snipped from weave.inline() | |
1455 | if nspace is None: |
|
1493 | if nspace is None: | |
1456 | call_frame = sys._getframe().f_back |
|
1494 | call_frame = sys._getframe().f_back | |
1457 | nspace = call_frame.f_locals |
|
1495 | nspace = call_frame.f_locals | |
1458 |
|
1496 | |||
1459 | if type(alist) in StringTypes: |
|
1497 | if type(alist) in StringTypes: | |
1460 | alist = alist.split() |
|
1498 | alist = alist.split() | |
1461 | for attr in alist: |
|
1499 | for attr in alist: | |
1462 | val = eval(attr,nspace) |
|
1500 | val = eval(attr,nspace) | |
1463 | setattr(obj,attr,val) |
|
1501 | setattr(obj,attr,val) | |
1464 |
|
1502 | |||
1465 | #---------------------------------------------------------------------------- |
|
1503 | #---------------------------------------------------------------------------- | |
1466 | def getattr_list(obj,alist,*args): |
|
1504 | def getattr_list(obj,alist,*args): | |
1467 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1505 | """getattr_list(obj,alist[, default]) -> attribute list. | |
1468 |
|
1506 | |||
1469 | Get a list of named attributes for an object. When a default argument is |
|
1507 | Get a list of named attributes for an object. When a default argument is | |
1470 | given, it is returned when the attribute doesn't exist; without it, an |
|
1508 | given, it is returned when the attribute doesn't exist; without it, an | |
1471 | exception is raised in that case. |
|
1509 | exception is raised in that case. | |
1472 |
|
1510 | |||
1473 | Note that alist can be given as a string, which will be automatically |
|
1511 | Note that alist can be given as a string, which will be automatically | |
1474 | split into a list on whitespace. If given as a list, it must be a list of |
|
1512 | split into a list on whitespace. If given as a list, it must be a list of | |
1475 | *strings* (the variable names themselves), not of variables.""" |
|
1513 | *strings* (the variable names themselves), not of variables.""" | |
1476 |
|
1514 | |||
1477 | if type(alist) in StringTypes: |
|
1515 | if type(alist) in StringTypes: | |
1478 | alist = alist.split() |
|
1516 | alist = alist.split() | |
1479 | if args: |
|
1517 | if args: | |
1480 | if len(args)==1: |
|
1518 | if len(args)==1: | |
1481 | default = args[0] |
|
1519 | default = args[0] | |
1482 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1520 | return map(lambda attr: getattr(obj,attr,default),alist) | |
1483 | else: |
|
1521 | else: | |
1484 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1522 | raise ValueError,'getattr_list() takes only one optional argument' | |
1485 | else: |
|
1523 | else: | |
1486 | return map(lambda attr: getattr(obj,attr),alist) |
|
1524 | return map(lambda attr: getattr(obj,attr),alist) | |
1487 |
|
1525 | |||
1488 | #---------------------------------------------------------------------------- |
|
1526 | #---------------------------------------------------------------------------- | |
1489 | def map_method(method,object_list,*argseq,**kw): |
|
1527 | def map_method(method,object_list,*argseq,**kw): | |
1490 | """map_method(method,object_list,*args,**kw) -> list |
|
1528 | """map_method(method,object_list,*args,**kw) -> list | |
1491 |
|
1529 | |||
1492 | Return a list of the results of applying the methods to the items of the |
|
1530 | Return a list of the results of applying the methods to the items of the | |
1493 | argument sequence(s). If more than one sequence is given, the method is |
|
1531 | argument sequence(s). If more than one sequence is given, the method is | |
1494 | called with an argument list consisting of the corresponding item of each |
|
1532 | called with an argument list consisting of the corresponding item of each | |
1495 | sequence. All sequences must be of the same length. |
|
1533 | sequence. All sequences must be of the same length. | |
1496 |
|
1534 | |||
1497 | Keyword arguments are passed verbatim to all objects called. |
|
1535 | Keyword arguments are passed verbatim to all objects called. | |
1498 |
|
1536 | |||
1499 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1537 | This is Python code, so it's not nearly as fast as the builtin map().""" | |
1500 |
|
1538 | |||
1501 | out_list = [] |
|
1539 | out_list = [] | |
1502 | idx = 0 |
|
1540 | idx = 0 | |
1503 | for object in object_list: |
|
1541 | for object in object_list: | |
1504 | try: |
|
1542 | try: | |
1505 | handler = getattr(object, method) |
|
1543 | handler = getattr(object, method) | |
1506 | except AttributeError: |
|
1544 | except AttributeError: | |
1507 | out_list.append(None) |
|
1545 | out_list.append(None) | |
1508 | else: |
|
1546 | else: | |
1509 | if argseq: |
|
1547 | if argseq: | |
1510 | args = map(lambda lst:lst[idx],argseq) |
|
1548 | args = map(lambda lst:lst[idx],argseq) | |
1511 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1549 | #print 'ob',object,'hand',handler,'ar',args # dbg | |
1512 | out_list.append(handler(args,**kw)) |
|
1550 | out_list.append(handler(args,**kw)) | |
1513 | else: |
|
1551 | else: | |
1514 | out_list.append(handler(**kw)) |
|
1552 | out_list.append(handler(**kw)) | |
1515 | idx += 1 |
|
1553 | idx += 1 | |
1516 | return out_list |
|
1554 | return out_list | |
1517 |
|
1555 | |||
1518 | #---------------------------------------------------------------------------- |
|
1556 | #---------------------------------------------------------------------------- | |
1519 | # Proposed popitem() extension, written as a method |
|
1557 | # Proposed popitem() extension, written as a method | |
1520 |
|
1558 | |||
1521 | class NotGiven: pass |
|
1559 | class NotGiven: pass | |
1522 |
|
1560 | |||
1523 | def popkey(dct,key,default=NotGiven): |
|
1561 | def popkey(dct,key,default=NotGiven): | |
1524 | """Return dct[key] and delete dct[key]. |
|
1562 | """Return dct[key] and delete dct[key]. | |
1525 |
|
1563 | |||
1526 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
1564 | If default is given, return it if dct[key] doesn't exist, otherwise raise | |
1527 | KeyError. """ |
|
1565 | KeyError. """ | |
1528 |
|
1566 | |||
1529 | try: |
|
1567 | try: | |
1530 | val = dct[key] |
|
1568 | val = dct[key] | |
1531 | except KeyError: |
|
1569 | except KeyError: | |
1532 | if default is NotGiven: |
|
1570 | if default is NotGiven: | |
1533 | raise |
|
1571 | raise | |
1534 | else: |
|
1572 | else: | |
1535 | return default |
|
1573 | return default | |
1536 | else: |
|
1574 | else: | |
1537 | del dct[key] |
|
1575 | del dct[key] | |
1538 | return val |
|
1576 | return val | |
1539 | #*************************** end of file <genutils.py> ********************** |
|
1577 | #*************************** end of file <genutils.py> ********************** | |
1540 |
|
1578 |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now