Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,2473 +1,2474 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 |
|
3 | |||
4 |
$Id: Magic.py 90 |
|
4 | $Id: Magic.py 907 2005-09-24 00:59:56Z fperez $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
8 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 |
|
13 | |||
14 | #**************************************************************************** |
|
14 | #**************************************************************************** | |
15 | # Modules and globals |
|
15 | # Modules and globals | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
18 | __author__ = '%s <%s>\n%s <%s>' % \ | |
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
20 | __license__ = Release.license |
|
20 | __license__ = Release.license | |
21 |
|
21 | |||
22 | # Python standard modules |
|
22 | # Python standard modules | |
23 | import __builtin__ |
|
23 | import __builtin__ | |
24 | import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time |
|
24 | import os,sys,inspect,pydoc,re,tempfile,pdb,bdb,time | |
25 | try: |
|
25 | try: | |
26 | import profile,pstats |
|
26 | import profile,pstats | |
27 | except ImportError: |
|
27 | except ImportError: | |
28 | profile = pstats = None |
|
28 | profile = pstats = None | |
29 | from getopt import getopt |
|
29 | from getopt import getopt | |
30 | from pprint import pprint, pformat |
|
30 | from pprint import pprint, pformat | |
31 | from cStringIO import StringIO |
|
31 | from cStringIO import StringIO | |
32 |
|
32 | |||
33 | # Homebrewed |
|
33 | # Homebrewed | |
34 | from IPython.Struct import Struct |
|
34 | from IPython.Struct import Struct | |
35 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
35 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
36 | from IPython.FakeModule import FakeModule |
|
36 | from IPython.FakeModule import FakeModule | |
37 | from IPython import OInspect |
|
37 | from IPython import OInspect | |
38 | from IPython.PyColorize import Parser |
|
38 | from IPython.PyColorize import Parser | |
39 | from IPython.genutils import * |
|
39 | from IPython.genutils import * | |
40 |
|
40 | |||
41 | # Globals to be set later by Magic constructor |
|
41 | # Globals to be set later by Magic constructor | |
42 | MAGIC_PREFIX = '' |
|
42 | MAGIC_PREFIX = '' | |
43 | MAGIC_ESCAPE = '' |
|
43 | MAGIC_ESCAPE = '' | |
44 |
|
44 | |||
45 | #*************************************************************************** |
|
45 | #*************************************************************************** | |
46 | # Utility functions |
|
46 | # Utility functions | |
47 | def magic2python(cmd): |
|
47 | def magic2python(cmd): | |
48 | """Convert a command string of magic syntax to valid Python code.""" |
|
48 | """Convert a command string of magic syntax to valid Python code.""" | |
49 |
|
49 | |||
50 | if cmd.startswith('#'+MAGIC_ESCAPE) or \ |
|
50 | if cmd.startswith('#'+MAGIC_ESCAPE) or \ | |
51 | cmd.startswith(MAGIC_ESCAPE): |
|
51 | cmd.startswith(MAGIC_ESCAPE): | |
52 | if cmd[0]=='#': |
|
52 | if cmd[0]=='#': | |
53 | cmd = cmd[1:] |
|
53 | cmd = cmd[1:] | |
54 | # we need to return the proper line end later |
|
54 | # we need to return the proper line end later | |
55 | if cmd[-1] == '\n': |
|
55 | if cmd[-1] == '\n': | |
56 | endl = '\n' |
|
56 | endl = '\n' | |
57 | else: |
|
57 | else: | |
58 | endl = '' |
|
58 | endl = '' | |
59 | try: |
|
59 | try: | |
60 | func,args = cmd[1:].split(' ',1) |
|
60 | func,args = cmd[1:].split(' ',1) | |
61 | except: |
|
61 | except: | |
62 | func,args = cmd[1:].rstrip(),'' |
|
62 | func,args = cmd[1:].rstrip(),'' | |
63 | args = args.replace('"','\\"').replace("'","\\'").rstrip() |
|
63 | args = args.replace('"','\\"').replace("'","\\'").rstrip() | |
64 | return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl) |
|
64 | return '%s%s ("%s")%s' % (MAGIC_PREFIX,func,args,endl) | |
65 | else: |
|
65 | else: | |
66 | return cmd |
|
66 | return cmd | |
67 |
|
67 | |||
68 | def on_off(tag): |
|
68 | def on_off(tag): | |
69 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
69 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
70 | return ['OFF','ON'][tag] |
|
70 | return ['OFF','ON'][tag] | |
71 |
|
71 | |||
72 | def get_py_filename(name): |
|
72 | def get_py_filename(name): | |
73 | """Return a valid python filename in the current directory. |
|
73 | """Return a valid python filename in the current directory. | |
74 |
|
74 | |||
75 | If the given name is not a file, it adds '.py' and searches again. |
|
75 | If the given name is not a file, it adds '.py' and searches again. | |
76 | Raises IOError with an informative message if the file isn't found.""" |
|
76 | Raises IOError with an informative message if the file isn't found.""" | |
77 |
|
77 | |||
78 | name = os.path.expanduser(name) |
|
78 | name = os.path.expanduser(name) | |
79 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
79 | if not os.path.isfile(name) and not name.endswith('.py'): | |
80 | name += '.py' |
|
80 | name += '.py' | |
81 | if os.path.isfile(name): |
|
81 | if os.path.isfile(name): | |
82 | return name |
|
82 | return name | |
83 | else: |
|
83 | else: | |
84 | raise IOError,'File `%s` not found.' % name |
|
84 | raise IOError,'File `%s` not found.' % name | |
85 |
|
85 | |||
86 |
|
86 | |||
87 | #**************************************************************************** |
|
87 | #**************************************************************************** | |
88 | # Utility classes |
|
88 | # Utility classes | |
89 | class Macro: |
|
89 | class Macro: | |
90 | """Simple class to store the value of macros as strings. |
|
90 | """Simple class to store the value of macros as strings. | |
91 |
|
91 | |||
92 | This allows us to later exec them by checking when something is an |
|
92 | This allows us to later exec them by checking when something is an | |
93 | instance of this class.""" |
|
93 | instance of this class.""" | |
94 |
|
94 | |||
95 | def __init__(self,cmds): |
|
95 | def __init__(self,cmds): | |
96 | """Build a macro from a list of commands.""" |
|
96 | """Build a macro from a list of commands.""" | |
97 |
|
97 | |||
98 | # Since the list may include multi-line entries, first make sure that |
|
98 | # Since the list may include multi-line entries, first make sure that | |
99 | # they've been all broken up before passing it to magic2python |
|
99 | # they've been all broken up before passing it to magic2python | |
100 | cmdlist = map(magic2python,''.join(cmds).split('\n')) |
|
100 | cmdlist = map(magic2python,''.join(cmds).split('\n')) | |
101 | self.value = '\n'.join(cmdlist) |
|
101 | self.value = '\n'.join(cmdlist) | |
102 |
|
102 | |||
103 | def __str__(self): |
|
103 | def __str__(self): | |
104 | return self.value |
|
104 | return self.value | |
105 |
|
105 | |||
106 | #*************************************************************************** |
|
106 | #*************************************************************************** | |
107 | # Main class implementing Magic functionality |
|
107 | # Main class implementing Magic functionality | |
108 | class Magic: |
|
108 | class Magic: | |
109 | """Magic functions for InteractiveShell. |
|
109 | """Magic functions for InteractiveShell. | |
110 |
|
110 | |||
111 | Shell functions which can be reached as %function_name. All magic |
|
111 | Shell functions which can be reached as %function_name. All magic | |
112 | functions should accept a string, which they can parse for their own |
|
112 | functions should accept a string, which they can parse for their own | |
113 | needs. This can make some functions easier to type, eg `%cd ../` |
|
113 | needs. This can make some functions easier to type, eg `%cd ../` | |
114 | vs. `%cd("../")` |
|
114 | vs. `%cd("../")` | |
115 |
|
115 | |||
116 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
116 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
117 | at the command line, but it is is needed in the definition. """ |
|
117 | at the command line, but it is is needed in the definition. """ | |
118 |
|
118 | |||
119 | # class globals |
|
119 | # class globals | |
120 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
120 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
121 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
121 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
122 |
|
122 | |||
123 | #...................................................................... |
|
123 | #...................................................................... | |
124 | # some utility functions |
|
124 | # some utility functions | |
125 |
|
125 | |||
126 | def __init__(self,shell): |
|
126 | def __init__(self,shell): | |
127 | # XXX This is hackish, clean up later to avoid these messy globals |
|
127 | # XXX This is hackish, clean up later to avoid these messy globals | |
128 | global MAGIC_PREFIX, MAGIC_ESCAPE |
|
128 | global MAGIC_PREFIX, MAGIC_ESCAPE | |
129 |
|
129 | |||
130 | self.options_table = {} |
|
130 | self.options_table = {} | |
131 | MAGIC_PREFIX = shell.name+'.magic_' |
|
131 | MAGIC_PREFIX = shell.name+'.magic_' | |
132 | MAGIC_ESCAPE = shell.ESC_MAGIC |
|
132 | MAGIC_ESCAPE = shell.ESC_MAGIC | |
133 | if profile is None: |
|
133 | if profile is None: | |
134 | self.magic_prun = self.profile_missing_notice |
|
134 | self.magic_prun = self.profile_missing_notice | |
135 |
|
135 | |||
136 | def profile_missing_notice(self, *args, **kwargs): |
|
136 | def profile_missing_notice(self, *args, **kwargs): | |
137 | error("""\ |
|
137 | error("""\ | |
138 | The profile module could not be found. If you are a Debian user, |
|
138 | The profile module could not be found. If you are a Debian user, | |
139 | it has been removed from the standard Debian package because of its non-free |
|
139 | it has been removed from the standard Debian package because of its non-free | |
140 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
140 | license. To use profiling, please install"python2.3-profiler" from non-free.""") | |
141 |
|
141 | |||
142 | def default_option(self,fn,optstr): |
|
142 | def default_option(self,fn,optstr): | |
143 | """Make an entry in the options_table for fn, with value optstr""" |
|
143 | """Make an entry in the options_table for fn, with value optstr""" | |
144 |
|
144 | |||
145 | if fn not in self.lsmagic(): |
|
145 | if fn not in self.lsmagic(): | |
146 | error("%s is not a magic function" % fn) |
|
146 | error("%s is not a magic function" % fn) | |
147 | self.options_table[fn] = optstr |
|
147 | self.options_table[fn] = optstr | |
148 |
|
148 | |||
149 | def lsmagic(self): |
|
149 | def lsmagic(self): | |
150 | """Return a list of currently available magic functions. |
|
150 | """Return a list of currently available magic functions. | |
151 |
|
151 | |||
152 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
152 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
153 | ['magic_ls','magic_cd',...]""" |
|
153 | ['magic_ls','magic_cd',...]""" | |
154 |
|
154 | |||
155 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
155 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
156 |
|
156 | |||
157 | # magics in class definition |
|
157 | # magics in class definition | |
158 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
158 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
159 | callable(Magic.__dict__[fn]) |
|
159 | callable(Magic.__dict__[fn]) | |
160 | # in instance namespace (run-time user additions) |
|
160 | # in instance namespace (run-time user additions) | |
161 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
161 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
162 | callable(self.__dict__[fn]) |
|
162 | callable(self.__dict__[fn]) | |
163 | # and bound magics by user (so they can access self): |
|
163 | # and bound magics by user (so they can access self): | |
164 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
164 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
165 | callable(self.__class__.__dict__[fn]) |
|
165 | callable(self.__class__.__dict__[fn]) | |
166 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
166 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
167 | filter(inst_magic,self.__dict__.keys()) + \ |
|
167 | filter(inst_magic,self.__dict__.keys()) + \ | |
168 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
168 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
169 | out = [] |
|
169 | out = [] | |
170 | for fn in magics: |
|
170 | for fn in magics: | |
171 | out.append(fn.replace('magic_','',1)) |
|
171 | out.append(fn.replace('magic_','',1)) | |
172 | out.sort() |
|
172 | out.sort() | |
173 | return out |
|
173 | return out | |
174 |
|
174 | |||
175 | def set_shell(self,shell): |
|
175 | def set_shell(self,shell): | |
176 | self.shell = shell |
|
176 | self.shell = shell | |
177 | self.alias_table = shell.alias_table |
|
177 | self.alias_table = shell.alias_table | |
178 |
|
178 | |||
179 | def extract_input_slices(self,slices): |
|
179 | def extract_input_slices(self,slices): | |
180 | """Return as a string a set of input history slices. |
|
180 | """Return as a string a set of input history slices. | |
181 |
|
181 | |||
182 | The set of slices is given as a list of strings (like ['1','4:8','9'], |
|
182 | The set of slices is given as a list of strings (like ['1','4:8','9'], | |
183 | since this function is for use by magic functions which get their |
|
183 | since this function is for use by magic functions which get their | |
184 | arguments as strings.""" |
|
184 | arguments as strings.""" | |
185 |
|
185 | |||
186 | cmds = [] |
|
186 | cmds = [] | |
187 | for chunk in slices: |
|
187 | for chunk in slices: | |
188 | if ':' in chunk: |
|
188 | if ':' in chunk: | |
189 | ini,fin = map(int,chunk.split(':')) |
|
189 | ini,fin = map(int,chunk.split(':')) | |
190 | else: |
|
190 | else: | |
191 | ini = int(chunk) |
|
191 | ini = int(chunk) | |
192 | fin = ini+1 |
|
192 | fin = ini+1 | |
193 | cmds.append(self.shell.input_hist[ini:fin]) |
|
193 | cmds.append(self.shell.input_hist[ini:fin]) | |
194 | return cmds |
|
194 | return cmds | |
195 |
|
195 | |||
196 | def _ofind(self,oname): |
|
196 | def _ofind(self,oname): | |
197 | """Find an object in the available namespaces. |
|
197 | """Find an object in the available namespaces. | |
198 |
|
198 | |||
199 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
199 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
200 |
|
200 | |||
201 | Has special code to detect magic functions. |
|
201 | Has special code to detect magic functions. | |
202 | """ |
|
202 | """ | |
203 |
|
203 | |||
204 | oname = oname.strip() |
|
204 | oname = oname.strip() | |
205 |
|
205 | |||
206 | # Namespaces to search in: |
|
206 | # Namespaces to search in: | |
207 | user_ns = self.shell.user_ns |
|
207 | user_ns = self.shell.user_ns | |
208 | internal_ns = self.shell.internal_ns |
|
208 | internal_ns = self.shell.internal_ns | |
209 | builtin_ns = __builtin__.__dict__ |
|
209 | builtin_ns = __builtin__.__dict__ | |
210 | alias_ns = self.shell.alias_table |
|
210 | alias_ns = self.shell.alias_table | |
211 |
|
211 | |||
212 | # Put them in a list. The order is important so that we find things in |
|
212 | # Put them in a list. The order is important so that we find things in | |
213 | # the same order that Python finds them. |
|
213 | # the same order that Python finds them. | |
214 | namespaces = [ ('Interactive',user_ns), |
|
214 | namespaces = [ ('Interactive',user_ns), | |
215 | ('IPython internal',internal_ns), |
|
215 | ('IPython internal',internal_ns), | |
216 | ('Python builtin',builtin_ns), |
|
216 | ('Python builtin',builtin_ns), | |
217 | ('Alias',alias_ns), |
|
217 | ('Alias',alias_ns), | |
218 | ] |
|
218 | ] | |
219 |
|
219 | |||
220 | # initialize results to 'null' |
|
220 | # initialize results to 'null' | |
221 | found = 0; obj = None; ospace = None; ds = None; |
|
221 | found = 0; obj = None; ospace = None; ds = None; | |
222 | ismagic = 0; isalias = 0 |
|
222 | ismagic = 0; isalias = 0 | |
223 |
|
223 | |||
224 | # Look for the given name by splitting it in parts. If the head is |
|
224 | # Look for the given name by splitting it in parts. If the head is | |
225 | # found, then we look for all the remaining parts as members, and only |
|
225 | # found, then we look for all the remaining parts as members, and only | |
226 | # declare success if we can find them all. |
|
226 | # declare success if we can find them all. | |
227 | oname_parts = oname.split('.') |
|
227 | oname_parts = oname.split('.') | |
228 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
228 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
229 | for nsname,ns in namespaces: |
|
229 | for nsname,ns in namespaces: | |
230 | try: |
|
230 | try: | |
231 | obj = ns[oname_head] |
|
231 | obj = ns[oname_head] | |
232 | except KeyError: |
|
232 | except KeyError: | |
233 | continue |
|
233 | continue | |
234 | else: |
|
234 | else: | |
235 | for part in oname_rest: |
|
235 | for part in oname_rest: | |
236 | try: |
|
236 | try: | |
237 | obj = getattr(obj,part) |
|
237 | obj = getattr(obj,part) | |
238 | except: |
|
238 | except: | |
239 | # Blanket except b/c some badly implemented objects |
|
239 | # Blanket except b/c some badly implemented objects | |
240 | # allow __getattr__ to raise exceptions other than |
|
240 | # allow __getattr__ to raise exceptions other than | |
241 | # AttributeError, which then crashes IPython. |
|
241 | # AttributeError, which then crashes IPython. | |
242 | break |
|
242 | break | |
243 | else: |
|
243 | else: | |
244 | # If we finish the for loop (no break), we got all members |
|
244 | # If we finish the for loop (no break), we got all members | |
245 | found = 1 |
|
245 | found = 1 | |
246 | ospace = nsname |
|
246 | ospace = nsname | |
247 | if ns == alias_ns: |
|
247 | if ns == alias_ns: | |
248 | isalias = 1 |
|
248 | isalias = 1 | |
249 | break # namespace loop |
|
249 | break # namespace loop | |
250 |
|
250 | |||
251 | # Try to see if it's magic |
|
251 | # Try to see if it's magic | |
252 | if not found: |
|
252 | if not found: | |
253 | if oname.startswith(self.shell.ESC_MAGIC): |
|
253 | if oname.startswith(self.shell.ESC_MAGIC): | |
254 | oname = oname[1:] |
|
254 | oname = oname[1:] | |
255 | obj = getattr(self,'magic_'+oname,None) |
|
255 | obj = getattr(self,'magic_'+oname,None) | |
256 | if obj is not None: |
|
256 | if obj is not None: | |
257 | found = 1 |
|
257 | found = 1 | |
258 | ospace = 'IPython internal' |
|
258 | ospace = 'IPython internal' | |
259 | ismagic = 1 |
|
259 | ismagic = 1 | |
260 |
|
260 | |||
261 | # Last try: special-case some literals like '', [], {}, etc: |
|
261 | # Last try: special-case some literals like '', [], {}, etc: | |
262 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
262 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
263 | obj = eval(oname_head) |
|
263 | obj = eval(oname_head) | |
264 | found = 1 |
|
264 | found = 1 | |
265 | ospace = 'Interactive' |
|
265 | ospace = 'Interactive' | |
266 |
|
266 | |||
267 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
267 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
268 | 'ismagic':ismagic, 'isalias':isalias} |
|
268 | 'ismagic':ismagic, 'isalias':isalias} | |
269 |
|
269 | |||
270 | def arg_err(self,func): |
|
270 | def arg_err(self,func): | |
271 | """Print docstring if incorrect arguments were passed""" |
|
271 | """Print docstring if incorrect arguments were passed""" | |
272 | print 'Error in arguments:' |
|
272 | print 'Error in arguments:' | |
273 | print OInspect.getdoc(func) |
|
273 | print OInspect.getdoc(func) | |
274 |
|
274 | |||
275 |
|
275 | |||
276 | def format_latex(self,str): |
|
276 | def format_latex(self,str): | |
277 | """Format a string for latex inclusion.""" |
|
277 | """Format a string for latex inclusion.""" | |
278 |
|
278 | |||
279 | # Characters that need to be escaped for latex: |
|
279 | # Characters that need to be escaped for latex: | |
280 | escape_re = re.compile(r'(%|_|\$)',re.MULTILINE) |
|
280 | escape_re = re.compile(r'(%|_|\$)',re.MULTILINE) | |
281 | # Magic command names as headers: |
|
281 | # Magic command names as headers: | |
282 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
282 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
283 | re.MULTILINE) |
|
283 | re.MULTILINE) | |
284 | # Magic commands |
|
284 | # Magic commands | |
285 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
285 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
286 | re.MULTILINE) |
|
286 | re.MULTILINE) | |
287 | # Paragraph continue |
|
287 | # Paragraph continue | |
288 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
288 | par_re = re.compile(r'\\$',re.MULTILINE) | |
289 |
|
289 | |||
290 | str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str) |
|
290 | str = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',str) | |
291 | str = cmd_re.sub(r'\\texttt{\g<cmd>}',str) |
|
291 | str = cmd_re.sub(r'\\texttt{\g<cmd>}',str) | |
292 | str = par_re.sub(r'\\\\',str) |
|
292 | str = par_re.sub(r'\\\\',str) | |
293 | str = escape_re.sub(r'\\\1',str) |
|
293 | str = escape_re.sub(r'\\\1',str) | |
294 | return str |
|
294 | return str | |
295 |
|
295 | |||
296 | def format_screen(self,str): |
|
296 | def format_screen(self,str): | |
297 | """Format a string for screen printing. |
|
297 | """Format a string for screen printing. | |
298 |
|
298 | |||
299 | This removes some latex-type format codes.""" |
|
299 | This removes some latex-type format codes.""" | |
300 | # Paragraph continue |
|
300 | # Paragraph continue | |
301 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
301 | par_re = re.compile(r'\\$',re.MULTILINE) | |
302 | str = par_re.sub('',str) |
|
302 | str = par_re.sub('',str) | |
303 | return str |
|
303 | return str | |
304 |
|
304 | |||
305 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
305 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
306 | """Parse options passed to an argument string. |
|
306 | """Parse options passed to an argument string. | |
307 |
|
307 | |||
308 | The interface is similar to that of getopt(), but it returns back a |
|
308 | The interface is similar to that of getopt(), but it returns back a | |
309 | Struct with the options as keys and the stripped argument string still |
|
309 | Struct with the options as keys and the stripped argument string still | |
310 | as a string. |
|
310 | as a string. | |
311 |
|
311 | |||
312 | arg_str is quoted as a true sys.argv vector by calling on the fly a |
|
312 | arg_str is quoted as a true sys.argv vector by calling on the fly a | |
313 | python process in a subshell. This allows us to easily expand |
|
313 | python process in a subshell. This allows us to easily expand | |
314 | variables, glob files, quote arguments, etc, with all the power and |
|
314 | variables, glob files, quote arguments, etc, with all the power and | |
315 | correctness of the underlying system shell. |
|
315 | correctness of the underlying system shell. | |
316 |
|
316 | |||
317 | Options: |
|
317 | Options: | |
318 | -mode: default 'string'. If given as 'list', the argument string is |
|
318 | -mode: default 'string'. If given as 'list', the argument string is | |
319 | returned as a list (split on whitespace) instead of a string. |
|
319 | returned as a list (split on whitespace) instead of a string. | |
320 |
|
320 | |||
321 | -list_all: put all option values in lists. Normally only options |
|
321 | -list_all: put all option values in lists. Normally only options | |
322 | appearing more than once are put in a list.""" |
|
322 | appearing more than once are put in a list.""" | |
323 |
|
323 | |||
324 | # inject default options at the beginning of the input line |
|
324 | # inject default options at the beginning of the input line | |
325 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
325 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
326 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
326 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
327 |
|
327 | |||
328 | mode = kw.get('mode','string') |
|
328 | mode = kw.get('mode','string') | |
329 | if mode not in ['string','list']: |
|
329 | if mode not in ['string','list']: | |
330 | raise ValueError,'incorrect mode given: %s' % mode |
|
330 | raise ValueError,'incorrect mode given: %s' % mode | |
331 | # Get options |
|
331 | # Get options | |
332 | list_all = kw.get('list_all',0) |
|
332 | list_all = kw.get('list_all',0) | |
333 |
|
333 | |||
334 | # Check if we have more than one argument to warrant extra processing: |
|
334 | # Check if we have more than one argument to warrant extra processing: | |
335 | odict = {} # Dictionary with options |
|
335 | odict = {} # Dictionary with options | |
336 | args = arg_str.split() |
|
336 | args = arg_str.split() | |
337 | if len(args) >= 1: |
|
337 | if len(args) >= 1: | |
338 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
338 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
339 | # need to look for options |
|
339 | # need to look for options | |
340 | argv = shlex_split(arg_str) |
|
340 | argv = shlex_split(arg_str) | |
341 | # Do regular option processing |
|
341 | # Do regular option processing | |
342 | opts,args = getopt(argv,opt_str,*long_opts) |
|
342 | opts,args = getopt(argv,opt_str,*long_opts) | |
343 | for o,a in opts: |
|
343 | for o,a in opts: | |
344 | if o.startswith('--'): |
|
344 | if o.startswith('--'): | |
345 | o = o[2:] |
|
345 | o = o[2:] | |
346 | else: |
|
346 | else: | |
347 | o = o[1:] |
|
347 | o = o[1:] | |
348 | try: |
|
348 | try: | |
349 | odict[o].append(a) |
|
349 | odict[o].append(a) | |
350 | except AttributeError: |
|
350 | except AttributeError: | |
351 | odict[o] = [odict[o],a] |
|
351 | odict[o] = [odict[o],a] | |
352 | except KeyError: |
|
352 | except KeyError: | |
353 | if list_all: |
|
353 | if list_all: | |
354 | odict[o] = [a] |
|
354 | odict[o] = [a] | |
355 | else: |
|
355 | else: | |
356 | odict[o] = a |
|
356 | odict[o] = a | |
357 |
|
357 | |||
358 | # Prepare opts,args for return |
|
358 | # Prepare opts,args for return | |
359 | opts = Struct(odict) |
|
359 | opts = Struct(odict) | |
360 | if mode == 'string': |
|
360 | if mode == 'string': | |
361 | args = ' '.join(args) |
|
361 | args = ' '.join(args) | |
362 |
|
362 | |||
363 | return opts,args |
|
363 | return opts,args | |
364 |
|
364 | |||
365 | #...................................................................... |
|
365 | #...................................................................... | |
366 | # And now the actual magic functions |
|
366 | # And now the actual magic functions | |
367 |
|
367 | |||
368 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
368 | # Functions for IPython shell work (vars,funcs, config, etc) | |
369 | def magic_lsmagic(self, parameter_s = ''): |
|
369 | def magic_lsmagic(self, parameter_s = ''): | |
370 | """List currently available magic functions.""" |
|
370 | """List currently available magic functions.""" | |
371 | mesc = self.shell.ESC_MAGIC |
|
371 | mesc = self.shell.ESC_MAGIC | |
372 | print 'Available magic functions:\n'+mesc+\ |
|
372 | print 'Available magic functions:\n'+mesc+\ | |
373 | (' '+mesc).join(self.lsmagic()) |
|
373 | (' '+mesc).join(self.lsmagic()) | |
374 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
374 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
375 | return None |
|
375 | return None | |
376 |
|
376 | |||
377 | def magic_magic(self, parameter_s = ''): |
|
377 | def magic_magic(self, parameter_s = ''): | |
378 | """Print information about the magic function system.""" |
|
378 | """Print information about the magic function system.""" | |
379 |
|
379 | |||
380 | mode = '' |
|
380 | mode = '' | |
381 | try: |
|
381 | try: | |
382 | if parameter_s.split()[0] == '-latex': |
|
382 | if parameter_s.split()[0] == '-latex': | |
383 | mode = 'latex' |
|
383 | mode = 'latex' | |
384 | except: |
|
384 | except: | |
385 | pass |
|
385 | pass | |
386 |
|
386 | |||
387 | magic_docs = [] |
|
387 | magic_docs = [] | |
388 | for fname in self.lsmagic(): |
|
388 | for fname in self.lsmagic(): | |
389 | mname = 'magic_' + fname |
|
389 | mname = 'magic_' + fname | |
390 | for space in (Magic,self,self.__class__): |
|
390 | for space in (Magic,self,self.__class__): | |
391 | try: |
|
391 | try: | |
392 | fn = space.__dict__[mname] |
|
392 | fn = space.__dict__[mname] | |
393 | except KeyError: |
|
393 | except KeyError: | |
394 | pass |
|
394 | pass | |
395 | else: |
|
395 | else: | |
396 | break |
|
396 | break | |
397 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
397 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
398 | fname,fn.__doc__)) |
|
398 | fname,fn.__doc__)) | |
399 | magic_docs = ''.join(magic_docs) |
|
399 | magic_docs = ''.join(magic_docs) | |
400 |
|
400 | |||
401 | if mode == 'latex': |
|
401 | if mode == 'latex': | |
402 | print self.format_latex(magic_docs) |
|
402 | print self.format_latex(magic_docs) | |
403 | return |
|
403 | return | |
404 | else: |
|
404 | else: | |
405 | magic_docs = self.format_screen(magic_docs) |
|
405 | magic_docs = self.format_screen(magic_docs) | |
406 |
|
406 | |||
407 | outmsg = """ |
|
407 | outmsg = """ | |
408 | IPython's 'magic' functions |
|
408 | IPython's 'magic' functions | |
409 | =========================== |
|
409 | =========================== | |
410 |
|
410 | |||
411 | The magic function system provides a series of functions which allow you to |
|
411 | The magic function system provides a series of functions which allow you to | |
412 | control the behavior of IPython itself, plus a lot of system-type |
|
412 | control the behavior of IPython itself, plus a lot of system-type | |
413 | features. All these functions are prefixed with a % character, but parameters |
|
413 | features. All these functions are prefixed with a % character, but parameters | |
414 | are given without parentheses or quotes. |
|
414 | are given without parentheses or quotes. | |
415 |
|
415 | |||
416 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
416 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
417 | %automagic function), you don't need to type in the % explicitly. By default, |
|
417 | %automagic function), you don't need to type in the % explicitly. By default, | |
418 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
418 | IPython ships with automagic on, so you should only rarely need the % escape. | |
419 |
|
419 | |||
420 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
420 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
421 | to 'mydir', if it exists. |
|
421 | to 'mydir', if it exists. | |
422 |
|
422 | |||
423 | You can define your own magic functions to extend the system. See the supplied |
|
423 | You can define your own magic functions to extend the system. See the supplied | |
424 | ipythonrc and example-magic.py files for details (in your ipython |
|
424 | ipythonrc and example-magic.py files for details (in your ipython | |
425 | configuration directory, typically $HOME/.ipython/). |
|
425 | configuration directory, typically $HOME/.ipython/). | |
426 |
|
426 | |||
427 | You can also define your own aliased names for magic functions. In your |
|
427 | You can also define your own aliased names for magic functions. In your | |
428 | ipythonrc file, placing a line like: |
|
428 | ipythonrc file, placing a line like: | |
429 |
|
429 | |||
430 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
430 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
431 |
|
431 | |||
432 | will define %pf as a new name for %profile. |
|
432 | will define %pf as a new name for %profile. | |
433 |
|
433 | |||
434 | You can also call magics in code using the ipmagic() function, which IPython |
|
434 | You can also call magics in code using the ipmagic() function, which IPython | |
435 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
435 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
436 |
|
436 | |||
437 | For a list of the available magic functions, use %lsmagic. For a description |
|
437 | For a list of the available magic functions, use %lsmagic. For a description | |
438 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
438 | of any of them, type %magic_name?, e.g. '%cd?'. | |
439 |
|
439 | |||
440 | Currently the magic system has the following functions:\n""" |
|
440 | Currently the magic system has the following functions:\n""" | |
441 |
|
441 | |||
442 | mesc = self.shell.ESC_MAGIC |
|
442 | mesc = self.shell.ESC_MAGIC | |
443 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
443 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
444 | "\n\n%s%s\n\n%s" % (outmsg, |
|
444 | "\n\n%s%s\n\n%s" % (outmsg, | |
445 | magic_docs,mesc,mesc, |
|
445 | magic_docs,mesc,mesc, | |
446 | (' '+mesc).join(self.lsmagic()), |
|
446 | (' '+mesc).join(self.lsmagic()), | |
447 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
447 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
448 |
|
448 | |||
449 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
449 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
450 |
|
450 | |||
451 | def magic_automagic(self, parameter_s = ''): |
|
451 | def magic_automagic(self, parameter_s = ''): | |
452 | """Make magic functions callable without having to type the initial %. |
|
452 | """Make magic functions callable without having to type the initial %. | |
453 |
|
453 | |||
454 | Toggles on/off (when off, you must call it as %automagic, of |
|
454 | Toggles on/off (when off, you must call it as %automagic, of | |
455 | course). Note that magic functions have lowest priority, so if there's |
|
455 | course). Note that magic functions have lowest priority, so if there's | |
456 | a variable whose name collides with that of a magic fn, automagic |
|
456 | a variable whose name collides with that of a magic fn, automagic | |
457 | won't work for that function (you get the variable instead). However, |
|
457 | won't work for that function (you get the variable instead). However, | |
458 | if you delete the variable (del var), the previously shadowed magic |
|
458 | if you delete the variable (del var), the previously shadowed magic | |
459 | function becomes visible to automagic again.""" |
|
459 | function becomes visible to automagic again.""" | |
460 |
|
460 | |||
461 | rc = self.shell.rc |
|
461 | rc = self.shell.rc | |
462 | rc.automagic = not rc.automagic |
|
462 | rc.automagic = not rc.automagic | |
463 | print '\n' + Magic.auto_status[rc.automagic] |
|
463 | print '\n' + Magic.auto_status[rc.automagic] | |
464 |
|
464 | |||
465 | def magic_autocall(self, parameter_s = ''): |
|
465 | def magic_autocall(self, parameter_s = ''): | |
466 | """Make functions callable without having to type parentheses. |
|
466 | """Make functions callable without having to type parentheses. | |
467 |
|
467 | |||
468 | This toggles the autocall command line option on and off.""" |
|
468 | This toggles the autocall command line option on and off.""" | |
469 |
|
469 | |||
470 | rc = self.shell.rc |
|
470 | rc = self.shell.rc | |
471 | rc.autocall = not rc.autocall |
|
471 | rc.autocall = not rc.autocall | |
472 | print "Automatic calling is:",['OFF','ON'][rc.autocall] |
|
472 | print "Automatic calling is:",['OFF','ON'][rc.autocall] | |
473 |
|
473 | |||
474 | def magic_autoindent(self, parameter_s = ''): |
|
474 | def magic_autoindent(self, parameter_s = ''): | |
475 | """Toggle autoindent on/off (if available).""" |
|
475 | """Toggle autoindent on/off (if available).""" | |
476 |
|
476 | |||
477 | self.shell.set_autoindent() |
|
477 | self.shell.set_autoindent() | |
478 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
478 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
479 |
|
479 | |||
480 | def magic_system_verbose(self, parameter_s = ''): |
|
480 | def magic_system_verbose(self, parameter_s = ''): | |
481 | """Toggle verbose printing of system calls on/off.""" |
|
481 | """Toggle verbose printing of system calls on/off.""" | |
482 |
|
482 | |||
483 | self.shell.rc_set_toggle('system_verbose') |
|
483 | self.shell.rc_set_toggle('system_verbose') | |
484 | print "System verbose printing is:",\ |
|
484 | print "System verbose printing is:",\ | |
485 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
485 | ['OFF','ON'][self.shell.rc.system_verbose] | |
486 |
|
486 | |||
487 | def magic_history(self, parameter_s = ''): |
|
487 | def magic_history(self, parameter_s = ''): | |
488 | """Print input history (_i<n> variables), with most recent last. |
|
488 | """Print input history (_i<n> variables), with most recent last. | |
489 |
|
489 | |||
490 | %history [-n] -> print at most 40 inputs (some may be multi-line)\\ |
|
490 | %history [-n] -> print at most 40 inputs (some may be multi-line)\\ | |
491 | %history [-n] n -> print at most n inputs\\ |
|
491 | %history [-n] n -> print at most n inputs\\ | |
492 | %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
492 | %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
493 |
|
493 | |||
494 | Each input's number <n> is shown, and is accessible as the |
|
494 | Each input's number <n> is shown, and is accessible as the | |
495 | automatically generated variable _i<n>. Multi-line statements are |
|
495 | automatically generated variable _i<n>. Multi-line statements are | |
496 | printed starting at a new line for easy copy/paste. |
|
496 | printed starting at a new line for easy copy/paste. | |
497 |
|
497 | |||
498 | If option -n is used, input numbers are not printed. This is useful if |
|
498 | If option -n is used, input numbers are not printed. This is useful if | |
499 | you want to get a printout of many lines which can be directly pasted |
|
499 | you want to get a printout of many lines which can be directly pasted | |
500 | into a text editor. |
|
500 | into a text editor. | |
501 |
|
501 | |||
502 | This feature is only available if numbered prompts are in use.""" |
|
502 | This feature is only available if numbered prompts are in use.""" | |
503 |
|
503 | |||
504 | if not self.do_full_cache: |
|
504 | if not self.do_full_cache: | |
505 | print 'This feature is only available if numbered prompts are in use.' |
|
505 | print 'This feature is only available if numbered prompts are in use.' | |
506 | return |
|
506 | return | |
507 | opts,args = self.parse_options(parameter_s,'n',mode='list') |
|
507 | opts,args = self.parse_options(parameter_s,'n',mode='list') | |
508 |
|
508 | |||
509 | default_length = 40 |
|
509 | default_length = 40 | |
510 | if len(args) == 0: |
|
510 | if len(args) == 0: | |
511 | final = self.outputcache.prompt_count |
|
511 | final = self.outputcache.prompt_count | |
512 | init = max(1,final-default_length) |
|
512 | init = max(1,final-default_length) | |
513 | elif len(args) == 1: |
|
513 | elif len(args) == 1: | |
514 | final = self.outputcache.prompt_count |
|
514 | final = self.outputcache.prompt_count | |
515 | init = max(1,final-int(args[0])) |
|
515 | init = max(1,final-int(args[0])) | |
516 | elif len(args) == 2: |
|
516 | elif len(args) == 2: | |
517 | init,final = map(int,args) |
|
517 | init,final = map(int,args) | |
518 | else: |
|
518 | else: | |
519 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
519 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
520 | print self.magic_hist.__doc__ |
|
520 | print self.magic_hist.__doc__ | |
521 | return |
|
521 | return | |
522 | width = len(str(final)) |
|
522 | width = len(str(final)) | |
523 | line_sep = ['','\n'] |
|
523 | line_sep = ['','\n'] | |
524 | input_hist = self.shell.input_hist |
|
524 | input_hist = self.shell.input_hist | |
525 | print_nums = not opts.has_key('n') |
|
525 | print_nums = not opts.has_key('n') | |
526 | for in_num in range(init,final): |
|
526 | for in_num in range(init,final): | |
527 | inline = input_hist[in_num] |
|
527 | inline = input_hist[in_num] | |
528 | multiline = inline.count('\n') > 1 |
|
528 | multiline = inline.count('\n') > 1 | |
529 | if print_nums: |
|
529 | if print_nums: | |
530 | print str(in_num).ljust(width)+':'+ line_sep[multiline], |
|
530 | print str(in_num).ljust(width)+':'+ line_sep[multiline], | |
531 | if inline.startswith('#'+self.shell.ESC_MAGIC) or \ |
|
531 | if inline.startswith('#'+self.shell.ESC_MAGIC) or \ | |
532 | inline.startswith('#!'): |
|
532 | inline.startswith('#!'): | |
533 | print inline[1:], |
|
533 | print inline[1:], | |
534 | else: |
|
534 | else: | |
535 | print inline, |
|
535 | print inline, | |
536 |
|
536 | |||
537 | def magic_hist(self, parameter_s=''): |
|
537 | def magic_hist(self, parameter_s=''): | |
538 | """Alternate name for %history.""" |
|
538 | """Alternate name for %history.""" | |
539 | return self.magic_history(parameter_s) |
|
539 | return self.magic_history(parameter_s) | |
540 |
|
540 | |||
541 | def magic_p(self, parameter_s=''): |
|
541 | def magic_p(self, parameter_s=''): | |
542 | """Just a short alias for Python's 'print'.""" |
|
542 | """Just a short alias for Python's 'print'.""" | |
543 | exec 'print ' + parameter_s in self.shell.user_ns |
|
543 | exec 'print ' + parameter_s in self.shell.user_ns | |
544 |
|
544 | |||
545 | def magic_r(self, parameter_s=''): |
|
545 | def magic_r(self, parameter_s=''): | |
546 | """Repeat previous input. |
|
546 | """Repeat previous input. | |
547 |
|
547 | |||
548 | If given an argument, repeats the previous command which starts with |
|
548 | If given an argument, repeats the previous command which starts with | |
549 | the same string, otherwise it just repeats the previous input. |
|
549 | the same string, otherwise it just repeats the previous input. | |
550 |
|
550 | |||
551 | Shell escaped commands (with ! as first character) are not recognized |
|
551 | Shell escaped commands (with ! as first character) are not recognized | |
552 | by this system, only pure python code and magic commands. |
|
552 | by this system, only pure python code and magic commands. | |
553 | """ |
|
553 | """ | |
554 |
|
554 | |||
555 | start = parameter_s.strip() |
|
555 | start = parameter_s.strip() | |
556 | esc_magic = self.shell.ESC_MAGIC |
|
556 | esc_magic = self.shell.ESC_MAGIC | |
557 | # Identify magic commands even if automagic is on (which means |
|
557 | # Identify magic commands even if automagic is on (which means | |
558 | # the in-memory version is different from that typed by the user). |
|
558 | # the in-memory version is different from that typed by the user). | |
559 | if self.shell.rc.automagic: |
|
559 | if self.shell.rc.automagic: | |
560 | start_magic = esc_magic+start |
|
560 | start_magic = esc_magic+start | |
561 | else: |
|
561 | else: | |
562 | start_magic = start |
|
562 | start_magic = start | |
563 | # Look through the input history in reverse |
|
563 | # Look through the input history in reverse | |
564 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
564 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
565 | input = self.shell.input_hist[n] |
|
565 | input = self.shell.input_hist[n] | |
566 | # skip plain 'r' lines so we don't recurse to infinity |
|
566 | # skip plain 'r' lines so we don't recurse to infinity | |
567 | if input != 'ipmagic("r")\n' and \ |
|
567 | if input != 'ipmagic("r")\n' and \ | |
568 | (input.startswith(start) or input.startswith(start_magic)): |
|
568 | (input.startswith(start) or input.startswith(start_magic)): | |
569 | #print 'match',`input` # dbg |
|
569 | #print 'match',`input` # dbg | |
570 | if input.startswith(esc_magic): |
|
570 | if input.startswith(esc_magic): | |
571 | input = magic2python(input) |
|
571 | input = magic2python(input) | |
572 | #print 'modified',`input` # dbg |
|
572 | #print 'modified',`input` # dbg | |
573 | print 'Executing:',input, |
|
573 | print 'Executing:',input, | |
574 | exec input in self.shell.user_ns |
|
574 | exec input in self.shell.user_ns | |
575 | return |
|
575 | return | |
576 | print 'No previous input matching `%s` found.' % start |
|
576 | print 'No previous input matching `%s` found.' % start | |
577 |
|
577 | |||
578 | def magic_page(self, parameter_s=''): |
|
578 | def magic_page(self, parameter_s=''): | |
579 | """Pretty print the object and display it through a pager. |
|
579 | """Pretty print the object and display it through a pager. | |
580 |
|
580 | |||
581 | If no parameter is given, use _ (last output).""" |
|
581 | If no parameter is given, use _ (last output).""" | |
582 | # After a function contributed by Olivier Aubert, slightly modified. |
|
582 | # After a function contributed by Olivier Aubert, slightly modified. | |
583 |
|
583 | |||
584 | oname = parameter_s and parameter_s or '_' |
|
584 | oname = parameter_s and parameter_s or '_' | |
585 | info = self._ofind(oname) |
|
585 | info = self._ofind(oname) | |
586 | if info['found']: |
|
586 | if info['found']: | |
587 | page(pformat(info['obj'])) |
|
587 | page(pformat(info['obj'])) | |
588 | else: |
|
588 | else: | |
589 | print 'Object `%s` not found' % oname |
|
589 | print 'Object `%s` not found' % oname | |
590 |
|
590 | |||
591 | def magic_profile(self, parameter_s=''): |
|
591 | def magic_profile(self, parameter_s=''): | |
592 | """Print your currently active IPyhton profile.""" |
|
592 | """Print your currently active IPyhton profile.""" | |
593 | if self.shell.rc.profile: |
|
593 | if self.shell.rc.profile: | |
594 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
594 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
595 | else: |
|
595 | else: | |
596 | print 'No profile active.' |
|
596 | print 'No profile active.' | |
597 |
|
597 | |||
598 | def _inspect(self,meth,oname,**kw): |
|
598 | def _inspect(self,meth,oname,**kw): | |
599 | """Generic interface to the inspector system. |
|
599 | """Generic interface to the inspector system. | |
600 |
|
600 | |||
601 | This function is meant to be called by pdef, pdoc & friends.""" |
|
601 | This function is meant to be called by pdef, pdoc & friends.""" | |
602 |
|
602 | |||
603 | oname = oname.strip() |
|
603 | oname = oname.strip() | |
604 | info = Struct(self._ofind(oname)) |
|
604 | info = Struct(self._ofind(oname)) | |
605 | if info.found: |
|
605 | if info.found: | |
606 | pmethod = getattr(self.shell.inspector,meth) |
|
606 | pmethod = getattr(self.shell.inspector,meth) | |
607 | formatter = info.ismagic and self.format_screen or None |
|
607 | formatter = info.ismagic and self.format_screen or None | |
608 | if meth == 'pdoc': |
|
608 | if meth == 'pdoc': | |
609 | pmethod(info.obj,oname,formatter) |
|
609 | pmethod(info.obj,oname,formatter) | |
610 | elif meth == 'pinfo': |
|
610 | elif meth == 'pinfo': | |
611 | pmethod(info.obj,oname,formatter,info,**kw) |
|
611 | pmethod(info.obj,oname,formatter,info,**kw) | |
612 | else: |
|
612 | else: | |
613 | pmethod(info.obj,oname) |
|
613 | pmethod(info.obj,oname) | |
614 | else: |
|
614 | else: | |
615 | print 'Object `%s` not found.' % oname |
|
615 | print 'Object `%s` not found.' % oname | |
616 | return 'not found' # so callers can take other action |
|
616 | return 'not found' # so callers can take other action | |
617 |
|
617 | |||
618 | def magic_pdef(self, parameter_s=''): |
|
618 | def magic_pdef(self, parameter_s=''): | |
619 | """Print the definition header for any callable object. |
|
619 | """Print the definition header for any callable object. | |
620 |
|
620 | |||
621 | If the object is a class, print the constructor information.""" |
|
621 | If the object is a class, print the constructor information.""" | |
622 | self._inspect('pdef',parameter_s) |
|
622 | self._inspect('pdef',parameter_s) | |
623 |
|
623 | |||
624 | def magic_pdoc(self, parameter_s=''): |
|
624 | def magic_pdoc(self, parameter_s=''): | |
625 | """Print the docstring for an object. |
|
625 | """Print the docstring for an object. | |
626 |
|
626 | |||
627 | If the given object is a class, it will print both the class and the |
|
627 | If the given object is a class, it will print both the class and the | |
628 | constructor docstrings.""" |
|
628 | constructor docstrings.""" | |
629 | self._inspect('pdoc',parameter_s) |
|
629 | self._inspect('pdoc',parameter_s) | |
630 |
|
630 | |||
631 | def magic_psource(self, parameter_s=''): |
|
631 | def magic_psource(self, parameter_s=''): | |
632 | """Print (or run through pager) the source code for an object.""" |
|
632 | """Print (or run through pager) the source code for an object.""" | |
633 | self._inspect('psource',parameter_s) |
|
633 | self._inspect('psource',parameter_s) | |
634 |
|
634 | |||
635 | def magic_pfile(self, parameter_s=''): |
|
635 | def magic_pfile(self, parameter_s=''): | |
636 | """Print (or run through pager) the file where an object is defined. |
|
636 | """Print (or run through pager) the file where an object is defined. | |
637 |
|
637 | |||
638 | The file opens at the line where the object definition begins. IPython |
|
638 | The file opens at the line where the object definition begins. IPython | |
639 | will honor the environment variable PAGER if set, and otherwise will |
|
639 | will honor the environment variable PAGER if set, and otherwise will | |
640 | do its best to print the file in a convenient form. |
|
640 | do its best to print the file in a convenient form. | |
641 |
|
641 | |||
642 | If the given argument is not an object currently defined, IPython will |
|
642 | If the given argument is not an object currently defined, IPython will | |
643 | try to interpret it as a filename (automatically adding a .py extension |
|
643 | try to interpret it as a filename (automatically adding a .py extension | |
644 | if needed). You can thus use %pfile as a syntax highlighting code |
|
644 | if needed). You can thus use %pfile as a syntax highlighting code | |
645 | viewer.""" |
|
645 | viewer.""" | |
646 |
|
646 | |||
647 | # first interpret argument as an object name |
|
647 | # first interpret argument as an object name | |
648 | out = self._inspect('pfile',parameter_s) |
|
648 | out = self._inspect('pfile',parameter_s) | |
649 | # if not, try the input as a filename |
|
649 | # if not, try the input as a filename | |
650 | if out == 'not found': |
|
650 | if out == 'not found': | |
651 | try: |
|
651 | try: | |
652 | filename = get_py_filename(parameter_s) |
|
652 | filename = get_py_filename(parameter_s) | |
653 | except IOError,msg: |
|
653 | except IOError,msg: | |
654 | print msg |
|
654 | print msg | |
655 | return |
|
655 | return | |
656 | page(self.shell.inspector.format(file(filename).read())) |
|
656 | page(self.shell.inspector.format(file(filename).read())) | |
657 |
|
657 | |||
658 | def magic_pinfo(self, parameter_s=''): |
|
658 | def magic_pinfo(self, parameter_s=''): | |
659 | """Provide detailed information about an object. |
|
659 | """Provide detailed information about an object. | |
660 |
|
660 | |||
661 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
661 | '%pinfo object' is just a synonym for object? or ?object.""" | |
662 |
|
662 | |||
663 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
663 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
664 |
|
664 | |||
665 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
665 | # detail_level: 0 -> obj? , 1 -> obj?? | |
666 | detail_level = 0 |
|
666 | detail_level = 0 | |
667 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
667 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
668 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
668 | # happen if the user types 'pinfo foo?' at the cmd line. | |
669 | pinfo,qmark1,oname,qmark2 = \ |
|
669 | pinfo,qmark1,oname,qmark2 = \ | |
670 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
670 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
671 | if pinfo or qmark1 or qmark2: |
|
671 | if pinfo or qmark1 or qmark2: | |
672 | detail_level = 1 |
|
672 | detail_level = 1 | |
673 | self._inspect('pinfo',oname,detail_level=detail_level) |
|
673 | self._inspect('pinfo',oname,detail_level=detail_level) | |
674 |
|
674 | |||
675 | def magic_who_ls(self, parameter_s=''): |
|
675 | def magic_who_ls(self, parameter_s=''): | |
676 | """Return a sorted list of all interactive variables. |
|
676 | """Return a sorted list of all interactive variables. | |
677 |
|
677 | |||
678 | If arguments are given, only variables of types matching these |
|
678 | If arguments are given, only variables of types matching these | |
679 | arguments are returned.""" |
|
679 | arguments are returned.""" | |
680 |
|
680 | |||
681 | user_ns = self.shell.user_ns |
|
681 | user_ns = self.shell.user_ns | |
682 | out = [] |
|
682 | out = [] | |
683 | typelist = parameter_s.split() |
|
683 | typelist = parameter_s.split() | |
684 | for i in self.shell.user_ns.keys(): |
|
684 | for i in self.shell.user_ns.keys(): | |
685 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
685 | if not (i.startswith('_') or i.startswith('_i')) \ | |
686 | and not (self.internal_ns.has_key(i) or |
|
686 | and not (self.internal_ns.has_key(i) or | |
687 | self.user_config_ns.has_key(i)): |
|
687 | self.user_config_ns.has_key(i)): | |
688 | if typelist: |
|
688 | if typelist: | |
689 | if type(user_ns[i]).__name__ in typelist: |
|
689 | if type(user_ns[i]).__name__ in typelist: | |
690 | out.append(i) |
|
690 | out.append(i) | |
691 | else: |
|
691 | else: | |
692 | out.append(i) |
|
692 | out.append(i) | |
693 | out.sort() |
|
693 | out.sort() | |
694 | return out |
|
694 | return out | |
695 |
|
695 | |||
696 | def magic_who(self, parameter_s=''): |
|
696 | def magic_who(self, parameter_s=''): | |
697 | """Print all interactive variables, with some minimal formatting. |
|
697 | """Print all interactive variables, with some minimal formatting. | |
698 |
|
698 | |||
699 | If any arguments are given, only variables whose type matches one of |
|
699 | If any arguments are given, only variables whose type matches one of | |
700 | these are printed. For example: |
|
700 | these are printed. For example: | |
701 |
|
701 | |||
702 | %who function str |
|
702 | %who function str | |
703 |
|
703 | |||
704 | will only list functions and strings, excluding all other types of |
|
704 | will only list functions and strings, excluding all other types of | |
705 | variables. To find the proper type names, simply use type(var) at a |
|
705 | variables. To find the proper type names, simply use type(var) at a | |
706 | command line to see how python prints type names. For example: |
|
706 | command line to see how python prints type names. For example: | |
707 |
|
707 | |||
708 | In [1]: type('hello')\\ |
|
708 | In [1]: type('hello')\\ | |
709 | Out[1]: <type 'str'> |
|
709 | Out[1]: <type 'str'> | |
710 |
|
710 | |||
711 | indicates that the type name for strings is 'str'. |
|
711 | indicates that the type name for strings is 'str'. | |
712 |
|
712 | |||
713 | %who always excludes executed names loaded through your configuration |
|
713 | %who always excludes executed names loaded through your configuration | |
714 | file and things which are internal to IPython. |
|
714 | file and things which are internal to IPython. | |
715 |
|
715 | |||
716 | This is deliberate, as typically you may load many modules and the |
|
716 | This is deliberate, as typically you may load many modules and the | |
717 | purpose of %who is to show you only what you've manually defined.""" |
|
717 | purpose of %who is to show you only what you've manually defined.""" | |
718 |
|
718 | |||
719 | varlist = self.magic_who_ls(parameter_s) |
|
719 | varlist = self.magic_who_ls(parameter_s) | |
720 | if not varlist: |
|
720 | if not varlist: | |
721 | print 'Interactive namespace is empty.' |
|
721 | print 'Interactive namespace is empty.' | |
722 | return |
|
722 | return | |
723 |
|
723 | |||
724 | # if we have variables, move on... |
|
724 | # if we have variables, move on... | |
725 |
|
725 | |||
726 | # stupid flushing problem: when prompts have no separators, stdout is |
|
726 | # stupid flushing problem: when prompts have no separators, stdout is | |
727 | # getting lost. I'm starting to think this is a python bug. I'm having |
|
727 | # getting lost. I'm starting to think this is a python bug. I'm having | |
728 | # to force a flush with a print because even a sys.stdout.flush |
|
728 | # to force a flush with a print because even a sys.stdout.flush | |
729 | # doesn't seem to do anything! |
|
729 | # doesn't seem to do anything! | |
730 |
|
730 | |||
731 | count = 0 |
|
731 | count = 0 | |
732 | for i in varlist: |
|
732 | for i in varlist: | |
733 | print i+'\t', |
|
733 | print i+'\t', | |
734 | count += 1 |
|
734 | count += 1 | |
735 | if count > 8: |
|
735 | if count > 8: | |
736 | count = 0 |
|
736 | count = 0 | |
737 |
|
737 | |||
738 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? |
|
738 | sys.stdout.flush() # FIXME. Why the hell isn't this flushing??? | |
739 |
|
739 | |||
740 | print # well, this does force a flush at the expense of an extra \n |
|
740 | print # well, this does force a flush at the expense of an extra \n | |
741 |
|
741 | |||
742 | def magic_whos(self, parameter_s=''): |
|
742 | def magic_whos(self, parameter_s=''): | |
743 | """Like %who, but gives some extra information about each variable. |
|
743 | """Like %who, but gives some extra information about each variable. | |
744 |
|
744 | |||
745 | The same type filtering of %who can be applied here. |
|
745 | The same type filtering of %who can be applied here. | |
746 |
|
746 | |||
747 | For all variables, the type is printed. Additionally it prints: |
|
747 | For all variables, the type is printed. Additionally it prints: | |
748 |
|
748 | |||
749 | - For {},[],(): their length. |
|
749 | - For {},[],(): their length. | |
750 |
|
750 | |||
751 | - For Numeric arrays, a summary with shape, number of elements, |
|
751 | - For Numeric arrays, a summary with shape, number of elements, | |
752 | typecode and size in memory. |
|
752 | typecode and size in memory. | |
753 |
|
753 | |||
754 | - Everything else: a string representation, snipping their middle if |
|
754 | - Everything else: a string representation, snipping their middle if | |
755 | too long.""" |
|
755 | too long.""" | |
756 |
|
756 | |||
757 | varnames = self.magic_who_ls(parameter_s) |
|
757 | varnames = self.magic_who_ls(parameter_s) | |
758 | if not varnames: |
|
758 | if not varnames: | |
759 | print 'Interactive namespace is empty.' |
|
759 | print 'Interactive namespace is empty.' | |
760 | return |
|
760 | return | |
761 |
|
761 | |||
762 | # if we have variables, move on... |
|
762 | # if we have variables, move on... | |
763 |
|
763 | |||
764 | # for these types, show len() instead of data: |
|
764 | # for these types, show len() instead of data: | |
765 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
765 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
766 |
|
766 | |||
767 | # for Numeric arrays, display summary info |
|
767 | # for Numeric arrays, display summary info | |
768 | try: |
|
768 | try: | |
769 | import Numeric |
|
769 | import Numeric | |
770 | except ImportError: |
|
770 | except ImportError: | |
771 | array_type = None |
|
771 | array_type = None | |
772 | else: |
|
772 | else: | |
773 | array_type = Numeric.ArrayType.__name__ |
|
773 | array_type = Numeric.ArrayType.__name__ | |
774 |
|
774 | |||
775 | # Find all variable names and types so we can figure out column sizes |
|
775 | # Find all variable names and types so we can figure out column sizes | |
776 | get_vars = lambda i: self.locals[i] |
|
776 | get_vars = lambda i: self.locals[i] | |
777 | type_name = lambda v: type(v).__name__ |
|
777 | type_name = lambda v: type(v).__name__ | |
778 | varlist = map(get_vars,varnames) |
|
778 | varlist = map(get_vars,varnames) | |
779 | typelist = map(type_name,varlist) |
|
779 | typelist = map(type_name,varlist) | |
780 | # column labels and # of spaces as separator |
|
780 | # column labels and # of spaces as separator | |
781 | varlabel = 'Variable' |
|
781 | varlabel = 'Variable' | |
782 | typelabel = 'Type' |
|
782 | typelabel = 'Type' | |
783 | datalabel = 'Data/Info' |
|
783 | datalabel = 'Data/Info' | |
784 | colsep = 3 |
|
784 | colsep = 3 | |
785 | # variable format strings |
|
785 | # variable format strings | |
786 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
786 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
787 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
787 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
788 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
788 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
789 | # find the size of the columns to format the output nicely |
|
789 | # find the size of the columns to format the output nicely | |
790 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
790 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
791 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
791 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
792 | # table header |
|
792 | # table header | |
793 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
793 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
794 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
794 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
795 | # and the table itself |
|
795 | # and the table itself | |
796 | kb = 1024 |
|
796 | kb = 1024 | |
797 | Mb = 1048576 # kb**2 |
|
797 | Mb = 1048576 # kb**2 | |
798 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
798 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
799 | print itpl(vformat), |
|
799 | print itpl(vformat), | |
800 | if vtype in seq_types: |
|
800 | if vtype in seq_types: | |
801 | print len(var) |
|
801 | print len(var) | |
802 | elif vtype==array_type: |
|
802 | elif vtype==array_type: | |
803 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
803 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
804 | vsize = Numeric.size(var) |
|
804 | vsize = Numeric.size(var) | |
805 | vbytes = vsize*var.itemsize() |
|
805 | vbytes = vsize*var.itemsize() | |
806 | if vbytes < 100000: |
|
806 | if vbytes < 100000: | |
807 | print aformat % (vshape,vsize,var.typecode(),vbytes) |
|
807 | print aformat % (vshape,vsize,var.typecode(),vbytes) | |
808 | else: |
|
808 | else: | |
809 | print aformat % (vshape,vsize,var.typecode(),vbytes), |
|
809 | print aformat % (vshape,vsize,var.typecode(),vbytes), | |
810 | if vbytes < Mb: |
|
810 | if vbytes < Mb: | |
811 | print '(%s kb)' % (vbytes/kb,) |
|
811 | print '(%s kb)' % (vbytes/kb,) | |
812 | else: |
|
812 | else: | |
813 | print '(%s Mb)' % (vbytes/Mb,) |
|
813 | print '(%s Mb)' % (vbytes/Mb,) | |
814 | else: |
|
814 | else: | |
815 | vstr = str(var) |
|
815 | vstr = str(var) | |
816 | if len(vstr) < 50: |
|
816 | if len(vstr) < 50: | |
817 | print vstr |
|
817 | print vstr | |
818 | else: |
|
818 | else: | |
819 | printpl(vfmt_short) |
|
819 | printpl(vfmt_short) | |
820 |
|
820 | |||
821 | def magic_reset(self, parameter_s=''): |
|
821 | def magic_reset(self, parameter_s=''): | |
822 | """Resets the namespace by removing all names defined by the user. |
|
822 | """Resets the namespace by removing all names defined by the user. | |
823 |
|
823 | |||
824 | Input/Output history are left around in case you need them.""" |
|
824 | Input/Output history are left around in case you need them.""" | |
825 |
|
825 | |||
826 | ans = raw_input( |
|
826 | ans = raw_input( | |
827 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") |
|
827 | "Once deleted, variables cannot be recovered. Proceed (y/n)? ") | |
828 | if not ans.lower() == 'y': |
|
828 | if not ans.lower() == 'y': | |
829 | print 'Nothing done.' |
|
829 | print 'Nothing done.' | |
830 | return |
|
830 | return | |
831 | for i in self.magic_who_ls(): |
|
831 | for i in self.magic_who_ls(): | |
832 | del(self.locals[i]) |
|
832 | del(self.locals[i]) | |
833 |
|
833 | |||
834 | def magic_config(self,parameter_s=''): |
|
834 | def magic_config(self,parameter_s=''): | |
835 | """Show IPython's internal configuration.""" |
|
835 | """Show IPython's internal configuration.""" | |
836 |
|
836 | |||
837 | page('Current configuration structure:\n'+ |
|
837 | page('Current configuration structure:\n'+ | |
838 | pformat(self.shell.rc.dict())) |
|
838 | pformat(self.shell.rc.dict())) | |
839 |
|
839 | |||
840 | def magic_logstart(self,parameter_s=''): |
|
840 | def magic_logstart(self,parameter_s=''): | |
841 | """Start logging anywhere in a session. |
|
841 | """Start logging anywhere in a session. | |
842 |
|
842 | |||
843 | %logstart [log_name [log_mode]] |
|
843 | %logstart [log_name [log_mode]] | |
844 |
|
844 | |||
845 | If no name is given, it defaults to a file named 'ipython.log' in your |
|
845 | If no name is given, it defaults to a file named 'ipython.log' in your | |
846 | current directory, in 'rotate' mode (see below). |
|
846 | current directory, in 'rotate' mode (see below). | |
847 |
|
847 | |||
848 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
848 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
849 | history up to that point and then continues logging. |
|
849 | history up to that point and then continues logging. | |
850 |
|
850 | |||
851 | %logstart takes a second optional parameter: logging mode. This can be one |
|
851 | %logstart takes a second optional parameter: logging mode. This can be one | |
852 | of (note that the modes are given unquoted):\\ |
|
852 | of (note that the modes are given unquoted):\\ | |
853 | over: overwrite existing log.\\ |
|
853 | over: overwrite existing log.\\ | |
854 | backup: rename (if exists) to name~ and start name.\\ |
|
854 | backup: rename (if exists) to name~ and start name.\\ | |
855 | append: well, that says it.\\ |
|
855 | append: well, that says it.\\ | |
856 | rotate: create rotating logs name.1~, name.2~, etc. |
|
856 | rotate: create rotating logs name.1~, name.2~, etc. | |
857 | """ |
|
857 | """ | |
858 |
|
858 | |||
859 | #FIXME. This function should all be moved to the Logger class. |
|
859 | #FIXME. This function should all be moved to the Logger class. | |
860 |
|
860 | |||
861 | valid_modes = qw('over backup append rotate') |
|
861 | valid_modes = qw('over backup append rotate') | |
862 | if self.LOG: |
|
862 | if self.LOG: | |
863 | print 'Logging is already in place. Logfile:',self.LOG |
|
863 | print 'Logging is already in place. Logfile:',self.LOG | |
864 | return |
|
864 | return | |
865 |
|
865 | |||
866 | par = parameter_s.strip() |
|
866 | par = parameter_s.strip() | |
867 | if not par: |
|
867 | if not par: | |
868 | logname = self.LOGDEF |
|
868 | logname = self.LOGDEF | |
869 | logmode = 'rotate' # use rotate for the auto-generated logs |
|
869 | logmode = 'rotate' # use rotate for the auto-generated logs | |
870 | else: |
|
870 | else: | |
871 | try: |
|
871 | try: | |
872 | logname,logmode = par.split() |
|
872 | logname,logmode = par.split() | |
873 | except: |
|
873 | except: | |
874 | try: |
|
874 | try: | |
875 | logname = par |
|
875 | logname = par | |
876 | logmode = 'backup' |
|
876 | logmode = 'backup' | |
877 | except: |
|
877 | except: | |
878 | warn('Usage: %log [log_name [log_mode]]') |
|
878 | warn('Usage: %log [log_name [log_mode]]') | |
879 | return |
|
879 | return | |
880 | if not logmode in valid_modes: |
|
880 | if not logmode in valid_modes: | |
881 | warn('Logging NOT activated.\n' |
|
881 | warn('Logging NOT activated.\n' | |
882 | 'Usage: %log [log_name [log_mode]]\n' |
|
882 | 'Usage: %log [log_name [log_mode]]\n' | |
883 | 'Valid modes: '+str(valid_modes)) |
|
883 | 'Valid modes: '+str(valid_modes)) | |
884 | return |
|
884 | return | |
885 |
|
885 | |||
886 | # If we made it this far, I think we're ok: |
|
886 | # If we made it this far, I think we're ok: | |
887 | print 'Activating auto-logging.' |
|
887 | print 'Activating auto-logging.' | |
888 | print 'Current session state plus future input saved to:',logname |
|
888 | print 'Current session state plus future input saved to:',logname | |
889 | print 'Logging mode: ',logmode |
|
889 | print 'Logging mode: ',logmode | |
890 | # put logname into rc struct as if it had been called on the command line, |
|
890 | # put logname into rc struct as if it had been called on the command line, | |
891 | # so it ends up saved in the log header |
|
891 | # so it ends up saved in the log header | |
892 | # Save it in case we need to restore it... |
|
892 | # Save it in case we need to restore it... | |
893 | old_logfile = self.shell.rc.opts.get('logfile','') |
|
893 | old_logfile = self.shell.rc.opts.get('logfile','') | |
894 | logname = os.path.expanduser(logname) |
|
894 | logname = os.path.expanduser(logname) | |
895 | self.shell.rc.opts.logfile = logname |
|
895 | self.shell.rc.opts.logfile = logname | |
896 | self.LOGMODE = logmode # FIXME: this should be set through a function. |
|
896 | self.LOGMODE = logmode # FIXME: this should be set through a function. | |
897 | try: |
|
897 | try: | |
898 | header = str(self.LOGHEAD) |
|
898 | header = str(self.LOGHEAD) | |
899 | self.create_log(header,logname) |
|
899 | self.create_log(header,logname) | |
900 | self.logstart(header,logname) |
|
900 | self.logstart(header,logname) | |
901 | except: |
|
901 | except: | |
902 | self.LOG = '' # we are NOT logging, something went wrong |
|
902 | self.LOG = '' # we are NOT logging, something went wrong | |
903 | self.shell.rc.opts.logfile = old_logfile |
|
903 | self.shell.rc.opts.logfile = old_logfile | |
904 | warn("Couldn't start log: "+str(sys.exc_info()[1])) |
|
904 | warn("Couldn't start log: "+str(sys.exc_info()[1])) | |
905 | else: # log input history up to this point |
|
905 | else: # log input history up to this point | |
906 | self.logfile.write(self.shell.user_ns['_ih'][1:]) |
|
906 | self.logfile.write(self.shell.user_ns['_ih'][1:]) | |
907 | self.logfile.flush() |
|
907 | self.logfile.flush() | |
908 |
|
908 | |||
909 | def magic_logoff(self,parameter_s=''): |
|
909 | def magic_logoff(self,parameter_s=''): | |
910 | """Temporarily stop logging. |
|
910 | """Temporarily stop logging. | |
911 |
|
911 | |||
912 | You must have previously started logging.""" |
|
912 | You must have previously started logging.""" | |
913 | self.switch_log(0) |
|
913 | self.switch_log(0) | |
914 |
|
914 | |||
915 | def magic_logon(self,parameter_s=''): |
|
915 | def magic_logon(self,parameter_s=''): | |
916 | """Restart logging. |
|
916 | """Restart logging. | |
917 |
|
917 | |||
918 | This function is for restarting logging which you've temporarily |
|
918 | This function is for restarting logging which you've temporarily | |
919 | stopped with %logoff. For starting logging for the first time, you |
|
919 | stopped with %logoff. For starting logging for the first time, you | |
920 | must use the %logstart function, which allows you to specify an |
|
920 | must use the %logstart function, which allows you to specify an | |
921 | optional log filename.""" |
|
921 | optional log filename.""" | |
922 |
|
922 | |||
923 | self.switch_log(1) |
|
923 | self.switch_log(1) | |
924 |
|
924 | |||
925 | def magic_logstate(self,parameter_s=''): |
|
925 | def magic_logstate(self,parameter_s=''): | |
926 | """Print the status of the logging system.""" |
|
926 | """Print the status of the logging system.""" | |
927 |
|
927 | |||
928 | self.logstate() |
|
928 | self.logstate() | |
929 |
|
929 | |||
930 | def magic_pdb(self, parameter_s=''): |
|
930 | def magic_pdb(self, parameter_s=''): | |
931 | """Control the calling of the pdb interactive debugger. |
|
931 | """Control the calling of the pdb interactive debugger. | |
932 |
|
932 | |||
933 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
933 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
934 | argument it works as a toggle. |
|
934 | argument it works as a toggle. | |
935 |
|
935 | |||
936 | When an exception is triggered, IPython can optionally call the |
|
936 | When an exception is triggered, IPython can optionally call the | |
937 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
937 | interactive pdb debugger after the traceback printout. %pdb toggles | |
938 | this feature on and off.""" |
|
938 | this feature on and off.""" | |
939 |
|
939 | |||
940 | par = parameter_s.strip().lower() |
|
940 | par = parameter_s.strip().lower() | |
941 |
|
941 | |||
942 | if par: |
|
942 | if par: | |
943 | try: |
|
943 | try: | |
944 | pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
944 | pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
945 | except KeyError: |
|
945 | except KeyError: | |
946 | print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.' |
|
946 | print 'Incorrect argument. Use on/1, off/0 or nothing for a toggle.' | |
947 | return |
|
947 | return | |
948 | else: |
|
948 | else: | |
949 | self.shell.InteractiveTB.call_pdb = pdb |
|
949 | self.shell.InteractiveTB.call_pdb = pdb | |
950 | else: |
|
950 | else: | |
951 | self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb |
|
951 | self.shell.InteractiveTB.call_pdb = 1 - self.shell.InteractiveTB.call_pdb | |
952 | print 'Automatic pdb calling has been turned',\ |
|
952 | print 'Automatic pdb calling has been turned',\ | |
953 | on_off(self.shell.InteractiveTB.call_pdb) |
|
953 | on_off(self.shell.InteractiveTB.call_pdb) | |
954 |
|
954 | |||
955 |
|
955 | |||
956 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
956 | def magic_prun(self, parameter_s ='',user_mode=1, | |
957 | opts=None,arg_lst=None,prog_ns=None): |
|
957 | opts=None,arg_lst=None,prog_ns=None): | |
958 |
|
958 | |||
959 | """Run a statement through the python code profiler. |
|
959 | """Run a statement through the python code profiler. | |
960 |
|
960 | |||
961 | Usage:\\ |
|
961 | Usage:\\ | |
962 | %prun [options] statement |
|
962 | %prun [options] statement | |
963 |
|
963 | |||
964 | The given statement (which doesn't require quote marks) is run via the |
|
964 | The given statement (which doesn't require quote marks) is run via the | |
965 | python profiler in a manner similar to the profile.run() function. |
|
965 | python profiler in a manner similar to the profile.run() function. | |
966 | Namespaces are internally managed to work correctly; profile.run |
|
966 | Namespaces are internally managed to work correctly; profile.run | |
967 | cannot be used in IPython because it makes certain assumptions about |
|
967 | cannot be used in IPython because it makes certain assumptions about | |
968 | namespaces which do not hold under IPython. |
|
968 | namespaces which do not hold under IPython. | |
969 |
|
969 | |||
970 | Options: |
|
970 | Options: | |
971 |
|
971 | |||
972 | -l <limit>: you can place restrictions on what or how much of the |
|
972 | -l <limit>: you can place restrictions on what or how much of the | |
973 | profile gets printed. The limit value can be: |
|
973 | profile gets printed. The limit value can be: | |
974 |
|
974 | |||
975 | * A string: only information for function names containing this string |
|
975 | * A string: only information for function names containing this string | |
976 | is printed. |
|
976 | is printed. | |
977 |
|
977 | |||
978 | * An integer: only these many lines are printed. |
|
978 | * An integer: only these many lines are printed. | |
979 |
|
979 | |||
980 | * A float (between 0 and 1): this fraction of the report is printed |
|
980 | * A float (between 0 and 1): this fraction of the report is printed | |
981 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
981 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
982 |
|
982 | |||
983 | You can combine several limits with repeated use of the option. For |
|
983 | You can combine several limits with repeated use of the option. For | |
984 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
984 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
985 | information about class constructors. |
|
985 | information about class constructors. | |
986 |
|
986 | |||
987 | -r: return the pstats.Stats object generated by the profiling. This |
|
987 | -r: return the pstats.Stats object generated by the profiling. This | |
988 | object has all the information about the profile in it, and you can |
|
988 | object has all the information about the profile in it, and you can | |
989 | later use it for further analysis or in other functions. |
|
989 | later use it for further analysis or in other functions. | |
990 |
|
990 | |||
991 | Since magic functions have a particular form of calling which prevents |
|
991 | Since magic functions have a particular form of calling which prevents | |
992 | you from writing something like:\\ |
|
992 | you from writing something like:\\ | |
993 | In [1]: p = %prun -r print 4 # invalid!\\ |
|
993 | In [1]: p = %prun -r print 4 # invalid!\\ | |
994 | you must instead use IPython's automatic variables to assign this:\\ |
|
994 | you must instead use IPython's automatic variables to assign this:\\ | |
995 | In [1]: %prun -r print 4 \\ |
|
995 | In [1]: %prun -r print 4 \\ | |
996 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ |
|
996 | Out[1]: <pstats.Stats instance at 0x8222cec>\\ | |
997 | In [2]: stats = _ |
|
997 | In [2]: stats = _ | |
998 |
|
998 | |||
999 | If you really need to assign this value via an explicit function call, |
|
999 | If you really need to assign this value via an explicit function call, | |
1000 | you can always tap directly into the true name of the magic function |
|
1000 | you can always tap directly into the true name of the magic function | |
1001 | by using the ipmagic function (which IPython automatically adds to the |
|
1001 | by using the ipmagic function (which IPython automatically adds to the | |
1002 | builtins):\\ |
|
1002 | builtins):\\ | |
1003 | In [3]: stats = ipmagic('prun','-r print 4') |
|
1003 | In [3]: stats = ipmagic('prun','-r print 4') | |
1004 |
|
1004 | |||
1005 | You can type ipmagic? for more details on ipmagic. |
|
1005 | You can type ipmagic? for more details on ipmagic. | |
1006 |
|
1006 | |||
1007 | -s <key>: sort profile by given key. You can provide more than one key |
|
1007 | -s <key>: sort profile by given key. You can provide more than one key | |
1008 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1008 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1009 | default sorting key is 'time'. |
|
1009 | default sorting key is 'time'. | |
1010 |
|
1010 | |||
1011 | The following is copied verbatim from the profile documentation |
|
1011 | The following is copied verbatim from the profile documentation | |
1012 | referenced below: |
|
1012 | referenced below: | |
1013 |
|
1013 | |||
1014 | When more than one key is provided, additional keys are used as |
|
1014 | When more than one key is provided, additional keys are used as | |
1015 | secondary criteria when the there is equality in all keys selected |
|
1015 | secondary criteria when the there is equality in all keys selected | |
1016 | before them. |
|
1016 | before them. | |
1017 |
|
1017 | |||
1018 | Abbreviations can be used for any key names, as long as the |
|
1018 | Abbreviations can be used for any key names, as long as the | |
1019 | abbreviation is unambiguous. The following are the keys currently |
|
1019 | abbreviation is unambiguous. The following are the keys currently | |
1020 | defined: |
|
1020 | defined: | |
1021 |
|
1021 | |||
1022 | Valid Arg Meaning\\ |
|
1022 | Valid Arg Meaning\\ | |
1023 | "calls" call count\\ |
|
1023 | "calls" call count\\ | |
1024 | "cumulative" cumulative time\\ |
|
1024 | "cumulative" cumulative time\\ | |
1025 | "file" file name\\ |
|
1025 | "file" file name\\ | |
1026 | "module" file name\\ |
|
1026 | "module" file name\\ | |
1027 | "pcalls" primitive call count\\ |
|
1027 | "pcalls" primitive call count\\ | |
1028 | "line" line number\\ |
|
1028 | "line" line number\\ | |
1029 | "name" function name\\ |
|
1029 | "name" function name\\ | |
1030 | "nfl" name/file/line\\ |
|
1030 | "nfl" name/file/line\\ | |
1031 | "stdname" standard name\\ |
|
1031 | "stdname" standard name\\ | |
1032 | "time" internal time |
|
1032 | "time" internal time | |
1033 |
|
1033 | |||
1034 | Note that all sorts on statistics are in descending order (placing |
|
1034 | Note that all sorts on statistics are in descending order (placing | |
1035 | most time consuming items first), where as name, file, and line number |
|
1035 | most time consuming items first), where as name, file, and line number | |
1036 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1036 | searches are in ascending order (i.e., alphabetical). The subtle | |
1037 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1037 | distinction between "nfl" and "stdname" is that the standard name is a | |
1038 | sort of the name as printed, which means that the embedded line |
|
1038 | sort of the name as printed, which means that the embedded line | |
1039 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1039 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1040 | would (if the file names were the same) appear in the string order |
|
1040 | would (if the file names were the same) appear in the string order | |
1041 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1041 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1042 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1042 | line numbers. In fact, sort_stats("nfl") is the same as | |
1043 | sort_stats("name", "file", "line"). |
|
1043 | sort_stats("name", "file", "line"). | |
1044 |
|
1044 | |||
1045 | -T <filename>: save profile results as shown on screen to a text |
|
1045 | -T <filename>: save profile results as shown on screen to a text | |
1046 | file. The profile is still shown on screen. |
|
1046 | file. The profile is still shown on screen. | |
1047 |
|
1047 | |||
1048 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1048 | -D <filename>: save (via dump_stats) profile statistics to given | |
1049 | filename. This data is in a format understod by the pstats module, and |
|
1049 | filename. This data is in a format understod by the pstats module, and | |
1050 | is generated by a call to the dump_stats() method of profile |
|
1050 | is generated by a call to the dump_stats() method of profile | |
1051 | objects. The profile is still shown on screen. |
|
1051 | objects. The profile is still shown on screen. | |
1052 |
|
1052 | |||
1053 | If you want to run complete programs under the profiler's control, use |
|
1053 | If you want to run complete programs under the profiler's control, use | |
1054 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1054 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1055 | contains profiler specific options as described here. |
|
1055 | contains profiler specific options as described here. | |
1056 |
|
1056 | |||
1057 | You can read the complete documentation for the profile module with:\\ |
|
1057 | You can read the complete documentation for the profile module with:\\ | |
1058 | In [1]: import profile; profile.help() """ |
|
1058 | In [1]: import profile; profile.help() """ | |
1059 |
|
1059 | |||
1060 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1060 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1061 | # protect user quote marks |
|
1061 | # protect user quote marks | |
1062 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1062 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1063 |
|
1063 | |||
1064 | if user_mode: # regular user call |
|
1064 | if user_mode: # regular user call | |
1065 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1065 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1066 | list_all=1) |
|
1066 | list_all=1) | |
1067 | namespace = self.shell.user_ns |
|
1067 | namespace = self.shell.user_ns | |
1068 | else: # called to run a program by %run -p |
|
1068 | else: # called to run a program by %run -p | |
1069 | try: |
|
1069 | try: | |
1070 | filename = get_py_filename(arg_lst[0]) |
|
1070 | filename = get_py_filename(arg_lst[0]) | |
1071 | except IOError,msg: |
|
1071 | except IOError,msg: | |
1072 | error(msg) |
|
1072 | error(msg) | |
1073 | return |
|
1073 | return | |
1074 |
|
1074 | |||
1075 | arg_str = 'execfile(filename,prog_ns)' |
|
1075 | arg_str = 'execfile(filename,prog_ns)' | |
1076 | namespace = locals() |
|
1076 | namespace = locals() | |
1077 |
|
1077 | |||
1078 | opts.merge(opts_def) |
|
1078 | opts.merge(opts_def) | |
1079 |
|
1079 | |||
1080 | prof = profile.Profile() |
|
1080 | prof = profile.Profile() | |
1081 | try: |
|
1081 | try: | |
1082 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1082 | prof = prof.runctx(arg_str,namespace,namespace) | |
1083 | sys_exit = '' |
|
1083 | sys_exit = '' | |
1084 | except SystemExit: |
|
1084 | except SystemExit: | |
1085 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1085 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1086 |
|
1086 | |||
1087 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1087 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1088 |
|
1088 | |||
1089 | lims = opts.l |
|
1089 | lims = opts.l | |
1090 | if lims: |
|
1090 | if lims: | |
1091 | lims = [] # rebuild lims with ints/floats/strings |
|
1091 | lims = [] # rebuild lims with ints/floats/strings | |
1092 | for lim in opts.l: |
|
1092 | for lim in opts.l: | |
1093 | try: |
|
1093 | try: | |
1094 | lims.append(int(lim)) |
|
1094 | lims.append(int(lim)) | |
1095 | except ValueError: |
|
1095 | except ValueError: | |
1096 | try: |
|
1096 | try: | |
1097 | lims.append(float(lim)) |
|
1097 | lims.append(float(lim)) | |
1098 | except ValueError: |
|
1098 | except ValueError: | |
1099 | lims.append(lim) |
|
1099 | lims.append(lim) | |
1100 |
|
1100 | |||
1101 | # trap output |
|
1101 | # trap output | |
1102 | sys_stdout = sys.stdout |
|
1102 | sys_stdout = sys.stdout | |
1103 | stdout_trap = StringIO() |
|
1103 | stdout_trap = StringIO() | |
1104 | try: |
|
1104 | try: | |
1105 | sys.stdout = stdout_trap |
|
1105 | sys.stdout = stdout_trap | |
1106 | stats.print_stats(*lims) |
|
1106 | stats.print_stats(*lims) | |
1107 | finally: |
|
1107 | finally: | |
1108 | sys.stdout = sys_stdout |
|
1108 | sys.stdout = sys_stdout | |
1109 | output = stdout_trap.getvalue() |
|
1109 | output = stdout_trap.getvalue() | |
1110 | output = output.rstrip() |
|
1110 | output = output.rstrip() | |
1111 |
|
1111 | |||
1112 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1112 | page(output,screen_lines=self.shell.rc.screen_length) | |
1113 | print sys_exit, |
|
1113 | print sys_exit, | |
1114 |
|
1114 | |||
1115 | dump_file = opts.D[0] |
|
1115 | dump_file = opts.D[0] | |
1116 | text_file = opts.T[0] |
|
1116 | text_file = opts.T[0] | |
1117 | if dump_file: |
|
1117 | if dump_file: | |
1118 | prof.dump_stats(dump_file) |
|
1118 | prof.dump_stats(dump_file) | |
1119 | print '\n*** Profile stats marshalled to file',\ |
|
1119 | print '\n*** Profile stats marshalled to file',\ | |
1120 | `dump_file`+'.',sys_exit |
|
1120 | `dump_file`+'.',sys_exit | |
1121 | if text_file: |
|
1121 | if text_file: | |
1122 | file(text_file,'w').write(output) |
|
1122 | file(text_file,'w').write(output) | |
1123 | print '\n*** Profile printout saved to text file',\ |
|
1123 | print '\n*** Profile printout saved to text file',\ | |
1124 | `text_file`+'.',sys_exit |
|
1124 | `text_file`+'.',sys_exit | |
1125 |
|
1125 | |||
1126 | if opts.has_key('r'): |
|
1126 | if opts.has_key('r'): | |
1127 | return stats |
|
1127 | return stats | |
1128 | else: |
|
1128 | else: | |
1129 | return None |
|
1129 | return None | |
1130 |
|
1130 | |||
1131 | def magic_run(self, parameter_s ='',runner=None): |
|
1131 | def magic_run(self, parameter_s ='',runner=None): | |
1132 | """Run the named file inside IPython as a program. |
|
1132 | """Run the named file inside IPython as a program. | |
1133 |
|
1133 | |||
1134 | Usage:\\ |
|
1134 | Usage:\\ | |
1135 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1135 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1136 |
|
1136 | |||
1137 | Parameters after the filename are passed as command-line arguments to |
|
1137 | Parameters after the filename are passed as command-line arguments to | |
1138 | the program (put in sys.argv). Then, control returns to IPython's |
|
1138 | the program (put in sys.argv). Then, control returns to IPython's | |
1139 | prompt. |
|
1139 | prompt. | |
1140 |
|
1140 | |||
1141 | This is similar to running at a system prompt:\\ |
|
1141 | This is similar to running at a system prompt:\\ | |
1142 | $ python file args\\ |
|
1142 | $ python file args\\ | |
1143 | but with the advantage of giving you IPython's tracebacks, and of |
|
1143 | but with the advantage of giving you IPython's tracebacks, and of | |
1144 | loading all variables into your interactive namespace for further use |
|
1144 | loading all variables into your interactive namespace for further use | |
1145 | (unless -p is used, see below). |
|
1145 | (unless -p is used, see below). | |
1146 |
|
1146 | |||
1147 | The file is executed in a namespace initially consisting only of |
|
1147 | The file is executed in a namespace initially consisting only of | |
1148 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1148 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1149 | sees its environment as if it were being run as a stand-alone |
|
1149 | sees its environment as if it were being run as a stand-alone | |
1150 | program. But after execution, the IPython interactive namespace gets |
|
1150 | program. But after execution, the IPython interactive namespace gets | |
1151 | updated with all variables defined in the program (except for __name__ |
|
1151 | updated with all variables defined in the program (except for __name__ | |
1152 | and sys.argv). This allows for very convenient loading of code for |
|
1152 | and sys.argv). This allows for very convenient loading of code for | |
1153 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1153 | interactive work, while giving each program a 'clean sheet' to run in. | |
1154 |
|
1154 | |||
1155 | Options: |
|
1155 | Options: | |
1156 |
|
1156 | |||
1157 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1157 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1158 | without extension (as python does under import). This allows running |
|
1158 | without extension (as python does under import). This allows running | |
1159 | scripts and reloading the definitions in them without calling code |
|
1159 | scripts and reloading the definitions in them without calling code | |
1160 | protected by an ' if __name__ == "__main__" ' clause. |
|
1160 | protected by an ' if __name__ == "__main__" ' clause. | |
1161 |
|
1161 | |||
1162 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1162 | -i: run the file in IPython's namespace instead of an empty one. This | |
1163 | is useful if you are experimenting with code written in a text editor |
|
1163 | is useful if you are experimenting with code written in a text editor | |
1164 | which depends on variables defined interactively. |
|
1164 | which depends on variables defined interactively. | |
1165 |
|
1165 | |||
1166 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1166 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1167 | being run. This is particularly useful if IPython is being used to |
|
1167 | being run. This is particularly useful if IPython is being used to | |
1168 | run unittests, which always exit with a sys.exit() call. In such |
|
1168 | run unittests, which always exit with a sys.exit() call. In such | |
1169 | cases you are interested in the output of the test results, not in |
|
1169 | cases you are interested in the output of the test results, not in | |
1170 | seeing a traceback of the unittest module. |
|
1170 | seeing a traceback of the unittest module. | |
1171 |
|
1171 | |||
1172 | -t: print timing information at the end of the run. IPython will give |
|
1172 | -t: print timing information at the end of the run. IPython will give | |
1173 | you an estimated CPU time consumption for your script, which under |
|
1173 | you an estimated CPU time consumption for your script, which under | |
1174 | Unix uses the resource module to avoid the wraparound problems of |
|
1174 | Unix uses the resource module to avoid the wraparound problems of | |
1175 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1175 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1176 | is also given (for Windows platforms this is reported as 0.0). |
|
1176 | is also given (for Windows platforms this is reported as 0.0). | |
1177 |
|
1177 | |||
1178 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1178 | If -t is given, an additional -N<N> option can be given, where <N> | |
1179 | must be an integer indicating how many times you want the script to |
|
1179 | must be an integer indicating how many times you want the script to | |
1180 | run. The final timing report will include total and per run results. |
|
1180 | run. The final timing report will include total and per run results. | |
1181 |
|
1181 | |||
1182 | For example (testing the script uniq_stable.py): |
|
1182 | For example (testing the script uniq_stable.py): | |
1183 |
|
1183 | |||
1184 | In [1]: run -t uniq_stable |
|
1184 | In [1]: run -t uniq_stable | |
1185 |
|
1185 | |||
1186 | IPython CPU timings (estimated):\\ |
|
1186 | IPython CPU timings (estimated):\\ | |
1187 | User : 0.19597 s.\\ |
|
1187 | User : 0.19597 s.\\ | |
1188 | System: 0.0 s.\\ |
|
1188 | System: 0.0 s.\\ | |
1189 |
|
1189 | |||
1190 | In [2]: run -t -N5 uniq_stable |
|
1190 | In [2]: run -t -N5 uniq_stable | |
1191 |
|
1191 | |||
1192 | IPython CPU timings (estimated):\\ |
|
1192 | IPython CPU timings (estimated):\\ | |
1193 | Total runs performed: 5\\ |
|
1193 | Total runs performed: 5\\ | |
1194 | Times : Total Per run\\ |
|
1194 | Times : Total Per run\\ | |
1195 | User : 0.910862 s, 0.1821724 s.\\ |
|
1195 | User : 0.910862 s, 0.1821724 s.\\ | |
1196 | System: 0.0 s, 0.0 s. |
|
1196 | System: 0.0 s, 0.0 s. | |
1197 |
|
1197 | |||
1198 | -d: run your program under the control of pdb, the Python debugger. |
|
1198 | -d: run your program under the control of pdb, the Python debugger. | |
1199 | This allows you to execute your program step by step, watch variables, |
|
1199 | This allows you to execute your program step by step, watch variables, | |
1200 | etc. Internally, what IPython does is similar to calling: |
|
1200 | etc. Internally, what IPython does is similar to calling: | |
1201 |
|
1201 | |||
1202 | pdb.run('execfile("YOURFILENAME")') |
|
1202 | pdb.run('execfile("YOURFILENAME")') | |
1203 |
|
1203 | |||
1204 | with a breakpoint set on line 1 of your file. You can change the line |
|
1204 | with a breakpoint set on line 1 of your file. You can change the line | |
1205 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1205 | number for this automatic breakpoint to be <N> by using the -bN option | |
1206 | (where N must be an integer). For example: |
|
1206 | (where N must be an integer). For example: | |
1207 |
|
1207 | |||
1208 | %run -d -b40 myscript |
|
1208 | %run -d -b40 myscript | |
1209 |
|
1209 | |||
1210 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1210 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1211 | the first breakpoint must be set on a line which actually does |
|
1211 | the first breakpoint must be set on a line which actually does | |
1212 | something (not a comment or docstring) for it to stop execution. |
|
1212 | something (not a comment or docstring) for it to stop execution. | |
1213 |
|
1213 | |||
1214 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1214 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1215 | first enter 'c' (without qoutes) to start execution up to the first |
|
1215 | first enter 'c' (without qoutes) to start execution up to the first | |
1216 | breakpoint. |
|
1216 | breakpoint. | |
1217 |
|
1217 | |||
1218 | Entering 'help' gives information about the use of the debugger. You |
|
1218 | Entering 'help' gives information about the use of the debugger. You | |
1219 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1219 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1220 | at a prompt. |
|
1220 | at a prompt. | |
1221 |
|
1221 | |||
1222 | -p: run program under the control of the Python profiler module (which |
|
1222 | -p: run program under the control of the Python profiler module (which | |
1223 | prints a detailed report of execution times, function calls, etc). |
|
1223 | prints a detailed report of execution times, function calls, etc). | |
1224 |
|
1224 | |||
1225 | You can pass other options after -p which affect the behavior of the |
|
1225 | You can pass other options after -p which affect the behavior of the | |
1226 | profiler itself. See the docs for %prun for details. |
|
1226 | profiler itself. See the docs for %prun for details. | |
1227 |
|
1227 | |||
1228 | In this mode, the program's variables do NOT propagate back to the |
|
1228 | In this mode, the program's variables do NOT propagate back to the | |
1229 | IPython interactive namespace (because they remain in the namespace |
|
1229 | IPython interactive namespace (because they remain in the namespace | |
1230 | where the profiler executes them). |
|
1230 | where the profiler executes them). | |
1231 |
|
1231 | |||
1232 | Internally this triggers a call to %prun, see its documentation for |
|
1232 | Internally this triggers a call to %prun, see its documentation for | |
1233 | details on the options available specifically for profiling.""" |
|
1233 | details on the options available specifically for profiling.""" | |
1234 |
|
1234 | |||
1235 | # get arguments and set sys.argv for program to be run. |
|
1235 | # get arguments and set sys.argv for program to be run. | |
1236 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1236 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1237 | mode='list',list_all=1) |
|
1237 | mode='list',list_all=1) | |
1238 |
|
1238 | |||
1239 | try: |
|
1239 | try: | |
1240 | filename = get_py_filename(arg_lst[0]) |
|
1240 | filename = get_py_filename(arg_lst[0]) | |
1241 | except IndexError: |
|
1241 | except IndexError: | |
1242 | warn('you must provide at least a filename.') |
|
1242 | warn('you must provide at least a filename.') | |
1243 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1243 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1244 | return |
|
1244 | return | |
1245 | except IOError,msg: |
|
1245 | except IOError,msg: | |
1246 | error(msg) |
|
1246 | error(msg) | |
1247 | return |
|
1247 | return | |
1248 |
|
1248 | |||
1249 | # Control the response to exit() calls made by the script being run |
|
1249 | # Control the response to exit() calls made by the script being run | |
1250 | exit_ignore = opts.has_key('e') |
|
1250 | exit_ignore = opts.has_key('e') | |
1251 |
|
1251 | |||
1252 | # Make sure that the running script gets a proper sys.argv as if it |
|
1252 | # Make sure that the running script gets a proper sys.argv as if it | |
1253 | # were run from a system shell. |
|
1253 | # were run from a system shell. | |
1254 | save_argv = sys.argv # save it for later restoring |
|
1254 | save_argv = sys.argv # save it for later restoring | |
1255 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1255 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1256 |
|
1256 | |||
1257 | if opts.has_key('i'): |
|
1257 | if opts.has_key('i'): | |
1258 | prog_ns = self.shell.user_ns |
|
1258 | prog_ns = self.shell.user_ns | |
1259 | __name__save = self.shell.user_ns['__name__'] |
|
1259 | __name__save = self.shell.user_ns['__name__'] | |
1260 | prog_ns['__name__'] = '__main__' |
|
1260 | prog_ns['__name__'] = '__main__' | |
1261 | else: |
|
1261 | else: | |
1262 | if opts.has_key('n'): |
|
1262 | if opts.has_key('n'): | |
1263 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1263 | name = os.path.splitext(os.path.basename(filename))[0] | |
1264 | else: |
|
1264 | else: | |
1265 | name = '__main__' |
|
1265 | name = '__main__' | |
1266 | prog_ns = {'__name__':name} |
|
1266 | prog_ns = {'__name__':name} | |
1267 |
|
1267 | |||
1268 | # pickle fix. See iplib for an explanation |
|
1268 | # pickle fix. See iplib for an explanation | |
1269 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1269 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) | |
1270 |
|
1270 | |||
1271 | stats = None |
|
1271 | stats = None | |
1272 | try: |
|
1272 | try: | |
1273 | if opts.has_key('p'): |
|
1273 | if opts.has_key('p'): | |
1274 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1274 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1275 | else: |
|
1275 | else: | |
1276 | if opts.has_key('d'): |
|
1276 | if opts.has_key('d'): | |
1277 | deb = pdb.Pdb() |
|
1277 | deb = pdb.Pdb() | |
1278 | # reset Breakpoint state, which is moronically kept |
|
1278 | # reset Breakpoint state, which is moronically kept | |
1279 | # in a class |
|
1279 | # in a class | |
1280 | bdb.Breakpoint.next = 1 |
|
1280 | bdb.Breakpoint.next = 1 | |
1281 | bdb.Breakpoint.bplist = {} |
|
1281 | bdb.Breakpoint.bplist = {} | |
1282 | bdb.Breakpoint.bpbynumber = [None] |
|
1282 | bdb.Breakpoint.bpbynumber = [None] | |
1283 | # Set an initial breakpoint to stop execution |
|
1283 | # Set an initial breakpoint to stop execution | |
1284 | maxtries = 10 |
|
1284 | maxtries = 10 | |
1285 | bp = int(opts.get('b',[1])[0]) |
|
1285 | bp = int(opts.get('b',[1])[0]) | |
1286 | checkline = deb.checkline(filename,bp) |
|
1286 | checkline = deb.checkline(filename,bp) | |
1287 | if not checkline: |
|
1287 | if not checkline: | |
1288 | for bp in range(bp+1,bp+maxtries+1): |
|
1288 | for bp in range(bp+1,bp+maxtries+1): | |
1289 | if deb.checkline(filename,bp): |
|
1289 | if deb.checkline(filename,bp): | |
1290 | break |
|
1290 | break | |
1291 | else: |
|
1291 | else: | |
1292 | msg = ("\nI failed to find a valid line to set " |
|
1292 | msg = ("\nI failed to find a valid line to set " | |
1293 | "a breakpoint\n" |
|
1293 | "a breakpoint\n" | |
1294 | "after trying up to line: %s.\n" |
|
1294 | "after trying up to line: %s.\n" | |
1295 | "Please set a valid breakpoint manually " |
|
1295 | "Please set a valid breakpoint manually " | |
1296 | "with the -b option." % bp) |
|
1296 | "with the -b option." % bp) | |
1297 | error(msg) |
|
1297 | error(msg) | |
1298 | return |
|
1298 | return | |
1299 | # if we find a good linenumber, set the breakpoint |
|
1299 | # if we find a good linenumber, set the breakpoint | |
1300 | deb.do_break('%s:%s' % (filename,bp)) |
|
1300 | deb.do_break('%s:%s' % (filename,bp)) | |
1301 | # Start file run |
|
1301 | # Start file run | |
1302 | print "NOTE: Enter 'c' at the", |
|
1302 | print "NOTE: Enter 'c' at the", | |
1303 | print "(Pdb) prompt to start your script." |
|
1303 | print "(Pdb) prompt to start your script." | |
1304 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1304 | deb.run('execfile("%s")' % filename,prog_ns) | |
1305 | else: |
|
1305 | else: | |
1306 | if runner is None: |
|
1306 | if runner is None: | |
1307 | runner = self.shell.safe_execfile |
|
1307 | runner = self.shell.safe_execfile | |
1308 | if opts.has_key('t'): |
|
1308 | if opts.has_key('t'): | |
1309 | try: |
|
1309 | try: | |
1310 | nruns = int(opts['N'][0]) |
|
1310 | nruns = int(opts['N'][0]) | |
1311 | if nruns < 1: |
|
1311 | if nruns < 1: | |
1312 | error('Number of runs must be >=1') |
|
1312 | error('Number of runs must be >=1') | |
1313 | return |
|
1313 | return | |
1314 | except (KeyError): |
|
1314 | except (KeyError): | |
1315 | nruns = 1 |
|
1315 | nruns = 1 | |
1316 | if nruns == 1: |
|
1316 | if nruns == 1: | |
1317 | t0 = clock2() |
|
1317 | t0 = clock2() | |
1318 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1318 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1319 | t1 = clock2() |
|
1319 | t1 = clock2() | |
1320 | t_usr = t1[0]-t0[0] |
|
1320 | t_usr = t1[0]-t0[0] | |
1321 | t_sys = t1[1]-t1[1] |
|
1321 | t_sys = t1[1]-t1[1] | |
1322 | print "\nIPython CPU timings (estimated):" |
|
1322 | print "\nIPython CPU timings (estimated):" | |
1323 | print " User : %10s s." % t_usr |
|
1323 | print " User : %10s s." % t_usr | |
1324 | print " System: %10s s." % t_sys |
|
1324 | print " System: %10s s." % t_sys | |
1325 | else: |
|
1325 | else: | |
1326 | runs = range(nruns) |
|
1326 | runs = range(nruns) | |
1327 | t0 = clock2() |
|
1327 | t0 = clock2() | |
1328 | for nr in runs: |
|
1328 | for nr in runs: | |
1329 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1329 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1330 | t1 = clock2() |
|
1330 | t1 = clock2() | |
1331 | t_usr = t1[0]-t0[0] |
|
1331 | t_usr = t1[0]-t0[0] | |
1332 | t_sys = t1[1]-t1[1] |
|
1332 | t_sys = t1[1]-t1[1] | |
1333 | print "\nIPython CPU timings (estimated):" |
|
1333 | print "\nIPython CPU timings (estimated):" | |
1334 | print "Total runs performed:",nruns |
|
1334 | print "Total runs performed:",nruns | |
1335 | print " Times : %10s %10s" % ('Total','Per run') |
|
1335 | print " Times : %10s %10s" % ('Total','Per run') | |
1336 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1336 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1337 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1337 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1338 |
|
1338 | |||
1339 | else: |
|
1339 | else: | |
1340 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1340 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1341 | if opts.has_key('i'): |
|
1341 | if opts.has_key('i'): | |
1342 | self.shell.user_ns['__name__'] = __name__save |
|
1342 | self.shell.user_ns['__name__'] = __name__save | |
1343 | else: |
|
1343 | else: | |
1344 | # update IPython interactive namespace |
|
1344 | # update IPython interactive namespace | |
1345 | del prog_ns['__name__'] |
|
1345 | del prog_ns['__name__'] | |
1346 | self.shell.user_ns.update(prog_ns) |
|
1346 | self.shell.user_ns.update(prog_ns) | |
1347 | finally: |
|
1347 | finally: | |
1348 | sys.argv = save_argv |
|
1348 | sys.argv = save_argv | |
1349 | return stats |
|
1349 | return stats | |
1350 |
|
1350 | |||
1351 | def magic_runlog(self, parameter_s =''): |
|
1351 | def magic_runlog(self, parameter_s =''): | |
1352 | """Run files as logs. |
|
1352 | """Run files as logs. | |
1353 |
|
1353 | |||
1354 | Usage:\\ |
|
1354 | Usage:\\ | |
1355 | %runlog file1 file2 ... |
|
1355 | %runlog file1 file2 ... | |
1356 |
|
1356 | |||
1357 | Run the named files (treating them as log files) in sequence inside |
|
1357 | Run the named files (treating them as log files) in sequence inside | |
1358 | the interpreter, and return to the prompt. This is much slower than |
|
1358 | the interpreter, and return to the prompt. This is much slower than | |
1359 | %run because each line is executed in a try/except block, but it |
|
1359 | %run because each line is executed in a try/except block, but it | |
1360 | allows running files with syntax errors in them. |
|
1360 | allows running files with syntax errors in them. | |
1361 |
|
1361 | |||
1362 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1362 | Normally IPython will guess when a file is one of its own logfiles, so | |
1363 | you can typically use %run even for logs. This shorthand allows you to |
|
1363 | you can typically use %run even for logs. This shorthand allows you to | |
1364 | force any file to be treated as a log file.""" |
|
1364 | force any file to be treated as a log file.""" | |
1365 |
|
1365 | |||
1366 | for f in parameter_s.split(): |
|
1366 | for f in parameter_s.split(): | |
1367 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1367 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1368 | self.shell.user_ns,islog=1) |
|
1368 | self.shell.user_ns,islog=1) | |
1369 |
|
1369 | |||
1370 | def magic_time(self,parameter_s = ''): |
|
1370 | def magic_time(self,parameter_s = ''): | |
1371 | """Time execution of a Python statement or expression. |
|
1371 | """Time execution of a Python statement or expression. | |
1372 |
|
1372 | |||
1373 | The CPU and wall clock times are printed, and the value of the |
|
1373 | The CPU and wall clock times are printed, and the value of the | |
1374 | expression (if any) is returned. Note that under Win32, system time |
|
1374 | expression (if any) is returned. Note that under Win32, system time | |
1375 | is always reported as 0, since it can not be measured. |
|
1375 | is always reported as 0, since it can not be measured. | |
1376 |
|
1376 | |||
1377 | This function provides very basic timing functionality. In Python |
|
1377 | This function provides very basic timing functionality. In Python | |
1378 | 2.3, the timeit module offers more control and sophistication, but for |
|
1378 | 2.3, the timeit module offers more control and sophistication, but for | |
1379 | now IPython supports Python 2.2, so we can not rely on timeit being |
|
1379 | now IPython supports Python 2.2, so we can not rely on timeit being | |
1380 | present. |
|
1380 | present. | |
1381 |
|
1381 | |||
1382 | Some examples: |
|
1382 | Some examples: | |
1383 |
|
1383 | |||
1384 | In [1]: time 2**128 |
|
1384 | In [1]: time 2**128 | |
1385 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1385 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1386 | Wall time: 0.00 |
|
1386 | Wall time: 0.00 | |
1387 | Out[1]: 340282366920938463463374607431768211456L |
|
1387 | Out[1]: 340282366920938463463374607431768211456L | |
1388 |
|
1388 | |||
1389 | In [2]: n = 1000000 |
|
1389 | In [2]: n = 1000000 | |
1390 |
|
1390 | |||
1391 | In [3]: time sum(range(n)) |
|
1391 | In [3]: time sum(range(n)) | |
1392 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1392 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1393 | Wall time: 1.37 |
|
1393 | Wall time: 1.37 | |
1394 | Out[3]: 499999500000L |
|
1394 | Out[3]: 499999500000L | |
1395 |
|
1395 | |||
1396 | In [4]: time print 'hello world' |
|
1396 | In [4]: time print 'hello world' | |
1397 | hello world |
|
1397 | hello world | |
1398 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1398 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1399 | Wall time: 0.00 |
|
1399 | Wall time: 0.00 | |
1400 | """ |
|
1400 | """ | |
1401 |
|
1401 | |||
1402 | # fail immediately if the given expression can't be compiled |
|
1402 | # fail immediately if the given expression can't be compiled | |
1403 | try: |
|
1403 | try: | |
1404 | mode = 'eval' |
|
1404 | mode = 'eval' | |
1405 | code = compile(parameter_s,'<timed eval>',mode) |
|
1405 | code = compile(parameter_s,'<timed eval>',mode) | |
1406 | except SyntaxError: |
|
1406 | except SyntaxError: | |
1407 | mode = 'exec' |
|
1407 | mode = 'exec' | |
1408 | code = compile(parameter_s,'<timed exec>',mode) |
|
1408 | code = compile(parameter_s,'<timed exec>',mode) | |
1409 | # skew measurement as little as possible |
|
1409 | # skew measurement as little as possible | |
1410 | glob = self.shell.user_ns |
|
1410 | glob = self.shell.user_ns | |
1411 | clk = clock2 |
|
1411 | clk = clock2 | |
1412 | wtime = time.time |
|
1412 | wtime = time.time | |
1413 | # time execution |
|
1413 | # time execution | |
1414 | wall_st = wtime() |
|
1414 | wall_st = wtime() | |
1415 | if mode=='eval': |
|
1415 | if mode=='eval': | |
1416 | st = clk() |
|
1416 | st = clk() | |
1417 | out = eval(code,glob) |
|
1417 | out = eval(code,glob) | |
1418 | end = clk() |
|
1418 | end = clk() | |
1419 | else: |
|
1419 | else: | |
1420 | st = clk() |
|
1420 | st = clk() | |
1421 | exec code in glob |
|
1421 | exec code in glob | |
1422 | end = clk() |
|
1422 | end = clk() | |
1423 | out = None |
|
1423 | out = None | |
1424 | wall_end = wtime() |
|
1424 | wall_end = wtime() | |
1425 | # Compute actual times and report |
|
1425 | # Compute actual times and report | |
1426 | wall_time = wall_end-wall_st |
|
1426 | wall_time = wall_end-wall_st | |
1427 | cpu_user = end[0]-st[0] |
|
1427 | cpu_user = end[0]-st[0] | |
1428 | cpu_sys = end[1]-st[1] |
|
1428 | cpu_sys = end[1]-st[1] | |
1429 | cpu_tot = cpu_user+cpu_sys |
|
1429 | cpu_tot = cpu_user+cpu_sys | |
1430 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1430 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1431 | (cpu_user,cpu_sys,cpu_tot) |
|
1431 | (cpu_user,cpu_sys,cpu_tot) | |
1432 | print "Wall time: %.2f" % wall_time |
|
1432 | print "Wall time: %.2f" % wall_time | |
1433 | return out |
|
1433 | return out | |
1434 |
|
1434 | |||
1435 | def magic_macro(self,parameter_s = ''): |
|
1435 | def magic_macro(self,parameter_s = ''): | |
1436 | """Define a set of input lines as a macro for future re-execution. |
|
1436 | """Define a set of input lines as a macro for future re-execution. | |
1437 |
|
1437 | |||
1438 | Usage:\\ |
|
1438 | Usage:\\ | |
1439 | %macro name n1:n2 n3:n4 ... n5 .. n6 ... |
|
1439 | %macro name n1:n2 n3:n4 ... n5 .. n6 ... | |
1440 |
|
1440 | |||
1441 | This will define a global variable called `name` which is a string |
|
1441 | This will define a global variable called `name` which is a string | |
1442 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1442 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1443 | above) from your input history into a single string. This variable |
|
1443 | above) from your input history into a single string. This variable | |
1444 | acts like an automatic function which re-executes those lines as if |
|
1444 | acts like an automatic function which re-executes those lines as if | |
1445 | you had typed them. You just type 'name' at the prompt and the code |
|
1445 | you had typed them. You just type 'name' at the prompt and the code | |
1446 | executes. |
|
1446 | executes. | |
1447 |
|
1447 | |||
1448 | Note that the slices use the standard Python slicing notation (5:8 |
|
1448 | Note that the slices use the standard Python slicing notation (5:8 | |
1449 | means include lines numbered 5,6,7). |
|
1449 | means include lines numbered 5,6,7). | |
1450 |
|
1450 | |||
1451 | For example, if your history contains (%hist prints it): |
|
1451 | For example, if your history contains (%hist prints it): | |
1452 |
|
1452 | |||
1453 | 44: x=1\\ |
|
1453 | 44: x=1\\ | |
1454 | 45: y=3\\ |
|
1454 | 45: y=3\\ | |
1455 | 46: z=x+y\\ |
|
1455 | 46: z=x+y\\ | |
1456 | 47: print x\\ |
|
1456 | 47: print x\\ | |
1457 | 48: a=5\\ |
|
1457 | 48: a=5\\ | |
1458 | 49: print 'x',x,'y',y\\ |
|
1458 | 49: print 'x',x,'y',y\\ | |
1459 |
|
1459 | |||
1460 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1460 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1461 | called my_macro with: |
|
1461 | called my_macro with: | |
1462 |
|
1462 | |||
1463 | In [51]: %macro my_macro 44:48 49 |
|
1463 | In [51]: %macro my_macro 44:48 49 | |
1464 |
|
1464 | |||
1465 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1465 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1466 | in one pass. |
|
1466 | in one pass. | |
1467 |
|
1467 | |||
1468 | You don't need to give the line-numbers in order, and any given line |
|
1468 | You don't need to give the line-numbers in order, and any given line | |
1469 | number can appear multiple times. You can assemble macros with any |
|
1469 | number can appear multiple times. You can assemble macros with any | |
1470 | lines from your input history in any order. |
|
1470 | lines from your input history in any order. | |
1471 |
|
1471 | |||
1472 | The macro is a simple object which holds its value in an attribute, |
|
1472 | The macro is a simple object which holds its value in an attribute, | |
1473 | but IPython's display system checks for macros and executes them as |
|
1473 | but IPython's display system checks for macros and executes them as | |
1474 | code instead of printing them when you type their name. |
|
1474 | code instead of printing them when you type their name. | |
1475 |
|
1475 | |||
1476 | You can view a macro's contents by explicitly printing it with: |
|
1476 | You can view a macro's contents by explicitly printing it with: | |
1477 |
|
1477 | |||
1478 | 'print macro_name'. |
|
1478 | 'print macro_name'. | |
1479 |
|
1479 | |||
1480 | For one-off cases which DON'T contain magic function calls in them you |
|
1480 | For one-off cases which DON'T contain magic function calls in them you | |
1481 | can obtain similar results by explicitly executing slices from your |
|
1481 | can obtain similar results by explicitly executing slices from your | |
1482 | input history with: |
|
1482 | input history with: | |
1483 |
|
1483 | |||
1484 | In [60]: exec In[44:48]+In[49]""" |
|
1484 | In [60]: exec In[44:48]+In[49]""" | |
1485 |
|
1485 | |||
1486 | args = parameter_s.split() |
|
1486 | args = parameter_s.split() | |
1487 | name,ranges = args[0], args[1:] |
|
1487 | name,ranges = args[0], args[1:] | |
1488 | #print 'rng',ranges # dbg |
|
1488 | #print 'rng',ranges # dbg | |
1489 | cmds = self.extract_input_slices(ranges) |
|
1489 | cmds = self.extract_input_slices(ranges) | |
1490 | macro = Macro(cmds) |
|
1490 | macro = Macro(cmds) | |
1491 | self.shell.user_ns.update({name:macro}) |
|
1491 | self.shell.user_ns.update({name:macro}) | |
1492 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1492 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1493 | print 'Macro contents:' |
|
1493 | print 'Macro contents:' | |
1494 | print str(macro).rstrip(), |
|
1494 | print str(macro).rstrip(), | |
1495 |
|
1495 | |||
1496 | def magic_save(self,parameter_s = ''): |
|
1496 | def magic_save(self,parameter_s = ''): | |
1497 | """Save a set of lines to a given filename. |
|
1497 | """Save a set of lines to a given filename. | |
1498 |
|
1498 | |||
1499 | Usage:\\ |
|
1499 | Usage:\\ | |
1500 | %save filename n1:n2 n3:n4 ... n5 .. n6 ... |
|
1500 | %save filename n1:n2 n3:n4 ... n5 .. n6 ... | |
1501 |
|
1501 | |||
1502 | This function uses the same syntax as %macro for line extraction, but |
|
1502 | This function uses the same syntax as %macro for line extraction, but | |
1503 | instead of creating a macro it saves the resulting string to the |
|
1503 | instead of creating a macro it saves the resulting string to the | |
1504 | filename you specify. |
|
1504 | filename you specify. | |
1505 |
|
1505 | |||
1506 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1506 | It adds a '.py' extension to the file if you don't do so yourself, and | |
1507 | it asks for confirmation before overwriting existing files.""" |
|
1507 | it asks for confirmation before overwriting existing files.""" | |
1508 |
|
1508 | |||
1509 | args = parameter_s.split() |
|
1509 | args = parameter_s.split() | |
1510 | fname,ranges = args[0], args[1:] |
|
1510 | fname,ranges = args[0], args[1:] | |
1511 | if not fname.endswith('.py'): |
|
1511 | if not fname.endswith('.py'): | |
1512 | fname += '.py' |
|
1512 | fname += '.py' | |
1513 | if os.path.isfile(fname): |
|
1513 | if os.path.isfile(fname): | |
1514 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1514 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
1515 | if ans.lower() not in ['y','yes']: |
|
1515 | if ans.lower() not in ['y','yes']: | |
1516 | print 'Operation cancelled.' |
|
1516 | print 'Operation cancelled.' | |
1517 | return |
|
1517 | return | |
1518 | cmds = ''.join(self.extract_input_slices(ranges)) |
|
1518 | cmds = ''.join(self.extract_input_slices(ranges)) | |
1519 | f = file(fname,'w') |
|
1519 | f = file(fname,'w') | |
1520 | f.write(cmds) |
|
1520 | f.write(cmds) | |
1521 | f.close() |
|
1521 | f.close() | |
1522 | print 'The following commands were written to file `%s`:' % fname |
|
1522 | print 'The following commands were written to file `%s`:' % fname | |
1523 | print cmds |
|
1523 | print cmds | |
1524 |
|
1524 | |||
1525 | def magic_ed(self,parameter_s = ''): |
|
1525 | def magic_ed(self,parameter_s = ''): | |
1526 | """Alias to %edit.""" |
|
1526 | """Alias to %edit.""" | |
1527 | return self.magic_edit(parameter_s) |
|
1527 | return self.magic_edit(parameter_s) | |
1528 |
|
1528 | |||
1529 | def magic_edit(self,parameter_s = '',last_call=['','']): |
|
1529 | def magic_edit(self,parameter_s = '',last_call=['','']): | |
1530 | """Bring up an editor and execute the resulting code. |
|
1530 | """Bring up an editor and execute the resulting code. | |
1531 |
|
1531 | |||
1532 | Usage: |
|
1532 | Usage: | |
1533 | %edit [options] [args] |
|
1533 | %edit [options] [args] | |
1534 |
|
1534 | |||
1535 | %edit runs IPython's editor hook. The default version of this hook is |
|
1535 | %edit runs IPython's editor hook. The default version of this hook is | |
1536 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1536 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
1537 | environment variable $EDITOR. If this isn't found, it will default to |
|
1537 | environment variable $EDITOR. If this isn't found, it will default to | |
1538 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1538 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
1539 | docstring for how to change the editor hook. |
|
1539 | docstring for how to change the editor hook. | |
1540 |
|
1540 | |||
1541 | You can also set the value of this editor via the command line option |
|
1541 | You can also set the value of this editor via the command line option | |
1542 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
1542 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
1543 | specifically for IPython an editor different from your typical default |
|
1543 | specifically for IPython an editor different from your typical default | |
1544 | (and for Windows users who typically don't set environment variables). |
|
1544 | (and for Windows users who typically don't set environment variables). | |
1545 |
|
1545 | |||
1546 | This command allows you to conveniently edit multi-line code right in |
|
1546 | This command allows you to conveniently edit multi-line code right in | |
1547 | your IPython session. |
|
1547 | your IPython session. | |
1548 |
|
1548 | |||
1549 | If called without arguments, %edit opens up an empty editor with a |
|
1549 | If called without arguments, %edit opens up an empty editor with a | |
1550 | temporary file and will execute the contents of this file when you |
|
1550 | temporary file and will execute the contents of this file when you | |
1551 | close it (don't forget to save it!). |
|
1551 | close it (don't forget to save it!). | |
1552 |
|
1552 | |||
1553 | Options: |
|
1553 | Options: | |
1554 |
|
1554 | |||
1555 | -p: this will call the editor with the same data as the previous time |
|
1555 | -p: this will call the editor with the same data as the previous time | |
1556 | it was used, regardless of how long ago (in your current session) it |
|
1556 | it was used, regardless of how long ago (in your current session) it | |
1557 | was. |
|
1557 | was. | |
1558 |
|
1558 | |||
1559 | -x: do not execute the edited code immediately upon exit. This is |
|
1559 | -x: do not execute the edited code immediately upon exit. This is | |
1560 | mainly useful if you are editing programs which need to be called with |
|
1560 | mainly useful if you are editing programs which need to be called with | |
1561 | command line arguments, which you can then do using %run. |
|
1561 | command line arguments, which you can then do using %run. | |
1562 |
|
1562 | |||
1563 | Arguments: |
|
1563 | Arguments: | |
1564 |
|
1564 | |||
1565 | If arguments are given, the following possibilites exist: |
|
1565 | If arguments are given, the following possibilites exist: | |
1566 |
|
1566 | |||
1567 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
1567 | - The arguments are numbers or pairs of colon-separated numbers (like | |
1568 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
1568 | 1 4:8 9). These are interpreted as lines of previous input to be | |
1569 | loaded into the editor. The syntax is the same of the %macro command. |
|
1569 | loaded into the editor. The syntax is the same of the %macro command. | |
1570 |
|
1570 | |||
1571 | - If the argument doesn't start with a number, it is evaluated as a |
|
1571 | - If the argument doesn't start with a number, it is evaluated as a | |
1572 | variable and its contents loaded into the editor. You can thus edit |
|
1572 | variable and its contents loaded into the editor. You can thus edit | |
1573 | any string which contains python code (including the result of |
|
1573 | any string which contains python code (including the result of | |
1574 | previous edits). |
|
1574 | previous edits). | |
1575 |
|
1575 | |||
1576 | - If the argument is the name of an object (other than a string), |
|
1576 | - If the argument is the name of an object (other than a string), | |
1577 | IPython will try to locate the file where it was defined and open the |
|
1577 | IPython will try to locate the file where it was defined and open the | |
1578 | editor at the point where it is defined. You can use `%edit function` |
|
1578 | editor at the point where it is defined. You can use `%edit function` | |
1579 | to load an editor exactly at the point where 'function' is defined, |
|
1579 | to load an editor exactly at the point where 'function' is defined, | |
1580 | edit it and have the file be executed automatically. |
|
1580 | edit it and have the file be executed automatically. | |
1581 |
|
1581 | |||
1582 | Note: opening at an exact line is only supported under Unix, and some |
|
1582 | Note: opening at an exact line is only supported under Unix, and some | |
1583 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
1583 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
1584 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
1584 | '+NUMBER' parameter necessary for this feature. Good editors like | |
1585 | (X)Emacs, vi, jed, pico and joe all do. |
|
1585 | (X)Emacs, vi, jed, pico and joe all do. | |
1586 |
|
1586 | |||
1587 | - If the argument is not found as a variable, IPython will look for a |
|
1587 | - If the argument is not found as a variable, IPython will look for a | |
1588 | file with that name (adding .py if necessary) and load it into the |
|
1588 | file with that name (adding .py if necessary) and load it into the | |
1589 | editor. It will execute its contents with execfile() when you exit, |
|
1589 | editor. It will execute its contents with execfile() when you exit, | |
1590 | loading any code in the file into your interactive namespace. |
|
1590 | loading any code in the file into your interactive namespace. | |
1591 |
|
1591 | |||
1592 | After executing your code, %edit will return as output the code you |
|
1592 | After executing your code, %edit will return as output the code you | |
1593 | typed in the editor (except when it was an existing file). This way |
|
1593 | typed in the editor (except when it was an existing file). This way | |
1594 | you can reload the code in further invocations of %edit as a variable, |
|
1594 | you can reload the code in further invocations of %edit as a variable, | |
1595 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
1595 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
1596 | the output. |
|
1596 | the output. | |
1597 |
|
1597 | |||
1598 | Note that %edit is also available through the alias %ed. |
|
1598 | Note that %edit is also available through the alias %ed. | |
1599 |
|
1599 | |||
1600 | This is an example of creating a simple function inside the editor and |
|
1600 | This is an example of creating a simple function inside the editor and | |
1601 | then modifying it. First, start up the editor: |
|
1601 | then modifying it. First, start up the editor: | |
1602 |
|
1602 | |||
1603 | In [1]: ed\\ |
|
1603 | In [1]: ed\\ | |
1604 | Editing... done. Executing edited code...\\ |
|
1604 | Editing... done. Executing edited code...\\ | |
1605 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
1605 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' | |
1606 |
|
1606 | |||
1607 | We can then call the function foo(): |
|
1607 | We can then call the function foo(): | |
1608 |
|
1608 | |||
1609 | In [2]: foo()\\ |
|
1609 | In [2]: foo()\\ | |
1610 | foo() was defined in an editing session |
|
1610 | foo() was defined in an editing session | |
1611 |
|
1611 | |||
1612 | Now we edit foo. IPython automatically loads the editor with the |
|
1612 | Now we edit foo. IPython automatically loads the editor with the | |
1613 | (temporary) file where foo() was previously defined: |
|
1613 | (temporary) file where foo() was previously defined: | |
1614 |
|
1614 | |||
1615 | In [3]: ed foo\\ |
|
1615 | In [3]: ed foo\\ | |
1616 | Editing... done. Executing edited code... |
|
1616 | Editing... done. Executing edited code... | |
1617 |
|
1617 | |||
1618 | And if we call foo() again we get the modified version: |
|
1618 | And if we call foo() again we get the modified version: | |
1619 |
|
1619 | |||
1620 | In [4]: foo()\\ |
|
1620 | In [4]: foo()\\ | |
1621 | foo() has now been changed! |
|
1621 | foo() has now been changed! | |
1622 |
|
1622 | |||
1623 | Here is an example of how to edit a code snippet successive |
|
1623 | Here is an example of how to edit a code snippet successive | |
1624 | times. First we call the editor: |
|
1624 | times. First we call the editor: | |
1625 |
|
1625 | |||
1626 | In [8]: ed\\ |
|
1626 | In [8]: ed\\ | |
1627 | Editing... done. Executing edited code...\\ |
|
1627 | Editing... done. Executing edited code...\\ | |
1628 | hello\\ |
|
1628 | hello\\ | |
1629 | Out[8]: "print 'hello'\\n" |
|
1629 | Out[8]: "print 'hello'\\n" | |
1630 |
|
1630 | |||
1631 | Now we call it again with the previous output (stored in _): |
|
1631 | Now we call it again with the previous output (stored in _): | |
1632 |
|
1632 | |||
1633 | In [9]: ed _\\ |
|
1633 | In [9]: ed _\\ | |
1634 | Editing... done. Executing edited code...\\ |
|
1634 | Editing... done. Executing edited code...\\ | |
1635 | hello world\\ |
|
1635 | hello world\\ | |
1636 | Out[9]: "print 'hello world'\\n" |
|
1636 | Out[9]: "print 'hello world'\\n" | |
1637 |
|
1637 | |||
1638 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
1638 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
1639 |
|
1639 | |||
1640 | In [10]: ed _8\\ |
|
1640 | In [10]: ed _8\\ | |
1641 | Editing... done. Executing edited code...\\ |
|
1641 | Editing... done. Executing edited code...\\ | |
1642 | hello again\\ |
|
1642 | hello again\\ | |
1643 | Out[10]: "print 'hello again'\\n" |
|
1643 | Out[10]: "print 'hello again'\\n" | |
1644 |
|
1644 | |||
1645 |
|
1645 | |||
1646 | Changing the default editor hook: |
|
1646 | Changing the default editor hook: | |
1647 |
|
1647 | |||
1648 | If you wish to write your own editor hook, you can put it in a |
|
1648 | If you wish to write your own editor hook, you can put it in a | |
1649 | configuration file which you load at startup time. The default hook |
|
1649 | configuration file which you load at startup time. The default hook | |
1650 | is defined in the IPython.hooks module, and you can use that as a |
|
1650 | is defined in the IPython.hooks module, and you can use that as a | |
1651 | starting example for further modifications. That file also has |
|
1651 | starting example for further modifications. That file also has | |
1652 | general instructions on how to set a new hook for use once you've |
|
1652 | general instructions on how to set a new hook for use once you've | |
1653 | defined it.""" |
|
1653 | defined it.""" | |
1654 |
|
1654 | |||
1655 | # FIXME: This function has become a convoluted mess. It needs a |
|
1655 | # FIXME: This function has become a convoluted mess. It needs a | |
1656 | # ground-up rewrite with clean, simple logic. |
|
1656 | # ground-up rewrite with clean, simple logic. | |
1657 |
|
1657 | |||
1658 | def make_filename(arg): |
|
1658 | def make_filename(arg): | |
1659 | "Make a filename from the given args" |
|
1659 | "Make a filename from the given args" | |
1660 | try: |
|
1660 | try: | |
1661 | filename = get_py_filename(arg) |
|
1661 | filename = get_py_filename(arg) | |
1662 | except IOError: |
|
1662 | except IOError: | |
1663 | if args.endswith('.py'): |
|
1663 | if args.endswith('.py'): | |
1664 | filename = arg |
|
1664 | filename = arg | |
1665 | else: |
|
1665 | else: | |
1666 | filename = None |
|
1666 | filename = None | |
1667 | return filename |
|
1667 | return filename | |
1668 |
|
1668 | |||
1669 | # custom exceptions |
|
1669 | # custom exceptions | |
1670 | class DataIsObject(Exception): pass |
|
1670 | class DataIsObject(Exception): pass | |
1671 |
|
1671 | |||
1672 | opts,args = self.parse_options(parameter_s,'px') |
|
1672 | opts,args = self.parse_options(parameter_s,'px') | |
1673 |
|
1673 | |||
1674 | # Default line number value |
|
1674 | # Default line number value | |
1675 | lineno = None |
|
1675 | lineno = None | |
1676 | if opts.has_key('p'): |
|
1676 | if opts.has_key('p'): | |
1677 | args = '_%s' % last_call[0] |
|
1677 | args = '_%s' % last_call[0] | |
1678 | if not self.shell.user_ns.has_key(args): |
|
1678 | if not self.shell.user_ns.has_key(args): | |
1679 | args = last_call[1] |
|
1679 | args = last_call[1] | |
1680 |
|
1680 | |||
1681 | # use last_call to remember the state of the previous call, but don't |
|
1681 | # use last_call to remember the state of the previous call, but don't | |
1682 | # let it be clobbered by successive '-p' calls. |
|
1682 | # let it be clobbered by successive '-p' calls. | |
1683 | try: |
|
1683 | try: | |
1684 | last_call[0] = self.shell.outputcache.prompt_count |
|
1684 | last_call[0] = self.shell.outputcache.prompt_count | |
1685 | if not opts.has_key('p'): |
|
1685 | if not opts.has_key('p'): | |
1686 | last_call[1] = parameter_s |
|
1686 | last_call[1] = parameter_s | |
1687 | except: |
|
1687 | except: | |
1688 | pass |
|
1688 | pass | |
1689 |
|
1689 | |||
1690 | # by default this is done with temp files, except when the given |
|
1690 | # by default this is done with temp files, except when the given | |
1691 | # arg is a filename |
|
1691 | # arg is a filename | |
1692 | use_temp = 1 |
|
1692 | use_temp = 1 | |
1693 |
|
1693 | |||
1694 | if re.match(r'\d',args): |
|
1694 | if re.match(r'\d',args): | |
1695 | # Mode where user specifies ranges of lines, like in %macro. |
|
1695 | # Mode where user specifies ranges of lines, like in %macro. | |
1696 | # This means that you can't edit files whose names begin with |
|
1696 | # This means that you can't edit files whose names begin with | |
1697 | # numbers this way. Tough. |
|
1697 | # numbers this way. Tough. | |
1698 | ranges = args.split() |
|
1698 | ranges = args.split() | |
1699 | data = ''.join(self.extract_input_slices(ranges)) |
|
1699 | data = ''.join(self.extract_input_slices(ranges)) | |
1700 | elif args.endswith('.py'): |
|
1700 | elif args.endswith('.py'): | |
1701 | filename = make_filename(args) |
|
1701 | filename = make_filename(args) | |
1702 | data = '' |
|
1702 | data = '' | |
1703 | use_temp = 0 |
|
1703 | use_temp = 0 | |
1704 | elif args: |
|
1704 | elif args: | |
1705 | try: |
|
1705 | try: | |
1706 | # Load the parameter given as a variable. If not a string, |
|
1706 | # Load the parameter given as a variable. If not a string, | |
1707 | # process it as an object instead (below) |
|
1707 | # process it as an object instead (below) | |
1708 |
|
1708 | |||
1709 | #print '*** args',args,'type',type(args) # dbg |
|
1709 | #print '*** args',args,'type',type(args) # dbg | |
1710 | data = eval(args,self.shell.user_ns) |
|
1710 | data = eval(args,self.shell.user_ns) | |
1711 | if not type(data) in StringTypes: |
|
1711 | if not type(data) in StringTypes: | |
1712 | raise DataIsObject |
|
1712 | raise DataIsObject | |
1713 | except (NameError,SyntaxError): |
|
1713 | except (NameError,SyntaxError): | |
1714 | # given argument is not a variable, try as a filename |
|
1714 | # given argument is not a variable, try as a filename | |
1715 | filename = make_filename(args) |
|
1715 | filename = make_filename(args) | |
1716 | if filename is None: |
|
1716 | if filename is None: | |
1717 | warn("Argument given (%s) can't be found as a variable " |
|
1717 | warn("Argument given (%s) can't be found as a variable " | |
1718 | "or as a filename." % args) |
|
1718 | "or as a filename." % args) | |
1719 | return |
|
1719 | return | |
1720 | data = '' |
|
1720 | data = '' | |
1721 | use_temp = 0 |
|
1721 | use_temp = 0 | |
1722 | except DataIsObject: |
|
1722 | except DataIsObject: | |
1723 | # For objects, try to edit the file where they are defined |
|
1723 | # For objects, try to edit the file where they are defined | |
1724 | try: |
|
1724 | try: | |
1725 | filename = inspect.getabsfile(data) |
|
1725 | filename = inspect.getabsfile(data) | |
1726 | datafile = 1 |
|
1726 | datafile = 1 | |
1727 | except TypeError: |
|
1727 | except TypeError: | |
1728 | filename = make_filename(args) |
|
1728 | filename = make_filename(args) | |
1729 | datafile = 1 |
|
1729 | datafile = 1 | |
1730 | warn('Could not find file where `%s` is defined.\n' |
|
1730 | warn('Could not find file where `%s` is defined.\n' | |
1731 | 'Opening a file named `%s`' % (args,filename)) |
|
1731 | 'Opening a file named `%s`' % (args,filename)) | |
1732 | # Now, make sure we can actually read the source (if it was in |
|
1732 | # Now, make sure we can actually read the source (if it was in | |
1733 | # a temp file it's gone by now). |
|
1733 | # a temp file it's gone by now). | |
1734 | if datafile: |
|
1734 | if datafile: | |
1735 | try: |
|
1735 | try: | |
1736 | lineno = inspect.getsourcelines(data)[1] |
|
1736 | lineno = inspect.getsourcelines(data)[1] | |
1737 | except IOError: |
|
1737 | except IOError: | |
1738 | filename = make_filename(args) |
|
1738 | filename = make_filename(args) | |
1739 | if filename is None: |
|
1739 | if filename is None: | |
1740 | warn('The file `%s` where `%s` was defined cannot ' |
|
1740 | warn('The file `%s` where `%s` was defined cannot ' | |
1741 | 'be read.' % (filename,data)) |
|
1741 | 'be read.' % (filename,data)) | |
1742 | return |
|
1742 | return | |
1743 | use_temp = 0 |
|
1743 | use_temp = 0 | |
1744 | else: |
|
1744 | else: | |
1745 | data = '' |
|
1745 | data = '' | |
1746 |
|
1746 | |||
1747 | if use_temp: |
|
1747 | if use_temp: | |
1748 | filename = tempfile.mktemp('.py') |
|
1748 | filename = tempfile.mktemp('.py') | |
1749 | self.shell.tempfiles.append(filename) |
|
1749 | self.shell.tempfiles.append(filename) | |
1750 |
|
1750 | |||
1751 | if data and use_temp: |
|
1751 | if data and use_temp: | |
1752 | tmp_file = open(filename,'w') |
|
1752 | tmp_file = open(filename,'w') | |
1753 | tmp_file.write(data) |
|
1753 | tmp_file.write(data) | |
1754 | tmp_file.close() |
|
1754 | tmp_file.close() | |
1755 |
|
1755 | |||
1756 | # do actual editing here |
|
1756 | # do actual editing here | |
1757 | print 'Editing...', |
|
1757 | print 'Editing...', | |
1758 | sys.stdout.flush() |
|
1758 | sys.stdout.flush() | |
1759 | self.shell.hooks.editor(filename,lineno) |
|
1759 | self.shell.hooks.editor(filename,lineno) | |
1760 | if opts.has_key('x'): # -x prevents actual execution |
|
1760 | if opts.has_key('x'): # -x prevents actual execution | |
1761 |
|
1761 | |||
1762 | else: |
|
1762 | else: | |
1763 | print 'done. Executing edited code...' |
|
1763 | print 'done. Executing edited code...' | |
1764 | try: |
|
1764 | try: | |
1765 | execfile(filename,self.shell.user_ns) |
|
1765 | execfile(filename,self.shell.user_ns) | |
1766 | except IOError,msg: |
|
1766 | except IOError,msg: | |
1767 | if msg.filename == filename: |
|
1767 | if msg.filename == filename: | |
1768 | warn('File not found. Did you forget to save?') |
|
1768 | warn('File not found. Did you forget to save?') | |
1769 | return |
|
1769 | return | |
1770 | else: |
|
1770 | else: | |
1771 | self.shell.showtraceback() |
|
1771 | self.shell.showtraceback() | |
1772 | except: |
|
1772 | except: | |
1773 | self.shell.showtraceback() |
|
1773 | self.shell.showtraceback() | |
1774 | if use_temp: |
|
1774 | if use_temp: | |
1775 | contents = open(filename).read() |
|
1775 | contents = open(filename).read() | |
1776 | return contents |
|
1776 | return contents | |
1777 |
|
1777 | |||
1778 | def magic_xmode(self,parameter_s = ''): |
|
1778 | def magic_xmode(self,parameter_s = ''): | |
1779 | """Switch modes for the exception handlers. |
|
1779 | """Switch modes for the exception handlers. | |
1780 |
|
1780 | |||
1781 | Valid modes: Plain, Context and Verbose. |
|
1781 | Valid modes: Plain, Context and Verbose. | |
1782 |
|
1782 | |||
1783 | If called without arguments, acts as a toggle.""" |
|
1783 | If called without arguments, acts as a toggle.""" | |
1784 |
|
1784 | |||
1785 | new_mode = parameter_s.strip().capitalize() |
|
1785 | new_mode = parameter_s.strip().capitalize() | |
1786 | try: |
|
1786 | try: | |
1787 | self.InteractiveTB.set_mode(mode = new_mode) |
|
1787 | self.InteractiveTB.set_mode(mode = new_mode) | |
1788 | print 'Exception reporting mode:',self.InteractiveTB.mode |
|
1788 | print 'Exception reporting mode:',self.InteractiveTB.mode | |
1789 | except: |
|
1789 | except: | |
1790 | warn('Error changing exception modes.\n' + str(sys.exc_info()[1])) |
|
1790 | warn('Error changing exception modes.\n' + str(sys.exc_info()[1])) | |
1791 |
|
1791 | |||
1792 | def magic_colors(self,parameter_s = ''): |
|
1792 | def magic_colors(self,parameter_s = ''): | |
1793 | """Switch color scheme for prompts, info system and exception handlers. |
|
1793 | """Switch color scheme for prompts, info system and exception handlers. | |
1794 |
|
1794 | |||
1795 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
1795 | Currently implemented schemes: NoColor, Linux, LightBG. | |
1796 |
|
1796 | |||
1797 | Color scheme names are not case-sensitive.""" |
|
1797 | Color scheme names are not case-sensitive.""" | |
1798 |
|
1798 | |||
1799 | new_scheme = parameter_s.strip() |
|
1799 | new_scheme = parameter_s.strip() | |
1800 | if not new_scheme: |
|
1800 | if not new_scheme: | |
1801 | print 'You must specify a color scheme.' |
|
1801 | print 'You must specify a color scheme.' | |
1802 | return |
|
1802 | return | |
1803 | # Under Windows, check for Gary Bishop's readline, which is necessary |
|
1803 | # Under Windows, check for Gary Bishop's readline, which is necessary | |
1804 | # for ANSI coloring |
|
1804 | # for ANSI coloring | |
1805 | if os.name in ['nt','dos']: |
|
1805 | if os.name in ['nt','dos']: | |
1806 | try: |
|
1806 | try: | |
1807 | import readline |
|
1807 | import readline | |
1808 | except ImportError: |
|
1808 | except ImportError: | |
1809 | has_readline = 0 |
|
1809 | has_readline = 0 | |
1810 | else: |
|
1810 | else: | |
1811 | try: |
|
1811 | try: | |
1812 | readline.GetOutputFile() |
|
1812 | readline.GetOutputFile() | |
1813 | except AttributeError: |
|
1813 | except AttributeError: | |
1814 | has_readline = 0 |
|
1814 | has_readline = 0 | |
1815 | else: |
|
1815 | else: | |
1816 | has_readline = 1 |
|
1816 | has_readline = 1 | |
1817 | if not has_readline: |
|
1817 | if not has_readline: | |
1818 | msg = """\ |
|
1818 | msg = """\ | |
1819 | Proper color support under MS Windows requires Gary Bishop's readline library. |
|
1819 | Proper color support under MS Windows requires Gary Bishop's readline library. | |
1820 | You can find it at: |
|
1820 | You can find it at: | |
1821 | http://sourceforge.net/projects/uncpythontools |
|
1821 | http://sourceforge.net/projects/uncpythontools | |
1822 | Gary's readline needs the ctypes module, from: |
|
1822 | Gary's readline needs the ctypes module, from: | |
1823 | http://starship.python.net/crew/theller/ctypes |
|
1823 | http://starship.python.net/crew/theller/ctypes | |
1824 |
|
1824 | |||
1825 | Defaulting color scheme to 'NoColor'""" |
|
1825 | Defaulting color scheme to 'NoColor'""" | |
1826 | new_scheme = 'NoColor' |
|
1826 | new_scheme = 'NoColor' | |
1827 | warn(msg) |
|
1827 | warn(msg) | |
1828 |
|
1828 | |||
1829 | # Set prompt colors |
|
1829 | # Set prompt colors | |
1830 | try: |
|
1830 | try: | |
1831 | self.shell.outputcache.set_colors(new_scheme) |
|
1831 | self.shell.outputcache.set_colors(new_scheme) | |
1832 | except: |
|
1832 | except: | |
1833 | warn('Error changing prompt color schemes.\n' |
|
1833 | warn('Error changing prompt color schemes.\n' | |
1834 | + str(sys.exc_info()[1])) |
|
1834 | + str(sys.exc_info()[1])) | |
1835 | else: |
|
1835 | else: | |
1836 | self.shell.rc.colors = \ |
|
1836 | self.shell.rc.colors = \ | |
1837 | self.shell.outputcache.color_table.active_scheme_name |
|
1837 | self.shell.outputcache.color_table.active_scheme_name | |
1838 | # Set exception colors |
|
1838 | # Set exception colors | |
1839 | try: |
|
1839 | try: | |
1840 | self.shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
1840 | self.shell.InteractiveTB.set_colors(scheme = new_scheme) | |
1841 | self.shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
1841 | self.shell.SyntaxTB.set_colors(scheme = new_scheme) | |
1842 | except: |
|
1842 | except: | |
1843 | warn('Error changing exception color schemes.\n' |
|
1843 | warn('Error changing exception color schemes.\n' | |
1844 | + str(sys.exc_info()[1])) |
|
1844 | + str(sys.exc_info()[1])) | |
1845 | # Set info (for 'object?') colors |
|
1845 | # Set info (for 'object?') colors | |
1846 | if self.shell.rc.color_info: |
|
1846 | if self.shell.rc.color_info: | |
1847 | try: |
|
1847 | try: | |
1848 | self.shell.inspector.set_active_scheme(new_scheme) |
|
1848 | self.shell.inspector.set_active_scheme(new_scheme) | |
1849 | except: |
|
1849 | except: | |
1850 | warn('Error changing object inspector color schemes.\n' |
|
1850 | warn('Error changing object inspector color schemes.\n' | |
1851 | + str(sys.exc_info()[1])) |
|
1851 | + str(sys.exc_info()[1])) | |
1852 | else: |
|
1852 | else: | |
1853 | self.shell.inspector.set_active_scheme('NoColor') |
|
1853 | self.shell.inspector.set_active_scheme('NoColor') | |
1854 |
|
1854 | |||
1855 | def magic_color_info(self,parameter_s = ''): |
|
1855 | def magic_color_info(self,parameter_s = ''): | |
1856 | """Toggle color_info. |
|
1856 | """Toggle color_info. | |
1857 |
|
1857 | |||
1858 | The color_info configuration parameter controls whether colors are |
|
1858 | The color_info configuration parameter controls whether colors are | |
1859 | used for displaying object details (by things like %psource, %pfile or |
|
1859 | used for displaying object details (by things like %psource, %pfile or | |
1860 | the '?' system). This function toggles this value with each call. |
|
1860 | the '?' system). This function toggles this value with each call. | |
1861 |
|
1861 | |||
1862 | Note that unless you have a fairly recent pager (less works better |
|
1862 | Note that unless you have a fairly recent pager (less works better | |
1863 | than more) in your system, using colored object information displays |
|
1863 | than more) in your system, using colored object information displays | |
1864 | will not work properly. Test it and see.""" |
|
1864 | will not work properly. Test it and see.""" | |
1865 |
|
1865 | |||
1866 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
1866 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
1867 | self.magic_colors(self.shell.rc.colors) |
|
1867 | self.magic_colors(self.shell.rc.colors) | |
1868 | print 'Object introspection functions have now coloring:', |
|
1868 | print 'Object introspection functions have now coloring:', | |
1869 | print ['OFF','ON'][self.shell.rc.color_info] |
|
1869 | print ['OFF','ON'][self.shell.rc.color_info] | |
1870 |
|
1870 | |||
1871 | def magic_Pprint(self, parameter_s=''): |
|
1871 | def magic_Pprint(self, parameter_s=''): | |
1872 | """Toggle pretty printing on/off.""" |
|
1872 | """Toggle pretty printing on/off.""" | |
1873 |
|
1873 | |||
1874 | self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint |
|
1874 | self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint | |
1875 | print 'Pretty printing has been turned', \ |
|
1875 | print 'Pretty printing has been turned', \ | |
1876 | ['OFF','ON'][self.shell.outputcache.Pprint] |
|
1876 | ['OFF','ON'][self.shell.outputcache.Pprint] | |
1877 |
|
1877 | |||
1878 | def magic_Exit(self, parameter_s=''): |
|
1878 | def magic_Exit(self, parameter_s=''): | |
1879 | """Exit IPython without confirmation.""" |
|
1879 | """Exit IPython without confirmation.""" | |
1880 |
|
1880 | |||
1881 | self.shell.exit_now = True |
|
1881 | self.shell.exit_now = True | |
1882 |
|
1882 | |||
1883 | def magic_Quit(self, parameter_s=''): |
|
1883 | def magic_Quit(self, parameter_s=''): | |
1884 | """Exit IPython without confirmation (like %Exit).""" |
|
1884 | """Exit IPython without confirmation (like %Exit).""" | |
1885 |
|
1885 | |||
1886 | self.shell.exit_now = True |
|
1886 | self.shell.exit_now = True | |
1887 |
|
1887 | |||
1888 | #...................................................................... |
|
1888 | #...................................................................... | |
1889 | # Functions to implement unix shell-type things |
|
1889 | # Functions to implement unix shell-type things | |
1890 |
|
1890 | |||
1891 | def magic_alias(self, parameter_s = ''): |
|
1891 | def magic_alias(self, parameter_s = ''): | |
1892 | """Define an alias for a system command. |
|
1892 | """Define an alias for a system command. | |
1893 |
|
1893 | |||
1894 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
1894 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
1895 |
|
1895 | |||
1896 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
1896 | Then, typing 'alias_name params' will execute the system command 'cmd | |
1897 | params' (from your underlying operating system). |
|
1897 | params' (from your underlying operating system). | |
1898 |
|
1898 | |||
1899 | Aliases have lower precedence than magic functions and Python normal |
|
1899 | Aliases have lower precedence than magic functions and Python normal | |
1900 | variables, so if 'foo' is both a Python variable and an alias, the |
|
1900 | variables, so if 'foo' is both a Python variable and an alias, the | |
1901 | alias can not be executed until 'del foo' removes the Python variable. |
|
1901 | alias can not be executed until 'del foo' removes the Python variable. | |
1902 |
|
1902 | |||
1903 | You can use the %l specifier in an alias definition to represent the |
|
1903 | You can use the %l specifier in an alias definition to represent the | |
1904 | whole line when the alias is called. For example: |
|
1904 | whole line when the alias is called. For example: | |
1905 |
|
1905 | |||
1906 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
1906 | In [2]: alias all echo "Input in brackets: <%l>"\\ | |
1907 | In [3]: all hello world\\ |
|
1907 | In [3]: all hello world\\ | |
1908 | Input in brackets: <hello world> |
|
1908 | Input in brackets: <hello world> | |
1909 |
|
1909 | |||
1910 | You can also define aliases with parameters using %s specifiers (one |
|
1910 | You can also define aliases with parameters using %s specifiers (one | |
1911 | per parameter): |
|
1911 | per parameter): | |
1912 |
|
1912 | |||
1913 | In [1]: alias parts echo first %s second %s\\ |
|
1913 | In [1]: alias parts echo first %s second %s\\ | |
1914 | In [2]: %parts A B\\ |
|
1914 | In [2]: %parts A B\\ | |
1915 | first A second B\\ |
|
1915 | first A second B\\ | |
1916 | In [3]: %parts A\\ |
|
1916 | In [3]: %parts A\\ | |
1917 | Incorrect number of arguments: 2 expected.\\ |
|
1917 | Incorrect number of arguments: 2 expected.\\ | |
1918 | parts is an alias to: 'echo first %s second %s' |
|
1918 | parts is an alias to: 'echo first %s second %s' | |
1919 |
|
1919 | |||
1920 | Note that %l and %s are mutually exclusive. You can only use one or |
|
1920 | Note that %l and %s are mutually exclusive. You can only use one or | |
1921 | the other in your aliases. |
|
1921 | the other in your aliases. | |
1922 |
|
1922 | |||
1923 | Aliases expand Python variables just like system calls using ! or !! |
|
1923 | Aliases expand Python variables just like system calls using ! or !! | |
1924 | do: all expressions prefixed with '$' get expanded. For details of |
|
1924 | do: all expressions prefixed with '$' get expanded. For details of | |
1925 | the semantic rules, see PEP-215: |
|
1925 | the semantic rules, see PEP-215: | |
1926 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
1926 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
1927 | IPython for variable expansion. If you want to access a true shell |
|
1927 | IPython for variable expansion. If you want to access a true shell | |
1928 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
1928 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
1929 |
|
1929 | |||
1930 | In [6]: alias show echo\\ |
|
1930 | In [6]: alias show echo\\ | |
1931 | In [7]: PATH='A Python string'\\ |
|
1931 | In [7]: PATH='A Python string'\\ | |
1932 | In [8]: show $PATH\\ |
|
1932 | In [8]: show $PATH\\ | |
1933 | A Python string\\ |
|
1933 | A Python string\\ | |
1934 | In [9]: show $$PATH\\ |
|
1934 | In [9]: show $$PATH\\ | |
1935 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
1935 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
1936 |
|
1936 | |||
1937 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
1937 | You can use the alias facility to acess all of $PATH. See the %rehash | |
1938 | and %rehashx functions, which automatically create aliases for the |
|
1938 | and %rehashx functions, which automatically create aliases for the | |
1939 | contents of your $PATH. |
|
1939 | contents of your $PATH. | |
1940 |
|
1940 | |||
1941 | If called with no parameters, %alias prints the current alias table.""" |
|
1941 | If called with no parameters, %alias prints the current alias table.""" | |
1942 |
|
1942 | |||
1943 | par = parameter_s.strip() |
|
1943 | par = parameter_s.strip() | |
1944 | if not par: |
|
1944 | if not par: | |
1945 | if self.shell.rc.automagic: |
|
1945 | if self.shell.rc.automagic: | |
1946 | prechar = '' |
|
1946 | prechar = '' | |
1947 | else: |
|
1947 | else: | |
1948 | prechar = self.shell.ESC_MAGIC |
|
1948 | prechar = self.shell.ESC_MAGIC | |
1949 | print 'Alias\t\tSystem Command\n'+'-'*30 |
|
1949 | print 'Alias\t\tSystem Command\n'+'-'*30 | |
1950 | atab = self.shell.alias_table |
|
1950 | atab = self.shell.alias_table | |
1951 | aliases = atab.keys() |
|
1951 | aliases = atab.keys() | |
1952 | aliases.sort() |
|
1952 | aliases.sort() | |
1953 | for alias in aliases: |
|
1953 | for alias in aliases: | |
1954 | print prechar+alias+'\t\t'+atab[alias][1] |
|
1954 | print prechar+alias+'\t\t'+atab[alias][1] | |
1955 | print '-'*30+'\nTotal number of aliases:',len(aliases) |
|
1955 | print '-'*30+'\nTotal number of aliases:',len(aliases) | |
1956 | return |
|
1956 | return | |
1957 | try: |
|
1957 | try: | |
1958 | alias,cmd = par.split(None,1) |
|
1958 | alias,cmd = par.split(None,1) | |
1959 | except: |
|
1959 | except: | |
1960 | print OInspect.getdoc(self.magic_alias) |
|
1960 | print OInspect.getdoc(self.magic_alias) | |
1961 | else: |
|
1961 | else: | |
1962 | nargs = cmd.count('%s') |
|
1962 | nargs = cmd.count('%s') | |
1963 | if nargs>0 and cmd.find('%l')>=0: |
|
1963 | if nargs>0 and cmd.find('%l')>=0: | |
1964 | error('The %s and %l specifiers are mutually exclusive ' |
|
1964 | error('The %s and %l specifiers are mutually exclusive ' | |
1965 | 'in alias definitions.') |
|
1965 | 'in alias definitions.') | |
1966 | else: # all looks OK |
|
1966 | else: # all looks OK | |
1967 | self.shell.alias_table[alias] = (nargs,cmd) |
|
1967 | self.shell.alias_table[alias] = (nargs,cmd) | |
1968 | self.shell.alias_table_validate(verbose=1) |
|
1968 | self.shell.alias_table_validate(verbose=1) | |
1969 | # end magic_alias |
|
1969 | # end magic_alias | |
1970 |
|
1970 | |||
1971 | def magic_unalias(self, parameter_s = ''): |
|
1971 | def magic_unalias(self, parameter_s = ''): | |
1972 | """Remove an alias""" |
|
1972 | """Remove an alias""" | |
1973 |
|
1973 | |||
1974 | aname = parameter_s.strip() |
|
1974 | aname = parameter_s.strip() | |
1975 | if aname in self.shell.alias_table: |
|
1975 | if aname in self.shell.alias_table: | |
1976 | del self.shell.alias_table[aname] |
|
1976 | del self.shell.alias_table[aname] | |
1977 |
|
1977 | |||
1978 | def magic_rehash(self, parameter_s = ''): |
|
1978 | def magic_rehash(self, parameter_s = ''): | |
1979 | """Update the alias table with all entries in $PATH. |
|
1979 | """Update the alias table with all entries in $PATH. | |
1980 |
|
1980 | |||
1981 | This version does no checks on execute permissions or whether the |
|
1981 | This version does no checks on execute permissions or whether the | |
1982 | contents of $PATH are truly files (instead of directories or something |
|
1982 | contents of $PATH are truly files (instead of directories or something | |
1983 | else). For such a safer (but slower) version, use %rehashx.""" |
|
1983 | else). For such a safer (but slower) version, use %rehashx.""" | |
1984 |
|
1984 | |||
1985 | # This function (and rehashx) manipulate the alias_table directly |
|
1985 | # This function (and rehashx) manipulate the alias_table directly | |
1986 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
1986 | # rather than calling magic_alias, for speed reasons. A rehash on a | |
1987 | # typical Linux box involves several thousand entries, so efficiency |
|
1987 | # typical Linux box involves several thousand entries, so efficiency | |
1988 | # here is a top concern. |
|
1988 | # here is a top concern. | |
1989 |
|
1989 | |||
1990 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
1990 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) | |
1991 | alias_table = self.shell.alias_table |
|
1991 | alias_table = self.shell.alias_table | |
1992 | for pdir in path: |
|
1992 | for pdir in path: | |
1993 | for ff in os.listdir(pdir): |
|
1993 | for ff in os.listdir(pdir): | |
1994 | # each entry in the alias table must be (N,name), where |
|
1994 | # each entry in the alias table must be (N,name), where | |
1995 | # N is the number of positional arguments of the alias. |
|
1995 | # N is the number of positional arguments of the alias. | |
1996 | alias_table[ff] = (0,ff) |
|
1996 | alias_table[ff] = (0,ff) | |
1997 | # Make sure the alias table doesn't contain keywords or builtins |
|
1997 | # Make sure the alias table doesn't contain keywords or builtins | |
1998 | self.shell.alias_table_validate() |
|
1998 | self.shell.alias_table_validate() | |
1999 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
1999 | # Call again init_auto_alias() so we get 'rm -i' and other modified | |
2000 | # aliases since %rehash will probably clobber them |
|
2000 | # aliases since %rehash will probably clobber them | |
2001 | self.shell.init_auto_alias() |
|
2001 | self.shell.init_auto_alias() | |
2002 |
|
2002 | |||
2003 | def magic_rehashx(self, parameter_s = ''): |
|
2003 | def magic_rehashx(self, parameter_s = ''): | |
2004 | """Update the alias table with all executable files in $PATH. |
|
2004 | """Update the alias table with all executable files in $PATH. | |
2005 |
|
2005 | |||
2006 | This version explicitly checks that every entry in $PATH is a file |
|
2006 | This version explicitly checks that every entry in $PATH is a file | |
2007 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2007 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2008 |
|
2008 | |||
2009 | Under Windows, it checks executability as a match agains a |
|
2009 | Under Windows, it checks executability as a match agains a | |
2010 | '|'-separated string of extensions, stored in the IPython config |
|
2010 | '|'-separated string of extensions, stored in the IPython config | |
2011 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ |
|
2011 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ | |
2012 |
|
2012 | |||
2013 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
2013 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) | |
2014 | alias_table = self.shell.alias_table |
|
2014 | alias_table = self.shell.alias_table | |
2015 |
|
2015 | |||
2016 | if os.name == 'posix': |
|
2016 | if os.name == 'posix': | |
2017 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2017 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2018 | os.access(fname,os.X_OK) |
|
2018 | os.access(fname,os.X_OK) | |
2019 | else: |
|
2019 | else: | |
2020 |
|
2020 | |||
2021 | try: |
|
2021 | try: | |
2022 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2022 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2023 | except KeyError: |
|
2023 | except KeyError: | |
2024 | winext = 'exe|com|bat' |
|
2024 | winext = 'exe|com|bat' | |
2025 |
|
2025 | |||
2026 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2026 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2027 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2027 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2028 | savedir = os.getcwd() |
|
2028 | savedir = os.getcwd() | |
2029 | try: |
|
2029 | try: | |
2030 | # write the whole loop for posix/Windows so we don't have an if in |
|
2030 | # write the whole loop for posix/Windows so we don't have an if in | |
2031 | # the innermost part |
|
2031 | # the innermost part | |
2032 | if os.name == 'posix': |
|
2032 | if os.name == 'posix': | |
2033 | for pdir in path: |
|
2033 | for pdir in path: | |
2034 | os.chdir(pdir) |
|
2034 | os.chdir(pdir) | |
2035 | for ff in os.listdir(pdir): |
|
2035 | for ff in os.listdir(pdir): | |
2036 | if isexec(ff): |
|
2036 | if isexec(ff): | |
2037 | # each entry in the alias table must be (N,name), |
|
2037 | # each entry in the alias table must be (N,name), | |
2038 | # where N is the number of positional arguments of the |
|
2038 | # where N is the number of positional arguments of the | |
2039 | # alias. |
|
2039 | # alias. | |
2040 | alias_table[ff] = (0,ff) |
|
2040 | alias_table[ff] = (0,ff) | |
2041 | else: |
|
2041 | else: | |
2042 | for pdir in path: |
|
2042 | for pdir in path: | |
2043 | os.chdir(pdir) |
|
2043 | os.chdir(pdir) | |
2044 | for ff in os.listdir(pdir): |
|
2044 | for ff in os.listdir(pdir): | |
2045 | if isexec(ff): |
|
2045 | if isexec(ff): | |
2046 | alias_table[execre.sub(r'\1',ff)] = (0,ff) |
|
2046 | alias_table[execre.sub(r'\1',ff)] = (0,ff) | |
2047 | # Make sure the alias table doesn't contain keywords or builtins |
|
2047 | # Make sure the alias table doesn't contain keywords or builtins | |
2048 | self.shell.alias_table_validate() |
|
2048 | self.shell.alias_table_validate() | |
2049 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2049 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2050 | # modified aliases since %rehashx will probably clobber them |
|
2050 | # modified aliases since %rehashx will probably clobber them | |
2051 | self.shell.init_auto_alias() |
|
2051 | self.shell.init_auto_alias() | |
2052 | finally: |
|
2052 | finally: | |
2053 | os.chdir(savedir) |
|
2053 | os.chdir(savedir) | |
2054 |
|
2054 | |||
2055 | def magic_pwd(self, parameter_s = ''): |
|
2055 | def magic_pwd(self, parameter_s = ''): | |
2056 | """Return the current working directory path.""" |
|
2056 | """Return the current working directory path.""" | |
2057 | return os.getcwd() |
|
2057 | return os.getcwd() | |
2058 |
|
2058 | |||
2059 | def magic_cd(self, parameter_s=''): |
|
2059 | def magic_cd(self, parameter_s=''): | |
2060 | """Change the current working directory. |
|
2060 | """Change the current working directory. | |
2061 |
|
2061 | |||
2062 | This command automatically maintains an internal list of directories |
|
2062 | This command automatically maintains an internal list of directories | |
2063 | you visit during your IPython session, in the variable _dh. The |
|
2063 | you visit during your IPython session, in the variable _dh. The | |
2064 | command %dhist shows this history nicely formatted. |
|
2064 | command %dhist shows this history nicely formatted. | |
2065 |
|
2065 | |||
2066 | Usage: |
|
2066 | Usage: | |
2067 |
|
2067 | |||
2068 | cd 'dir': changes to directory 'dir'. |
|
2068 | cd 'dir': changes to directory 'dir'. | |
2069 |
|
2069 | |||
2070 | cd -: changes to the last visited directory. |
|
2070 | cd -: changes to the last visited directory. | |
2071 |
|
2071 | |||
2072 | cd -<n>: changes to the n-th directory in the directory history. |
|
2072 | cd -<n>: changes to the n-th directory in the directory history. | |
2073 |
|
2073 | |||
2074 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2074 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2075 | (note: cd <bookmark_name> is enough if there is no |
|
2075 | (note: cd <bookmark_name> is enough if there is no | |
2076 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2076 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2077 |
|
2077 | |||
2078 | Options: |
|
2078 | Options: | |
2079 |
|
2079 | |||
2080 | -q: quiet. Do not print the working directory after the cd command is |
|
2080 | -q: quiet. Do not print the working directory after the cd command is | |
2081 | executed. By default IPython's cd command does print this directory, |
|
2081 | executed. By default IPython's cd command does print this directory, | |
2082 | since the default prompts do not display path information. |
|
2082 | since the default prompts do not display path information. | |
2083 |
|
2083 | |||
2084 | Note that !cd doesn't work for this purpose because the shell where |
|
2084 | Note that !cd doesn't work for this purpose because the shell where | |
2085 | !command runs is immediately discarded after executing 'command'.""" |
|
2085 | !command runs is immediately discarded after executing 'command'.""" | |
2086 |
|
2086 | |||
2087 | parameter_s = parameter_s.strip() |
|
2087 | parameter_s = parameter_s.strip() | |
2088 | bkms = self.shell.persist.get("bookmarks",{}) |
|
2088 | bkms = self.shell.persist.get("bookmarks",{}) | |
2089 |
|
2089 | |||
2090 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2090 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2091 | # jump in directory history by number |
|
2091 | # jump in directory history by number | |
2092 | if numcd: |
|
2092 | if numcd: | |
2093 | nn = int(numcd.group(2)) |
|
2093 | nn = int(numcd.group(2)) | |
2094 | try: |
|
2094 | try: | |
2095 | ps = self.shell.user_ns['_dh'][nn] |
|
2095 | ps = self.shell.user_ns['_dh'][nn] | |
2096 | except IndexError: |
|
2096 | except IndexError: | |
2097 | print 'The requested directory does not exist in history.' |
|
2097 | print 'The requested directory does not exist in history.' | |
2098 | return |
|
2098 | return | |
2099 | else: |
|
2099 | else: | |
2100 | opts = {} |
|
2100 | opts = {} | |
2101 | else: |
|
2101 | else: | |
2102 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2102 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2103 | # jump to previous |
|
2103 | # jump to previous | |
2104 | if ps == '-': |
|
2104 | if ps == '-': | |
2105 | try: |
|
2105 | try: | |
2106 | ps = self.shell.user_ns['_dh'][-2] |
|
2106 | ps = self.shell.user_ns['_dh'][-2] | |
2107 | except IndexError: |
|
2107 | except IndexError: | |
2108 | print 'No previous directory to change to.' |
|
2108 | print 'No previous directory to change to.' | |
2109 | return |
|
2109 | return | |
2110 | # jump to bookmark |
|
2110 | # jump to bookmark | |
2111 | elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)): |
|
2111 | elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)): | |
2112 | if bkms.has_key(ps): |
|
2112 | if bkms.has_key(ps): | |
2113 | target = bkms[ps] |
|
2113 | target = bkms[ps] | |
2114 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2114 | print '(bookmark:%s) -> %s' % (ps,target) | |
2115 | ps = target |
|
2115 | ps = target | |
2116 | else: |
|
2116 | else: | |
2117 | if bkms: |
|
2117 | if bkms: | |
2118 | error("Bookmark '%s' not found. " |
|
2118 | error("Bookmark '%s' not found. " | |
2119 | "Use '%bookmark -l' to see your bookmarks." % ps) |
|
2119 | "Use '%bookmark -l' to see your bookmarks." % ps) | |
2120 | else: |
|
2120 | else: | |
2121 | print "Bookmarks not set - use %bookmark <bookmarkname>" |
|
2121 | print "Bookmarks not set - use %bookmark <bookmarkname>" | |
2122 | return |
|
2122 | return | |
2123 |
|
2123 | |||
2124 | # at this point ps should point to the target dir |
|
2124 | # at this point ps should point to the target dir | |
2125 | if ps: |
|
2125 | if ps: | |
2126 | try: |
|
2126 | try: | |
2127 | os.chdir(os.path.expanduser(ps)) |
|
2127 | os.chdir(os.path.expanduser(ps)) | |
2128 | except OSError: |
|
2128 | except OSError: | |
2129 | print sys.exc_info()[1] |
|
2129 | print sys.exc_info()[1] | |
2130 | else: |
|
2130 | else: | |
2131 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2131 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2132 | else: |
|
2132 | else: | |
2133 | os.chdir(self.home_dir) |
|
2133 | os.chdir(self.home_dir) | |
2134 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2134 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2135 | if not 'q' in opts: |
|
2135 | if not 'q' in opts: | |
2136 | print self.shell.user_ns['_dh'][-1] |
|
2136 | print self.shell.user_ns['_dh'][-1] | |
2137 |
|
2137 | |||
2138 | def magic_dhist(self, parameter_s=''): |
|
2138 | def magic_dhist(self, parameter_s=''): | |
2139 | """Print your history of visited directories. |
|
2139 | """Print your history of visited directories. | |
2140 |
|
2140 | |||
2141 | %dhist -> print full history\\ |
|
2141 | %dhist -> print full history\\ | |
2142 | %dhist n -> print last n entries only\\ |
|
2142 | %dhist n -> print last n entries only\\ | |
2143 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2143 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2144 |
|
2144 | |||
2145 | This history is automatically maintained by the %cd command, and |
|
2145 | This history is automatically maintained by the %cd command, and | |
2146 | always available as the global list variable _dh. You can use %cd -<n> |
|
2146 | always available as the global list variable _dh. You can use %cd -<n> | |
2147 | to go to directory number <n>.""" |
|
2147 | to go to directory number <n>.""" | |
2148 |
|
2148 | |||
2149 | dh = self.shell.user_ns['_dh'] |
|
2149 | dh = self.shell.user_ns['_dh'] | |
2150 | if parameter_s: |
|
2150 | if parameter_s: | |
2151 | try: |
|
2151 | try: | |
2152 | args = map(int,parameter_s.split()) |
|
2152 | args = map(int,parameter_s.split()) | |
2153 | except: |
|
2153 | except: | |
2154 | self.arg_err(Magic.magic_dhist) |
|
2154 | self.arg_err(Magic.magic_dhist) | |
2155 | return |
|
2155 | return | |
2156 | if len(args) == 1: |
|
2156 | if len(args) == 1: | |
2157 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2157 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2158 | elif len(args) == 2: |
|
2158 | elif len(args) == 2: | |
2159 | ini,fin = args |
|
2159 | ini,fin = args | |
2160 | else: |
|
2160 | else: | |
2161 | self.arg_err(Magic.magic_dhist) |
|
2161 | self.arg_err(Magic.magic_dhist) | |
2162 | return |
|
2162 | return | |
2163 | else: |
|
2163 | else: | |
2164 | ini,fin = 0,len(dh) |
|
2164 | ini,fin = 0,len(dh) | |
2165 | nlprint(dh, |
|
2165 | nlprint(dh, | |
2166 | header = 'Directory history (kept in _dh)', |
|
2166 | header = 'Directory history (kept in _dh)', | |
2167 | start=ini,stop=fin) |
|
2167 | start=ini,stop=fin) | |
2168 |
|
2168 | |||
2169 | def magic_env(self, parameter_s=''): |
|
2169 | def magic_env(self, parameter_s=''): | |
2170 | """List environment variables.""" |
|
2170 | """List environment variables.""" | |
2171 |
|
2171 | |||
2172 | # environ is an instance of UserDict |
|
2172 | # environ is an instance of UserDict | |
2173 | return os.environ.data |
|
2173 | return os.environ.data | |
2174 |
|
2174 | |||
2175 | def magic_pushd(self, parameter_s=''): |
|
2175 | def magic_pushd(self, parameter_s=''): | |
2176 | """Place the current dir on stack and change directory. |
|
2176 | """Place the current dir on stack and change directory. | |
2177 |
|
2177 | |||
2178 | Usage:\\ |
|
2178 | Usage:\\ | |
2179 | %pushd ['dirname'] |
|
2179 | %pushd ['dirname'] | |
2180 |
|
2180 | |||
2181 | %pushd with no arguments does a %pushd to your home directory. |
|
2181 | %pushd with no arguments does a %pushd to your home directory. | |
2182 | """ |
|
2182 | """ | |
2183 | if parameter_s == '': parameter_s = '~' |
|
2183 | if parameter_s == '': parameter_s = '~' | |
2184 | if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \ |
|
2184 | if len(self.dir_stack)>0 and os.path.expanduser(parameter_s) != \ | |
2185 | os.path.expanduser(self.dir_stack[0]): |
|
2185 | os.path.expanduser(self.dir_stack[0]): | |
2186 | try: |
|
2186 | try: | |
2187 | self.magic_cd(parameter_s) |
|
2187 | self.magic_cd(parameter_s) | |
2188 | self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2188 | self.dir_stack.insert(0,os.getcwd().replace(self.home_dir,'~')) | |
2189 | self.magic_dirs() |
|
2189 | self.magic_dirs() | |
2190 | except: |
|
2190 | except: | |
2191 | print 'Invalid directory' |
|
2191 | print 'Invalid directory' | |
2192 | else: |
|
2192 | else: | |
2193 | print 'You are already there!' |
|
2193 | print 'You are already there!' | |
2194 |
|
2194 | |||
2195 | def magic_popd(self, parameter_s=''): |
|
2195 | def magic_popd(self, parameter_s=''): | |
2196 | """Change to directory popped off the top of the stack. |
|
2196 | """Change to directory popped off the top of the stack. | |
2197 | """ |
|
2197 | """ | |
2198 | if len (self.dir_stack) > 1: |
|
2198 | if len (self.dir_stack) > 1: | |
2199 | self.dir_stack.pop(0) |
|
2199 | self.dir_stack.pop(0) | |
2200 | self.magic_cd(self.dir_stack[0]) |
|
2200 | self.magic_cd(self.dir_stack[0]) | |
2201 | print self.dir_stack[0] |
|
2201 | print self.dir_stack[0] | |
2202 | else: |
|
2202 | else: | |
2203 | print "You can't remove the starting directory from the stack:",\ |
|
2203 | print "You can't remove the starting directory from the stack:",\ | |
2204 | self.dir_stack |
|
2204 | self.dir_stack | |
2205 |
|
2205 | |||
2206 | def magic_dirs(self, parameter_s=''): |
|
2206 | def magic_dirs(self, parameter_s=''): | |
2207 | """Return the current directory stack.""" |
|
2207 | """Return the current directory stack.""" | |
2208 |
|
2208 | |||
2209 | return self.dir_stack[:] |
|
2209 | return self.dir_stack[:] | |
2210 |
|
2210 | |||
2211 | def magic_sc(self, parameter_s=''): |
|
2211 | def magic_sc(self, parameter_s=''): | |
2212 | """Shell capture - execute a shell command and capture its output. |
|
2212 | """Shell capture - execute a shell command and capture its output. | |
2213 |
|
2213 | |||
2214 | %sc [options] varname=command |
|
2214 | %sc [options] varname=command | |
2215 |
|
2215 | |||
2216 | IPython will run the given command using commands.getoutput(), and |
|
2216 | IPython will run the given command using commands.getoutput(), and | |
2217 | will then update the user's interactive namespace with a variable |
|
2217 | will then update the user's interactive namespace with a variable | |
2218 | called varname, containing the value of the call. Your command can |
|
2218 | called varname, containing the value of the call. Your command can | |
2219 | contain shell wildcards, pipes, etc. |
|
2219 | contain shell wildcards, pipes, etc. | |
2220 |
|
2220 | |||
2221 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2221 | The '=' sign in the syntax is mandatory, and the variable name you | |
2222 | supply must follow Python's standard conventions for valid names. |
|
2222 | supply must follow Python's standard conventions for valid names. | |
2223 |
|
2223 | |||
2224 | Options: |
|
2224 | Options: | |
2225 |
|
2225 | |||
2226 | -l: list output. Split the output on newlines into a list before |
|
2226 | -l: list output. Split the output on newlines into a list before | |
2227 | assigning it to the given variable. By default the output is stored |
|
2227 | assigning it to the given variable. By default the output is stored | |
2228 | as a single string. |
|
2228 | as a single string. | |
2229 |
|
2229 | |||
2230 | -v: verbose. Print the contents of the variable. |
|
2230 | -v: verbose. Print the contents of the variable. | |
2231 |
|
2231 | |||
2232 | In most cases you should not need to split as a list, because the |
|
2232 | In most cases you should not need to split as a list, because the | |
2233 | returned value is a special type of string which can automatically |
|
2233 | returned value is a special type of string which can automatically | |
2234 | provide its contents either as a list (split on newlines) or as a |
|
2234 | provide its contents either as a list (split on newlines) or as a | |
2235 | space-separated string. These are convenient, respectively, either |
|
2235 | space-separated string. These are convenient, respectively, either | |
2236 | for sequential processing or to be passed to a shell command. |
|
2236 | for sequential processing or to be passed to a shell command. | |
2237 |
|
2237 | |||
2238 | For example: |
|
2238 | For example: | |
2239 |
|
2239 | |||
2240 | # Capture into variable a |
|
2240 | # Capture into variable a | |
2241 | In [9]: sc a=ls *py |
|
2241 | In [9]: sc a=ls *py | |
2242 |
|
2242 | |||
2243 | # a is a string with embedded newlines |
|
2243 | # a is a string with embedded newlines | |
2244 | In [10]: a |
|
2244 | In [10]: a | |
2245 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2245 | Out[10]: 'setup.py\nwin32_manual_post_install.py' | |
2246 |
|
2246 | |||
2247 | # which can be seen as a list: |
|
2247 | # which can be seen as a list: | |
2248 | In [11]: a.l |
|
2248 | In [11]: a.l | |
2249 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2249 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] | |
2250 |
|
2250 | |||
2251 | # or as a whitespace-separated string: |
|
2251 | # or as a whitespace-separated string: | |
2252 | In [12]: a.s |
|
2252 | In [12]: a.s | |
2253 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2253 | Out[12]: 'setup.py win32_manual_post_install.py' | |
2254 |
|
2254 | |||
2255 | # a.s is useful to pass as a single command line: |
|
2255 | # a.s is useful to pass as a single command line: | |
2256 | In [13]: !wc -l $a.s |
|
2256 | In [13]: !wc -l $a.s | |
2257 | 146 setup.py |
|
2257 | 146 setup.py | |
2258 | 130 win32_manual_post_install.py |
|
2258 | 130 win32_manual_post_install.py | |
2259 | 276 total |
|
2259 | 276 total | |
2260 |
|
2260 | |||
2261 | # while the list form is useful to loop over: |
|
2261 | # while the list form is useful to loop over: | |
2262 | In [14]: for f in a.l: |
|
2262 | In [14]: for f in a.l: | |
2263 | ....: !wc -l $f |
|
2263 | ....: !wc -l $f | |
2264 | ....: |
|
2264 | ....: | |
2265 | 146 setup.py |
|
2265 | 146 setup.py | |
2266 | 130 win32_manual_post_install.py |
|
2266 | 130 win32_manual_post_install.py | |
2267 |
|
2267 | |||
2268 | Similiarly, the lists returned by the -l option are also special, in |
|
2268 | Similiarly, the lists returned by the -l option are also special, in | |
2269 | the sense that you can equally invoke the .s attribute on them to |
|
2269 | the sense that you can equally invoke the .s attribute on them to | |
2270 | automatically get a whitespace-separated string from their contents: |
|
2270 | automatically get a whitespace-separated string from their contents: | |
2271 |
|
2271 | |||
2272 | In [1]: sc -l b=ls *py |
|
2272 | In [1]: sc -l b=ls *py | |
2273 |
|
2273 | |||
2274 | In [2]: b |
|
2274 | In [2]: b | |
2275 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2275 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] | |
2276 |
|
2276 | |||
2277 | In [3]: b.s |
|
2277 | In [3]: b.s | |
2278 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2278 | Out[3]: 'setup.py win32_manual_post_install.py' | |
2279 |
|
2279 | |||
2280 | In summary, both the lists and strings used for ouptut capture have |
|
2280 | In summary, both the lists and strings used for ouptut capture have | |
2281 | the following special attributes: |
|
2281 | the following special attributes: | |
2282 |
|
2282 | |||
2283 | .l (or .list) : value as list. |
|
2283 | .l (or .list) : value as list. | |
2284 | .n (or .nlstr): value as newline-separated string. |
|
2284 | .n (or .nlstr): value as newline-separated string. | |
2285 | .s (or .spstr): value as space-separated string. |
|
2285 | .s (or .spstr): value as space-separated string. | |
2286 | """ |
|
2286 | """ | |
2287 |
|
2287 | |||
2288 | opts,args = self.parse_options(parameter_s,'lv') |
|
2288 | opts,args = self.parse_options(parameter_s,'lv') | |
2289 | # Try to get a variable name and command to run |
|
2289 | # Try to get a variable name and command to run | |
2290 | try: |
|
2290 | try: | |
2291 | # the variable name must be obtained from the parse_options |
|
2291 | # the variable name must be obtained from the parse_options | |
2292 | # output, which uses shlex.split to strip options out. |
|
2292 | # output, which uses shlex.split to strip options out. | |
2293 | var,_ = args.split('=',1) |
|
2293 | var,_ = args.split('=',1) | |
2294 | var = var.strip() |
|
2294 | var = var.strip() | |
2295 | # But the the command has to be extracted from the original input |
|
2295 | # But the the command has to be extracted from the original input | |
2296 | # parameter_s, not on what parse_options returns, to avoid the |
|
2296 | # parameter_s, not on what parse_options returns, to avoid the | |
2297 | # quote stripping which shlex.split performs on it. |
|
2297 | # quote stripping which shlex.split performs on it. | |
2298 | _,cmd = parameter_s.split('=',1) |
|
2298 | _,cmd = parameter_s.split('=',1) | |
2299 | except ValueError: |
|
2299 | except ValueError: | |
2300 | var,cmd = '','' |
|
2300 | var,cmd = '','' | |
2301 | if not var: |
|
2301 | if not var: | |
2302 | error('you must specify a variable to assign the command to.') |
|
2302 | error('you must specify a variable to assign the command to.') | |
2303 | return |
|
2303 | return | |
2304 | # If all looks ok, proceed |
|
2304 | # If all looks ok, proceed | |
2305 | out,err = self.shell.getoutputerror(cmd) |
|
2305 | out,err = self.shell.getoutputerror(cmd) | |
2306 | if err: |
|
2306 | if err: | |
2307 | print >> Term.cerr,err |
|
2307 | print >> Term.cerr,err | |
2308 | if opts.has_key('l'): |
|
2308 | if opts.has_key('l'): | |
2309 | out = SList(out.split('\n')) |
|
2309 | out = SList(out.split('\n')) | |
2310 | else: |
|
2310 | else: | |
2311 | out = LSString(out) |
|
2311 | out = LSString(out) | |
2312 | if opts.has_key('v'): |
|
2312 | if opts.has_key('v'): | |
2313 | print '%s ==\n%s' % (var,pformat(out)) |
|
2313 | print '%s ==\n%s' % (var,pformat(out)) | |
2314 | self.shell.user_ns.update({var:out}) |
|
2314 | self.shell.user_ns.update({var:out}) | |
2315 |
|
2315 | |||
2316 | def magic_sx(self, parameter_s=''): |
|
2316 | def magic_sx(self, parameter_s=''): | |
2317 | """Shell execute - run a shell command and capture its output. |
|
2317 | """Shell execute - run a shell command and capture its output. | |
2318 |
|
2318 | |||
2319 | %sx command |
|
2319 | %sx command | |
2320 |
|
2320 | |||
2321 | IPython will run the given command using commands.getoutput(), and |
|
2321 | IPython will run the given command using commands.getoutput(), and | |
2322 | return the result formatted as a list (split on '\\n'). Since the |
|
2322 | return the result formatted as a list (split on '\\n'). Since the | |
2323 | output is _returned_, it will be stored in ipython's regular output |
|
2323 | output is _returned_, it will be stored in ipython's regular output | |
2324 | cache Out[N] and in the '_N' automatic variables. |
|
2324 | cache Out[N] and in the '_N' automatic variables. | |
2325 |
|
2325 | |||
2326 | Notes: |
|
2326 | Notes: | |
2327 |
|
2327 | |||
2328 | 1) If an input line begins with '!!', then %sx is automatically |
|
2328 | 1) If an input line begins with '!!', then %sx is automatically | |
2329 | invoked. That is, while: |
|
2329 | invoked. That is, while: | |
2330 | !ls |
|
2330 | !ls | |
2331 | causes ipython to simply issue system('ls'), typing |
|
2331 | causes ipython to simply issue system('ls'), typing | |
2332 | !!ls |
|
2332 | !!ls | |
2333 | is a shorthand equivalent to: |
|
2333 | is a shorthand equivalent to: | |
2334 | %sx ls |
|
2334 | %sx ls | |
2335 |
|
2335 | |||
2336 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2336 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2337 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2337 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2338 | to process line-oriented shell output via further python commands. |
|
2338 | to process line-oriented shell output via further python commands. | |
2339 | %sc is meant to provide much finer control, but requires more |
|
2339 | %sc is meant to provide much finer control, but requires more | |
2340 | typing. |
|
2340 | typing. | |
2341 |
|
2341 | |||
2342 | 3) Just like %sc -l, this is a list with special attributes: |
|
2342 | 3) Just like %sc -l, this is a list with special attributes: | |
2343 |
|
2343 | |||
2344 | .l (or .list) : value as list. |
|
2344 | .l (or .list) : value as list. | |
2345 | .n (or .nlstr): value as newline-separated string. |
|
2345 | .n (or .nlstr): value as newline-separated string. | |
2346 | .s (or .spstr): value as whitespace-separated string. |
|
2346 | .s (or .spstr): value as whitespace-separated string. | |
2347 |
|
2347 | |||
2348 | This is very useful when trying to use such lists as arguments to |
|
2348 | This is very useful when trying to use such lists as arguments to | |
2349 | system commands.""" |
|
2349 | system commands.""" | |
2350 |
|
2350 | |||
2351 | if parameter_s: |
|
2351 | if parameter_s: | |
2352 | out,err = self.shell.getoutputerror(parameter_s) |
|
2352 | out,err = self.shell.getoutputerror(parameter_s) | |
2353 | if err: |
|
2353 | if err: | |
2354 | print >> Term.cerr,err |
|
2354 | print >> Term.cerr,err | |
2355 | return SList(out.split('\n')) |
|
2355 | return SList(out.split('\n')) | |
2356 |
|
2356 | |||
2357 | def magic_bg(self, parameter_s=''): |
|
2357 | def magic_bg(self, parameter_s=''): | |
2358 | """Run a job in the background, in a separate thread. |
|
2358 | """Run a job in the background, in a separate thread. | |
2359 |
|
2359 | |||
2360 | For example, |
|
2360 | For example, | |
2361 |
|
2361 | |||
2362 | %bg myfunc(x,y,z=1) |
|
2362 | %bg myfunc(x,y,z=1) | |
2363 |
|
2363 | |||
2364 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2364 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
2365 | execution starts, a message will be printed indicating the job |
|
2365 | execution starts, a message will be printed indicating the job | |
2366 | number. If your job number is 5, you can use |
|
2366 | number. If your job number is 5, you can use | |
2367 |
|
2367 | |||
2368 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2368 | myvar = jobs.result(5) or myvar = jobs[5].result | |
2369 |
|
2369 | |||
2370 | to assign this result to variable 'myvar'. |
|
2370 | to assign this result to variable 'myvar'. | |
2371 |
|
2371 | |||
2372 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2372 | IPython has a job manager, accessible via the 'jobs' object. You can | |
2373 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2373 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
2374 | its attributes. All attributes not starting with an underscore are |
|
2374 | its attributes. All attributes not starting with an underscore are | |
2375 | meant for public use. |
|
2375 | meant for public use. | |
2376 |
|
2376 | |||
2377 | In particular, look at the jobs.new() method, which is used to create |
|
2377 | In particular, look at the jobs.new() method, which is used to create | |
2378 | new jobs. This magic %bg function is just a convenience wrapper |
|
2378 | new jobs. This magic %bg function is just a convenience wrapper | |
2379 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2379 | around jobs.new(), for expression-based jobs. If you want to create a | |
2380 | new job with an explicit function object and arguments, you must call |
|
2380 | new job with an explicit function object and arguments, you must call | |
2381 | jobs.new() directly. |
|
2381 | jobs.new() directly. | |
2382 |
|
2382 | |||
2383 | The jobs.new docstring also describes in detail several important |
|
2383 | The jobs.new docstring also describes in detail several important | |
2384 | caveats associated with a thread-based model for background job |
|
2384 | caveats associated with a thread-based model for background job | |
2385 | execution. Type jobs.new? for details. |
|
2385 | execution. Type jobs.new? for details. | |
2386 |
|
2386 | |||
2387 | You can check the status of all jobs with jobs.status(). |
|
2387 | You can check the status of all jobs with jobs.status(). | |
2388 |
|
2388 | |||
2389 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2389 | The jobs variable is set by IPython into the Python builtin namespace. | |
2390 | If you ever declare a variable named 'jobs', you will shadow this |
|
2390 | If you ever declare a variable named 'jobs', you will shadow this | |
2391 | name. You can either delete your global jobs variable to regain |
|
2391 | name. You can either delete your global jobs variable to regain | |
2392 | access to the job manager, or make a new name and assign it manually |
|
2392 | access to the job manager, or make a new name and assign it manually | |
2393 | to the manager (stored in IPython's namespace). For example, to |
|
2393 | to the manager (stored in IPython's namespace). For example, to | |
2394 | assign the job manager to the Jobs name, use: |
|
2394 | assign the job manager to the Jobs name, use: | |
2395 |
|
2395 | |||
2396 | Jobs = __builtins__.jobs""" |
|
2396 | Jobs = __builtins__.jobs""" | |
2397 |
|
2397 | |||
2398 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2398 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
2399 |
|
2399 | |||
2400 | def magic_bookmark(self, parameter_s=''): |
|
2400 | def magic_bookmark(self, parameter_s=''): | |
2401 | """Manage IPython's bookmark system. |
|
2401 | """Manage IPython's bookmark system. | |
2402 |
|
2402 | |||
2403 | %bookmark <name> - set bookmark to current dir |
|
2403 | %bookmark <name> - set bookmark to current dir | |
2404 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2404 | %bookmark <name> <dir> - set bookmark to <dir> | |
2405 | %bookmark -l - list all bookmarks |
|
2405 | %bookmark -l - list all bookmarks | |
2406 | %bookmark -d <name> - remove bookmark |
|
2406 | %bookmark -d <name> - remove bookmark | |
2407 | %bookmark -r - remove all bookmarks |
|
2407 | %bookmark -r - remove all bookmarks | |
2408 |
|
2408 | |||
2409 | You can later on access a bookmarked folder with: |
|
2409 | You can later on access a bookmarked folder with: | |
2410 | %cd -b <name> |
|
2410 | %cd -b <name> | |
2411 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2411 | or simply '%cd <name>' if there is no directory called <name> AND | |
2412 | there is such a bookmark defined. |
|
2412 | there is such a bookmark defined. | |
2413 |
|
2413 | |||
2414 | Your bookmarks persist through IPython sessions, but they are |
|
2414 | Your bookmarks persist through IPython sessions, but they are | |
2415 | associated with each profile.""" |
|
2415 | associated with each profile.""" | |
2416 |
|
2416 | |||
2417 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2417 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
2418 | if len(args) > 2: |
|
2418 | if len(args) > 2: | |
2419 | error('You can only give at most two arguments') |
|
2419 | error('You can only give at most two arguments') | |
2420 | return |
|
2420 | return | |
2421 |
|
2421 | |||
2422 | bkms = self.shell.persist.get('bookmarks',{}) |
|
2422 | bkms = self.shell.persist.get('bookmarks',{}) | |
2423 |
|
2423 | |||
2424 | if opts.has_key('d'): |
|
2424 | if opts.has_key('d'): | |
2425 | try: |
|
2425 | try: | |
2426 | todel = args[0] |
|
2426 | todel = args[0] | |
2427 | except IndexError: |
|
2427 | except IndexError: | |
2428 | error('You must provide a bookmark to delete') |
|
2428 | error('You must provide a bookmark to delete') | |
2429 | else: |
|
2429 | else: | |
2430 | try: |
|
2430 | try: | |
2431 | del bkms[todel] |
|
2431 | del bkms[todel] | |
2432 | except: |
|
2432 | except: | |
2433 | error("Can't delete bookmark '%s'" % todel) |
|
2433 | error("Can't delete bookmark '%s'" % todel) | |
2434 | elif opts.has_key('r'): |
|
2434 | elif opts.has_key('r'): | |
2435 | bkms = {} |
|
2435 | bkms = {} | |
2436 | elif opts.has_key('l'): |
|
2436 | elif opts.has_key('l'): | |
2437 | bks = bkms.keys() |
|
2437 | bks = bkms.keys() | |
2438 | bks.sort() |
|
2438 | bks.sort() | |
2439 | if bks: |
|
2439 | if bks: | |
2440 | size = max(map(len,bks)) |
|
2440 | size = max(map(len,bks)) | |
2441 | else: |
|
2441 | else: | |
2442 | size = 0 |
|
2442 | size = 0 | |
2443 | fmt = '%-'+str(size)+'s -> %s' |
|
2443 | fmt = '%-'+str(size)+'s -> %s' | |
2444 | print 'Current bookmarks:' |
|
2444 | print 'Current bookmarks:' | |
2445 | for bk in bks: |
|
2445 | for bk in bks: | |
2446 | print fmt % (bk,bkms[bk]) |
|
2446 | print fmt % (bk,bkms[bk]) | |
2447 | else: |
|
2447 | else: | |
2448 | if not args: |
|
2448 | if not args: | |
2449 | error("You must specify the bookmark name") |
|
2449 | error("You must specify the bookmark name") | |
2450 | elif len(args)==1: |
|
2450 | elif len(args)==1: | |
2451 | bkms[args[0]] = os.getcwd() |
|
2451 | bkms[args[0]] = os.getcwd() | |
2452 | elif len(args)==2: |
|
2452 | elif len(args)==2: | |
2453 | bkms[args[0]] = args[1] |
|
2453 | bkms[args[0]] = args[1] | |
2454 | self.persist['bookmarks'] = bkms |
|
2454 | self.persist['bookmarks'] = bkms | |
2455 |
|
2455 | |||
2456 | def magic_pycat(self, parameter_s=''): |
|
2456 | def magic_pycat(self, parameter_s=''): | |
2457 | """Show a syntax-highlighted file through a pager. |
|
2457 | """Show a syntax-highlighted file through a pager. | |
2458 |
|
2458 | |||
2459 | This magic is similar to the cat utility, but it will assume the file |
|
2459 | This magic is similar to the cat utility, but it will assume the file | |
2460 | to be Python source and will show it with syntax highlighting. """ |
|
2460 | to be Python source and will show it with syntax highlighting. """ | |
2461 |
|
2461 | |||
2462 | try: |
|
2462 | try: | |
2463 | filename = get_py_filename(parameter_s) |
|
2463 | filename = get_py_filename(parameter_s) | |
2464 | except IndexError: |
|
2464 | except IndexError: | |
2465 | warn('you must provide at least a filename.') |
|
2465 | warn('you must provide at least a filename.') | |
|
2466 | return | |||
2466 | fobj=open(filename,'r') |
|
2467 | fobj=open(filename,'r') | |
2467 | source = fobj.read() |
|
2468 | source = fobj.read() | |
2468 | fobj.close() |
|
2469 | fobj.close() | |
2469 | colorize = Parser().format |
|
2470 | colorize = Parser().format | |
2470 | colorized_src = colorize(source,'str',self.shell.rc['colors']) |
|
2471 | colorized_src = colorize(source,'str',self.shell.rc['colors']) | |
2471 | page(colorized_src,screen_lines=self.shell.rc.screen_length) |
|
2472 | page(colorized_src,screen_lines=self.shell.rc.screen_length) | |
2472 |
|
2473 | |||
2473 | # end Magic |
|
2474 | # end Magic |
@@ -1,178 +1,201 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 sys | |
14 | import exceptions |
|
14 | import exceptions | |
15 | import re |
|
15 | import re | |
16 |
|
16 | |||
17 | from IPython.PyColorize import Parser |
|
17 | from IPython.PyColorize import Parser | |
18 | from IPython.genutils import marquee, shlex_split |
|
18 | from IPython.genutils import marquee, shlex_split | |
19 |
|
19 | |||
20 | class DemoError(exceptions.Exception): pass |
|
20 | class DemoError(exceptions.Exception): pass | |
21 |
|
21 | |||
22 | class Demo: |
|
22 | class Demo: | |
23 | def __init__(self,fname,arg_str='',mark_pause='# pause', |
|
23 | def __init__(self,fname,arg_str='',mark_pause='# pause', | |
24 | mark_silent='# silent',auto=False): |
|
24 | mark_silent='# silent',mark_auto='# auto',auto=False): | |
25 | """Make a new demo object. To run the demo, simply call the object. |
|
25 | """Make a new demo object. To run the demo, simply call the object. | |
26 |
|
26 | |||
27 | Inputs: |
|
27 | Inputs: | |
28 |
|
28 | |||
29 | - fname = filename. |
|
29 | - fname = filename. | |
30 |
|
30 | |||
31 | Optional inputs: |
|
31 | Optional inputs: | |
32 |
|
32 | |||
33 | - arg_str(''): a string of arguments, internally converted to a list |
|
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 |
|
34 | just like sys.argv, so the demo script can see a similar | |
35 | environment. |
|
35 | environment. | |
36 |
|
36 | |||
37 |
- mark_pause ('# pause') |
|
37 | - mark_pause ('# pause'): marks for pausing (block boundaries). The | |
38 | (block boundaries) and to tag blocks as silent. The marks are |
|
38 | marks are turned into regexps which match them as standalone in a | |
39 | turned into regexps which match them as standalone in a line, with |
|
39 | line, with all leading/trailing whitespace ignored. | |
40 | all leading/trailing whitespace ignored. |
|
|||
41 |
|
40 | |||
42 | - auto(False): flag to run each block automatically without |
|
41 | - mark_silent('# silent'): mark blocks as silent, which means that | |
43 | confirmation. Note that silent blocks are always automatically |
|
42 | they are executed without printing their content to screen. Silent | |
44 | executed. This flag is an attribute of the object, and can be |
|
43 | blocks are always automatically executed. | |
45 | changed at runtime simply by reassigning it. |
|
44 | ||
|
45 | - mark_auto ('# auto'): mark individual blocks as automatically | |||
|
46 | executed (without asking for confirmation). | |||
|
47 | ||||
|
48 | - auto(False): global flag to run all blocks automatically without | |||
|
49 | confirmation. This attribute overrides the block-level tags and | |||
|
50 | applies to the whole demo. It is an attribute of the object, and | |||
|
51 | can be changed at runtime simply by reassigning it to a boolean | |||
|
52 | value. | |||
46 | """ |
|
53 | """ | |
47 |
|
54 | |||
48 | self.fname = fname |
|
55 | self.fname = fname | |
|
56 | self.sys_argv = [fname] + shlex_split(arg_str) | |||
49 | self.mark_pause = mark_pause |
|
57 | self.mark_pause = mark_pause | |
50 | self.re_pause = re.compile(r'^\s*%s\s*$' % mark_pause,re.MULTILINE) |
|
|||
51 | self.mark_silent = mark_silent |
|
58 | self.mark_silent = mark_silent | |
|
59 | self.re_pause = re.compile(r'^\s*%s\s*$' % mark_pause,re.MULTILINE) | |||
52 | self.re_silent = re.compile(r'^\s*%s\s*$' % mark_silent,re.MULTILINE) |
|
60 | self.re_silent = re.compile(r'^\s*%s\s*$' % mark_silent,re.MULTILINE) | |
|
61 | self.re_auto = re.compile(r'^\s*%s\s*$' % mark_auto,re.MULTILINE) | |||
53 | self.auto = auto |
|
62 | self.auto = auto | |
54 | self.sys_argv = [fname]+shlex_split(arg_str) |
|
|||
55 |
|
63 | |||
56 | # get a few things from ipython. While it's a bit ugly design-wise, |
|
64 | # get a few things from ipython. While it's a bit ugly design-wise, | |
57 | # it ensures that things like color scheme and the like are always in |
|
65 | # it ensures that things like color scheme and the like are always in | |
58 | # sync with the ipython mode being used. This class is only meant to |
|
66 | # sync with the ipython mode being used. This class is only meant to | |
59 | # be used inside ipython anyways, so it's OK. |
|
67 | # be used inside ipython anyways, so it's OK. | |
60 |
self.ip_showt |
|
68 | self.ip_showtb = __IPYTHON__.showtraceback | |
61 | self.ip_ns = __IPYTHON__.user_ns |
|
69 | self.ip_ns = __IPYTHON__.user_ns | |
62 | self.ip_colors = __IPYTHON__.rc['colors'] |
|
70 | self.ip_colors = __IPYTHON__.rc['colors'] | |
|
71 | self.colorize = Parser().format | |||
|
72 | ||||
|
73 | # load user data and initialize data structures | |||
|
74 | self.reload() | |||
63 |
|
75 | |||
|
76 | def reload(self): | |||
|
77 | """Reload source from disk and initialize state.""" | |||
64 | # read data and parse into blocks |
|
78 | # read data and parse into blocks | |
65 | fobj = file(fname,'r') |
|
79 | fobj = file(self.fname,'r') | |
66 | self.src = fobj.read() |
|
80 | self.src = fobj.read() | |
67 | fobj.close() |
|
81 | fobj.close() | |
68 |
|
|
82 | src_blocks = [b.strip() for b in self.re_pause.split(self.src) if b] | |
69 |
self.silent = [bool(self.re_silent.findall(b)) for b in |
|
83 | self._silent = [bool(self.re_silent.findall(b)) for b in src_blocks] | |
70 | self.nblocks = len(self.src_blocks) |
|
84 | self._auto = [bool(self.re_auto.findall(b)) for b in src_blocks] | |
|
85 | # strip out the 'auto' markers | |||
|
86 | src_b = [] | |||
|
87 | auto_strip = lambda s: self.re_auto.sub('',s) | |||
|
88 | for i,b in enumerate(src_blocks): | |||
|
89 | if self._auto[i]: | |||
|
90 | src_b.append(auto_strip(b)) | |||
|
91 | else: | |||
|
92 | src_b.append(b) | |||
|
93 | self.nblocks = len(src_b) | |||
|
94 | self.src_blocks = src_b | |||
71 |
|
95 | |||
72 | # try to colorize blocks |
|
96 | # try to colorize blocks | |
73 | colorize = Parser().format |
|
|||
74 | col_scheme = self.ip_colors |
|
97 | col_scheme = self.ip_colors | |
75 | self.src_blocks_colored = [colorize(s_blk,'str',col_scheme) |
|
98 | self.src_blocks_colored = [self.colorize(s_blk,'str',col_scheme) | |
76 | for s_blk in self.src_blocks] |
|
99 | for s_blk in self.src_blocks] | |
77 |
|
100 | # ensure clean namespace and seek offset | ||
78 | # finish initialization |
|
|||
79 | self.reset() |
|
101 | self.reset() | |
80 |
|
102 | |||
81 | def reset(self): |
|
103 | def reset(self): | |
82 | """Reset the namespace and seek pointer to restart the demo""" |
|
104 | """Reset the namespace and seek pointer to restart the demo""" | |
83 | self.user_ns = {} |
|
105 | self.user_ns = {} | |
84 | self.finished = False |
|
106 | self.finished = False | |
85 | self.block_index = 0 |
|
107 | self.block_index = 0 | |
86 |
|
108 | |||
87 | def again(self): |
|
109 | def again(self): | |
88 | """Repeat the last block""" |
|
110 | """Repeat the last block""" | |
89 | self.block_index -= 1 |
|
111 | self.block_index -= 1 | |
90 | self.finished = False |
|
112 | self.finished = False | |
91 | self() |
|
113 | self() | |
92 |
|
114 | |||
93 | def _validate_index(self,index): |
|
115 | def _validate_index(self,index): | |
94 | if index<0 or index>=self.nblocks: |
|
116 | if index<0 or index>=self.nblocks: | |
95 | raise ValueError('invalid block index %s' % index) |
|
117 | raise ValueError('invalid block index %s' % index) | |
96 |
|
118 | |||
97 | def seek(self,index): |
|
119 | def seek(self,index): | |
98 | """Move the current seek pointer to the given block""" |
|
120 | """Move the current seek pointer to the given block""" | |
99 | self._validate_index(index) |
|
121 | self._validate_index(index) | |
100 |
self.block_index = index |
|
122 | self.block_index = index | |
101 | self.finished = False |
|
123 | self.finished = False | |
102 |
|
124 | |||
103 |
def show |
|
125 | def show(self,index=None): | |
104 | """Show a single block on screen""" |
|
126 | """Show a single block on screen""" | |
105 | if index is None: |
|
127 | if index is None: | |
106 | if self.finished: |
|
128 | if self.finished: | |
107 | print 'Demo finished. Use reset() if you want to rerun it.' |
|
129 | print 'Demo finished. Use reset() if you want to rerun it.' | |
108 | return |
|
130 | return | |
109 | index = self.block_index |
|
131 | index = self.block_index | |
110 | else: |
|
132 | else: | |
111 | self._validate_index(index) |
|
133 | self._validate_index(index) | |
112 | print marquee('<%s> block # %s (%s remaining)' % |
|
134 | print marquee('<%s> block # %s (%s remaining)' % | |
113 | (self.fname,index,self.nblocks-index-1)) |
|
135 | (self.fname,index,self.nblocks-index-1)) | |
114 | print self.src_blocks_colored[index], |
|
136 | print self.src_blocks_colored[index], | |
115 |
|
137 | |||
116 | def show(self): |
|
138 | def show_all(self): | |
117 | """Show entire demo on screen, block by block""" |
|
139 | """Show entire demo on screen, block by block""" | |
118 |
|
140 | |||
119 | fname = self.fname |
|
141 | fname = self.fname | |
120 | nblocks = self.nblocks |
|
142 | nblocks = self.nblocks | |
121 | silent = self.silent |
|
143 | silent = self._silent | |
122 | for index,block in enumerate(self.src_blocks_colored): |
|
144 | for index,block in enumerate(self.src_blocks_colored): | |
123 | if silent[index]: |
|
145 | if silent[index]: | |
124 | print marquee('<%s> SILENT block # %s (%s remaining)' % |
|
146 | print marquee('<%s> SILENT block # %s (%s remaining)' % | |
125 | (fname,index,nblocks-index-1)) |
|
147 | (fname,index,nblocks-index-1)) | |
126 | else: |
|
148 | else: | |
127 | print marquee('<%s> block # %s (%s remaining)' % |
|
149 | print marquee('<%s> block # %s (%s remaining)' % | |
128 | (fname,index,nblocks-index-1)) |
|
150 | (fname,index,nblocks-index-1)) | |
129 | print block, |
|
151 | print block, | |
130 |
|
152 | |||
131 | def __call__(self,index=None): |
|
153 | def __call__(self,index=None): | |
132 | """run a block of the demo. |
|
154 | """run a block of the demo. | |
133 |
|
155 | |||
134 | If index is given, it should be an integer >=1 and <= nblocks. This |
|
156 | If index is given, it should be an integer >=1 and <= nblocks. This | |
135 | means that the calling convention is one off from typical Python |
|
157 | means that the calling convention is one off from typical Python | |
136 | lists. The reason for the inconsistency is that the demo always |
|
158 | lists. The reason for the inconsistency is that the demo always | |
137 | prints 'Block n/N, and N is the total, so it would be very odd to use |
|
159 | prints 'Block n/N, and N is the total, so it would be very odd to use | |
138 | zero-indexing here.""" |
|
160 | zero-indexing here.""" | |
139 |
|
161 | |||
140 | if index is None and self.finished: |
|
162 | if index is None and self.finished: | |
141 | print 'Demo finished. Use reset() if you want to rerun it.' |
|
163 | print 'Demo finished. Use reset() if you want to rerun it.' | |
142 | return |
|
164 | return | |
143 | if index is None: |
|
165 | if index is None: | |
144 | index = self.block_index |
|
166 | index = self.block_index | |
145 | self._validate_index(index) |
|
167 | self._validate_index(index) | |
146 | try: |
|
168 | try: | |
147 | next_block = self.src_blocks[index] |
|
169 | next_block = self.src_blocks[index] | |
148 | self.block_index += 1 |
|
170 | self.block_index += 1 | |
149 | if self.silent[index]: |
|
171 | if self._silent[index]: | |
150 | print marquee('Executing silent block # %s (%s remaining)' % |
|
172 | print marquee('Executing silent block # %s (%s remaining)' % | |
151 | (index,self.nblocks-index-1)) |
|
173 | (index,self.nblocks-index-1)) | |
152 | else: |
|
174 | else: | |
153 |
self.show |
|
175 | self.show(index) | |
154 | if self.auto: |
|
176 | if self.auto or self._auto[index]: | |
155 | print marquee('output') |
|
177 | print marquee('output') | |
156 | else: |
|
178 | else: | |
157 | print marquee('Press <q> to quit, <Enter> to execute...'), |
|
179 | print marquee('Press <q> to quit, <Enter> to execute...'), | |
158 | ans = raw_input().strip() |
|
180 | ans = raw_input().strip() | |
159 | if ans: |
|
181 | if ans: | |
160 | print marquee('Block NOT executed') |
|
182 | print marquee('Block NOT executed') | |
161 | return |
|
183 | return | |
162 | try: |
|
184 | try: | |
163 | save_argv = sys.argv |
|
185 | save_argv = sys.argv | |
164 | sys.argv = self.sys_argv |
|
186 | sys.argv = self.sys_argv | |
165 | exec next_block in self.user_ns |
|
187 | exec next_block in self.user_ns | |
166 | finally: |
|
188 | finally: | |
167 | sys.argv = save_argv |
|
189 | sys.argv = save_argv | |
168 |
|
190 | |||
169 | except: |
|
191 | except: | |
170 |
self.ip_showt |
|
192 | self.ip_showtb(filename=self.fname) | |
171 | else: |
|
193 | else: | |
172 | self.ip_ns.update(self.user_ns) |
|
194 | self.ip_ns.update(self.user_ns) | |
173 |
|
195 | |||
174 | if self.block_index == self.nblocks: |
|
196 | if self.block_index == self.nblocks: | |
175 |
|
197 | |||
176 | print marquee(' END OF DEMO ') |
|
198 | print marquee(' END OF DEMO ') | |
177 | print marquee('Use reset() if you want to rerun it.') |
|
199 | print marquee('Use reset() if you want to rerun it.') | |
178 | self.finished = True |
|
200 | self.finished = True | |
|
201 |
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