Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,3116 +1,3122 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 22 |
|
4 | $Id: Magic.py 2221 2007-04-06 02:58:37Z fperez $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 |
|
13 | |||
14 | #**************************************************************************** |
|
14 | #**************************************************************************** | |
15 | # Modules and globals |
|
15 | # Modules and globals | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
18 | __author__ = '%s <%s>\n%s <%s>' % \ | |
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
20 | __license__ = Release.license |
|
20 | __license__ = Release.license | |
21 |
|
21 | |||
22 | # Python standard modules |
|
22 | # Python standard modules | |
23 | import __builtin__ |
|
23 | import __builtin__ | |
24 | import bdb |
|
24 | import bdb | |
25 | import inspect |
|
25 | import inspect | |
26 | import os |
|
26 | import os | |
27 | import pdb |
|
27 | import pdb | |
28 | import pydoc |
|
28 | import pydoc | |
29 | import sys |
|
29 | import sys | |
30 | import re |
|
30 | import re | |
31 | import tempfile |
|
31 | import tempfile | |
32 | import time |
|
32 | import time | |
33 | import cPickle as pickle |
|
33 | import cPickle as pickle | |
34 | import textwrap |
|
34 | import textwrap | |
35 | from cStringIO import StringIO |
|
35 | from cStringIO import StringIO | |
36 | from getopt import getopt,GetoptError |
|
36 | from getopt import getopt,GetoptError | |
37 | from pprint import pprint, pformat |
|
37 | from pprint import pprint, pformat | |
38 |
|
38 | |||
39 | # cProfile was added in Python2.5 |
|
39 | # cProfile was added in Python2.5 | |
40 | try: |
|
40 | try: | |
41 | import cProfile as profile |
|
41 | import cProfile as profile | |
42 | import pstats |
|
42 | import pstats | |
43 | except ImportError: |
|
43 | except ImportError: | |
44 | # profile isn't bundled by default in Debian for license reasons |
|
44 | # profile isn't bundled by default in Debian for license reasons | |
45 | try: |
|
45 | try: | |
46 | import profile,pstats |
|
46 | import profile,pstats | |
47 | except ImportError: |
|
47 | except ImportError: | |
48 | profile = pstats = None |
|
48 | profile = pstats = None | |
49 |
|
49 | |||
50 | # Homebrewed |
|
50 | # Homebrewed | |
51 | import IPython |
|
51 | import IPython | |
52 | from IPython import Debugger, OInspect, wildcard |
|
52 | from IPython import Debugger, OInspect, wildcard | |
53 | from IPython.FakeModule import FakeModule |
|
53 | from IPython.FakeModule import FakeModule | |
54 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
54 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
55 | from IPython.PyColorize import Parser |
|
55 | from IPython.PyColorize import Parser | |
56 | from IPython.ipstruct import Struct |
|
56 | from IPython.ipstruct import Struct | |
57 | from IPython.macro import Macro |
|
57 | from IPython.macro import Macro | |
58 | from IPython.genutils import * |
|
58 | from IPython.genutils import * | |
59 | from IPython import platutils |
|
59 | from IPython import platutils | |
60 |
|
60 | |||
61 | #*************************************************************************** |
|
61 | #*************************************************************************** | |
62 | # Utility functions |
|
62 | # Utility functions | |
63 | def on_off(tag): |
|
63 | def on_off(tag): | |
64 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
64 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
65 | return ['OFF','ON'][tag] |
|
65 | return ['OFF','ON'][tag] | |
66 |
|
66 | |||
67 | class Bunch: pass |
|
67 | class Bunch: pass | |
68 |
|
68 | |||
69 | #*************************************************************************** |
|
69 | #*************************************************************************** | |
70 | # Main class implementing Magic functionality |
|
70 | # Main class implementing Magic functionality | |
71 | class Magic: |
|
71 | class Magic: | |
72 | """Magic functions for InteractiveShell. |
|
72 | """Magic functions for InteractiveShell. | |
73 |
|
73 | |||
74 | Shell functions which can be reached as %function_name. All magic |
|
74 | Shell functions which can be reached as %function_name. All magic | |
75 | functions should accept a string, which they can parse for their own |
|
75 | functions should accept a string, which they can parse for their own | |
76 | needs. This can make some functions easier to type, eg `%cd ../` |
|
76 | needs. This can make some functions easier to type, eg `%cd ../` | |
77 | vs. `%cd("../")` |
|
77 | vs. `%cd("../")` | |
78 |
|
78 | |||
79 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
79 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
80 | at the command line, but it is is needed in the definition. """ |
|
80 | at the command line, but it is is needed in the definition. """ | |
81 |
|
81 | |||
82 | # class globals |
|
82 | # class globals | |
83 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
83 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
84 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
84 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
85 |
|
85 | |||
86 | #...................................................................... |
|
86 | #...................................................................... | |
87 | # some utility functions |
|
87 | # some utility functions | |
88 |
|
88 | |||
89 | def __init__(self,shell): |
|
89 | def __init__(self,shell): | |
90 |
|
90 | |||
91 | self.options_table = {} |
|
91 | self.options_table = {} | |
92 | if profile is None: |
|
92 | if profile is None: | |
93 | self.magic_prun = self.profile_missing_notice |
|
93 | self.magic_prun = self.profile_missing_notice | |
94 | self.shell = shell |
|
94 | self.shell = shell | |
95 |
|
95 | |||
96 | # namespace for holding state we may need |
|
96 | # namespace for holding state we may need | |
97 | self._magic_state = Bunch() |
|
97 | self._magic_state = Bunch() | |
98 |
|
98 | |||
99 | def profile_missing_notice(self, *args, **kwargs): |
|
99 | def profile_missing_notice(self, *args, **kwargs): | |
100 | error("""\ |
|
100 | error("""\ | |
101 | The profile module could not be found. If you are a Debian user, |
|
101 | The profile module could not be found. If you are a Debian user, | |
102 | it has been removed from the standard Debian package because of its non-free |
|
102 | it has been removed from the standard Debian package because of its non-free | |
103 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
103 | license. To use profiling, please install"python2.3-profiler" from non-free.""") | |
104 |
|
104 | |||
105 | def default_option(self,fn,optstr): |
|
105 | def default_option(self,fn,optstr): | |
106 | """Make an entry in the options_table for fn, with value optstr""" |
|
106 | """Make an entry in the options_table for fn, with value optstr""" | |
107 |
|
107 | |||
108 | if fn not in self.lsmagic(): |
|
108 | if fn not in self.lsmagic(): | |
109 | error("%s is not a magic function" % fn) |
|
109 | error("%s is not a magic function" % fn) | |
110 | self.options_table[fn] = optstr |
|
110 | self.options_table[fn] = optstr | |
111 |
|
111 | |||
112 | def lsmagic(self): |
|
112 | def lsmagic(self): | |
113 | """Return a list of currently available magic functions. |
|
113 | """Return a list of currently available magic functions. | |
114 |
|
114 | |||
115 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
115 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
116 | ['magic_ls','magic_cd',...]""" |
|
116 | ['magic_ls','magic_cd',...]""" | |
117 |
|
117 | |||
118 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
118 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
119 |
|
119 | |||
120 | # magics in class definition |
|
120 | # magics in class definition | |
121 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
121 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
122 | callable(Magic.__dict__[fn]) |
|
122 | callable(Magic.__dict__[fn]) | |
123 | # in instance namespace (run-time user additions) |
|
123 | # in instance namespace (run-time user additions) | |
124 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
124 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
125 | callable(self.__dict__[fn]) |
|
125 | callable(self.__dict__[fn]) | |
126 | # and bound magics by user (so they can access self): |
|
126 | # and bound magics by user (so they can access self): | |
127 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
127 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
128 | callable(self.__class__.__dict__[fn]) |
|
128 | callable(self.__class__.__dict__[fn]) | |
129 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
129 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
130 | filter(inst_magic,self.__dict__.keys()) + \ |
|
130 | filter(inst_magic,self.__dict__.keys()) + \ | |
131 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
131 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
132 | out = [] |
|
132 | out = [] | |
133 | for fn in magics: |
|
133 | for fn in magics: | |
134 | out.append(fn.replace('magic_','',1)) |
|
134 | out.append(fn.replace('magic_','',1)) | |
135 | out.sort() |
|
135 | out.sort() | |
136 | return out |
|
136 | return out | |
137 |
|
137 | |||
138 | def extract_input_slices(self,slices,raw=False): |
|
138 | def extract_input_slices(self,slices,raw=False): | |
139 | """Return as a string a set of input history slices. |
|
139 | """Return as a string a set of input history slices. | |
140 |
|
140 | |||
141 | Inputs: |
|
141 | Inputs: | |
142 |
|
142 | |||
143 | - slices: the set of slices is given as a list of strings (like |
|
143 | - slices: the set of slices is given as a list of strings (like | |
144 | ['1','4:8','9'], since this function is for use by magic functions |
|
144 | ['1','4:8','9'], since this function is for use by magic functions | |
145 | which get their arguments as strings. |
|
145 | which get their arguments as strings. | |
146 |
|
146 | |||
147 | Optional inputs: |
|
147 | Optional inputs: | |
148 |
|
148 | |||
149 | - raw(False): by default, the processed input is used. If this is |
|
149 | - raw(False): by default, the processed input is used. If this is | |
150 | true, the raw input history is used instead. |
|
150 | true, the raw input history is used instead. | |
151 |
|
151 | |||
152 | Note that slices can be called with two notations: |
|
152 | Note that slices can be called with two notations: | |
153 |
|
153 | |||
154 | N:M -> standard python form, means including items N...(M-1). |
|
154 | N:M -> standard python form, means including items N...(M-1). | |
155 |
|
155 | |||
156 | N-M -> include items N..M (closed endpoint).""" |
|
156 | N-M -> include items N..M (closed endpoint).""" | |
157 |
|
157 | |||
158 | if raw: |
|
158 | if raw: | |
159 | hist = self.shell.input_hist_raw |
|
159 | hist = self.shell.input_hist_raw | |
160 | else: |
|
160 | else: | |
161 | hist = self.shell.input_hist |
|
161 | hist = self.shell.input_hist | |
162 |
|
162 | |||
163 | cmds = [] |
|
163 | cmds = [] | |
164 | for chunk in slices: |
|
164 | for chunk in slices: | |
165 | if ':' in chunk: |
|
165 | if ':' in chunk: | |
166 | ini,fin = map(int,chunk.split(':')) |
|
166 | ini,fin = map(int,chunk.split(':')) | |
167 | elif '-' in chunk: |
|
167 | elif '-' in chunk: | |
168 | ini,fin = map(int,chunk.split('-')) |
|
168 | ini,fin = map(int,chunk.split('-')) | |
169 | fin += 1 |
|
169 | fin += 1 | |
170 | else: |
|
170 | else: | |
171 | ini = int(chunk) |
|
171 | ini = int(chunk) | |
172 | fin = ini+1 |
|
172 | fin = ini+1 | |
173 | cmds.append(hist[ini:fin]) |
|
173 | cmds.append(hist[ini:fin]) | |
174 | return cmds |
|
174 | return cmds | |
175 |
|
175 | |||
176 | def _ofind(self, oname, namespaces=None): |
|
176 | def _ofind(self, oname, namespaces=None): | |
177 | """Find an object in the available namespaces. |
|
177 | """Find an object in the available namespaces. | |
178 |
|
178 | |||
179 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
179 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
180 |
|
180 | |||
181 | Has special code to detect magic functions. |
|
181 | Has special code to detect magic functions. | |
182 | """ |
|
182 | """ | |
183 |
|
183 | |||
184 | oname = oname.strip() |
|
184 | oname = oname.strip() | |
185 |
|
185 | |||
186 | alias_ns = None |
|
186 | alias_ns = None | |
187 | if namespaces is None: |
|
187 | if namespaces is None: | |
188 | # Namespaces to search in: |
|
188 | # Namespaces to search in: | |
189 | # Put them in a list. The order is important so that we |
|
189 | # Put them in a list. The order is important so that we | |
190 | # find things in the same order that Python finds them. |
|
190 | # find things in the same order that Python finds them. | |
191 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
191 | namespaces = [ ('Interactive', self.shell.user_ns), | |
192 | ('IPython internal', self.shell.internal_ns), |
|
192 | ('IPython internal', self.shell.internal_ns), | |
193 | ('Python builtin', __builtin__.__dict__), |
|
193 | ('Python builtin', __builtin__.__dict__), | |
194 | ('Alias', self.shell.alias_table), |
|
194 | ('Alias', self.shell.alias_table), | |
195 | ] |
|
195 | ] | |
196 | alias_ns = self.shell.alias_table |
|
196 | alias_ns = self.shell.alias_table | |
197 |
|
197 | |||
198 | # initialize results to 'null' |
|
198 | # initialize results to 'null' | |
199 | found = 0; obj = None; ospace = None; ds = None; |
|
199 | found = 0; obj = None; ospace = None; ds = None; | |
200 | ismagic = 0; isalias = 0; parent = None |
|
200 | ismagic = 0; isalias = 0; parent = None | |
201 |
|
201 | |||
202 | # Look for the given name by splitting it in parts. If the head is |
|
202 | # Look for the given name by splitting it in parts. If the head is | |
203 | # found, then we look for all the remaining parts as members, and only |
|
203 | # found, then we look for all the remaining parts as members, and only | |
204 | # declare success if we can find them all. |
|
204 | # declare success if we can find them all. | |
205 | oname_parts = oname.split('.') |
|
205 | oname_parts = oname.split('.') | |
206 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
206 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
207 | for nsname,ns in namespaces: |
|
207 | for nsname,ns in namespaces: | |
208 | try: |
|
208 | try: | |
209 | obj = ns[oname_head] |
|
209 | obj = ns[oname_head] | |
210 | except KeyError: |
|
210 | except KeyError: | |
211 | continue |
|
211 | continue | |
212 | else: |
|
212 | else: | |
213 | #print 'oname_rest:', oname_rest # dbg |
|
213 | #print 'oname_rest:', oname_rest # dbg | |
214 | for part in oname_rest: |
|
214 | for part in oname_rest: | |
215 | try: |
|
215 | try: | |
216 | parent = obj |
|
216 | parent = obj | |
217 | obj = getattr(obj,part) |
|
217 | obj = getattr(obj,part) | |
218 | except: |
|
218 | except: | |
219 | # Blanket except b/c some badly implemented objects |
|
219 | # Blanket except b/c some badly implemented objects | |
220 | # allow __getattr__ to raise exceptions other than |
|
220 | # allow __getattr__ to raise exceptions other than | |
221 | # AttributeError, which then crashes IPython. |
|
221 | # AttributeError, which then crashes IPython. | |
222 | break |
|
222 | break | |
223 | else: |
|
223 | else: | |
224 | # If we finish the for loop (no break), we got all members |
|
224 | # If we finish the for loop (no break), we got all members | |
225 | found = 1 |
|
225 | found = 1 | |
226 | ospace = nsname |
|
226 | ospace = nsname | |
227 | if ns == alias_ns: |
|
227 | if ns == alias_ns: | |
228 | isalias = 1 |
|
228 | isalias = 1 | |
229 | break # namespace loop |
|
229 | break # namespace loop | |
230 |
|
230 | |||
231 | # Try to see if it's magic |
|
231 | # Try to see if it's magic | |
232 | if not found: |
|
232 | if not found: | |
233 | if oname.startswith(self.shell.ESC_MAGIC): |
|
233 | if oname.startswith(self.shell.ESC_MAGIC): | |
234 | oname = oname[1:] |
|
234 | oname = oname[1:] | |
235 | obj = getattr(self,'magic_'+oname,None) |
|
235 | obj = getattr(self,'magic_'+oname,None) | |
236 | if obj is not None: |
|
236 | if obj is not None: | |
237 | found = 1 |
|
237 | found = 1 | |
238 | ospace = 'IPython internal' |
|
238 | ospace = 'IPython internal' | |
239 | ismagic = 1 |
|
239 | ismagic = 1 | |
240 |
|
240 | |||
241 | # Last try: special-case some literals like '', [], {}, etc: |
|
241 | # Last try: special-case some literals like '', [], {}, etc: | |
242 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
242 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
243 | obj = eval(oname_head) |
|
243 | obj = eval(oname_head) | |
244 | found = 1 |
|
244 | found = 1 | |
245 | ospace = 'Interactive' |
|
245 | ospace = 'Interactive' | |
246 |
|
246 | |||
247 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
247 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
248 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
248 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
249 |
|
249 | |||
250 | def arg_err(self,func): |
|
250 | def arg_err(self,func): | |
251 | """Print docstring if incorrect arguments were passed""" |
|
251 | """Print docstring if incorrect arguments were passed""" | |
252 | print 'Error in arguments:' |
|
252 | print 'Error in arguments:' | |
253 | print OInspect.getdoc(func) |
|
253 | print OInspect.getdoc(func) | |
254 |
|
254 | |||
255 | def format_latex(self,strng): |
|
255 | def format_latex(self,strng): | |
256 | """Format a string for latex inclusion.""" |
|
256 | """Format a string for latex inclusion.""" | |
257 |
|
257 | |||
258 | # Characters that need to be escaped for latex: |
|
258 | # Characters that need to be escaped for latex: | |
259 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
259 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
260 | # Magic command names as headers: |
|
260 | # Magic command names as headers: | |
261 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
261 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
262 | re.MULTILINE) |
|
262 | re.MULTILINE) | |
263 | # Magic commands |
|
263 | # Magic commands | |
264 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
264 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
265 | re.MULTILINE) |
|
265 | re.MULTILINE) | |
266 | # Paragraph continue |
|
266 | # Paragraph continue | |
267 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
267 | par_re = re.compile(r'\\$',re.MULTILINE) | |
268 |
|
268 | |||
269 | # The "\n" symbol |
|
269 | # The "\n" symbol | |
270 | newline_re = re.compile(r'\\n') |
|
270 | newline_re = re.compile(r'\\n') | |
271 |
|
271 | |||
272 | # Now build the string for output: |
|
272 | # Now build the string for output: | |
273 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
273 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
274 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
274 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
275 | strng) |
|
275 | strng) | |
276 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
276 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
277 | strng = par_re.sub(r'\\\\',strng) |
|
277 | strng = par_re.sub(r'\\\\',strng) | |
278 | strng = escape_re.sub(r'\\\1',strng) |
|
278 | strng = escape_re.sub(r'\\\1',strng) | |
279 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
279 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
280 | return strng |
|
280 | return strng | |
281 |
|
281 | |||
282 | def format_screen(self,strng): |
|
282 | def format_screen(self,strng): | |
283 | """Format a string for screen printing. |
|
283 | """Format a string for screen printing. | |
284 |
|
284 | |||
285 | This removes some latex-type format codes.""" |
|
285 | This removes some latex-type format codes.""" | |
286 | # Paragraph continue |
|
286 | # Paragraph continue | |
287 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
287 | par_re = re.compile(r'\\$',re.MULTILINE) | |
288 | strng = par_re.sub('',strng) |
|
288 | strng = par_re.sub('',strng) | |
289 | return strng |
|
289 | return strng | |
290 |
|
290 | |||
291 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
291 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
292 | """Parse options passed to an argument string. |
|
292 | """Parse options passed to an argument string. | |
293 |
|
293 | |||
294 | The interface is similar to that of getopt(), but it returns back a |
|
294 | The interface is similar to that of getopt(), but it returns back a | |
295 | Struct with the options as keys and the stripped argument string still |
|
295 | Struct with the options as keys and the stripped argument string still | |
296 | as a string. |
|
296 | as a string. | |
297 |
|
297 | |||
298 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
298 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
299 | This allows us to easily expand variables, glob files, quote |
|
299 | This allows us to easily expand variables, glob files, quote | |
300 | arguments, etc. |
|
300 | arguments, etc. | |
301 |
|
301 | |||
302 | Options: |
|
302 | Options: | |
303 | -mode: default 'string'. If given as 'list', the argument string is |
|
303 | -mode: default 'string'. If given as 'list', the argument string is | |
304 | returned as a list (split on whitespace) instead of a string. |
|
304 | returned as a list (split on whitespace) instead of a string. | |
305 |
|
305 | |||
306 | -list_all: put all option values in lists. Normally only options |
|
306 | -list_all: put all option values in lists. Normally only options | |
307 | appearing more than once are put in a list. |
|
307 | appearing more than once are put in a list. | |
308 |
|
308 | |||
309 | -posix (True): whether to split the input line in POSIX mode or not, |
|
309 | -posix (True): whether to split the input line in POSIX mode or not, | |
310 | as per the conventions outlined in the shlex module from the |
|
310 | as per the conventions outlined in the shlex module from the | |
311 | standard library.""" |
|
311 | standard library.""" | |
312 |
|
312 | |||
313 | # inject default options at the beginning of the input line |
|
313 | # inject default options at the beginning of the input line | |
314 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
314 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
315 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
315 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
316 |
|
316 | |||
317 | mode = kw.get('mode','string') |
|
317 | mode = kw.get('mode','string') | |
318 | if mode not in ['string','list']: |
|
318 | if mode not in ['string','list']: | |
319 | raise ValueError,'incorrect mode given: %s' % mode |
|
319 | raise ValueError,'incorrect mode given: %s' % mode | |
320 | # Get options |
|
320 | # Get options | |
321 | list_all = kw.get('list_all',0) |
|
321 | list_all = kw.get('list_all',0) | |
322 | posix = kw.get('posix',True) |
|
322 | posix = kw.get('posix',True) | |
323 |
|
323 | |||
324 | # Check if we have more than one argument to warrant extra processing: |
|
324 | # Check if we have more than one argument to warrant extra processing: | |
325 | odict = {} # Dictionary with options |
|
325 | odict = {} # Dictionary with options | |
326 | args = arg_str.split() |
|
326 | args = arg_str.split() | |
327 | if len(args) >= 1: |
|
327 | if len(args) >= 1: | |
328 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
328 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
329 | # need to look for options |
|
329 | # need to look for options | |
330 | argv = arg_split(arg_str,posix) |
|
330 | argv = arg_split(arg_str,posix) | |
331 | # Do regular option processing |
|
331 | # Do regular option processing | |
332 | try: |
|
332 | try: | |
333 | opts,args = getopt(argv,opt_str,*long_opts) |
|
333 | opts,args = getopt(argv,opt_str,*long_opts) | |
334 | except GetoptError,e: |
|
334 | except GetoptError,e: | |
335 | raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
335 | raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
336 | " ".join(long_opts))) |
|
336 | " ".join(long_opts))) | |
337 | for o,a in opts: |
|
337 | for o,a in opts: | |
338 | if o.startswith('--'): |
|
338 | if o.startswith('--'): | |
339 | o = o[2:] |
|
339 | o = o[2:] | |
340 | else: |
|
340 | else: | |
341 | o = o[1:] |
|
341 | o = o[1:] | |
342 | try: |
|
342 | try: | |
343 | odict[o].append(a) |
|
343 | odict[o].append(a) | |
344 | except AttributeError: |
|
344 | except AttributeError: | |
345 | odict[o] = [odict[o],a] |
|
345 | odict[o] = [odict[o],a] | |
346 | except KeyError: |
|
346 | except KeyError: | |
347 | if list_all: |
|
347 | if list_all: | |
348 | odict[o] = [a] |
|
348 | odict[o] = [a] | |
349 | else: |
|
349 | else: | |
350 | odict[o] = a |
|
350 | odict[o] = a | |
351 |
|
351 | |||
352 | # Prepare opts,args for return |
|
352 | # Prepare opts,args for return | |
353 | opts = Struct(odict) |
|
353 | opts = Struct(odict) | |
354 | if mode == 'string': |
|
354 | if mode == 'string': | |
355 | args = ' '.join(args) |
|
355 | args = ' '.join(args) | |
356 |
|
356 | |||
357 | return opts,args |
|
357 | return opts,args | |
358 |
|
358 | |||
359 | #...................................................................... |
|
359 | #...................................................................... | |
360 | # And now the actual magic functions |
|
360 | # And now the actual magic functions | |
361 |
|
361 | |||
362 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
362 | # Functions for IPython shell work (vars,funcs, config, etc) | |
363 | def magic_lsmagic(self, parameter_s = ''): |
|
363 | def magic_lsmagic(self, parameter_s = ''): | |
364 | """List currently available magic functions.""" |
|
364 | """List currently available magic functions.""" | |
365 | mesc = self.shell.ESC_MAGIC |
|
365 | mesc = self.shell.ESC_MAGIC | |
366 | print 'Available magic functions:\n'+mesc+\ |
|
366 | print 'Available magic functions:\n'+mesc+\ | |
367 | (' '+mesc).join(self.lsmagic()) |
|
367 | (' '+mesc).join(self.lsmagic()) | |
368 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
368 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
369 | return None |
|
369 | return None | |
370 |
|
370 | |||
371 | def magic_magic(self, parameter_s = ''): |
|
371 | def magic_magic(self, parameter_s = ''): | |
372 | """Print information about the magic function system.""" |
|
372 | """Print information about the magic function system.""" | |
373 |
|
373 | |||
374 | mode = '' |
|
374 | mode = '' | |
375 | try: |
|
375 | try: | |
376 | if parameter_s.split()[0] == '-latex': |
|
376 | if parameter_s.split()[0] == '-latex': | |
377 | mode = 'latex' |
|
377 | mode = 'latex' | |
378 | if parameter_s.split()[0] == '-brief': |
|
378 | if parameter_s.split()[0] == '-brief': | |
379 | mode = 'brief' |
|
379 | mode = 'brief' | |
380 | except: |
|
380 | except: | |
381 | pass |
|
381 | pass | |
382 |
|
382 | |||
383 | magic_docs = [] |
|
383 | magic_docs = [] | |
384 | for fname in self.lsmagic(): |
|
384 | for fname in self.lsmagic(): | |
385 | mname = 'magic_' + fname |
|
385 | mname = 'magic_' + fname | |
386 | for space in (Magic,self,self.__class__): |
|
386 | for space in (Magic,self,self.__class__): | |
387 | try: |
|
387 | try: | |
388 | fn = space.__dict__[mname] |
|
388 | fn = space.__dict__[mname] | |
389 | except KeyError: |
|
389 | except KeyError: | |
390 | pass |
|
390 | pass | |
391 | else: |
|
391 | else: | |
392 | break |
|
392 | break | |
393 | if mode == 'brief': |
|
393 | if mode == 'brief': | |
394 | # only first line |
|
394 | # only first line | |
395 | fndoc = fn.__doc__.split('\n',1)[0] |
|
395 | fndoc = fn.__doc__.split('\n',1)[0] | |
396 | else: |
|
396 | else: | |
397 | fndoc = fn.__doc__ |
|
397 | fndoc = fn.__doc__ | |
398 |
|
398 | |||
399 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
399 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
400 | fname,fndoc)) |
|
400 | fname,fndoc)) | |
401 | magic_docs = ''.join(magic_docs) |
|
401 | magic_docs = ''.join(magic_docs) | |
402 |
|
402 | |||
403 | if mode == 'latex': |
|
403 | if mode == 'latex': | |
404 | print self.format_latex(magic_docs) |
|
404 | print self.format_latex(magic_docs) | |
405 | return |
|
405 | return | |
406 | else: |
|
406 | else: | |
407 | magic_docs = self.format_screen(magic_docs) |
|
407 | magic_docs = self.format_screen(magic_docs) | |
408 | if mode == 'brief': |
|
408 | if mode == 'brief': | |
409 | return magic_docs |
|
409 | return magic_docs | |
410 |
|
410 | |||
411 | outmsg = """ |
|
411 | outmsg = """ | |
412 | IPython's 'magic' functions |
|
412 | IPython's 'magic' functions | |
413 | =========================== |
|
413 | =========================== | |
414 |
|
414 | |||
415 | The magic function system provides a series of functions which allow you to |
|
415 | The magic function system provides a series of functions which allow you to | |
416 | control the behavior of IPython itself, plus a lot of system-type |
|
416 | control the behavior of IPython itself, plus a lot of system-type | |
417 | features. All these functions are prefixed with a % character, but parameters |
|
417 | features. All these functions are prefixed with a % character, but parameters | |
418 | are given without parentheses or quotes. |
|
418 | are given without parentheses or quotes. | |
419 |
|
419 | |||
420 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
420 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
421 | %automagic function), you don't need to type in the % explicitly. By default, |
|
421 | %automagic function), you don't need to type in the % explicitly. By default, | |
422 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
422 | IPython ships with automagic on, so you should only rarely need the % escape. | |
423 |
|
423 | |||
424 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
424 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
425 | to 'mydir', if it exists. |
|
425 | to 'mydir', if it exists. | |
426 |
|
426 | |||
427 | You can define your own magic functions to extend the system. See the supplied |
|
427 | You can define your own magic functions to extend the system. See the supplied | |
428 | ipythonrc and example-magic.py files for details (in your ipython |
|
428 | ipythonrc and example-magic.py files for details (in your ipython | |
429 | configuration directory, typically $HOME/.ipython/). |
|
429 | configuration directory, typically $HOME/.ipython/). | |
430 |
|
430 | |||
431 | You can also define your own aliased names for magic functions. In your |
|
431 | You can also define your own aliased names for magic functions. In your | |
432 | ipythonrc file, placing a line like: |
|
432 | ipythonrc file, placing a line like: | |
433 |
|
433 | |||
434 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
434 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
435 |
|
435 | |||
436 | will define %pf as a new name for %profile. |
|
436 | will define %pf as a new name for %profile. | |
437 |
|
437 | |||
438 | You can also call magics in code using the ipmagic() function, which IPython |
|
438 | You can also call magics in code using the ipmagic() function, which IPython | |
439 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
439 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
440 |
|
440 | |||
441 | For a list of the available magic functions, use %lsmagic. For a description |
|
441 | For a list of the available magic functions, use %lsmagic. For a description | |
442 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
442 | of any of them, type %magic_name?, e.g. '%cd?'. | |
443 |
|
443 | |||
444 | Currently the magic system has the following functions:\n""" |
|
444 | Currently the magic system has the following functions:\n""" | |
445 |
|
445 | |||
446 | mesc = self.shell.ESC_MAGIC |
|
446 | mesc = self.shell.ESC_MAGIC | |
447 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
447 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
448 | "\n\n%s%s\n\n%s" % (outmsg, |
|
448 | "\n\n%s%s\n\n%s" % (outmsg, | |
449 | magic_docs,mesc,mesc, |
|
449 | magic_docs,mesc,mesc, | |
450 | (' '+mesc).join(self.lsmagic()), |
|
450 | (' '+mesc).join(self.lsmagic()), | |
451 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
451 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
452 |
|
452 | |||
453 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
453 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
454 |
|
454 | |||
455 | def magic_automagic(self, parameter_s = ''): |
|
455 | def magic_automagic(self, parameter_s = ''): | |
456 | """Make magic functions callable without having to type the initial %. |
|
456 | """Make magic functions callable without having to type the initial %. | |
457 |
|
457 | |||
458 | Without argumentsl toggles on/off (when off, you must call it as |
|
458 | Without argumentsl toggles on/off (when off, you must call it as | |
459 | %automagic, of course). With arguments it sets the value, and you can |
|
459 | %automagic, of course). With arguments it sets the value, and you can | |
460 | use any of (case insensitive): |
|
460 | use any of (case insensitive): | |
461 |
|
461 | |||
462 | - on,1,True: to activate |
|
462 | - on,1,True: to activate | |
463 |
|
463 | |||
464 | - off,0,False: to deactivate. |
|
464 | - off,0,False: to deactivate. | |
465 |
|
465 | |||
466 | Note that magic functions have lowest priority, so if there's a |
|
466 | Note that magic functions have lowest priority, so if there's a | |
467 | variable whose name collides with that of a magic fn, automagic won't |
|
467 | variable whose name collides with that of a magic fn, automagic won't | |
468 | work for that function (you get the variable instead). However, if you |
|
468 | work for that function (you get the variable instead). However, if you | |
469 | delete the variable (del var), the previously shadowed magic function |
|
469 | delete the variable (del var), the previously shadowed magic function | |
470 | becomes visible to automagic again.""" |
|
470 | becomes visible to automagic again.""" | |
471 |
|
471 | |||
472 | rc = self.shell.rc |
|
472 | rc = self.shell.rc | |
473 | arg = parameter_s.lower() |
|
473 | arg = parameter_s.lower() | |
474 | if parameter_s in ('on','1','true'): |
|
474 | if parameter_s in ('on','1','true'): | |
475 | rc.automagic = True |
|
475 | rc.automagic = True | |
476 | elif parameter_s in ('off','0','false'): |
|
476 | elif parameter_s in ('off','0','false'): | |
477 | rc.automagic = False |
|
477 | rc.automagic = False | |
478 | else: |
|
478 | else: | |
479 | rc.automagic = not rc.automagic |
|
479 | rc.automagic = not rc.automagic | |
480 | print '\n' + Magic.auto_status[rc.automagic] |
|
480 | print '\n' + Magic.auto_status[rc.automagic] | |
481 |
|
481 | |||
482 | def magic_autocall(self, parameter_s = ''): |
|
482 | def magic_autocall(self, parameter_s = ''): | |
483 | """Make functions callable without having to type parentheses. |
|
483 | """Make functions callable without having to type parentheses. | |
484 |
|
484 | |||
485 | Usage: |
|
485 | Usage: | |
486 |
|
486 | |||
487 | %autocall [mode] |
|
487 | %autocall [mode] | |
488 |
|
488 | |||
489 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
489 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
490 | value is toggled on and off (remembering the previous state).""" |
|
490 | value is toggled on and off (remembering the previous state).""" | |
491 |
|
491 | |||
492 | rc = self.shell.rc |
|
492 | rc = self.shell.rc | |
493 |
|
493 | |||
494 | if parameter_s: |
|
494 | if parameter_s: | |
495 | arg = int(parameter_s) |
|
495 | arg = int(parameter_s) | |
496 | else: |
|
496 | else: | |
497 | arg = 'toggle' |
|
497 | arg = 'toggle' | |
498 |
|
498 | |||
499 | if not arg in (0,1,2,'toggle'): |
|
499 | if not arg in (0,1,2,'toggle'): | |
500 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
500 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
501 | return |
|
501 | return | |
502 |
|
502 | |||
503 | if arg in (0,1,2): |
|
503 | if arg in (0,1,2): | |
504 | rc.autocall = arg |
|
504 | rc.autocall = arg | |
505 | else: # toggle |
|
505 | else: # toggle | |
506 | if rc.autocall: |
|
506 | if rc.autocall: | |
507 | self._magic_state.autocall_save = rc.autocall |
|
507 | self._magic_state.autocall_save = rc.autocall | |
508 | rc.autocall = 0 |
|
508 | rc.autocall = 0 | |
509 | else: |
|
509 | else: | |
510 | try: |
|
510 | try: | |
511 | rc.autocall = self._magic_state.autocall_save |
|
511 | rc.autocall = self._magic_state.autocall_save | |
512 | except AttributeError: |
|
512 | except AttributeError: | |
513 | rc.autocall = self._magic_state.autocall_save = 1 |
|
513 | rc.autocall = self._magic_state.autocall_save = 1 | |
514 |
|
514 | |||
515 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
515 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] | |
516 |
|
516 | |||
517 | def magic_autoindent(self, parameter_s = ''): |
|
517 | def magic_autoindent(self, parameter_s = ''): | |
518 | """Toggle autoindent on/off (if available).""" |
|
518 | """Toggle autoindent on/off (if available).""" | |
519 |
|
519 | |||
520 | self.shell.set_autoindent() |
|
520 | self.shell.set_autoindent() | |
521 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
521 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
522 |
|
522 | |||
523 | def magic_system_verbose(self, parameter_s = ''): |
|
523 | def magic_system_verbose(self, parameter_s = ''): | |
524 | """Set verbose printing of system calls. |
|
524 | """Set verbose printing of system calls. | |
525 |
|
525 | |||
526 | If called without an argument, act as a toggle""" |
|
526 | If called without an argument, act as a toggle""" | |
527 |
|
527 | |||
528 | if parameter_s: |
|
528 | if parameter_s: | |
529 | val = bool(eval(parameter_s)) |
|
529 | val = bool(eval(parameter_s)) | |
530 | else: |
|
530 | else: | |
531 | val = None |
|
531 | val = None | |
532 |
|
532 | |||
533 | self.shell.rc_set_toggle('system_verbose',val) |
|
533 | self.shell.rc_set_toggle('system_verbose',val) | |
534 | print "System verbose printing is:",\ |
|
534 | print "System verbose printing is:",\ | |
535 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
535 | ['OFF','ON'][self.shell.rc.system_verbose] | |
536 |
|
536 | |||
537 | def magic_history(self, parameter_s = ''): |
|
537 | def magic_history(self, parameter_s = ''): | |
538 | """Print input history (_i<n> variables), with most recent last. |
|
538 | """Print input history (_i<n> variables), with most recent last. | |
539 |
|
539 | |||
540 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
540 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
541 | %history n -> print at most n inputs\\ |
|
541 | %history n -> print at most n inputs\\ | |
542 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
542 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
543 |
|
543 | |||
544 | Each input's number <n> is shown, and is accessible as the |
|
544 | Each input's number <n> is shown, and is accessible as the | |
545 | automatically generated variable _i<n>. Multi-line statements are |
|
545 | automatically generated variable _i<n>. Multi-line statements are | |
546 | printed starting at a new line for easy copy/paste. |
|
546 | printed starting at a new line for easy copy/paste. | |
547 |
|
547 | |||
548 |
|
548 | |||
549 | Options: |
|
549 | Options: | |
550 |
|
550 | |||
551 | -n: do NOT print line numbers. This is useful if you want to get a |
|
551 | -n: do NOT print line numbers. This is useful if you want to get a | |
552 | printout of many lines which can be directly pasted into a text |
|
552 | printout of many lines which can be directly pasted into a text | |
553 | editor. |
|
553 | editor. | |
554 |
|
554 | |||
555 | This feature is only available if numbered prompts are in use. |
|
555 | This feature is only available if numbered prompts are in use. | |
556 |
|
556 | |||
557 | -r: print the 'raw' history. IPython filters your input and |
|
557 | -r: print the 'raw' history. IPython filters your input and | |
558 | converts it all into valid Python source before executing it (things |
|
558 | converts it all into valid Python source before executing it (things | |
559 | like magics or aliases are turned into function calls, for |
|
559 | like magics or aliases are turned into function calls, for | |
560 | example). With this option, you'll see the unfiltered history |
|
560 | example). With this option, you'll see the unfiltered history | |
561 | instead of the filtered version: '%cd /' will be seen as '%cd /' |
|
561 | instead of the filtered version: '%cd /' will be seen as '%cd /' | |
562 | instead of '_ip.magic("%cd /")'. |
|
562 | instead of '_ip.magic("%cd /")'. | |
563 | """ |
|
563 | """ | |
564 |
|
564 | |||
565 | shell = self.shell |
|
565 | shell = self.shell | |
566 | if not shell.outputcache.do_full_cache: |
|
566 | if not shell.outputcache.do_full_cache: | |
567 | print 'This feature is only available if numbered prompts are in use.' |
|
567 | print 'This feature is only available if numbered prompts are in use.' | |
568 | return |
|
568 | return | |
569 | opts,args = self.parse_options(parameter_s,'nr',mode='list') |
|
569 | opts,args = self.parse_options(parameter_s,'nr',mode='list') | |
570 |
|
570 | |||
571 | if opts.has_key('r'): |
|
571 | if opts.has_key('r'): | |
572 | input_hist = shell.input_hist_raw |
|
572 | input_hist = shell.input_hist_raw | |
573 | else: |
|
573 | else: | |
574 | input_hist = shell.input_hist |
|
574 | input_hist = shell.input_hist | |
575 |
|
575 | |||
576 | default_length = 40 |
|
576 | default_length = 40 | |
577 | if len(args) == 0: |
|
577 | if len(args) == 0: | |
578 | final = len(input_hist) |
|
578 | final = len(input_hist) | |
579 | init = max(1,final-default_length) |
|
579 | init = max(1,final-default_length) | |
580 | elif len(args) == 1: |
|
580 | elif len(args) == 1: | |
581 | final = len(input_hist) |
|
581 | final = len(input_hist) | |
582 | init = max(1,final-int(args[0])) |
|
582 | init = max(1,final-int(args[0])) | |
583 | elif len(args) == 2: |
|
583 | elif len(args) == 2: | |
584 | init,final = map(int,args) |
|
584 | init,final = map(int,args) | |
585 | else: |
|
585 | else: | |
586 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
586 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
587 | print self.magic_hist.__doc__ |
|
587 | print self.magic_hist.__doc__ | |
588 | return |
|
588 | return | |
589 | width = len(str(final)) |
|
589 | width = len(str(final)) | |
590 | line_sep = ['','\n'] |
|
590 | line_sep = ['','\n'] | |
591 | print_nums = not opts.has_key('n') |
|
591 | print_nums = not opts.has_key('n') | |
592 | for in_num in range(init,final): |
|
592 | for in_num in range(init,final): | |
593 | inline = input_hist[in_num] |
|
593 | inline = input_hist[in_num] | |
594 | multiline = int(inline.count('\n') > 1) |
|
594 | multiline = int(inline.count('\n') > 1) | |
595 | if print_nums: |
|
595 | if print_nums: | |
596 | print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), |
|
596 | print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), | |
597 | print inline, |
|
597 | print inline, | |
598 |
|
598 | |||
599 | def magic_hist(self, parameter_s=''): |
|
599 | def magic_hist(self, parameter_s=''): | |
600 | """Alternate name for %history.""" |
|
600 | """Alternate name for %history.""" | |
601 | return self.magic_history(parameter_s) |
|
601 | return self.magic_history(parameter_s) | |
602 |
|
602 | |||
603 | def magic_p(self, parameter_s=''): |
|
603 | def magic_p(self, parameter_s=''): | |
604 | """Just a short alias for Python's 'print'.""" |
|
604 | """Just a short alias for Python's 'print'.""" | |
605 | exec 'print ' + parameter_s in self.shell.user_ns |
|
605 | exec 'print ' + parameter_s in self.shell.user_ns | |
606 |
|
606 | |||
607 | def magic_r(self, parameter_s=''): |
|
607 | def magic_r(self, parameter_s=''): | |
608 | """Repeat previous input. |
|
608 | """Repeat previous input. | |
609 |
|
609 | |||
610 | If given an argument, repeats the previous command which starts with |
|
610 | If given an argument, repeats the previous command which starts with | |
611 | the same string, otherwise it just repeats the previous input. |
|
611 | the same string, otherwise it just repeats the previous input. | |
612 |
|
612 | |||
613 | Shell escaped commands (with ! as first character) are not recognized |
|
613 | Shell escaped commands (with ! as first character) are not recognized | |
614 | by this system, only pure python code and magic commands. |
|
614 | by this system, only pure python code and magic commands. | |
615 | """ |
|
615 | """ | |
616 |
|
616 | |||
617 | start = parameter_s.strip() |
|
617 | start = parameter_s.strip() | |
618 | esc_magic = self.shell.ESC_MAGIC |
|
618 | esc_magic = self.shell.ESC_MAGIC | |
619 | # Identify magic commands even if automagic is on (which means |
|
619 | # Identify magic commands even if automagic is on (which means | |
620 | # the in-memory version is different from that typed by the user). |
|
620 | # the in-memory version is different from that typed by the user). | |
621 | if self.shell.rc.automagic: |
|
621 | if self.shell.rc.automagic: | |
622 | start_magic = esc_magic+start |
|
622 | start_magic = esc_magic+start | |
623 | else: |
|
623 | else: | |
624 | start_magic = start |
|
624 | start_magic = start | |
625 | # Look through the input history in reverse |
|
625 | # Look through the input history in reverse | |
626 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
626 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
627 | input = self.shell.input_hist[n] |
|
627 | input = self.shell.input_hist[n] | |
628 | # skip plain 'r' lines so we don't recurse to infinity |
|
628 | # skip plain 'r' lines so we don't recurse to infinity | |
629 | if input != '_ip.magic("r")\n' and \ |
|
629 | if input != '_ip.magic("r")\n' and \ | |
630 | (input.startswith(start) or input.startswith(start_magic)): |
|
630 | (input.startswith(start) or input.startswith(start_magic)): | |
631 | #print 'match',`input` # dbg |
|
631 | #print 'match',`input` # dbg | |
632 | print 'Executing:',input, |
|
632 | print 'Executing:',input, | |
633 | self.shell.runlines(input) |
|
633 | self.shell.runlines(input) | |
634 | return |
|
634 | return | |
635 | print 'No previous input matching `%s` found.' % start |
|
635 | print 'No previous input matching `%s` found.' % start | |
636 |
|
636 | |||
637 | def magic_page(self, parameter_s=''): |
|
637 | def magic_page(self, parameter_s=''): | |
638 | """Pretty print the object and display it through a pager. |
|
638 | """Pretty print the object and display it through a pager. | |
639 |
|
639 | |||
640 | %page [options] OBJECT |
|
640 | %page [options] OBJECT | |
641 |
|
641 | |||
642 | If no object is given, use _ (last output). |
|
642 | If no object is given, use _ (last output). | |
643 |
|
643 | |||
644 | Options: |
|
644 | Options: | |
645 |
|
645 | |||
646 | -r: page str(object), don't pretty-print it.""" |
|
646 | -r: page str(object), don't pretty-print it.""" | |
647 |
|
647 | |||
648 | # After a function contributed by Olivier Aubert, slightly modified. |
|
648 | # After a function contributed by Olivier Aubert, slightly modified. | |
649 |
|
649 | |||
650 | # Process options/args |
|
650 | # Process options/args | |
651 | opts,args = self.parse_options(parameter_s,'r') |
|
651 | opts,args = self.parse_options(parameter_s,'r') | |
652 | raw = 'r' in opts |
|
652 | raw = 'r' in opts | |
653 |
|
653 | |||
654 | oname = args and args or '_' |
|
654 | oname = args and args or '_' | |
655 | info = self._ofind(oname) |
|
655 | info = self._ofind(oname) | |
656 | if info['found']: |
|
656 | if info['found']: | |
657 | txt = (raw and str or pformat)( info['obj'] ) |
|
657 | txt = (raw and str or pformat)( info['obj'] ) | |
658 | page(txt) |
|
658 | page(txt) | |
659 | else: |
|
659 | else: | |
660 | print 'Object `%s` not found' % oname |
|
660 | print 'Object `%s` not found' % oname | |
661 |
|
661 | |||
662 | def magic_profile(self, parameter_s=''): |
|
662 | def magic_profile(self, parameter_s=''): | |
663 | """Print your currently active IPyhton profile.""" |
|
663 | """Print your currently active IPyhton profile.""" | |
664 | if self.shell.rc.profile: |
|
664 | if self.shell.rc.profile: | |
665 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
665 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
666 | else: |
|
666 | else: | |
667 | print 'No profile active.' |
|
667 | print 'No profile active.' | |
668 |
|
668 | |||
669 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
669 | def _inspect(self,meth,oname,namespaces=None,**kw): | |
670 | """Generic interface to the inspector system. |
|
670 | """Generic interface to the inspector system. | |
671 |
|
671 | |||
672 | This function is meant to be called by pdef, pdoc & friends.""" |
|
672 | This function is meant to be called by pdef, pdoc & friends.""" | |
673 |
|
673 | |||
674 | #oname = oname.strip() |
|
674 | #oname = oname.strip() | |
675 | #print '1- oname: <%r>' % oname # dbg |
|
675 | #print '1- oname: <%r>' % oname # dbg | |
676 | try: |
|
676 | try: | |
677 | oname = oname.strip().encode('ascii') |
|
677 | oname = oname.strip().encode('ascii') | |
678 | #print '2- oname: <%r>' % oname # dbg |
|
678 | #print '2- oname: <%r>' % oname # dbg | |
679 | except UnicodeEncodeError: |
|
679 | except UnicodeEncodeError: | |
680 | print 'Python identifiers can only contain ascii characters.' |
|
680 | print 'Python identifiers can only contain ascii characters.' | |
681 | return 'not found' |
|
681 | return 'not found' | |
682 |
|
682 | |||
683 | info = Struct(self._ofind(oname, namespaces)) |
|
683 | info = Struct(self._ofind(oname, namespaces)) | |
684 |
|
684 | |||
685 | if info.found: |
|
685 | if info.found: | |
686 | # Get the docstring of the class property if it exists. |
|
686 | # Get the docstring of the class property if it exists. | |
687 | path = oname.split('.') |
|
687 | path = oname.split('.') | |
688 | root = '.'.join(path[:-1]) |
|
688 | root = '.'.join(path[:-1]) | |
689 | if info.parent is not None: |
|
689 | if info.parent is not None: | |
690 | try: |
|
690 | try: | |
691 | target = getattr(info.parent, '__class__') |
|
691 | target = getattr(info.parent, '__class__') | |
692 | # The object belongs to a class instance. |
|
692 | # The object belongs to a class instance. | |
693 | try: |
|
693 | try: | |
694 | target = getattr(target, path[-1]) |
|
694 | target = getattr(target, path[-1]) | |
695 | # The class defines the object. |
|
695 | # The class defines the object. | |
696 | if isinstance(target, property): |
|
696 | if isinstance(target, property): | |
697 | oname = root + '.__class__.' + path[-1] |
|
697 | oname = root + '.__class__.' + path[-1] | |
698 | info = Struct(self._ofind(oname)) |
|
698 | info = Struct(self._ofind(oname)) | |
699 | except AttributeError: pass |
|
699 | except AttributeError: pass | |
700 | except AttributeError: pass |
|
700 | except AttributeError: pass | |
701 |
|
701 | |||
702 | pmethod = getattr(self.shell.inspector,meth) |
|
702 | pmethod = getattr(self.shell.inspector,meth) | |
703 | formatter = info.ismagic and self.format_screen or None |
|
703 | formatter = info.ismagic and self.format_screen or None | |
704 | if meth == 'pdoc': |
|
704 | if meth == 'pdoc': | |
705 | pmethod(info.obj,oname,formatter) |
|
705 | pmethod(info.obj,oname,formatter) | |
706 | elif meth == 'pinfo': |
|
706 | elif meth == 'pinfo': | |
707 | pmethod(info.obj,oname,formatter,info,**kw) |
|
707 | pmethod(info.obj,oname,formatter,info,**kw) | |
708 | else: |
|
708 | else: | |
709 | pmethod(info.obj,oname) |
|
709 | pmethod(info.obj,oname) | |
710 | else: |
|
710 | else: | |
711 | print 'Object `%s` not found.' % oname |
|
711 | print 'Object `%s` not found.' % oname | |
712 | return 'not found' # so callers can take other action |
|
712 | return 'not found' # so callers can take other action | |
713 |
|
713 | |||
714 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
714 | def magic_pdef(self, parameter_s='', namespaces=None): | |
715 | """Print the definition header for any callable object. |
|
715 | """Print the definition header for any callable object. | |
716 |
|
716 | |||
717 | If the object is a class, print the constructor information.""" |
|
717 | If the object is a class, print the constructor information.""" | |
718 | self._inspect('pdef',parameter_s, namespaces) |
|
718 | self._inspect('pdef',parameter_s, namespaces) | |
719 |
|
719 | |||
720 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
720 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
721 | """Print the docstring for an object. |
|
721 | """Print the docstring for an object. | |
722 |
|
722 | |||
723 | If the given object is a class, it will print both the class and the |
|
723 | If the given object is a class, it will print both the class and the | |
724 | constructor docstrings.""" |
|
724 | constructor docstrings.""" | |
725 | self._inspect('pdoc',parameter_s, namespaces) |
|
725 | self._inspect('pdoc',parameter_s, namespaces) | |
726 |
|
726 | |||
727 | def magic_psource(self, parameter_s='', namespaces=None): |
|
727 | def magic_psource(self, parameter_s='', namespaces=None): | |
728 | """Print (or run through pager) the source code for an object.""" |
|
728 | """Print (or run through pager) the source code for an object.""" | |
729 | self._inspect('psource',parameter_s, namespaces) |
|
729 | self._inspect('psource',parameter_s, namespaces) | |
730 |
|
730 | |||
731 | def magic_pfile(self, parameter_s=''): |
|
731 | def magic_pfile(self, parameter_s=''): | |
732 | """Print (or run through pager) the file where an object is defined. |
|
732 | """Print (or run through pager) the file where an object is defined. | |
733 |
|
733 | |||
734 | The file opens at the line where the object definition begins. IPython |
|
734 | The file opens at the line where the object definition begins. IPython | |
735 | will honor the environment variable PAGER if set, and otherwise will |
|
735 | will honor the environment variable PAGER if set, and otherwise will | |
736 | do its best to print the file in a convenient form. |
|
736 | do its best to print the file in a convenient form. | |
737 |
|
737 | |||
738 | If the given argument is not an object currently defined, IPython will |
|
738 | If the given argument is not an object currently defined, IPython will | |
739 | try to interpret it as a filename (automatically adding a .py extension |
|
739 | try to interpret it as a filename (automatically adding a .py extension | |
740 | if needed). You can thus use %pfile as a syntax highlighting code |
|
740 | if needed). You can thus use %pfile as a syntax highlighting code | |
741 | viewer.""" |
|
741 | viewer.""" | |
742 |
|
742 | |||
743 | # first interpret argument as an object name |
|
743 | # first interpret argument as an object name | |
744 | out = self._inspect('pfile',parameter_s) |
|
744 | out = self._inspect('pfile',parameter_s) | |
745 | # if not, try the input as a filename |
|
745 | # if not, try the input as a filename | |
746 | if out == 'not found': |
|
746 | if out == 'not found': | |
747 | try: |
|
747 | try: | |
748 | filename = get_py_filename(parameter_s) |
|
748 | filename = get_py_filename(parameter_s) | |
749 | except IOError,msg: |
|
749 | except IOError,msg: | |
750 | print msg |
|
750 | print msg | |
751 | return |
|
751 | return | |
752 | page(self.shell.inspector.format(file(filename).read())) |
|
752 | page(self.shell.inspector.format(file(filename).read())) | |
753 |
|
753 | |||
754 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
754 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
755 | """Provide detailed information about an object. |
|
755 | """Provide detailed information about an object. | |
756 |
|
756 | |||
757 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
757 | '%pinfo object' is just a synonym for object? or ?object.""" | |
758 |
|
758 | |||
759 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
759 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
760 |
|
760 | |||
761 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
761 | # detail_level: 0 -> obj? , 1 -> obj?? | |
762 | detail_level = 0 |
|
762 | detail_level = 0 | |
763 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
763 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
764 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
764 | # happen if the user types 'pinfo foo?' at the cmd line. | |
765 | pinfo,qmark1,oname,qmark2 = \ |
|
765 | pinfo,qmark1,oname,qmark2 = \ | |
766 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
766 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
767 | if pinfo or qmark1 or qmark2: |
|
767 | if pinfo or qmark1 or qmark2: | |
768 | detail_level = 1 |
|
768 | detail_level = 1 | |
769 | if "*" in oname: |
|
769 | if "*" in oname: | |
770 | self.magic_psearch(oname) |
|
770 | self.magic_psearch(oname) | |
771 | else: |
|
771 | else: | |
772 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
772 | self._inspect('pinfo', oname, detail_level=detail_level, | |
773 | namespaces=namespaces) |
|
773 | namespaces=namespaces) | |
774 |
|
774 | |||
775 | def magic_psearch(self, parameter_s=''): |
|
775 | def magic_psearch(self, parameter_s=''): | |
776 | """Search for object in namespaces by wildcard. |
|
776 | """Search for object in namespaces by wildcard. | |
777 |
|
777 | |||
778 | %psearch [options] PATTERN [OBJECT TYPE] |
|
778 | %psearch [options] PATTERN [OBJECT TYPE] | |
779 |
|
779 | |||
780 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
780 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
781 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
781 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
782 | rest of the command line must be unchanged (options come first), so |
|
782 | rest of the command line must be unchanged (options come first), so | |
783 | for example the following forms are equivalent |
|
783 | for example the following forms are equivalent | |
784 |
|
784 | |||
785 | %psearch -i a* function |
|
785 | %psearch -i a* function | |
786 | -i a* function? |
|
786 | -i a* function? | |
787 | ?-i a* function |
|
787 | ?-i a* function | |
788 |
|
788 | |||
789 | Arguments: |
|
789 | Arguments: | |
790 |
|
790 | |||
791 | PATTERN |
|
791 | PATTERN | |
792 |
|
792 | |||
793 | where PATTERN is a string containing * as a wildcard similar to its |
|
793 | where PATTERN is a string containing * as a wildcard similar to its | |
794 | use in a shell. The pattern is matched in all namespaces on the |
|
794 | use in a shell. The pattern is matched in all namespaces on the | |
795 | search path. By default objects starting with a single _ are not |
|
795 | search path. By default objects starting with a single _ are not | |
796 | matched, many IPython generated objects have a single |
|
796 | matched, many IPython generated objects have a single | |
797 | underscore. The default is case insensitive matching. Matching is |
|
797 | underscore. The default is case insensitive matching. Matching is | |
798 | also done on the attributes of objects and not only on the objects |
|
798 | also done on the attributes of objects and not only on the objects | |
799 | in a module. |
|
799 | in a module. | |
800 |
|
800 | |||
801 | [OBJECT TYPE] |
|
801 | [OBJECT TYPE] | |
802 |
|
802 | |||
803 | Is the name of a python type from the types module. The name is |
|
803 | Is the name of a python type from the types module. The name is | |
804 | given in lowercase without the ending type, ex. StringType is |
|
804 | given in lowercase without the ending type, ex. StringType is | |
805 | written string. By adding a type here only objects matching the |
|
805 | written string. By adding a type here only objects matching the | |
806 | given type are matched. Using all here makes the pattern match all |
|
806 | given type are matched. Using all here makes the pattern match all | |
807 | types (this is the default). |
|
807 | types (this is the default). | |
808 |
|
808 | |||
809 | Options: |
|
809 | Options: | |
810 |
|
810 | |||
811 | -a: makes the pattern match even objects whose names start with a |
|
811 | -a: makes the pattern match even objects whose names start with a | |
812 | single underscore. These names are normally ommitted from the |
|
812 | single underscore. These names are normally ommitted from the | |
813 | search. |
|
813 | search. | |
814 |
|
814 | |||
815 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
815 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
816 | these options is given, the default is read from your ipythonrc |
|
816 | these options is given, the default is read from your ipythonrc | |
817 | file. The option name which sets this value is |
|
817 | file. The option name which sets this value is | |
818 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
818 | 'wildcards_case_sensitive'. If this option is not specified in your | |
819 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
819 | ipythonrc file, IPython's internal default is to do a case sensitive | |
820 | search. |
|
820 | search. | |
821 |
|
821 | |||
822 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
822 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
823 | specifiy can be searched in any of the following namespaces: |
|
823 | specifiy can be searched in any of the following namespaces: | |
824 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
824 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
825 | 'builtin' and 'user' are the search defaults. Note that you should |
|
825 | 'builtin' and 'user' are the search defaults. Note that you should | |
826 | not use quotes when specifying namespaces. |
|
826 | not use quotes when specifying namespaces. | |
827 |
|
827 | |||
828 | 'Builtin' contains the python module builtin, 'user' contains all |
|
828 | 'Builtin' contains the python module builtin, 'user' contains all | |
829 | user data, 'alias' only contain the shell aliases and no python |
|
829 | user data, 'alias' only contain the shell aliases and no python | |
830 | objects, 'internal' contains objects used by IPython. The |
|
830 | objects, 'internal' contains objects used by IPython. The | |
831 | 'user_global' namespace is only used by embedded IPython instances, |
|
831 | 'user_global' namespace is only used by embedded IPython instances, | |
832 | and it contains module-level globals. You can add namespaces to the |
|
832 | and it contains module-level globals. You can add namespaces to the | |
833 | search with -s or exclude them with -e (these options can be given |
|
833 | search with -s or exclude them with -e (these options can be given | |
834 | more than once). |
|
834 | more than once). | |
835 |
|
835 | |||
836 | Examples: |
|
836 | Examples: | |
837 |
|
837 | |||
838 | %psearch a* -> objects beginning with an a |
|
838 | %psearch a* -> objects beginning with an a | |
839 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
839 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
840 | %psearch a* function -> all functions beginning with an a |
|
840 | %psearch a* function -> all functions beginning with an a | |
841 | %psearch re.e* -> objects beginning with an e in module re |
|
841 | %psearch re.e* -> objects beginning with an e in module re | |
842 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
842 | %psearch r*.e* -> objects that start with e in modules starting in r | |
843 | %psearch r*.* string -> all strings in modules beginning with r |
|
843 | %psearch r*.* string -> all strings in modules beginning with r | |
844 |
|
844 | |||
845 | Case sensitve search: |
|
845 | Case sensitve search: | |
846 |
|
846 | |||
847 | %psearch -c a* list all object beginning with lower case a |
|
847 | %psearch -c a* list all object beginning with lower case a | |
848 |
|
848 | |||
849 | Show objects beginning with a single _: |
|
849 | Show objects beginning with a single _: | |
850 |
|
850 | |||
851 | %psearch -a _* list objects beginning with a single underscore""" |
|
851 | %psearch -a _* list objects beginning with a single underscore""" | |
852 | try: |
|
852 | try: | |
853 | parameter_s = parameter_s.encode('ascii') |
|
853 | parameter_s = parameter_s.encode('ascii') | |
854 | except UnicodeEncodeError: |
|
854 | except UnicodeEncodeError: | |
855 | print 'Python identifiers can only contain ascii characters.' |
|
855 | print 'Python identifiers can only contain ascii characters.' | |
856 | return |
|
856 | return | |
857 |
|
857 | |||
858 | # default namespaces to be searched |
|
858 | # default namespaces to be searched | |
859 | def_search = ['user','builtin'] |
|
859 | def_search = ['user','builtin'] | |
860 |
|
860 | |||
861 | # Process options/args |
|
861 | # Process options/args | |
862 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
862 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
863 | opt = opts.get |
|
863 | opt = opts.get | |
864 | shell = self.shell |
|
864 | shell = self.shell | |
865 | psearch = shell.inspector.psearch |
|
865 | psearch = shell.inspector.psearch | |
866 |
|
866 | |||
867 | # select case options |
|
867 | # select case options | |
868 | if opts.has_key('i'): |
|
868 | if opts.has_key('i'): | |
869 | ignore_case = True |
|
869 | ignore_case = True | |
870 | elif opts.has_key('c'): |
|
870 | elif opts.has_key('c'): | |
871 | ignore_case = False |
|
871 | ignore_case = False | |
872 | else: |
|
872 | else: | |
873 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
873 | ignore_case = not shell.rc.wildcards_case_sensitive | |
874 |
|
874 | |||
875 | # Build list of namespaces to search from user options |
|
875 | # Build list of namespaces to search from user options | |
876 | def_search.extend(opt('s',[])) |
|
876 | def_search.extend(opt('s',[])) | |
877 | ns_exclude = ns_exclude=opt('e',[]) |
|
877 | ns_exclude = ns_exclude=opt('e',[]) | |
878 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
878 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
879 |
|
879 | |||
880 | # Call the actual search |
|
880 | # Call the actual search | |
881 | try: |
|
881 | try: | |
882 | psearch(args,shell.ns_table,ns_search, |
|
882 | psearch(args,shell.ns_table,ns_search, | |
883 | show_all=opt('a'),ignore_case=ignore_case) |
|
883 | show_all=opt('a'),ignore_case=ignore_case) | |
884 | except: |
|
884 | except: | |
885 | shell.showtraceback() |
|
885 | shell.showtraceback() | |
886 |
|
886 | |||
887 | def magic_who_ls(self, parameter_s=''): |
|
887 | def magic_who_ls(self, parameter_s=''): | |
888 | """Return a sorted list of all interactive variables. |
|
888 | """Return a sorted list of all interactive variables. | |
889 |
|
889 | |||
890 | If arguments are given, only variables of types matching these |
|
890 | If arguments are given, only variables of types matching these | |
891 | arguments are returned.""" |
|
891 | arguments are returned.""" | |
892 |
|
892 | |||
893 | user_ns = self.shell.user_ns |
|
893 | user_ns = self.shell.user_ns | |
894 | internal_ns = self.shell.internal_ns |
|
894 | internal_ns = self.shell.internal_ns | |
895 | user_config_ns = self.shell.user_config_ns |
|
895 | user_config_ns = self.shell.user_config_ns | |
896 | out = [] |
|
896 | out = [] | |
897 | typelist = parameter_s.split() |
|
897 | typelist = parameter_s.split() | |
898 |
|
898 | |||
899 | for i in user_ns: |
|
899 | for i in user_ns: | |
900 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
900 | if not (i.startswith('_') or i.startswith('_i')) \ | |
901 | and not (i in internal_ns or i in user_config_ns): |
|
901 | and not (i in internal_ns or i in user_config_ns): | |
902 | if typelist: |
|
902 | if typelist: | |
903 | if type(user_ns[i]).__name__ in typelist: |
|
903 | if type(user_ns[i]).__name__ in typelist: | |
904 | out.append(i) |
|
904 | out.append(i) | |
905 | else: |
|
905 | else: | |
906 | out.append(i) |
|
906 | out.append(i) | |
907 | out.sort() |
|
907 | out.sort() | |
908 | return out |
|
908 | return out | |
909 |
|
909 | |||
910 | def magic_who(self, parameter_s=''): |
|
910 | def magic_who(self, parameter_s=''): | |
911 | """Print all interactive variables, with some minimal formatting. |
|
911 | """Print all interactive variables, with some minimal formatting. | |
912 |
|
912 | |||
913 | If any arguments are given, only variables whose type matches one of |
|
913 | If any arguments are given, only variables whose type matches one of | |
914 | these are printed. For example: |
|
914 | these are printed. For example: | |
915 |
|
915 | |||
916 | %who function str |
|
916 | %who function str | |
917 |
|
917 | |||
918 | will only list functions and strings, excluding all other types of |
|
918 | will only list functions and strings, excluding all other types of | |
919 | variables. To find the proper type names, simply use type(var) at a |
|
919 | variables. To find the proper type names, simply use type(var) at a | |
920 | command line to see how python prints type names. For example: |
|
920 | command line to see how python prints type names. For example: | |
921 |
|
921 | |||
922 | In [1]: type('hello')\\ |
|
922 | In [1]: type('hello')\\ | |
923 | Out[1]: <type 'str'> |
|
923 | Out[1]: <type 'str'> | |
924 |
|
924 | |||
925 | indicates that the type name for strings is 'str'. |
|
925 | indicates that the type name for strings is 'str'. | |
926 |
|
926 | |||
927 | %who always excludes executed names loaded through your configuration |
|
927 | %who always excludes executed names loaded through your configuration | |
928 | file and things which are internal to IPython. |
|
928 | file and things which are internal to IPython. | |
929 |
|
929 | |||
930 | This is deliberate, as typically you may load many modules and the |
|
930 | This is deliberate, as typically you may load many modules and the | |
931 | purpose of %who is to show you only what you've manually defined.""" |
|
931 | purpose of %who is to show you only what you've manually defined.""" | |
932 |
|
932 | |||
933 | varlist = self.magic_who_ls(parameter_s) |
|
933 | varlist = self.magic_who_ls(parameter_s) | |
934 | if not varlist: |
|
934 | if not varlist: | |
935 | print 'Interactive namespace is empty.' |
|
935 | if parameter_s: | |
|
936 | print 'No variables match your requested type.' | |||
|
937 | else: | |||
|
938 | print 'Interactive namespace is empty.' | |||
936 | return |
|
939 | return | |
937 |
|
940 | |||
938 | # if we have variables, move on... |
|
941 | # if we have variables, move on... | |
939 | count = 0 |
|
942 | count = 0 | |
940 | for i in varlist: |
|
943 | for i in varlist: | |
941 | print i+'\t', |
|
944 | print i+'\t', | |
942 | count += 1 |
|
945 | count += 1 | |
943 | if count > 8: |
|
946 | if count > 8: | |
944 | count = 0 |
|
947 | count = 0 | |
945 |
|
948 | |||
946 |
|
949 | |||
947 |
|
950 | |||
948 | def magic_whos(self, parameter_s=''): |
|
951 | def magic_whos(self, parameter_s=''): | |
949 | """Like %who, but gives some extra information about each variable. |
|
952 | """Like %who, but gives some extra information about each variable. | |
950 |
|
953 | |||
951 | The same type filtering of %who can be applied here. |
|
954 | The same type filtering of %who can be applied here. | |
952 |
|
955 | |||
953 | For all variables, the type is printed. Additionally it prints: |
|
956 | For all variables, the type is printed. Additionally it prints: | |
954 |
|
957 | |||
955 | - For {},[],(): their length. |
|
958 | - For {},[],(): their length. | |
956 |
|
959 | |||
957 | - For numpy and Numeric arrays, a summary with shape, number of |
|
960 | - For numpy and Numeric arrays, a summary with shape, number of | |
958 | elements, typecode and size in memory. |
|
961 | elements, typecode and size in memory. | |
959 |
|
962 | |||
960 | - Everything else: a string representation, snipping their middle if |
|
963 | - Everything else: a string representation, snipping their middle if | |
961 | too long.""" |
|
964 | too long.""" | |
962 |
|
965 | |||
963 | varnames = self.magic_who_ls(parameter_s) |
|
966 | varnames = self.magic_who_ls(parameter_s) | |
964 | if not varnames: |
|
967 | if not varnames: | |
965 | print 'Interactive namespace is empty.' |
|
968 | if parameter_s: | |
|
969 | print 'No variables match your requested type.' | |||
|
970 | else: | |||
|
971 | print 'Interactive namespace is empty.' | |||
966 | return |
|
972 | return | |
967 |
|
973 | |||
968 | # if we have variables, move on... |
|
974 | # if we have variables, move on... | |
969 |
|
975 | |||
970 | # for these types, show len() instead of data: |
|
976 | # for these types, show len() instead of data: | |
971 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
977 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
972 |
|
978 | |||
973 | # for numpy/Numeric arrays, display summary info |
|
979 | # for numpy/Numeric arrays, display summary info | |
974 | try: |
|
980 | try: | |
975 | import numpy |
|
981 | import numpy | |
976 | except ImportError: |
|
982 | except ImportError: | |
977 | ndarray_type = None |
|
983 | ndarray_type = None | |
978 | else: |
|
984 | else: | |
979 | ndarray_type = numpy.ndarray.__name__ |
|
985 | ndarray_type = numpy.ndarray.__name__ | |
980 | try: |
|
986 | try: | |
981 | import Numeric |
|
987 | import Numeric | |
982 | except ImportError: |
|
988 | except ImportError: | |
983 | array_type = None |
|
989 | array_type = None | |
984 | else: |
|
990 | else: | |
985 | array_type = Numeric.ArrayType.__name__ |
|
991 | array_type = Numeric.ArrayType.__name__ | |
986 |
|
992 | |||
987 | # Find all variable names and types so we can figure out column sizes |
|
993 | # Find all variable names and types so we can figure out column sizes | |
988 | def get_vars(i): |
|
994 | def get_vars(i): | |
989 | return self.shell.user_ns[i] |
|
995 | return self.shell.user_ns[i] | |
990 |
|
996 | |||
991 | # some types are well known and can be shorter |
|
997 | # some types are well known and can be shorter | |
992 | abbrevs = {'IPython.macro.Macro' : 'Macro'} |
|
998 | abbrevs = {'IPython.macro.Macro' : 'Macro'} | |
993 | def type_name(v): |
|
999 | def type_name(v): | |
994 | tn = type(v).__name__ |
|
1000 | tn = type(v).__name__ | |
995 | return abbrevs.get(tn,tn) |
|
1001 | return abbrevs.get(tn,tn) | |
996 |
|
1002 | |||
997 | varlist = map(get_vars,varnames) |
|
1003 | varlist = map(get_vars,varnames) | |
998 |
|
1004 | |||
999 | typelist = [] |
|
1005 | typelist = [] | |
1000 | for vv in varlist: |
|
1006 | for vv in varlist: | |
1001 | tt = type_name(vv) |
|
1007 | tt = type_name(vv) | |
1002 |
|
1008 | |||
1003 | if tt=='instance': |
|
1009 | if tt=='instance': | |
1004 | typelist.append( abbrevs.get(str(vv.__class__), |
|
1010 | typelist.append( abbrevs.get(str(vv.__class__), | |
1005 | str(vv.__class__))) |
|
1011 | str(vv.__class__))) | |
1006 | else: |
|
1012 | else: | |
1007 | typelist.append(tt) |
|
1013 | typelist.append(tt) | |
1008 |
|
1014 | |||
1009 | # column labels and # of spaces as separator |
|
1015 | # column labels and # of spaces as separator | |
1010 | varlabel = 'Variable' |
|
1016 | varlabel = 'Variable' | |
1011 | typelabel = 'Type' |
|
1017 | typelabel = 'Type' | |
1012 | datalabel = 'Data/Info' |
|
1018 | datalabel = 'Data/Info' | |
1013 | colsep = 3 |
|
1019 | colsep = 3 | |
1014 | # variable format strings |
|
1020 | # variable format strings | |
1015 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
1021 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
1016 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
1022 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
1017 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1023 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
1018 | # find the size of the columns to format the output nicely |
|
1024 | # find the size of the columns to format the output nicely | |
1019 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1025 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
1020 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1026 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
1021 | # table header |
|
1027 | # table header | |
1022 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1028 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
1023 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1029 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
1024 | # and the table itself |
|
1030 | # and the table itself | |
1025 | kb = 1024 |
|
1031 | kb = 1024 | |
1026 | Mb = 1048576 # kb**2 |
|
1032 | Mb = 1048576 # kb**2 | |
1027 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1033 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
1028 | print itpl(vformat), |
|
1034 | print itpl(vformat), | |
1029 | if vtype in seq_types: |
|
1035 | if vtype in seq_types: | |
1030 | print len(var) |
|
1036 | print len(var) | |
1031 | elif vtype in [array_type,ndarray_type]: |
|
1037 | elif vtype in [array_type,ndarray_type]: | |
1032 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1038 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
1033 | if vtype==ndarray_type: |
|
1039 | if vtype==ndarray_type: | |
1034 | # numpy |
|
1040 | # numpy | |
1035 | vsize = var.size |
|
1041 | vsize = var.size | |
1036 | vbytes = vsize*var.itemsize |
|
1042 | vbytes = vsize*var.itemsize | |
1037 | vdtype = var.dtype |
|
1043 | vdtype = var.dtype | |
1038 | else: |
|
1044 | else: | |
1039 | # Numeric |
|
1045 | # Numeric | |
1040 | vsize = Numeric.size(var) |
|
1046 | vsize = Numeric.size(var) | |
1041 | vbytes = vsize*var.itemsize() |
|
1047 | vbytes = vsize*var.itemsize() | |
1042 | vdtype = var.typecode() |
|
1048 | vdtype = var.typecode() | |
1043 |
|
1049 | |||
1044 | if vbytes < 100000: |
|
1050 | if vbytes < 100000: | |
1045 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1051 | print aformat % (vshape,vsize,vdtype,vbytes) | |
1046 | else: |
|
1052 | else: | |
1047 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1053 | print aformat % (vshape,vsize,vdtype,vbytes), | |
1048 | if vbytes < Mb: |
|
1054 | if vbytes < Mb: | |
1049 | print '(%s kb)' % (vbytes/kb,) |
|
1055 | print '(%s kb)' % (vbytes/kb,) | |
1050 | else: |
|
1056 | else: | |
1051 | print '(%s Mb)' % (vbytes/Mb,) |
|
1057 | print '(%s Mb)' % (vbytes/Mb,) | |
1052 | else: |
|
1058 | else: | |
1053 | vstr = str(var).replace('\n','\\n') |
|
1059 | vstr = str(var).replace('\n','\\n') | |
1054 | if len(vstr) < 50: |
|
1060 | if len(vstr) < 50: | |
1055 | print vstr |
|
1061 | print vstr | |
1056 | else: |
|
1062 | else: | |
1057 | printpl(vfmt_short) |
|
1063 | printpl(vfmt_short) | |
1058 |
|
1064 | |||
1059 | def magic_reset(self, parameter_s=''): |
|
1065 | def magic_reset(self, parameter_s=''): | |
1060 | """Resets the namespace by removing all names defined by the user. |
|
1066 | """Resets the namespace by removing all names defined by the user. | |
1061 |
|
1067 | |||
1062 | Input/Output history are left around in case you need them.""" |
|
1068 | Input/Output history are left around in case you need them.""" | |
1063 |
|
1069 | |||
1064 | ans = self.shell.ask_yes_no( |
|
1070 | ans = self.shell.ask_yes_no( | |
1065 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1071 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1066 | if not ans: |
|
1072 | if not ans: | |
1067 | print 'Nothing done.' |
|
1073 | print 'Nothing done.' | |
1068 | return |
|
1074 | return | |
1069 | user_ns = self.shell.user_ns |
|
1075 | user_ns = self.shell.user_ns | |
1070 | for i in self.magic_who_ls(): |
|
1076 | for i in self.magic_who_ls(): | |
1071 | del(user_ns[i]) |
|
1077 | del(user_ns[i]) | |
1072 |
|
1078 | |||
1073 | def magic_logstart(self,parameter_s=''): |
|
1079 | def magic_logstart(self,parameter_s=''): | |
1074 | """Start logging anywhere in a session. |
|
1080 | """Start logging anywhere in a session. | |
1075 |
|
1081 | |||
1076 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1082 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1077 |
|
1083 | |||
1078 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1084 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1079 | current directory, in 'rotate' mode (see below). |
|
1085 | current directory, in 'rotate' mode (see below). | |
1080 |
|
1086 | |||
1081 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1087 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1082 | history up to that point and then continues logging. |
|
1088 | history up to that point and then continues logging. | |
1083 |
|
1089 | |||
1084 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1090 | %logstart takes a second optional parameter: logging mode. This can be one | |
1085 | of (note that the modes are given unquoted):\\ |
|
1091 | of (note that the modes are given unquoted):\\ | |
1086 | append: well, that says it.\\ |
|
1092 | append: well, that says it.\\ | |
1087 | backup: rename (if exists) to name~ and start name.\\ |
|
1093 | backup: rename (if exists) to name~ and start name.\\ | |
1088 | global: single logfile in your home dir, appended to.\\ |
|
1094 | global: single logfile in your home dir, appended to.\\ | |
1089 | over : overwrite existing log.\\ |
|
1095 | over : overwrite existing log.\\ | |
1090 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1096 | rotate: create rotating logs name.1~, name.2~, etc. | |
1091 |
|
1097 | |||
1092 | Options: |
|
1098 | Options: | |
1093 |
|
1099 | |||
1094 | -o: log also IPython's output. In this mode, all commands which |
|
1100 | -o: log also IPython's output. In this mode, all commands which | |
1095 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1101 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1096 | their corresponding input line. The output lines are always |
|
1102 | their corresponding input line. The output lines are always | |
1097 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1103 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1098 | Python code. |
|
1104 | Python code. | |
1099 |
|
1105 | |||
1100 | Since this marker is always the same, filtering only the output from |
|
1106 | Since this marker is always the same, filtering only the output from | |
1101 | a log is very easy, using for example a simple awk call: |
|
1107 | a log is very easy, using for example a simple awk call: | |
1102 |
|
1108 | |||
1103 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1109 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1104 |
|
1110 | |||
1105 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1111 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1106 | input, so that user lines are logged in their final form, converted |
|
1112 | input, so that user lines are logged in their final form, converted | |
1107 | into valid Python. For example, %Exit is logged as |
|
1113 | into valid Python. For example, %Exit is logged as | |
1108 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1114 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1109 | exactly as typed, with no transformations applied. |
|
1115 | exactly as typed, with no transformations applied. | |
1110 |
|
1116 | |||
1111 | -t: put timestamps before each input line logged (these are put in |
|
1117 | -t: put timestamps before each input line logged (these are put in | |
1112 | comments).""" |
|
1118 | comments).""" | |
1113 |
|
1119 | |||
1114 | opts,par = self.parse_options(parameter_s,'ort') |
|
1120 | opts,par = self.parse_options(parameter_s,'ort') | |
1115 | log_output = 'o' in opts |
|
1121 | log_output = 'o' in opts | |
1116 | log_raw_input = 'r' in opts |
|
1122 | log_raw_input = 'r' in opts | |
1117 | timestamp = 't' in opts |
|
1123 | timestamp = 't' in opts | |
1118 |
|
1124 | |||
1119 | rc = self.shell.rc |
|
1125 | rc = self.shell.rc | |
1120 | logger = self.shell.logger |
|
1126 | logger = self.shell.logger | |
1121 |
|
1127 | |||
1122 | # if no args are given, the defaults set in the logger constructor by |
|
1128 | # if no args are given, the defaults set in the logger constructor by | |
1123 | # ipytohn remain valid |
|
1129 | # ipytohn remain valid | |
1124 | if par: |
|
1130 | if par: | |
1125 | try: |
|
1131 | try: | |
1126 | logfname,logmode = par.split() |
|
1132 | logfname,logmode = par.split() | |
1127 | except: |
|
1133 | except: | |
1128 | logfname = par |
|
1134 | logfname = par | |
1129 | logmode = 'backup' |
|
1135 | logmode = 'backup' | |
1130 | else: |
|
1136 | else: | |
1131 | logfname = logger.logfname |
|
1137 | logfname = logger.logfname | |
1132 | logmode = logger.logmode |
|
1138 | logmode = logger.logmode | |
1133 | # put logfname into rc struct as if it had been called on the command |
|
1139 | # put logfname into rc struct as if it had been called on the command | |
1134 | # line, so it ends up saved in the log header Save it in case we need |
|
1140 | # line, so it ends up saved in the log header Save it in case we need | |
1135 | # to restore it... |
|
1141 | # to restore it... | |
1136 | old_logfile = rc.opts.get('logfile','') |
|
1142 | old_logfile = rc.opts.get('logfile','') | |
1137 | if logfname: |
|
1143 | if logfname: | |
1138 | logfname = os.path.expanduser(logfname) |
|
1144 | logfname = os.path.expanduser(logfname) | |
1139 | rc.opts.logfile = logfname |
|
1145 | rc.opts.logfile = logfname | |
1140 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1146 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) | |
1141 | try: |
|
1147 | try: | |
1142 | started = logger.logstart(logfname,loghead,logmode, |
|
1148 | started = logger.logstart(logfname,loghead,logmode, | |
1143 | log_output,timestamp,log_raw_input) |
|
1149 | log_output,timestamp,log_raw_input) | |
1144 | except: |
|
1150 | except: | |
1145 | rc.opts.logfile = old_logfile |
|
1151 | rc.opts.logfile = old_logfile | |
1146 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1152 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1147 | else: |
|
1153 | else: | |
1148 | # log input history up to this point, optionally interleaving |
|
1154 | # log input history up to this point, optionally interleaving | |
1149 | # output if requested |
|
1155 | # output if requested | |
1150 |
|
1156 | |||
1151 | if timestamp: |
|
1157 | if timestamp: | |
1152 | # disable timestamping for the previous history, since we've |
|
1158 | # disable timestamping for the previous history, since we've | |
1153 | # lost those already (no time machine here). |
|
1159 | # lost those already (no time machine here). | |
1154 | logger.timestamp = False |
|
1160 | logger.timestamp = False | |
1155 |
|
1161 | |||
1156 | if log_raw_input: |
|
1162 | if log_raw_input: | |
1157 | input_hist = self.shell.input_hist_raw |
|
1163 | input_hist = self.shell.input_hist_raw | |
1158 | else: |
|
1164 | else: | |
1159 | input_hist = self.shell.input_hist |
|
1165 | input_hist = self.shell.input_hist | |
1160 |
|
1166 | |||
1161 | if log_output: |
|
1167 | if log_output: | |
1162 | log_write = logger.log_write |
|
1168 | log_write = logger.log_write | |
1163 | output_hist = self.shell.output_hist |
|
1169 | output_hist = self.shell.output_hist | |
1164 | for n in range(1,len(input_hist)-1): |
|
1170 | for n in range(1,len(input_hist)-1): | |
1165 | log_write(input_hist[n].rstrip()) |
|
1171 | log_write(input_hist[n].rstrip()) | |
1166 | if n in output_hist: |
|
1172 | if n in output_hist: | |
1167 | log_write(repr(output_hist[n]),'output') |
|
1173 | log_write(repr(output_hist[n]),'output') | |
1168 | else: |
|
1174 | else: | |
1169 | logger.log_write(input_hist[1:]) |
|
1175 | logger.log_write(input_hist[1:]) | |
1170 | if timestamp: |
|
1176 | if timestamp: | |
1171 | # re-enable timestamping |
|
1177 | # re-enable timestamping | |
1172 | logger.timestamp = True |
|
1178 | logger.timestamp = True | |
1173 |
|
1179 | |||
1174 | print ('Activating auto-logging. ' |
|
1180 | print ('Activating auto-logging. ' | |
1175 | 'Current session state plus future input saved.') |
|
1181 | 'Current session state plus future input saved.') | |
1176 | logger.logstate() |
|
1182 | logger.logstate() | |
1177 |
|
1183 | |||
1178 | def magic_logoff(self,parameter_s=''): |
|
1184 | def magic_logoff(self,parameter_s=''): | |
1179 | """Temporarily stop logging. |
|
1185 | """Temporarily stop logging. | |
1180 |
|
1186 | |||
1181 | You must have previously started logging.""" |
|
1187 | You must have previously started logging.""" | |
1182 | self.shell.logger.switch_log(0) |
|
1188 | self.shell.logger.switch_log(0) | |
1183 |
|
1189 | |||
1184 | def magic_logon(self,parameter_s=''): |
|
1190 | def magic_logon(self,parameter_s=''): | |
1185 | """Restart logging. |
|
1191 | """Restart logging. | |
1186 |
|
1192 | |||
1187 | This function is for restarting logging which you've temporarily |
|
1193 | This function is for restarting logging which you've temporarily | |
1188 | stopped with %logoff. For starting logging for the first time, you |
|
1194 | stopped with %logoff. For starting logging for the first time, you | |
1189 | must use the %logstart function, which allows you to specify an |
|
1195 | must use the %logstart function, which allows you to specify an | |
1190 | optional log filename.""" |
|
1196 | optional log filename.""" | |
1191 |
|
1197 | |||
1192 | self.shell.logger.switch_log(1) |
|
1198 | self.shell.logger.switch_log(1) | |
1193 |
|
1199 | |||
1194 | def magic_logstate(self,parameter_s=''): |
|
1200 | def magic_logstate(self,parameter_s=''): | |
1195 | """Print the status of the logging system.""" |
|
1201 | """Print the status of the logging system.""" | |
1196 |
|
1202 | |||
1197 | self.shell.logger.logstate() |
|
1203 | self.shell.logger.logstate() | |
1198 |
|
1204 | |||
1199 | def magic_pdb(self, parameter_s=''): |
|
1205 | def magic_pdb(self, parameter_s=''): | |
1200 | """Control the automatic calling of the pdb interactive debugger. |
|
1206 | """Control the automatic calling of the pdb interactive debugger. | |
1201 |
|
1207 | |||
1202 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1208 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1203 | argument it works as a toggle. |
|
1209 | argument it works as a toggle. | |
1204 |
|
1210 | |||
1205 | When an exception is triggered, IPython can optionally call the |
|
1211 | When an exception is triggered, IPython can optionally call the | |
1206 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1212 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1207 | this feature on and off. |
|
1213 | this feature on and off. | |
1208 |
|
1214 | |||
1209 | The initial state of this feature is set in your ipythonrc |
|
1215 | The initial state of this feature is set in your ipythonrc | |
1210 | configuration file (the variable is called 'pdb'). |
|
1216 | configuration file (the variable is called 'pdb'). | |
1211 |
|
1217 | |||
1212 | If you want to just activate the debugger AFTER an exception has fired, |
|
1218 | If you want to just activate the debugger AFTER an exception has fired, | |
1213 | without having to type '%pdb on' and rerunning your code, you can use |
|
1219 | without having to type '%pdb on' and rerunning your code, you can use | |
1214 | the %debug magic.""" |
|
1220 | the %debug magic.""" | |
1215 |
|
1221 | |||
1216 | par = parameter_s.strip().lower() |
|
1222 | par = parameter_s.strip().lower() | |
1217 |
|
1223 | |||
1218 | if par: |
|
1224 | if par: | |
1219 | try: |
|
1225 | try: | |
1220 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1226 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1221 | except KeyError: |
|
1227 | except KeyError: | |
1222 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1228 | print ('Incorrect argument. Use on/1, off/0, ' | |
1223 | 'or nothing for a toggle.') |
|
1229 | 'or nothing for a toggle.') | |
1224 | return |
|
1230 | return | |
1225 | else: |
|
1231 | else: | |
1226 | # toggle |
|
1232 | # toggle | |
1227 | new_pdb = not self.shell.call_pdb |
|
1233 | new_pdb = not self.shell.call_pdb | |
1228 |
|
1234 | |||
1229 | # set on the shell |
|
1235 | # set on the shell | |
1230 | self.shell.call_pdb = new_pdb |
|
1236 | self.shell.call_pdb = new_pdb | |
1231 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1237 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1232 |
|
1238 | |||
1233 | def magic_debug(self, parameter_s=''): |
|
1239 | def magic_debug(self, parameter_s=''): | |
1234 | """Activate the interactive debugger in post-mortem mode. |
|
1240 | """Activate the interactive debugger in post-mortem mode. | |
1235 |
|
1241 | |||
1236 | If an exception has just occurred, this lets you inspect its stack |
|
1242 | If an exception has just occurred, this lets you inspect its stack | |
1237 | frames interactively. Note that this will always work only on the last |
|
1243 | frames interactively. Note that this will always work only on the last | |
1238 | traceback that occurred, so you must call this quickly after an |
|
1244 | traceback that occurred, so you must call this quickly after an | |
1239 | exception that you wish to inspect has fired, because if another one |
|
1245 | exception that you wish to inspect has fired, because if another one | |
1240 | occurs, it clobbers the previous one. |
|
1246 | occurs, it clobbers the previous one. | |
1241 |
|
1247 | |||
1242 | If you want IPython to automatically do this on every exception, see |
|
1248 | If you want IPython to automatically do this on every exception, see | |
1243 | the %pdb magic for more details. |
|
1249 | the %pdb magic for more details. | |
1244 | """ |
|
1250 | """ | |
1245 |
|
1251 | |||
1246 | self.shell.debugger(force=True) |
|
1252 | self.shell.debugger(force=True) | |
1247 |
|
1253 | |||
1248 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1254 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1249 | opts=None,arg_lst=None,prog_ns=None): |
|
1255 | opts=None,arg_lst=None,prog_ns=None): | |
1250 |
|
1256 | |||
1251 | """Run a statement through the python code profiler. |
|
1257 | """Run a statement through the python code profiler. | |
1252 |
|
1258 | |||
1253 | Usage:\\ |
|
1259 | Usage:\\ | |
1254 | %prun [options] statement |
|
1260 | %prun [options] statement | |
1255 |
|
1261 | |||
1256 | The given statement (which doesn't require quote marks) is run via the |
|
1262 | The given statement (which doesn't require quote marks) is run via the | |
1257 | python profiler in a manner similar to the profile.run() function. |
|
1263 | python profiler in a manner similar to the profile.run() function. | |
1258 | Namespaces are internally managed to work correctly; profile.run |
|
1264 | Namespaces are internally managed to work correctly; profile.run | |
1259 | cannot be used in IPython because it makes certain assumptions about |
|
1265 | cannot be used in IPython because it makes certain assumptions about | |
1260 | namespaces which do not hold under IPython. |
|
1266 | namespaces which do not hold under IPython. | |
1261 |
|
1267 | |||
1262 | Options: |
|
1268 | Options: | |
1263 |
|
1269 | |||
1264 | -l <limit>: you can place restrictions on what or how much of the |
|
1270 | -l <limit>: you can place restrictions on what or how much of the | |
1265 | profile gets printed. The limit value can be: |
|
1271 | profile gets printed. The limit value can be: | |
1266 |
|
1272 | |||
1267 | * A string: only information for function names containing this string |
|
1273 | * A string: only information for function names containing this string | |
1268 | is printed. |
|
1274 | is printed. | |
1269 |
|
1275 | |||
1270 | * An integer: only these many lines are printed. |
|
1276 | * An integer: only these many lines are printed. | |
1271 |
|
1277 | |||
1272 | * A float (between 0 and 1): this fraction of the report is printed |
|
1278 | * A float (between 0 and 1): this fraction of the report is printed | |
1273 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1279 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1274 |
|
1280 | |||
1275 | You can combine several limits with repeated use of the option. For |
|
1281 | You can combine several limits with repeated use of the option. For | |
1276 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1282 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1277 | information about class constructors. |
|
1283 | information about class constructors. | |
1278 |
|
1284 | |||
1279 | -r: return the pstats.Stats object generated by the profiling. This |
|
1285 | -r: return the pstats.Stats object generated by the profiling. This | |
1280 | object has all the information about the profile in it, and you can |
|
1286 | object has all the information about the profile in it, and you can | |
1281 | later use it for further analysis or in other functions. |
|
1287 | later use it for further analysis or in other functions. | |
1282 |
|
1288 | |||
1283 | -s <key>: sort profile by given key. You can provide more than one key |
|
1289 | -s <key>: sort profile by given key. You can provide more than one key | |
1284 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1290 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1285 | default sorting key is 'time'. |
|
1291 | default sorting key is 'time'. | |
1286 |
|
1292 | |||
1287 | The following is copied verbatim from the profile documentation |
|
1293 | The following is copied verbatim from the profile documentation | |
1288 | referenced below: |
|
1294 | referenced below: | |
1289 |
|
1295 | |||
1290 | When more than one key is provided, additional keys are used as |
|
1296 | When more than one key is provided, additional keys are used as | |
1291 | secondary criteria when the there is equality in all keys selected |
|
1297 | secondary criteria when the there is equality in all keys selected | |
1292 | before them. |
|
1298 | before them. | |
1293 |
|
1299 | |||
1294 | Abbreviations can be used for any key names, as long as the |
|
1300 | Abbreviations can be used for any key names, as long as the | |
1295 | abbreviation is unambiguous. The following are the keys currently |
|
1301 | abbreviation is unambiguous. The following are the keys currently | |
1296 | defined: |
|
1302 | defined: | |
1297 |
|
1303 | |||
1298 | Valid Arg Meaning\\ |
|
1304 | Valid Arg Meaning\\ | |
1299 | "calls" call count\\ |
|
1305 | "calls" call count\\ | |
1300 | "cumulative" cumulative time\\ |
|
1306 | "cumulative" cumulative time\\ | |
1301 | "file" file name\\ |
|
1307 | "file" file name\\ | |
1302 | "module" file name\\ |
|
1308 | "module" file name\\ | |
1303 | "pcalls" primitive call count\\ |
|
1309 | "pcalls" primitive call count\\ | |
1304 | "line" line number\\ |
|
1310 | "line" line number\\ | |
1305 | "name" function name\\ |
|
1311 | "name" function name\\ | |
1306 | "nfl" name/file/line\\ |
|
1312 | "nfl" name/file/line\\ | |
1307 | "stdname" standard name\\ |
|
1313 | "stdname" standard name\\ | |
1308 | "time" internal time |
|
1314 | "time" internal time | |
1309 |
|
1315 | |||
1310 | Note that all sorts on statistics are in descending order (placing |
|
1316 | Note that all sorts on statistics are in descending order (placing | |
1311 | most time consuming items first), where as name, file, and line number |
|
1317 | most time consuming items first), where as name, file, and line number | |
1312 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1318 | searches are in ascending order (i.e., alphabetical). The subtle | |
1313 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1319 | distinction between "nfl" and "stdname" is that the standard name is a | |
1314 | sort of the name as printed, which means that the embedded line |
|
1320 | sort of the name as printed, which means that the embedded line | |
1315 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1321 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1316 | would (if the file names were the same) appear in the string order |
|
1322 | would (if the file names were the same) appear in the string order | |
1317 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1323 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1318 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1324 | line numbers. In fact, sort_stats("nfl") is the same as | |
1319 | sort_stats("name", "file", "line"). |
|
1325 | sort_stats("name", "file", "line"). | |
1320 |
|
1326 | |||
1321 | -T <filename>: save profile results as shown on screen to a text |
|
1327 | -T <filename>: save profile results as shown on screen to a text | |
1322 | file. The profile is still shown on screen. |
|
1328 | file. The profile is still shown on screen. | |
1323 |
|
1329 | |||
1324 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1330 | -D <filename>: save (via dump_stats) profile statistics to given | |
1325 | filename. This data is in a format understod by the pstats module, and |
|
1331 | filename. This data is in a format understod by the pstats module, and | |
1326 | is generated by a call to the dump_stats() method of profile |
|
1332 | is generated by a call to the dump_stats() method of profile | |
1327 | objects. The profile is still shown on screen. |
|
1333 | objects. The profile is still shown on screen. | |
1328 |
|
1334 | |||
1329 | If you want to run complete programs under the profiler's control, use |
|
1335 | If you want to run complete programs under the profiler's control, use | |
1330 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1336 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1331 | contains profiler specific options as described here. |
|
1337 | contains profiler specific options as described here. | |
1332 |
|
1338 | |||
1333 | You can read the complete documentation for the profile module with:\\ |
|
1339 | You can read the complete documentation for the profile module with:\\ | |
1334 | In [1]: import profile; profile.help() """ |
|
1340 | In [1]: import profile; profile.help() """ | |
1335 |
|
1341 | |||
1336 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1342 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1337 | # protect user quote marks |
|
1343 | # protect user quote marks | |
1338 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1344 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1339 |
|
1345 | |||
1340 | if user_mode: # regular user call |
|
1346 | if user_mode: # regular user call | |
1341 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1347 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1342 | list_all=1) |
|
1348 | list_all=1) | |
1343 | namespace = self.shell.user_ns |
|
1349 | namespace = self.shell.user_ns | |
1344 | else: # called to run a program by %run -p |
|
1350 | else: # called to run a program by %run -p | |
1345 | try: |
|
1351 | try: | |
1346 | filename = get_py_filename(arg_lst[0]) |
|
1352 | filename = get_py_filename(arg_lst[0]) | |
1347 | except IOError,msg: |
|
1353 | except IOError,msg: | |
1348 | error(msg) |
|
1354 | error(msg) | |
1349 | return |
|
1355 | return | |
1350 |
|
1356 | |||
1351 | arg_str = 'execfile(filename,prog_ns)' |
|
1357 | arg_str = 'execfile(filename,prog_ns)' | |
1352 | namespace = locals() |
|
1358 | namespace = locals() | |
1353 |
|
1359 | |||
1354 | opts.merge(opts_def) |
|
1360 | opts.merge(opts_def) | |
1355 |
|
1361 | |||
1356 | prof = profile.Profile() |
|
1362 | prof = profile.Profile() | |
1357 | try: |
|
1363 | try: | |
1358 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1364 | prof = prof.runctx(arg_str,namespace,namespace) | |
1359 | sys_exit = '' |
|
1365 | sys_exit = '' | |
1360 | except SystemExit: |
|
1366 | except SystemExit: | |
1361 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1367 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1362 |
|
1368 | |||
1363 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1369 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1364 |
|
1370 | |||
1365 | lims = opts.l |
|
1371 | lims = opts.l | |
1366 | if lims: |
|
1372 | if lims: | |
1367 | lims = [] # rebuild lims with ints/floats/strings |
|
1373 | lims = [] # rebuild lims with ints/floats/strings | |
1368 | for lim in opts.l: |
|
1374 | for lim in opts.l: | |
1369 | try: |
|
1375 | try: | |
1370 | lims.append(int(lim)) |
|
1376 | lims.append(int(lim)) | |
1371 | except ValueError: |
|
1377 | except ValueError: | |
1372 | try: |
|
1378 | try: | |
1373 | lims.append(float(lim)) |
|
1379 | lims.append(float(lim)) | |
1374 | except ValueError: |
|
1380 | except ValueError: | |
1375 | lims.append(lim) |
|
1381 | lims.append(lim) | |
1376 |
|
1382 | |||
1377 | # Trap output. |
|
1383 | # Trap output. | |
1378 | stdout_trap = StringIO() |
|
1384 | stdout_trap = StringIO() | |
1379 |
|
1385 | |||
1380 | if hasattr(stats,'stream'): |
|
1386 | if hasattr(stats,'stream'): | |
1381 | # In newer versions of python, the stats object has a 'stream' |
|
1387 | # In newer versions of python, the stats object has a 'stream' | |
1382 | # attribute to write into. |
|
1388 | # attribute to write into. | |
1383 | stats.stream = stdout_trap |
|
1389 | stats.stream = stdout_trap | |
1384 | stats.print_stats(*lims) |
|
1390 | stats.print_stats(*lims) | |
1385 | else: |
|
1391 | else: | |
1386 | # For older versions, we manually redirect stdout during printing |
|
1392 | # For older versions, we manually redirect stdout during printing | |
1387 | sys_stdout = sys.stdout |
|
1393 | sys_stdout = sys.stdout | |
1388 | try: |
|
1394 | try: | |
1389 | sys.stdout = stdout_trap |
|
1395 | sys.stdout = stdout_trap | |
1390 | stats.print_stats(*lims) |
|
1396 | stats.print_stats(*lims) | |
1391 | finally: |
|
1397 | finally: | |
1392 | sys.stdout = sys_stdout |
|
1398 | sys.stdout = sys_stdout | |
1393 |
|
1399 | |||
1394 | output = stdout_trap.getvalue() |
|
1400 | output = stdout_trap.getvalue() | |
1395 | output = output.rstrip() |
|
1401 | output = output.rstrip() | |
1396 |
|
1402 | |||
1397 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1403 | page(output,screen_lines=self.shell.rc.screen_length) | |
1398 | print sys_exit, |
|
1404 | print sys_exit, | |
1399 |
|
1405 | |||
1400 | dump_file = opts.D[0] |
|
1406 | dump_file = opts.D[0] | |
1401 | text_file = opts.T[0] |
|
1407 | text_file = opts.T[0] | |
1402 | if dump_file: |
|
1408 | if dump_file: | |
1403 | prof.dump_stats(dump_file) |
|
1409 | prof.dump_stats(dump_file) | |
1404 | print '\n*** Profile stats marshalled to file',\ |
|
1410 | print '\n*** Profile stats marshalled to file',\ | |
1405 | `dump_file`+'.',sys_exit |
|
1411 | `dump_file`+'.',sys_exit | |
1406 | if text_file: |
|
1412 | if text_file: | |
1407 | pfile = file(text_file,'w') |
|
1413 | pfile = file(text_file,'w') | |
1408 | pfile.write(output) |
|
1414 | pfile.write(output) | |
1409 | pfile.close() |
|
1415 | pfile.close() | |
1410 | print '\n*** Profile printout saved to text file',\ |
|
1416 | print '\n*** Profile printout saved to text file',\ | |
1411 | `text_file`+'.',sys_exit |
|
1417 | `text_file`+'.',sys_exit | |
1412 |
|
1418 | |||
1413 | if opts.has_key('r'): |
|
1419 | if opts.has_key('r'): | |
1414 | return stats |
|
1420 | return stats | |
1415 | else: |
|
1421 | else: | |
1416 | return None |
|
1422 | return None | |
1417 |
|
1423 | |||
1418 | def magic_run(self, parameter_s ='',runner=None): |
|
1424 | def magic_run(self, parameter_s ='',runner=None): | |
1419 | """Run the named file inside IPython as a program. |
|
1425 | """Run the named file inside IPython as a program. | |
1420 |
|
1426 | |||
1421 | Usage:\\ |
|
1427 | Usage:\\ | |
1422 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1428 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1423 |
|
1429 | |||
1424 | Parameters after the filename are passed as command-line arguments to |
|
1430 | Parameters after the filename are passed as command-line arguments to | |
1425 | the program (put in sys.argv). Then, control returns to IPython's |
|
1431 | the program (put in sys.argv). Then, control returns to IPython's | |
1426 | prompt. |
|
1432 | prompt. | |
1427 |
|
1433 | |||
1428 | This is similar to running at a system prompt:\\ |
|
1434 | This is similar to running at a system prompt:\\ | |
1429 | $ python file args\\ |
|
1435 | $ python file args\\ | |
1430 | but with the advantage of giving you IPython's tracebacks, and of |
|
1436 | but with the advantage of giving you IPython's tracebacks, and of | |
1431 | loading all variables into your interactive namespace for further use |
|
1437 | loading all variables into your interactive namespace for further use | |
1432 | (unless -p is used, see below). |
|
1438 | (unless -p is used, see below). | |
1433 |
|
1439 | |||
1434 | The file is executed in a namespace initially consisting only of |
|
1440 | The file is executed in a namespace initially consisting only of | |
1435 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1441 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1436 | sees its environment as if it were being run as a stand-alone |
|
1442 | sees its environment as if it were being run as a stand-alone | |
1437 | program. But after execution, the IPython interactive namespace gets |
|
1443 | program. But after execution, the IPython interactive namespace gets | |
1438 | updated with all variables defined in the program (except for __name__ |
|
1444 | updated with all variables defined in the program (except for __name__ | |
1439 | and sys.argv). This allows for very convenient loading of code for |
|
1445 | and sys.argv). This allows for very convenient loading of code for | |
1440 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1446 | interactive work, while giving each program a 'clean sheet' to run in. | |
1441 |
|
1447 | |||
1442 | Options: |
|
1448 | Options: | |
1443 |
|
1449 | |||
1444 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1450 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1445 | without extension (as python does under import). This allows running |
|
1451 | without extension (as python does under import). This allows running | |
1446 | scripts and reloading the definitions in them without calling code |
|
1452 | scripts and reloading the definitions in them without calling code | |
1447 | protected by an ' if __name__ == "__main__" ' clause. |
|
1453 | protected by an ' if __name__ == "__main__" ' clause. | |
1448 |
|
1454 | |||
1449 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1455 | -i: run the file in IPython's namespace instead of an empty one. This | |
1450 | is useful if you are experimenting with code written in a text editor |
|
1456 | is useful if you are experimenting with code written in a text editor | |
1451 | which depends on variables defined interactively. |
|
1457 | which depends on variables defined interactively. | |
1452 |
|
1458 | |||
1453 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1459 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1454 | being run. This is particularly useful if IPython is being used to |
|
1460 | being run. This is particularly useful if IPython is being used to | |
1455 | run unittests, which always exit with a sys.exit() call. In such |
|
1461 | run unittests, which always exit with a sys.exit() call. In such | |
1456 | cases you are interested in the output of the test results, not in |
|
1462 | cases you are interested in the output of the test results, not in | |
1457 | seeing a traceback of the unittest module. |
|
1463 | seeing a traceback of the unittest module. | |
1458 |
|
1464 | |||
1459 | -t: print timing information at the end of the run. IPython will give |
|
1465 | -t: print timing information at the end of the run. IPython will give | |
1460 | you an estimated CPU time consumption for your script, which under |
|
1466 | you an estimated CPU time consumption for your script, which under | |
1461 | Unix uses the resource module to avoid the wraparound problems of |
|
1467 | Unix uses the resource module to avoid the wraparound problems of | |
1462 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1468 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1463 | is also given (for Windows platforms this is reported as 0.0). |
|
1469 | is also given (for Windows platforms this is reported as 0.0). | |
1464 |
|
1470 | |||
1465 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1471 | If -t is given, an additional -N<N> option can be given, where <N> | |
1466 | must be an integer indicating how many times you want the script to |
|
1472 | must be an integer indicating how many times you want the script to | |
1467 | run. The final timing report will include total and per run results. |
|
1473 | run. The final timing report will include total and per run results. | |
1468 |
|
1474 | |||
1469 | For example (testing the script uniq_stable.py): |
|
1475 | For example (testing the script uniq_stable.py): | |
1470 |
|
1476 | |||
1471 | In [1]: run -t uniq_stable |
|
1477 | In [1]: run -t uniq_stable | |
1472 |
|
1478 | |||
1473 | IPython CPU timings (estimated):\\ |
|
1479 | IPython CPU timings (estimated):\\ | |
1474 | User : 0.19597 s.\\ |
|
1480 | User : 0.19597 s.\\ | |
1475 | System: 0.0 s.\\ |
|
1481 | System: 0.0 s.\\ | |
1476 |
|
1482 | |||
1477 | In [2]: run -t -N5 uniq_stable |
|
1483 | In [2]: run -t -N5 uniq_stable | |
1478 |
|
1484 | |||
1479 | IPython CPU timings (estimated):\\ |
|
1485 | IPython CPU timings (estimated):\\ | |
1480 | Total runs performed: 5\\ |
|
1486 | Total runs performed: 5\\ | |
1481 | Times : Total Per run\\ |
|
1487 | Times : Total Per run\\ | |
1482 | User : 0.910862 s, 0.1821724 s.\\ |
|
1488 | User : 0.910862 s, 0.1821724 s.\\ | |
1483 | System: 0.0 s, 0.0 s. |
|
1489 | System: 0.0 s, 0.0 s. | |
1484 |
|
1490 | |||
1485 | -d: run your program under the control of pdb, the Python debugger. |
|
1491 | -d: run your program under the control of pdb, the Python debugger. | |
1486 | This allows you to execute your program step by step, watch variables, |
|
1492 | This allows you to execute your program step by step, watch variables, | |
1487 | etc. Internally, what IPython does is similar to calling: |
|
1493 | etc. Internally, what IPython does is similar to calling: | |
1488 |
|
1494 | |||
1489 | pdb.run('execfile("YOURFILENAME")') |
|
1495 | pdb.run('execfile("YOURFILENAME")') | |
1490 |
|
1496 | |||
1491 | with a breakpoint set on line 1 of your file. You can change the line |
|
1497 | with a breakpoint set on line 1 of your file. You can change the line | |
1492 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1498 | number for this automatic breakpoint to be <N> by using the -bN option | |
1493 | (where N must be an integer). For example: |
|
1499 | (where N must be an integer). For example: | |
1494 |
|
1500 | |||
1495 | %run -d -b40 myscript |
|
1501 | %run -d -b40 myscript | |
1496 |
|
1502 | |||
1497 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1503 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1498 | the first breakpoint must be set on a line which actually does |
|
1504 | the first breakpoint must be set on a line which actually does | |
1499 | something (not a comment or docstring) for it to stop execution. |
|
1505 | something (not a comment or docstring) for it to stop execution. | |
1500 |
|
1506 | |||
1501 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1507 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1502 | first enter 'c' (without qoutes) to start execution up to the first |
|
1508 | first enter 'c' (without qoutes) to start execution up to the first | |
1503 | breakpoint. |
|
1509 | breakpoint. | |
1504 |
|
1510 | |||
1505 | Entering 'help' gives information about the use of the debugger. You |
|
1511 | Entering 'help' gives information about the use of the debugger. You | |
1506 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1512 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1507 | at a prompt. |
|
1513 | at a prompt. | |
1508 |
|
1514 | |||
1509 | -p: run program under the control of the Python profiler module (which |
|
1515 | -p: run program under the control of the Python profiler module (which | |
1510 | prints a detailed report of execution times, function calls, etc). |
|
1516 | prints a detailed report of execution times, function calls, etc). | |
1511 |
|
1517 | |||
1512 | You can pass other options after -p which affect the behavior of the |
|
1518 | You can pass other options after -p which affect the behavior of the | |
1513 | profiler itself. See the docs for %prun for details. |
|
1519 | profiler itself. See the docs for %prun for details. | |
1514 |
|
1520 | |||
1515 | In this mode, the program's variables do NOT propagate back to the |
|
1521 | In this mode, the program's variables do NOT propagate back to the | |
1516 | IPython interactive namespace (because they remain in the namespace |
|
1522 | IPython interactive namespace (because they remain in the namespace | |
1517 | where the profiler executes them). |
|
1523 | where the profiler executes them). | |
1518 |
|
1524 | |||
1519 | Internally this triggers a call to %prun, see its documentation for |
|
1525 | Internally this triggers a call to %prun, see its documentation for | |
1520 | details on the options available specifically for profiling. |
|
1526 | details on the options available specifically for profiling. | |
1521 |
|
1527 | |||
1522 | There is one special usage for which the text above doesn't apply: |
|
1528 | There is one special usage for which the text above doesn't apply: | |
1523 | if the filename ends with .ipy, the file is run as ipython script, |
|
1529 | if the filename ends with .ipy, the file is run as ipython script, | |
1524 | just as if the commands were written on IPython prompt. |
|
1530 | just as if the commands were written on IPython prompt. | |
1525 | """ |
|
1531 | """ | |
1526 |
|
1532 | |||
1527 | # get arguments and set sys.argv for program to be run. |
|
1533 | # get arguments and set sys.argv for program to be run. | |
1528 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1534 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1529 | mode='list',list_all=1) |
|
1535 | mode='list',list_all=1) | |
1530 |
|
1536 | |||
1531 | try: |
|
1537 | try: | |
1532 | filename = get_py_filename(arg_lst[0]) |
|
1538 | filename = get_py_filename(arg_lst[0]) | |
1533 | except IndexError: |
|
1539 | except IndexError: | |
1534 | warn('you must provide at least a filename.') |
|
1540 | warn('you must provide at least a filename.') | |
1535 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1541 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1536 | return |
|
1542 | return | |
1537 | except IOError,msg: |
|
1543 | except IOError,msg: | |
1538 | error(msg) |
|
1544 | error(msg) | |
1539 | return |
|
1545 | return | |
1540 |
|
1546 | |||
1541 | if filename.lower().endswith('.ipy'): |
|
1547 | if filename.lower().endswith('.ipy'): | |
1542 | self.api.runlines(open(filename).read()) |
|
1548 | self.api.runlines(open(filename).read()) | |
1543 | return |
|
1549 | return | |
1544 |
|
1550 | |||
1545 | # Control the response to exit() calls made by the script being run |
|
1551 | # Control the response to exit() calls made by the script being run | |
1546 | exit_ignore = opts.has_key('e') |
|
1552 | exit_ignore = opts.has_key('e') | |
1547 |
|
1553 | |||
1548 | # Make sure that the running script gets a proper sys.argv as if it |
|
1554 | # Make sure that the running script gets a proper sys.argv as if it | |
1549 | # were run from a system shell. |
|
1555 | # were run from a system shell. | |
1550 | save_argv = sys.argv # save it for later restoring |
|
1556 | save_argv = sys.argv # save it for later restoring | |
1551 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1557 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1552 |
|
1558 | |||
1553 | if opts.has_key('i'): |
|
1559 | if opts.has_key('i'): | |
1554 | prog_ns = self.shell.user_ns |
|
1560 | prog_ns = self.shell.user_ns | |
1555 | __name__save = self.shell.user_ns['__name__'] |
|
1561 | __name__save = self.shell.user_ns['__name__'] | |
1556 | prog_ns['__name__'] = '__main__' |
|
1562 | prog_ns['__name__'] = '__main__' | |
1557 | else: |
|
1563 | else: | |
1558 | if opts.has_key('n'): |
|
1564 | if opts.has_key('n'): | |
1559 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1565 | name = os.path.splitext(os.path.basename(filename))[0] | |
1560 | else: |
|
1566 | else: | |
1561 | name = '__main__' |
|
1567 | name = '__main__' | |
1562 | prog_ns = {'__name__':name} |
|
1568 | prog_ns = {'__name__':name} | |
1563 |
|
1569 | |||
1564 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1570 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1565 | # set the __file__ global in the script's namespace |
|
1571 | # set the __file__ global in the script's namespace | |
1566 | prog_ns['__file__'] = filename |
|
1572 | prog_ns['__file__'] = filename | |
1567 |
|
1573 | |||
1568 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1574 | # pickle fix. See iplib for an explanation. But we need to make sure | |
1569 | # that, if we overwrite __main__, we replace it at the end |
|
1575 | # that, if we overwrite __main__, we replace it at the end | |
1570 | if prog_ns['__name__'] == '__main__': |
|
1576 | if prog_ns['__name__'] == '__main__': | |
1571 | restore_main = sys.modules['__main__'] |
|
1577 | restore_main = sys.modules['__main__'] | |
1572 | else: |
|
1578 | else: | |
1573 | restore_main = False |
|
1579 | restore_main = False | |
1574 |
|
1580 | |||
1575 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1581 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) | |
1576 |
|
1582 | |||
1577 | stats = None |
|
1583 | stats = None | |
1578 | try: |
|
1584 | try: | |
1579 | if self.shell.has_readline: |
|
1585 | if self.shell.has_readline: | |
1580 | self.shell.savehist() |
|
1586 | self.shell.savehist() | |
1581 |
|
1587 | |||
1582 | if opts.has_key('p'): |
|
1588 | if opts.has_key('p'): | |
1583 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1589 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1584 | else: |
|
1590 | else: | |
1585 | if opts.has_key('d'): |
|
1591 | if opts.has_key('d'): | |
1586 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1592 | deb = Debugger.Pdb(self.shell.rc.colors) | |
1587 | # reset Breakpoint state, which is moronically kept |
|
1593 | # reset Breakpoint state, which is moronically kept | |
1588 | # in a class |
|
1594 | # in a class | |
1589 | bdb.Breakpoint.next = 1 |
|
1595 | bdb.Breakpoint.next = 1 | |
1590 | bdb.Breakpoint.bplist = {} |
|
1596 | bdb.Breakpoint.bplist = {} | |
1591 | bdb.Breakpoint.bpbynumber = [None] |
|
1597 | bdb.Breakpoint.bpbynumber = [None] | |
1592 | # Set an initial breakpoint to stop execution |
|
1598 | # Set an initial breakpoint to stop execution | |
1593 | maxtries = 10 |
|
1599 | maxtries = 10 | |
1594 | bp = int(opts.get('b',[1])[0]) |
|
1600 | bp = int(opts.get('b',[1])[0]) | |
1595 | checkline = deb.checkline(filename,bp) |
|
1601 | checkline = deb.checkline(filename,bp) | |
1596 | if not checkline: |
|
1602 | if not checkline: | |
1597 | for bp in range(bp+1,bp+maxtries+1): |
|
1603 | for bp in range(bp+1,bp+maxtries+1): | |
1598 | if deb.checkline(filename,bp): |
|
1604 | if deb.checkline(filename,bp): | |
1599 | break |
|
1605 | break | |
1600 | else: |
|
1606 | else: | |
1601 | msg = ("\nI failed to find a valid line to set " |
|
1607 | msg = ("\nI failed to find a valid line to set " | |
1602 | "a breakpoint\n" |
|
1608 | "a breakpoint\n" | |
1603 | "after trying up to line: %s.\n" |
|
1609 | "after trying up to line: %s.\n" | |
1604 | "Please set a valid breakpoint manually " |
|
1610 | "Please set a valid breakpoint manually " | |
1605 | "with the -b option." % bp) |
|
1611 | "with the -b option." % bp) | |
1606 | error(msg) |
|
1612 | error(msg) | |
1607 | return |
|
1613 | return | |
1608 | # if we find a good linenumber, set the breakpoint |
|
1614 | # if we find a good linenumber, set the breakpoint | |
1609 | deb.do_break('%s:%s' % (filename,bp)) |
|
1615 | deb.do_break('%s:%s' % (filename,bp)) | |
1610 | # Start file run |
|
1616 | # Start file run | |
1611 | print "NOTE: Enter 'c' at the", |
|
1617 | print "NOTE: Enter 'c' at the", | |
1612 | print "%s prompt to start your script." % deb.prompt |
|
1618 | print "%s prompt to start your script." % deb.prompt | |
1613 | try: |
|
1619 | try: | |
1614 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1620 | deb.run('execfile("%s")' % filename,prog_ns) | |
1615 |
|
1621 | |||
1616 | except: |
|
1622 | except: | |
1617 | etype, value, tb = sys.exc_info() |
|
1623 | etype, value, tb = sys.exc_info() | |
1618 | # Skip three frames in the traceback: the %run one, |
|
1624 | # Skip three frames in the traceback: the %run one, | |
1619 | # one inside bdb.py, and the command-line typed by the |
|
1625 | # one inside bdb.py, and the command-line typed by the | |
1620 | # user (run by exec in pdb itself). |
|
1626 | # user (run by exec in pdb itself). | |
1621 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1627 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1622 | else: |
|
1628 | else: | |
1623 | if runner is None: |
|
1629 | if runner is None: | |
1624 | runner = self.shell.safe_execfile |
|
1630 | runner = self.shell.safe_execfile | |
1625 | if opts.has_key('t'): |
|
1631 | if opts.has_key('t'): | |
1626 | try: |
|
1632 | try: | |
1627 | nruns = int(opts['N'][0]) |
|
1633 | nruns = int(opts['N'][0]) | |
1628 | if nruns < 1: |
|
1634 | if nruns < 1: | |
1629 | error('Number of runs must be >=1') |
|
1635 | error('Number of runs must be >=1') | |
1630 | return |
|
1636 | return | |
1631 | except (KeyError): |
|
1637 | except (KeyError): | |
1632 | nruns = 1 |
|
1638 | nruns = 1 | |
1633 | if nruns == 1: |
|
1639 | if nruns == 1: | |
1634 | t0 = clock2() |
|
1640 | t0 = clock2() | |
1635 | runner(filename,prog_ns,prog_ns, |
|
1641 | runner(filename,prog_ns,prog_ns, | |
1636 | exit_ignore=exit_ignore) |
|
1642 | exit_ignore=exit_ignore) | |
1637 | t1 = clock2() |
|
1643 | t1 = clock2() | |
1638 | t_usr = t1[0]-t0[0] |
|
1644 | t_usr = t1[0]-t0[0] | |
1639 | t_sys = t1[1]-t1[1] |
|
1645 | t_sys = t1[1]-t1[1] | |
1640 | print "\nIPython CPU timings (estimated):" |
|
1646 | print "\nIPython CPU timings (estimated):" | |
1641 | print " User : %10s s." % t_usr |
|
1647 | print " User : %10s s." % t_usr | |
1642 | print " System: %10s s." % t_sys |
|
1648 | print " System: %10s s." % t_sys | |
1643 | else: |
|
1649 | else: | |
1644 | runs = range(nruns) |
|
1650 | runs = range(nruns) | |
1645 | t0 = clock2() |
|
1651 | t0 = clock2() | |
1646 | for nr in runs: |
|
1652 | for nr in runs: | |
1647 | runner(filename,prog_ns,prog_ns, |
|
1653 | runner(filename,prog_ns,prog_ns, | |
1648 | exit_ignore=exit_ignore) |
|
1654 | exit_ignore=exit_ignore) | |
1649 | t1 = clock2() |
|
1655 | t1 = clock2() | |
1650 | t_usr = t1[0]-t0[0] |
|
1656 | t_usr = t1[0]-t0[0] | |
1651 | t_sys = t1[1]-t1[1] |
|
1657 | t_sys = t1[1]-t1[1] | |
1652 | print "\nIPython CPU timings (estimated):" |
|
1658 | print "\nIPython CPU timings (estimated):" | |
1653 | print "Total runs performed:",nruns |
|
1659 | print "Total runs performed:",nruns | |
1654 | print " Times : %10s %10s" % ('Total','Per run') |
|
1660 | print " Times : %10s %10s" % ('Total','Per run') | |
1655 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1661 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1656 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1662 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1657 |
|
1663 | |||
1658 | else: |
|
1664 | else: | |
1659 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1665 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1660 | if opts.has_key('i'): |
|
1666 | if opts.has_key('i'): | |
1661 | self.shell.user_ns['__name__'] = __name__save |
|
1667 | self.shell.user_ns['__name__'] = __name__save | |
1662 | else: |
|
1668 | else: | |
1663 | # update IPython interactive namespace |
|
1669 | # update IPython interactive namespace | |
1664 | del prog_ns['__name__'] |
|
1670 | del prog_ns['__name__'] | |
1665 | self.shell.user_ns.update(prog_ns) |
|
1671 | self.shell.user_ns.update(prog_ns) | |
1666 | finally: |
|
1672 | finally: | |
1667 | sys.argv = save_argv |
|
1673 | sys.argv = save_argv | |
1668 | if restore_main: |
|
1674 | if restore_main: | |
1669 | sys.modules['__main__'] = restore_main |
|
1675 | sys.modules['__main__'] = restore_main | |
1670 | if self.shell.has_readline: |
|
1676 | if self.shell.has_readline: | |
1671 | self.shell.readline.read_history_file(self.shell.histfile) |
|
1677 | self.shell.readline.read_history_file(self.shell.histfile) | |
1672 |
|
1678 | |||
1673 | return stats |
|
1679 | return stats | |
1674 |
|
1680 | |||
1675 | def magic_runlog(self, parameter_s =''): |
|
1681 | def magic_runlog(self, parameter_s =''): | |
1676 | """Run files as logs. |
|
1682 | """Run files as logs. | |
1677 |
|
1683 | |||
1678 | Usage:\\ |
|
1684 | Usage:\\ | |
1679 | %runlog file1 file2 ... |
|
1685 | %runlog file1 file2 ... | |
1680 |
|
1686 | |||
1681 | Run the named files (treating them as log files) in sequence inside |
|
1687 | Run the named files (treating them as log files) in sequence inside | |
1682 | the interpreter, and return to the prompt. This is much slower than |
|
1688 | the interpreter, and return to the prompt. This is much slower than | |
1683 | %run because each line is executed in a try/except block, but it |
|
1689 | %run because each line is executed in a try/except block, but it | |
1684 | allows running files with syntax errors in them. |
|
1690 | allows running files with syntax errors in them. | |
1685 |
|
1691 | |||
1686 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1692 | Normally IPython will guess when a file is one of its own logfiles, so | |
1687 | you can typically use %run even for logs. This shorthand allows you to |
|
1693 | you can typically use %run even for logs. This shorthand allows you to | |
1688 | force any file to be treated as a log file.""" |
|
1694 | force any file to be treated as a log file.""" | |
1689 |
|
1695 | |||
1690 | for f in parameter_s.split(): |
|
1696 | for f in parameter_s.split(): | |
1691 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1697 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1692 | self.shell.user_ns,islog=1) |
|
1698 | self.shell.user_ns,islog=1) | |
1693 |
|
1699 | |||
1694 | def magic_timeit(self, parameter_s =''): |
|
1700 | def magic_timeit(self, parameter_s =''): | |
1695 | """Time execution of a Python statement or expression |
|
1701 | """Time execution of a Python statement or expression | |
1696 |
|
1702 | |||
1697 | Usage:\\ |
|
1703 | Usage:\\ | |
1698 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1704 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1699 |
|
1705 | |||
1700 | Time execution of a Python statement or expression using the timeit |
|
1706 | Time execution of a Python statement or expression using the timeit | |
1701 | module. |
|
1707 | module. | |
1702 |
|
1708 | |||
1703 | Options: |
|
1709 | Options: | |
1704 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1710 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1705 | is not given, a fitting value is chosen. |
|
1711 | is not given, a fitting value is chosen. | |
1706 |
|
1712 | |||
1707 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1713 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1708 | Default: 3 |
|
1714 | Default: 3 | |
1709 |
|
1715 | |||
1710 | -t: use time.time to measure the time, which is the default on Unix. |
|
1716 | -t: use time.time to measure the time, which is the default on Unix. | |
1711 | This function measures wall time. |
|
1717 | This function measures wall time. | |
1712 |
|
1718 | |||
1713 | -c: use time.clock to measure the time, which is the default on |
|
1719 | -c: use time.clock to measure the time, which is the default on | |
1714 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1720 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1715 | instead and returns the CPU user time. |
|
1721 | instead and returns the CPU user time. | |
1716 |
|
1722 | |||
1717 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1723 | -p<P>: use a precision of <P> digits to display the timing result. | |
1718 | Default: 3 |
|
1724 | Default: 3 | |
1719 |
|
1725 | |||
1720 |
|
1726 | |||
1721 | Examples:\\ |
|
1727 | Examples:\\ | |
1722 | In [1]: %timeit pass |
|
1728 | In [1]: %timeit pass | |
1723 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1729 | 10000000 loops, best of 3: 53.3 ns per loop | |
1724 |
|
1730 | |||
1725 | In [2]: u = None |
|
1731 | In [2]: u = None | |
1726 |
|
1732 | |||
1727 | In [3]: %timeit u is None |
|
1733 | In [3]: %timeit u is None | |
1728 | 10000000 loops, best of 3: 184 ns per loop |
|
1734 | 10000000 loops, best of 3: 184 ns per loop | |
1729 |
|
1735 | |||
1730 | In [4]: %timeit -r 4 u == None |
|
1736 | In [4]: %timeit -r 4 u == None | |
1731 | 1000000 loops, best of 4: 242 ns per loop |
|
1737 | 1000000 loops, best of 4: 242 ns per loop | |
1732 |
|
1738 | |||
1733 | In [5]: import time |
|
1739 | In [5]: import time | |
1734 |
|
1740 | |||
1735 | In [6]: %timeit -n1 time.sleep(2) |
|
1741 | In [6]: %timeit -n1 time.sleep(2) | |
1736 | 1 loops, best of 3: 2 s per loop |
|
1742 | 1 loops, best of 3: 2 s per loop | |
1737 |
|
1743 | |||
1738 |
|
1744 | |||
1739 | The times reported by %timeit will be slightly higher than those |
|
1745 | The times reported by %timeit will be slightly higher than those | |
1740 | reported by the timeit.py script when variables are accessed. This is |
|
1746 | reported by the timeit.py script when variables are accessed. This is | |
1741 | due to the fact that %timeit executes the statement in the namespace |
|
1747 | due to the fact that %timeit executes the statement in the namespace | |
1742 | of the shell, compared with timeit.py, which uses a single setup |
|
1748 | of the shell, compared with timeit.py, which uses a single setup | |
1743 | statement to import function or create variables. Generally, the bias |
|
1749 | statement to import function or create variables. Generally, the bias | |
1744 | does not matter as long as results from timeit.py are not mixed with |
|
1750 | does not matter as long as results from timeit.py are not mixed with | |
1745 | those from %timeit.""" |
|
1751 | those from %timeit.""" | |
1746 |
|
1752 | |||
1747 | import timeit |
|
1753 | import timeit | |
1748 | import math |
|
1754 | import math | |
1749 |
|
1755 | |||
1750 | units = ["s", "ms", "\xc2\xb5s", "ns"] |
|
1756 | units = ["s", "ms", "\xc2\xb5s", "ns"] | |
1751 | scaling = [1, 1e3, 1e6, 1e9] |
|
1757 | scaling = [1, 1e3, 1e6, 1e9] | |
1752 |
|
1758 | |||
1753 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1759 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1754 | posix=False) |
|
1760 | posix=False) | |
1755 | if stmt == "": |
|
1761 | if stmt == "": | |
1756 | return |
|
1762 | return | |
1757 | timefunc = timeit.default_timer |
|
1763 | timefunc = timeit.default_timer | |
1758 | number = int(getattr(opts, "n", 0)) |
|
1764 | number = int(getattr(opts, "n", 0)) | |
1759 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1765 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1760 | precision = int(getattr(opts, "p", 3)) |
|
1766 | precision = int(getattr(opts, "p", 3)) | |
1761 | if hasattr(opts, "t"): |
|
1767 | if hasattr(opts, "t"): | |
1762 | timefunc = time.time |
|
1768 | timefunc = time.time | |
1763 | if hasattr(opts, "c"): |
|
1769 | if hasattr(opts, "c"): | |
1764 | timefunc = clock |
|
1770 | timefunc = clock | |
1765 |
|
1771 | |||
1766 | timer = timeit.Timer(timer=timefunc) |
|
1772 | timer = timeit.Timer(timer=timefunc) | |
1767 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1773 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1768 | # but is there a better way to achieve that the code stmt has access |
|
1774 | # but is there a better way to achieve that the code stmt has access | |
1769 | # to the shell namespace? |
|
1775 | # to the shell namespace? | |
1770 |
|
1776 | |||
1771 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1777 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1772 | 'setup': "pass"} |
|
1778 | 'setup': "pass"} | |
1773 | code = compile(src, "<magic-timeit>", "exec") |
|
1779 | code = compile(src, "<magic-timeit>", "exec") | |
1774 | ns = {} |
|
1780 | ns = {} | |
1775 | exec code in self.shell.user_ns, ns |
|
1781 | exec code in self.shell.user_ns, ns | |
1776 | timer.inner = ns["inner"] |
|
1782 | timer.inner = ns["inner"] | |
1777 |
|
1783 | |||
1778 | if number == 0: |
|
1784 | if number == 0: | |
1779 | # determine number so that 0.2 <= total time < 2.0 |
|
1785 | # determine number so that 0.2 <= total time < 2.0 | |
1780 | number = 1 |
|
1786 | number = 1 | |
1781 | for i in range(1, 10): |
|
1787 | for i in range(1, 10): | |
1782 | number *= 10 |
|
1788 | number *= 10 | |
1783 | if timer.timeit(number) >= 0.2: |
|
1789 | if timer.timeit(number) >= 0.2: | |
1784 | break |
|
1790 | break | |
1785 |
|
1791 | |||
1786 | best = min(timer.repeat(repeat, number)) / number |
|
1792 | best = min(timer.repeat(repeat, number)) / number | |
1787 |
|
1793 | |||
1788 | if best > 0.0: |
|
1794 | if best > 0.0: | |
1789 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1795 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1790 | else: |
|
1796 | else: | |
1791 | order = 3 |
|
1797 | order = 3 | |
1792 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1798 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1793 | precision, |
|
1799 | precision, | |
1794 | best * scaling[order], |
|
1800 | best * scaling[order], | |
1795 | units[order]) |
|
1801 | units[order]) | |
1796 |
|
1802 | |||
1797 | def magic_time(self,parameter_s = ''): |
|
1803 | def magic_time(self,parameter_s = ''): | |
1798 | """Time execution of a Python statement or expression. |
|
1804 | """Time execution of a Python statement or expression. | |
1799 |
|
1805 | |||
1800 | The CPU and wall clock times are printed, and the value of the |
|
1806 | The CPU and wall clock times are printed, and the value of the | |
1801 | expression (if any) is returned. Note that under Win32, system time |
|
1807 | expression (if any) is returned. Note that under Win32, system time | |
1802 | is always reported as 0, since it can not be measured. |
|
1808 | is always reported as 0, since it can not be measured. | |
1803 |
|
1809 | |||
1804 | This function provides very basic timing functionality. In Python |
|
1810 | This function provides very basic timing functionality. In Python | |
1805 | 2.3, the timeit module offers more control and sophistication, so this |
|
1811 | 2.3, the timeit module offers more control and sophistication, so this | |
1806 | could be rewritten to use it (patches welcome). |
|
1812 | could be rewritten to use it (patches welcome). | |
1807 |
|
1813 | |||
1808 | Some examples: |
|
1814 | Some examples: | |
1809 |
|
1815 | |||
1810 | In [1]: time 2**128 |
|
1816 | In [1]: time 2**128 | |
1811 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1817 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1812 | Wall time: 0.00 |
|
1818 | Wall time: 0.00 | |
1813 | Out[1]: 340282366920938463463374607431768211456L |
|
1819 | Out[1]: 340282366920938463463374607431768211456L | |
1814 |
|
1820 | |||
1815 | In [2]: n = 1000000 |
|
1821 | In [2]: n = 1000000 | |
1816 |
|
1822 | |||
1817 | In [3]: time sum(range(n)) |
|
1823 | In [3]: time sum(range(n)) | |
1818 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1824 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1819 | Wall time: 1.37 |
|
1825 | Wall time: 1.37 | |
1820 | Out[3]: 499999500000L |
|
1826 | Out[3]: 499999500000L | |
1821 |
|
1827 | |||
1822 | In [4]: time print 'hello world' |
|
1828 | In [4]: time print 'hello world' | |
1823 | hello world |
|
1829 | hello world | |
1824 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1830 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1825 | Wall time: 0.00 |
|
1831 | Wall time: 0.00 | |
1826 | """ |
|
1832 | """ | |
1827 |
|
1833 | |||
1828 | # fail immediately if the given expression can't be compiled |
|
1834 | # fail immediately if the given expression can't be compiled | |
1829 | try: |
|
1835 | try: | |
1830 | mode = 'eval' |
|
1836 | mode = 'eval' | |
1831 | code = compile(parameter_s,'<timed eval>',mode) |
|
1837 | code = compile(parameter_s,'<timed eval>',mode) | |
1832 | except SyntaxError: |
|
1838 | except SyntaxError: | |
1833 | mode = 'exec' |
|
1839 | mode = 'exec' | |
1834 | code = compile(parameter_s,'<timed exec>',mode) |
|
1840 | code = compile(parameter_s,'<timed exec>',mode) | |
1835 | # skew measurement as little as possible |
|
1841 | # skew measurement as little as possible | |
1836 | glob = self.shell.user_ns |
|
1842 | glob = self.shell.user_ns | |
1837 | clk = clock2 |
|
1843 | clk = clock2 | |
1838 | wtime = time.time |
|
1844 | wtime = time.time | |
1839 | # time execution |
|
1845 | # time execution | |
1840 | wall_st = wtime() |
|
1846 | wall_st = wtime() | |
1841 | if mode=='eval': |
|
1847 | if mode=='eval': | |
1842 | st = clk() |
|
1848 | st = clk() | |
1843 | out = eval(code,glob) |
|
1849 | out = eval(code,glob) | |
1844 | end = clk() |
|
1850 | end = clk() | |
1845 | else: |
|
1851 | else: | |
1846 | st = clk() |
|
1852 | st = clk() | |
1847 | exec code in glob |
|
1853 | exec code in glob | |
1848 | end = clk() |
|
1854 | end = clk() | |
1849 | out = None |
|
1855 | out = None | |
1850 | wall_end = wtime() |
|
1856 | wall_end = wtime() | |
1851 | # Compute actual times and report |
|
1857 | # Compute actual times and report | |
1852 | wall_time = wall_end-wall_st |
|
1858 | wall_time = wall_end-wall_st | |
1853 | cpu_user = end[0]-st[0] |
|
1859 | cpu_user = end[0]-st[0] | |
1854 | cpu_sys = end[1]-st[1] |
|
1860 | cpu_sys = end[1]-st[1] | |
1855 | cpu_tot = cpu_user+cpu_sys |
|
1861 | cpu_tot = cpu_user+cpu_sys | |
1856 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1862 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1857 | (cpu_user,cpu_sys,cpu_tot) |
|
1863 | (cpu_user,cpu_sys,cpu_tot) | |
1858 | print "Wall time: %.2f" % wall_time |
|
1864 | print "Wall time: %.2f" % wall_time | |
1859 | return out |
|
1865 | return out | |
1860 |
|
1866 | |||
1861 | def magic_macro(self,parameter_s = ''): |
|
1867 | def magic_macro(self,parameter_s = ''): | |
1862 | """Define a set of input lines as a macro for future re-execution. |
|
1868 | """Define a set of input lines as a macro for future re-execution. | |
1863 |
|
1869 | |||
1864 | Usage:\\ |
|
1870 | Usage:\\ | |
1865 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1871 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1866 |
|
1872 | |||
1867 | Options: |
|
1873 | Options: | |
1868 |
|
1874 | |||
1869 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1875 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1870 | so that magics are loaded in their transformed version to valid |
|
1876 | so that magics are loaded in their transformed version to valid | |
1871 | Python. If this option is given, the raw input as typed as the |
|
1877 | Python. If this option is given, the raw input as typed as the | |
1872 | command line is used instead. |
|
1878 | command line is used instead. | |
1873 |
|
1879 | |||
1874 | This will define a global variable called `name` which is a string |
|
1880 | This will define a global variable called `name` which is a string | |
1875 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1881 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1876 | above) from your input history into a single string. This variable |
|
1882 | above) from your input history into a single string. This variable | |
1877 | acts like an automatic function which re-executes those lines as if |
|
1883 | acts like an automatic function which re-executes those lines as if | |
1878 | you had typed them. You just type 'name' at the prompt and the code |
|
1884 | you had typed them. You just type 'name' at the prompt and the code | |
1879 | executes. |
|
1885 | executes. | |
1880 |
|
1886 | |||
1881 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1887 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1882 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1888 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1883 | using the lines numbered 5,6 and 7. |
|
1889 | using the lines numbered 5,6 and 7. | |
1884 |
|
1890 | |||
1885 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1891 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1886 | notation, where N:M means numbers N through M-1. |
|
1892 | notation, where N:M means numbers N through M-1. | |
1887 |
|
1893 | |||
1888 | For example, if your history contains (%hist prints it): |
|
1894 | For example, if your history contains (%hist prints it): | |
1889 |
|
1895 | |||
1890 | 44: x=1\\ |
|
1896 | 44: x=1\\ | |
1891 | 45: y=3\\ |
|
1897 | 45: y=3\\ | |
1892 | 46: z=x+y\\ |
|
1898 | 46: z=x+y\\ | |
1893 | 47: print x\\ |
|
1899 | 47: print x\\ | |
1894 | 48: a=5\\ |
|
1900 | 48: a=5\\ | |
1895 | 49: print 'x',x,'y',y\\ |
|
1901 | 49: print 'x',x,'y',y\\ | |
1896 |
|
1902 | |||
1897 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1903 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1898 | called my_macro with: |
|
1904 | called my_macro with: | |
1899 |
|
1905 | |||
1900 | In [51]: %macro my_macro 44-47 49 |
|
1906 | In [51]: %macro my_macro 44-47 49 | |
1901 |
|
1907 | |||
1902 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1908 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1903 | in one pass. |
|
1909 | in one pass. | |
1904 |
|
1910 | |||
1905 | You don't need to give the line-numbers in order, and any given line |
|
1911 | You don't need to give the line-numbers in order, and any given line | |
1906 | number can appear multiple times. You can assemble macros with any |
|
1912 | number can appear multiple times. You can assemble macros with any | |
1907 | lines from your input history in any order. |
|
1913 | lines from your input history in any order. | |
1908 |
|
1914 | |||
1909 | The macro is a simple object which holds its value in an attribute, |
|
1915 | The macro is a simple object which holds its value in an attribute, | |
1910 | but IPython's display system checks for macros and executes them as |
|
1916 | but IPython's display system checks for macros and executes them as | |
1911 | code instead of printing them when you type their name. |
|
1917 | code instead of printing them when you type their name. | |
1912 |
|
1918 | |||
1913 | You can view a macro's contents by explicitly printing it with: |
|
1919 | You can view a macro's contents by explicitly printing it with: | |
1914 |
|
1920 | |||
1915 | 'print macro_name'. |
|
1921 | 'print macro_name'. | |
1916 |
|
1922 | |||
1917 | For one-off cases which DON'T contain magic function calls in them you |
|
1923 | For one-off cases which DON'T contain magic function calls in them you | |
1918 | can obtain similar results by explicitly executing slices from your |
|
1924 | can obtain similar results by explicitly executing slices from your | |
1919 | input history with: |
|
1925 | input history with: | |
1920 |
|
1926 | |||
1921 | In [60]: exec In[44:48]+In[49]""" |
|
1927 | In [60]: exec In[44:48]+In[49]""" | |
1922 |
|
1928 | |||
1923 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1929 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1924 | name,ranges = args[0], args[1:] |
|
1930 | name,ranges = args[0], args[1:] | |
1925 | #print 'rng',ranges # dbg |
|
1931 | #print 'rng',ranges # dbg | |
1926 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1932 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1927 | macro = Macro(lines) |
|
1933 | macro = Macro(lines) | |
1928 | self.shell.user_ns.update({name:macro}) |
|
1934 | self.shell.user_ns.update({name:macro}) | |
1929 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1935 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1930 | print 'Macro contents:' |
|
1936 | print 'Macro contents:' | |
1931 | print macro, |
|
1937 | print macro, | |
1932 |
|
1938 | |||
1933 | def magic_save(self,parameter_s = ''): |
|
1939 | def magic_save(self,parameter_s = ''): | |
1934 | """Save a set of lines to a given filename. |
|
1940 | """Save a set of lines to a given filename. | |
1935 |
|
1941 | |||
1936 | Usage:\\ |
|
1942 | Usage:\\ | |
1937 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1943 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1938 |
|
1944 | |||
1939 | Options: |
|
1945 | Options: | |
1940 |
|
1946 | |||
1941 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1947 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1942 | so that magics are loaded in their transformed version to valid |
|
1948 | so that magics are loaded in their transformed version to valid | |
1943 | Python. If this option is given, the raw input as typed as the |
|
1949 | Python. If this option is given, the raw input as typed as the | |
1944 | command line is used instead. |
|
1950 | command line is used instead. | |
1945 |
|
1951 | |||
1946 | This function uses the same syntax as %macro for line extraction, but |
|
1952 | This function uses the same syntax as %macro for line extraction, but | |
1947 | instead of creating a macro it saves the resulting string to the |
|
1953 | instead of creating a macro it saves the resulting string to the | |
1948 | filename you specify. |
|
1954 | filename you specify. | |
1949 |
|
1955 | |||
1950 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1956 | It adds a '.py' extension to the file if you don't do so yourself, and | |
1951 | it asks for confirmation before overwriting existing files.""" |
|
1957 | it asks for confirmation before overwriting existing files.""" | |
1952 |
|
1958 | |||
1953 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1959 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1954 | fname,ranges = args[0], args[1:] |
|
1960 | fname,ranges = args[0], args[1:] | |
1955 | if not fname.endswith('.py'): |
|
1961 | if not fname.endswith('.py'): | |
1956 | fname += '.py' |
|
1962 | fname += '.py' | |
1957 | if os.path.isfile(fname): |
|
1963 | if os.path.isfile(fname): | |
1958 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1964 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
1959 | if ans.lower() not in ['y','yes']: |
|
1965 | if ans.lower() not in ['y','yes']: | |
1960 | print 'Operation cancelled.' |
|
1966 | print 'Operation cancelled.' | |
1961 | return |
|
1967 | return | |
1962 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
1968 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
1963 | f = file(fname,'w') |
|
1969 | f = file(fname,'w') | |
1964 | f.write(cmds) |
|
1970 | f.write(cmds) | |
1965 | f.close() |
|
1971 | f.close() | |
1966 | print 'The following commands were written to file `%s`:' % fname |
|
1972 | print 'The following commands were written to file `%s`:' % fname | |
1967 | print cmds |
|
1973 | print cmds | |
1968 |
|
1974 | |||
1969 | def _edit_macro(self,mname,macro): |
|
1975 | def _edit_macro(self,mname,macro): | |
1970 | """open an editor with the macro data in a file""" |
|
1976 | """open an editor with the macro data in a file""" | |
1971 | filename = self.shell.mktempfile(macro.value) |
|
1977 | filename = self.shell.mktempfile(macro.value) | |
1972 | self.shell.hooks.editor(filename) |
|
1978 | self.shell.hooks.editor(filename) | |
1973 |
|
1979 | |||
1974 | # and make a new macro object, to replace the old one |
|
1980 | # and make a new macro object, to replace the old one | |
1975 | mfile = open(filename) |
|
1981 | mfile = open(filename) | |
1976 | mvalue = mfile.read() |
|
1982 | mvalue = mfile.read() | |
1977 | mfile.close() |
|
1983 | mfile.close() | |
1978 | self.shell.user_ns[mname] = Macro(mvalue) |
|
1984 | self.shell.user_ns[mname] = Macro(mvalue) | |
1979 |
|
1985 | |||
1980 | def magic_ed(self,parameter_s=''): |
|
1986 | def magic_ed(self,parameter_s=''): | |
1981 | """Alias to %edit.""" |
|
1987 | """Alias to %edit.""" | |
1982 | return self.magic_edit(parameter_s) |
|
1988 | return self.magic_edit(parameter_s) | |
1983 |
|
1989 | |||
1984 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
1990 | def magic_edit(self,parameter_s='',last_call=['','']): | |
1985 | """Bring up an editor and execute the resulting code. |
|
1991 | """Bring up an editor and execute the resulting code. | |
1986 |
|
1992 | |||
1987 | Usage: |
|
1993 | Usage: | |
1988 | %edit [options] [args] |
|
1994 | %edit [options] [args] | |
1989 |
|
1995 | |||
1990 | %edit runs IPython's editor hook. The default version of this hook is |
|
1996 | %edit runs IPython's editor hook. The default version of this hook is | |
1991 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1997 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
1992 | environment variable $EDITOR. If this isn't found, it will default to |
|
1998 | environment variable $EDITOR. If this isn't found, it will default to | |
1993 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1999 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
1994 | docstring for how to change the editor hook. |
|
2000 | docstring for how to change the editor hook. | |
1995 |
|
2001 | |||
1996 | You can also set the value of this editor via the command line option |
|
2002 | You can also set the value of this editor via the command line option | |
1997 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2003 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
1998 | specifically for IPython an editor different from your typical default |
|
2004 | specifically for IPython an editor different from your typical default | |
1999 | (and for Windows users who typically don't set environment variables). |
|
2005 | (and for Windows users who typically don't set environment variables). | |
2000 |
|
2006 | |||
2001 | This command allows you to conveniently edit multi-line code right in |
|
2007 | This command allows you to conveniently edit multi-line code right in | |
2002 | your IPython session. |
|
2008 | your IPython session. | |
2003 |
|
2009 | |||
2004 | If called without arguments, %edit opens up an empty editor with a |
|
2010 | If called without arguments, %edit opens up an empty editor with a | |
2005 | temporary file and will execute the contents of this file when you |
|
2011 | temporary file and will execute the contents of this file when you | |
2006 | close it (don't forget to save it!). |
|
2012 | close it (don't forget to save it!). | |
2007 |
|
2013 | |||
2008 |
|
2014 | |||
2009 | Options: |
|
2015 | Options: | |
2010 |
|
2016 | |||
2011 | -n <number>: open the editor at a specified line number. By default, |
|
2017 | -n <number>: open the editor at a specified line number. By default, | |
2012 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2018 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2013 | you can configure this by providing your own modified hook if your |
|
2019 | you can configure this by providing your own modified hook if your | |
2014 | favorite editor supports line-number specifications with a different |
|
2020 | favorite editor supports line-number specifications with a different | |
2015 | syntax. |
|
2021 | syntax. | |
2016 |
|
2022 | |||
2017 | -p: this will call the editor with the same data as the previous time |
|
2023 | -p: this will call the editor with the same data as the previous time | |
2018 | it was used, regardless of how long ago (in your current session) it |
|
2024 | it was used, regardless of how long ago (in your current session) it | |
2019 | was. |
|
2025 | was. | |
2020 |
|
2026 | |||
2021 | -r: use 'raw' input. This option only applies to input taken from the |
|
2027 | -r: use 'raw' input. This option only applies to input taken from the | |
2022 | user's history. By default, the 'processed' history is used, so that |
|
2028 | user's history. By default, the 'processed' history is used, so that | |
2023 | magics are loaded in their transformed version to valid Python. If |
|
2029 | magics are loaded in their transformed version to valid Python. If | |
2024 | this option is given, the raw input as typed as the command line is |
|
2030 | this option is given, the raw input as typed as the command line is | |
2025 | used instead. When you exit the editor, it will be executed by |
|
2031 | used instead. When you exit the editor, it will be executed by | |
2026 | IPython's own processor. |
|
2032 | IPython's own processor. | |
2027 |
|
2033 | |||
2028 | -x: do not execute the edited code immediately upon exit. This is |
|
2034 | -x: do not execute the edited code immediately upon exit. This is | |
2029 | mainly useful if you are editing programs which need to be called with |
|
2035 | mainly useful if you are editing programs which need to be called with | |
2030 | command line arguments, which you can then do using %run. |
|
2036 | command line arguments, which you can then do using %run. | |
2031 |
|
2037 | |||
2032 |
|
2038 | |||
2033 | Arguments: |
|
2039 | Arguments: | |
2034 |
|
2040 | |||
2035 | If arguments are given, the following possibilites exist: |
|
2041 | If arguments are given, the following possibilites exist: | |
2036 |
|
2042 | |||
2037 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2043 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2038 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2044 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2039 | loaded into the editor. The syntax is the same of the %macro command. |
|
2045 | loaded into the editor. The syntax is the same of the %macro command. | |
2040 |
|
2046 | |||
2041 | - If the argument doesn't start with a number, it is evaluated as a |
|
2047 | - If the argument doesn't start with a number, it is evaluated as a | |
2042 | variable and its contents loaded into the editor. You can thus edit |
|
2048 | variable and its contents loaded into the editor. You can thus edit | |
2043 | any string which contains python code (including the result of |
|
2049 | any string which contains python code (including the result of | |
2044 | previous edits). |
|
2050 | previous edits). | |
2045 |
|
2051 | |||
2046 | - If the argument is the name of an object (other than a string), |
|
2052 | - If the argument is the name of an object (other than a string), | |
2047 | IPython will try to locate the file where it was defined and open the |
|
2053 | IPython will try to locate the file where it was defined and open the | |
2048 | editor at the point where it is defined. You can use `%edit function` |
|
2054 | editor at the point where it is defined. You can use `%edit function` | |
2049 | to load an editor exactly at the point where 'function' is defined, |
|
2055 | to load an editor exactly at the point where 'function' is defined, | |
2050 | edit it and have the file be executed automatically. |
|
2056 | edit it and have the file be executed automatically. | |
2051 |
|
2057 | |||
2052 | If the object is a macro (see %macro for details), this opens up your |
|
2058 | If the object is a macro (see %macro for details), this opens up your | |
2053 | specified editor with a temporary file containing the macro's data. |
|
2059 | specified editor with a temporary file containing the macro's data. | |
2054 | Upon exit, the macro is reloaded with the contents of the file. |
|
2060 | Upon exit, the macro is reloaded with the contents of the file. | |
2055 |
|
2061 | |||
2056 | Note: opening at an exact line is only supported under Unix, and some |
|
2062 | Note: opening at an exact line is only supported under Unix, and some | |
2057 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2063 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2058 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2064 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2059 | (X)Emacs, vi, jed, pico and joe all do. |
|
2065 | (X)Emacs, vi, jed, pico and joe all do. | |
2060 |
|
2066 | |||
2061 | - If the argument is not found as a variable, IPython will look for a |
|
2067 | - If the argument is not found as a variable, IPython will look for a | |
2062 | file with that name (adding .py if necessary) and load it into the |
|
2068 | file with that name (adding .py if necessary) and load it into the | |
2063 | editor. It will execute its contents with execfile() when you exit, |
|
2069 | editor. It will execute its contents with execfile() when you exit, | |
2064 | loading any code in the file into your interactive namespace. |
|
2070 | loading any code in the file into your interactive namespace. | |
2065 |
|
2071 | |||
2066 | After executing your code, %edit will return as output the code you |
|
2072 | After executing your code, %edit will return as output the code you | |
2067 | typed in the editor (except when it was an existing file). This way |
|
2073 | typed in the editor (except when it was an existing file). This way | |
2068 | you can reload the code in further invocations of %edit as a variable, |
|
2074 | you can reload the code in further invocations of %edit as a variable, | |
2069 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2075 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2070 | the output. |
|
2076 | the output. | |
2071 |
|
2077 | |||
2072 | Note that %edit is also available through the alias %ed. |
|
2078 | Note that %edit is also available through the alias %ed. | |
2073 |
|
2079 | |||
2074 | This is an example of creating a simple function inside the editor and |
|
2080 | This is an example of creating a simple function inside the editor and | |
2075 | then modifying it. First, start up the editor: |
|
2081 | then modifying it. First, start up the editor: | |
2076 |
|
2082 | |||
2077 | In [1]: ed\\ |
|
2083 | In [1]: ed\\ | |
2078 | Editing... done. Executing edited code...\\ |
|
2084 | Editing... done. Executing edited code...\\ | |
2079 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
2085 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' | |
2080 |
|
2086 | |||
2081 | We can then call the function foo(): |
|
2087 | We can then call the function foo(): | |
2082 |
|
2088 | |||
2083 | In [2]: foo()\\ |
|
2089 | In [2]: foo()\\ | |
2084 | foo() was defined in an editing session |
|
2090 | foo() was defined in an editing session | |
2085 |
|
2091 | |||
2086 | Now we edit foo. IPython automatically loads the editor with the |
|
2092 | Now we edit foo. IPython automatically loads the editor with the | |
2087 | (temporary) file where foo() was previously defined: |
|
2093 | (temporary) file where foo() was previously defined: | |
2088 |
|
2094 | |||
2089 | In [3]: ed foo\\ |
|
2095 | In [3]: ed foo\\ | |
2090 | Editing... done. Executing edited code... |
|
2096 | Editing... done. Executing edited code... | |
2091 |
|
2097 | |||
2092 | And if we call foo() again we get the modified version: |
|
2098 | And if we call foo() again we get the modified version: | |
2093 |
|
2099 | |||
2094 | In [4]: foo()\\ |
|
2100 | In [4]: foo()\\ | |
2095 | foo() has now been changed! |
|
2101 | foo() has now been changed! | |
2096 |
|
2102 | |||
2097 | Here is an example of how to edit a code snippet successive |
|
2103 | Here is an example of how to edit a code snippet successive | |
2098 | times. First we call the editor: |
|
2104 | times. First we call the editor: | |
2099 |
|
2105 | |||
2100 | In [8]: ed\\ |
|
2106 | In [8]: ed\\ | |
2101 | Editing... done. Executing edited code...\\ |
|
2107 | Editing... done. Executing edited code...\\ | |
2102 | hello\\ |
|
2108 | hello\\ | |
2103 | Out[8]: "print 'hello'\\n" |
|
2109 | Out[8]: "print 'hello'\\n" | |
2104 |
|
2110 | |||
2105 | Now we call it again with the previous output (stored in _): |
|
2111 | Now we call it again with the previous output (stored in _): | |
2106 |
|
2112 | |||
2107 | In [9]: ed _\\ |
|
2113 | In [9]: ed _\\ | |
2108 | Editing... done. Executing edited code...\\ |
|
2114 | Editing... done. Executing edited code...\\ | |
2109 | hello world\\ |
|
2115 | hello world\\ | |
2110 | Out[9]: "print 'hello world'\\n" |
|
2116 | Out[9]: "print 'hello world'\\n" | |
2111 |
|
2117 | |||
2112 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2118 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2113 |
|
2119 | |||
2114 | In [10]: ed _8\\ |
|
2120 | In [10]: ed _8\\ | |
2115 | Editing... done. Executing edited code...\\ |
|
2121 | Editing... done. Executing edited code...\\ | |
2116 | hello again\\ |
|
2122 | hello again\\ | |
2117 | Out[10]: "print 'hello again'\\n" |
|
2123 | Out[10]: "print 'hello again'\\n" | |
2118 |
|
2124 | |||
2119 |
|
2125 | |||
2120 | Changing the default editor hook: |
|
2126 | Changing the default editor hook: | |
2121 |
|
2127 | |||
2122 | If you wish to write your own editor hook, you can put it in a |
|
2128 | If you wish to write your own editor hook, you can put it in a | |
2123 | configuration file which you load at startup time. The default hook |
|
2129 | configuration file which you load at startup time. The default hook | |
2124 | is defined in the IPython.hooks module, and you can use that as a |
|
2130 | is defined in the IPython.hooks module, and you can use that as a | |
2125 | starting example for further modifications. That file also has |
|
2131 | starting example for further modifications. That file also has | |
2126 | general instructions on how to set a new hook for use once you've |
|
2132 | general instructions on how to set a new hook for use once you've | |
2127 | defined it.""" |
|
2133 | defined it.""" | |
2128 |
|
2134 | |||
2129 | # FIXME: This function has become a convoluted mess. It needs a |
|
2135 | # FIXME: This function has become a convoluted mess. It needs a | |
2130 | # ground-up rewrite with clean, simple logic. |
|
2136 | # ground-up rewrite with clean, simple logic. | |
2131 |
|
2137 | |||
2132 | def make_filename(arg): |
|
2138 | def make_filename(arg): | |
2133 | "Make a filename from the given args" |
|
2139 | "Make a filename from the given args" | |
2134 | try: |
|
2140 | try: | |
2135 | filename = get_py_filename(arg) |
|
2141 | filename = get_py_filename(arg) | |
2136 | except IOError: |
|
2142 | except IOError: | |
2137 | if args.endswith('.py'): |
|
2143 | if args.endswith('.py'): | |
2138 | filename = arg |
|
2144 | filename = arg | |
2139 | else: |
|
2145 | else: | |
2140 | filename = None |
|
2146 | filename = None | |
2141 | return filename |
|
2147 | return filename | |
2142 |
|
2148 | |||
2143 | # custom exceptions |
|
2149 | # custom exceptions | |
2144 | class DataIsObject(Exception): pass |
|
2150 | class DataIsObject(Exception): pass | |
2145 |
|
2151 | |||
2146 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2152 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2147 | # Set a few locals from the options for convenience: |
|
2153 | # Set a few locals from the options for convenience: | |
2148 | opts_p = opts.has_key('p') |
|
2154 | opts_p = opts.has_key('p') | |
2149 | opts_r = opts.has_key('r') |
|
2155 | opts_r = opts.has_key('r') | |
2150 |
|
2156 | |||
2151 | # Default line number value |
|
2157 | # Default line number value | |
2152 | lineno = opts.get('n',None) |
|
2158 | lineno = opts.get('n',None) | |
2153 |
|
2159 | |||
2154 | if opts_p: |
|
2160 | if opts_p: | |
2155 | args = '_%s' % last_call[0] |
|
2161 | args = '_%s' % last_call[0] | |
2156 | if not self.shell.user_ns.has_key(args): |
|
2162 | if not self.shell.user_ns.has_key(args): | |
2157 | args = last_call[1] |
|
2163 | args = last_call[1] | |
2158 |
|
2164 | |||
2159 | # use last_call to remember the state of the previous call, but don't |
|
2165 | # use last_call to remember the state of the previous call, but don't | |
2160 | # let it be clobbered by successive '-p' calls. |
|
2166 | # let it be clobbered by successive '-p' calls. | |
2161 | try: |
|
2167 | try: | |
2162 | last_call[0] = self.shell.outputcache.prompt_count |
|
2168 | last_call[0] = self.shell.outputcache.prompt_count | |
2163 | if not opts_p: |
|
2169 | if not opts_p: | |
2164 | last_call[1] = parameter_s |
|
2170 | last_call[1] = parameter_s | |
2165 | except: |
|
2171 | except: | |
2166 | pass |
|
2172 | pass | |
2167 |
|
2173 | |||
2168 | # by default this is done with temp files, except when the given |
|
2174 | # by default this is done with temp files, except when the given | |
2169 | # arg is a filename |
|
2175 | # arg is a filename | |
2170 | use_temp = 1 |
|
2176 | use_temp = 1 | |
2171 |
|
2177 | |||
2172 | if re.match(r'\d',args): |
|
2178 | if re.match(r'\d',args): | |
2173 | # Mode where user specifies ranges of lines, like in %macro. |
|
2179 | # Mode where user specifies ranges of lines, like in %macro. | |
2174 | # This means that you can't edit files whose names begin with |
|
2180 | # This means that you can't edit files whose names begin with | |
2175 | # numbers this way. Tough. |
|
2181 | # numbers this way. Tough. | |
2176 | ranges = args.split() |
|
2182 | ranges = args.split() | |
2177 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2183 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2178 | elif args.endswith('.py'): |
|
2184 | elif args.endswith('.py'): | |
2179 | filename = make_filename(args) |
|
2185 | filename = make_filename(args) | |
2180 | data = '' |
|
2186 | data = '' | |
2181 | use_temp = 0 |
|
2187 | use_temp = 0 | |
2182 | elif args: |
|
2188 | elif args: | |
2183 | try: |
|
2189 | try: | |
2184 | # Load the parameter given as a variable. If not a string, |
|
2190 | # Load the parameter given as a variable. If not a string, | |
2185 | # process it as an object instead (below) |
|
2191 | # process it as an object instead (below) | |
2186 |
|
2192 | |||
2187 | #print '*** args',args,'type',type(args) # dbg |
|
2193 | #print '*** args',args,'type',type(args) # dbg | |
2188 | data = eval(args,self.shell.user_ns) |
|
2194 | data = eval(args,self.shell.user_ns) | |
2189 | if not type(data) in StringTypes: |
|
2195 | if not type(data) in StringTypes: | |
2190 | raise DataIsObject |
|
2196 | raise DataIsObject | |
2191 |
|
2197 | |||
2192 | except (NameError,SyntaxError): |
|
2198 | except (NameError,SyntaxError): | |
2193 | # given argument is not a variable, try as a filename |
|
2199 | # given argument is not a variable, try as a filename | |
2194 | filename = make_filename(args) |
|
2200 | filename = make_filename(args) | |
2195 | if filename is None: |
|
2201 | if filename is None: | |
2196 | warn("Argument given (%s) can't be found as a variable " |
|
2202 | warn("Argument given (%s) can't be found as a variable " | |
2197 | "or as a filename." % args) |
|
2203 | "or as a filename." % args) | |
2198 | return |
|
2204 | return | |
2199 |
|
2205 | |||
2200 | data = '' |
|
2206 | data = '' | |
2201 | use_temp = 0 |
|
2207 | use_temp = 0 | |
2202 | except DataIsObject: |
|
2208 | except DataIsObject: | |
2203 |
|
2209 | |||
2204 | # macros have a special edit function |
|
2210 | # macros have a special edit function | |
2205 | if isinstance(data,Macro): |
|
2211 | if isinstance(data,Macro): | |
2206 | self._edit_macro(args,data) |
|
2212 | self._edit_macro(args,data) | |
2207 | return |
|
2213 | return | |
2208 |
|
2214 | |||
2209 | # For objects, try to edit the file where they are defined |
|
2215 | # For objects, try to edit the file where they are defined | |
2210 | try: |
|
2216 | try: | |
2211 | filename = inspect.getabsfile(data) |
|
2217 | filename = inspect.getabsfile(data) | |
2212 | datafile = 1 |
|
2218 | datafile = 1 | |
2213 | except TypeError: |
|
2219 | except TypeError: | |
2214 | filename = make_filename(args) |
|
2220 | filename = make_filename(args) | |
2215 | datafile = 1 |
|
2221 | datafile = 1 | |
2216 | warn('Could not find file where `%s` is defined.\n' |
|
2222 | warn('Could not find file where `%s` is defined.\n' | |
2217 | 'Opening a file named `%s`' % (args,filename)) |
|
2223 | 'Opening a file named `%s`' % (args,filename)) | |
2218 | # Now, make sure we can actually read the source (if it was in |
|
2224 | # Now, make sure we can actually read the source (if it was in | |
2219 | # a temp file it's gone by now). |
|
2225 | # a temp file it's gone by now). | |
2220 | if datafile: |
|
2226 | if datafile: | |
2221 | try: |
|
2227 | try: | |
2222 | if lineno is None: |
|
2228 | if lineno is None: | |
2223 | lineno = inspect.getsourcelines(data)[1] |
|
2229 | lineno = inspect.getsourcelines(data)[1] | |
2224 | except IOError: |
|
2230 | except IOError: | |
2225 | filename = make_filename(args) |
|
2231 | filename = make_filename(args) | |
2226 | if filename is None: |
|
2232 | if filename is None: | |
2227 | warn('The file `%s` where `%s` was defined cannot ' |
|
2233 | warn('The file `%s` where `%s` was defined cannot ' | |
2228 | 'be read.' % (filename,data)) |
|
2234 | 'be read.' % (filename,data)) | |
2229 | return |
|
2235 | return | |
2230 | use_temp = 0 |
|
2236 | use_temp = 0 | |
2231 | else: |
|
2237 | else: | |
2232 | data = '' |
|
2238 | data = '' | |
2233 |
|
2239 | |||
2234 | if use_temp: |
|
2240 | if use_temp: | |
2235 | filename = self.shell.mktempfile(data) |
|
2241 | filename = self.shell.mktempfile(data) | |
2236 | print 'IPython will make a temporary file named:',filename |
|
2242 | print 'IPython will make a temporary file named:',filename | |
2237 |
|
2243 | |||
2238 | # do actual editing here |
|
2244 | # do actual editing here | |
2239 | print 'Editing...', |
|
2245 | print 'Editing...', | |
2240 | sys.stdout.flush() |
|
2246 | sys.stdout.flush() | |
2241 | self.shell.hooks.editor(filename,lineno) |
|
2247 | self.shell.hooks.editor(filename,lineno) | |
2242 | if opts.has_key('x'): # -x prevents actual execution |
|
2248 | if opts.has_key('x'): # -x prevents actual execution | |
2243 |
|
2249 | |||
2244 | else: |
|
2250 | else: | |
2245 | print 'done. Executing edited code...' |
|
2251 | print 'done. Executing edited code...' | |
2246 | if opts_r: |
|
2252 | if opts_r: | |
2247 | self.shell.runlines(file_read(filename)) |
|
2253 | self.shell.runlines(file_read(filename)) | |
2248 | else: |
|
2254 | else: | |
2249 | self.shell.safe_execfile(filename,self.shell.user_ns) |
|
2255 | self.shell.safe_execfile(filename,self.shell.user_ns) | |
2250 | if use_temp: |
|
2256 | if use_temp: | |
2251 | try: |
|
2257 | try: | |
2252 | return open(filename).read() |
|
2258 | return open(filename).read() | |
2253 | except IOError,msg: |
|
2259 | except IOError,msg: | |
2254 | if msg.filename == filename: |
|
2260 | if msg.filename == filename: | |
2255 | warn('File not found. Did you forget to save?') |
|
2261 | warn('File not found. Did you forget to save?') | |
2256 | return |
|
2262 | return | |
2257 | else: |
|
2263 | else: | |
2258 | self.shell.showtraceback() |
|
2264 | self.shell.showtraceback() | |
2259 |
|
2265 | |||
2260 | def magic_xmode(self,parameter_s = ''): |
|
2266 | def magic_xmode(self,parameter_s = ''): | |
2261 | """Switch modes for the exception handlers. |
|
2267 | """Switch modes for the exception handlers. | |
2262 |
|
2268 | |||
2263 | Valid modes: Plain, Context and Verbose. |
|
2269 | Valid modes: Plain, Context and Verbose. | |
2264 |
|
2270 | |||
2265 | If called without arguments, acts as a toggle.""" |
|
2271 | If called without arguments, acts as a toggle.""" | |
2266 |
|
2272 | |||
2267 | def xmode_switch_err(name): |
|
2273 | def xmode_switch_err(name): | |
2268 | warn('Error changing %s exception modes.\n%s' % |
|
2274 | warn('Error changing %s exception modes.\n%s' % | |
2269 | (name,sys.exc_info()[1])) |
|
2275 | (name,sys.exc_info()[1])) | |
2270 |
|
2276 | |||
2271 | shell = self.shell |
|
2277 | shell = self.shell | |
2272 | new_mode = parameter_s.strip().capitalize() |
|
2278 | new_mode = parameter_s.strip().capitalize() | |
2273 | try: |
|
2279 | try: | |
2274 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2280 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2275 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2281 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2276 | except: |
|
2282 | except: | |
2277 | xmode_switch_err('user') |
|
2283 | xmode_switch_err('user') | |
2278 |
|
2284 | |||
2279 | # threaded shells use a special handler in sys.excepthook |
|
2285 | # threaded shells use a special handler in sys.excepthook | |
2280 | if shell.isthreaded: |
|
2286 | if shell.isthreaded: | |
2281 | try: |
|
2287 | try: | |
2282 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2288 | shell.sys_excepthook.set_mode(mode=new_mode) | |
2283 | except: |
|
2289 | except: | |
2284 | xmode_switch_err('threaded') |
|
2290 | xmode_switch_err('threaded') | |
2285 |
|
2291 | |||
2286 | def magic_colors(self,parameter_s = ''): |
|
2292 | def magic_colors(self,parameter_s = ''): | |
2287 | """Switch color scheme for prompts, info system and exception handlers. |
|
2293 | """Switch color scheme for prompts, info system and exception handlers. | |
2288 |
|
2294 | |||
2289 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2295 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2290 |
|
2296 | |||
2291 | Color scheme names are not case-sensitive.""" |
|
2297 | Color scheme names are not case-sensitive.""" | |
2292 |
|
2298 | |||
2293 | def color_switch_err(name): |
|
2299 | def color_switch_err(name): | |
2294 | warn('Error changing %s color schemes.\n%s' % |
|
2300 | warn('Error changing %s color schemes.\n%s' % | |
2295 | (name,sys.exc_info()[1])) |
|
2301 | (name,sys.exc_info()[1])) | |
2296 |
|
2302 | |||
2297 |
|
2303 | |||
2298 | new_scheme = parameter_s.strip() |
|
2304 | new_scheme = parameter_s.strip() | |
2299 | if not new_scheme: |
|
2305 | if not new_scheme: | |
2300 | print 'You must specify a color scheme.' |
|
2306 | print 'You must specify a color scheme.' | |
2301 | return |
|
2307 | return | |
2302 | import IPython.rlineimpl as readline |
|
2308 | import IPython.rlineimpl as readline | |
2303 | if not readline.have_readline: |
|
2309 | if not readline.have_readline: | |
2304 | msg = """\ |
|
2310 | msg = """\ | |
2305 | Proper color support under MS Windows requires the pyreadline library. |
|
2311 | Proper color support under MS Windows requires the pyreadline library. | |
2306 | You can find it at: |
|
2312 | You can find it at: | |
2307 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2313 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2308 | Gary's readline needs the ctypes module, from: |
|
2314 | Gary's readline needs the ctypes module, from: | |
2309 | http://starship.python.net/crew/theller/ctypes |
|
2315 | http://starship.python.net/crew/theller/ctypes | |
2310 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2316 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2311 |
|
2317 | |||
2312 | Defaulting color scheme to 'NoColor'""" |
|
2318 | Defaulting color scheme to 'NoColor'""" | |
2313 | new_scheme = 'NoColor' |
|
2319 | new_scheme = 'NoColor' | |
2314 | warn(msg) |
|
2320 | warn(msg) | |
2315 | # local shortcut |
|
2321 | # local shortcut | |
2316 | shell = self.shell |
|
2322 | shell = self.shell | |
2317 |
|
2323 | |||
2318 | # Set prompt colors |
|
2324 | # Set prompt colors | |
2319 | try: |
|
2325 | try: | |
2320 | shell.outputcache.set_colors(new_scheme) |
|
2326 | shell.outputcache.set_colors(new_scheme) | |
2321 | except: |
|
2327 | except: | |
2322 | color_switch_err('prompt') |
|
2328 | color_switch_err('prompt') | |
2323 | else: |
|
2329 | else: | |
2324 | shell.rc.colors = \ |
|
2330 | shell.rc.colors = \ | |
2325 | shell.outputcache.color_table.active_scheme_name |
|
2331 | shell.outputcache.color_table.active_scheme_name | |
2326 | # Set exception colors |
|
2332 | # Set exception colors | |
2327 | try: |
|
2333 | try: | |
2328 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2334 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2329 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2335 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2330 | except: |
|
2336 | except: | |
2331 | color_switch_err('exception') |
|
2337 | color_switch_err('exception') | |
2332 |
|
2338 | |||
2333 | # threaded shells use a verbose traceback in sys.excepthook |
|
2339 | # threaded shells use a verbose traceback in sys.excepthook | |
2334 | if shell.isthreaded: |
|
2340 | if shell.isthreaded: | |
2335 | try: |
|
2341 | try: | |
2336 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2342 | shell.sys_excepthook.set_colors(scheme=new_scheme) | |
2337 | except: |
|
2343 | except: | |
2338 | color_switch_err('system exception handler') |
|
2344 | color_switch_err('system exception handler') | |
2339 |
|
2345 | |||
2340 | # Set info (for 'object?') colors |
|
2346 | # Set info (for 'object?') colors | |
2341 | if shell.rc.color_info: |
|
2347 | if shell.rc.color_info: | |
2342 | try: |
|
2348 | try: | |
2343 | shell.inspector.set_active_scheme(new_scheme) |
|
2349 | shell.inspector.set_active_scheme(new_scheme) | |
2344 | except: |
|
2350 | except: | |
2345 | color_switch_err('object inspector') |
|
2351 | color_switch_err('object inspector') | |
2346 | else: |
|
2352 | else: | |
2347 | shell.inspector.set_active_scheme('NoColor') |
|
2353 | shell.inspector.set_active_scheme('NoColor') | |
2348 |
|
2354 | |||
2349 | def magic_color_info(self,parameter_s = ''): |
|
2355 | def magic_color_info(self,parameter_s = ''): | |
2350 | """Toggle color_info. |
|
2356 | """Toggle color_info. | |
2351 |
|
2357 | |||
2352 | The color_info configuration parameter controls whether colors are |
|
2358 | The color_info configuration parameter controls whether colors are | |
2353 | used for displaying object details (by things like %psource, %pfile or |
|
2359 | used for displaying object details (by things like %psource, %pfile or | |
2354 | the '?' system). This function toggles this value with each call. |
|
2360 | the '?' system). This function toggles this value with each call. | |
2355 |
|
2361 | |||
2356 | Note that unless you have a fairly recent pager (less works better |
|
2362 | Note that unless you have a fairly recent pager (less works better | |
2357 | than more) in your system, using colored object information displays |
|
2363 | than more) in your system, using colored object information displays | |
2358 | will not work properly. Test it and see.""" |
|
2364 | will not work properly. Test it and see.""" | |
2359 |
|
2365 | |||
2360 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2366 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
2361 | self.magic_colors(self.shell.rc.colors) |
|
2367 | self.magic_colors(self.shell.rc.colors) | |
2362 | print 'Object introspection functions have now coloring:', |
|
2368 | print 'Object introspection functions have now coloring:', | |
2363 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2369 | print ['OFF','ON'][self.shell.rc.color_info] | |
2364 |
|
2370 | |||
2365 | def magic_Pprint(self, parameter_s=''): |
|
2371 | def magic_Pprint(self, parameter_s=''): | |
2366 | """Toggle pretty printing on/off.""" |
|
2372 | """Toggle pretty printing on/off.""" | |
2367 |
|
2373 | |||
2368 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2374 | self.shell.rc.pprint = 1 - self.shell.rc.pprint | |
2369 | print 'Pretty printing has been turned', \ |
|
2375 | print 'Pretty printing has been turned', \ | |
2370 | ['OFF','ON'][self.shell.rc.pprint] |
|
2376 | ['OFF','ON'][self.shell.rc.pprint] | |
2371 |
|
2377 | |||
2372 | def magic_exit(self, parameter_s=''): |
|
2378 | def magic_exit(self, parameter_s=''): | |
2373 | """Exit IPython, confirming if configured to do so. |
|
2379 | """Exit IPython, confirming if configured to do so. | |
2374 |
|
2380 | |||
2375 | You can configure whether IPython asks for confirmation upon exit by |
|
2381 | You can configure whether IPython asks for confirmation upon exit by | |
2376 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2382 | setting the confirm_exit flag in the ipythonrc file.""" | |
2377 |
|
2383 | |||
2378 | self.shell.exit() |
|
2384 | self.shell.exit() | |
2379 |
|
2385 | |||
2380 | def magic_quit(self, parameter_s=''): |
|
2386 | def magic_quit(self, parameter_s=''): | |
2381 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2387 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
2382 |
|
2388 | |||
2383 | self.shell.exit() |
|
2389 | self.shell.exit() | |
2384 |
|
2390 | |||
2385 | def magic_Exit(self, parameter_s=''): |
|
2391 | def magic_Exit(self, parameter_s=''): | |
2386 | """Exit IPython without confirmation.""" |
|
2392 | """Exit IPython without confirmation.""" | |
2387 |
|
2393 | |||
2388 | self.shell.exit_now = True |
|
2394 | self.shell.exit_now = True | |
2389 |
|
2395 | |||
2390 | def magic_Quit(self, parameter_s=''): |
|
2396 | def magic_Quit(self, parameter_s=''): | |
2391 | """Exit IPython without confirmation (like %Exit).""" |
|
2397 | """Exit IPython without confirmation (like %Exit).""" | |
2392 |
|
2398 | |||
2393 | self.shell.exit_now = True |
|
2399 | self.shell.exit_now = True | |
2394 |
|
2400 | |||
2395 | #...................................................................... |
|
2401 | #...................................................................... | |
2396 | # Functions to implement unix shell-type things |
|
2402 | # Functions to implement unix shell-type things | |
2397 |
|
2403 | |||
2398 | def magic_alias(self, parameter_s = ''): |
|
2404 | def magic_alias(self, parameter_s = ''): | |
2399 | """Define an alias for a system command. |
|
2405 | """Define an alias for a system command. | |
2400 |
|
2406 | |||
2401 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2407 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2402 |
|
2408 | |||
2403 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2409 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2404 | params' (from your underlying operating system). |
|
2410 | params' (from your underlying operating system). | |
2405 |
|
2411 | |||
2406 | Aliases have lower precedence than magic functions and Python normal |
|
2412 | Aliases have lower precedence than magic functions and Python normal | |
2407 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2413 | variables, so if 'foo' is both a Python variable and an alias, the | |
2408 | alias can not be executed until 'del foo' removes the Python variable. |
|
2414 | alias can not be executed until 'del foo' removes the Python variable. | |
2409 |
|
2415 | |||
2410 | You can use the %l specifier in an alias definition to represent the |
|
2416 | You can use the %l specifier in an alias definition to represent the | |
2411 | whole line when the alias is called. For example: |
|
2417 | whole line when the alias is called. For example: | |
2412 |
|
2418 | |||
2413 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
2419 | In [2]: alias all echo "Input in brackets: <%l>"\\ | |
2414 | In [3]: all hello world\\ |
|
2420 | In [3]: all hello world\\ | |
2415 | Input in brackets: <hello world> |
|
2421 | Input in brackets: <hello world> | |
2416 |
|
2422 | |||
2417 | You can also define aliases with parameters using %s specifiers (one |
|
2423 | You can also define aliases with parameters using %s specifiers (one | |
2418 | per parameter): |
|
2424 | per parameter): | |
2419 |
|
2425 | |||
2420 | In [1]: alias parts echo first %s second %s\\ |
|
2426 | In [1]: alias parts echo first %s second %s\\ | |
2421 | In [2]: %parts A B\\ |
|
2427 | In [2]: %parts A B\\ | |
2422 | first A second B\\ |
|
2428 | first A second B\\ | |
2423 | In [3]: %parts A\\ |
|
2429 | In [3]: %parts A\\ | |
2424 | Incorrect number of arguments: 2 expected.\\ |
|
2430 | Incorrect number of arguments: 2 expected.\\ | |
2425 | parts is an alias to: 'echo first %s second %s' |
|
2431 | parts is an alias to: 'echo first %s second %s' | |
2426 |
|
2432 | |||
2427 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2433 | Note that %l and %s are mutually exclusive. You can only use one or | |
2428 | the other in your aliases. |
|
2434 | the other in your aliases. | |
2429 |
|
2435 | |||
2430 | Aliases expand Python variables just like system calls using ! or !! |
|
2436 | Aliases expand Python variables just like system calls using ! or !! | |
2431 | do: all expressions prefixed with '$' get expanded. For details of |
|
2437 | do: all expressions prefixed with '$' get expanded. For details of | |
2432 | the semantic rules, see PEP-215: |
|
2438 | the semantic rules, see PEP-215: | |
2433 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2439 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2434 | IPython for variable expansion. If you want to access a true shell |
|
2440 | IPython for variable expansion. If you want to access a true shell | |
2435 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2441 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2436 |
|
2442 | |||
2437 | In [6]: alias show echo\\ |
|
2443 | In [6]: alias show echo\\ | |
2438 | In [7]: PATH='A Python string'\\ |
|
2444 | In [7]: PATH='A Python string'\\ | |
2439 | In [8]: show $PATH\\ |
|
2445 | In [8]: show $PATH\\ | |
2440 | A Python string\\ |
|
2446 | A Python string\\ | |
2441 | In [9]: show $$PATH\\ |
|
2447 | In [9]: show $$PATH\\ | |
2442 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2448 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2443 |
|
2449 | |||
2444 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2450 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2445 | and %rehashx functions, which automatically create aliases for the |
|
2451 | and %rehashx functions, which automatically create aliases for the | |
2446 | contents of your $PATH. |
|
2452 | contents of your $PATH. | |
2447 |
|
2453 | |||
2448 | If called with no parameters, %alias prints the current alias table.""" |
|
2454 | If called with no parameters, %alias prints the current alias table.""" | |
2449 |
|
2455 | |||
2450 | par = parameter_s.strip() |
|
2456 | par = parameter_s.strip() | |
2451 | if not par: |
|
2457 | if not par: | |
2452 | stored = self.db.get('stored_aliases', {} ) |
|
2458 | stored = self.db.get('stored_aliases', {} ) | |
2453 | atab = self.shell.alias_table |
|
2459 | atab = self.shell.alias_table | |
2454 | aliases = atab.keys() |
|
2460 | aliases = atab.keys() | |
2455 | aliases.sort() |
|
2461 | aliases.sort() | |
2456 | res = [] |
|
2462 | res = [] | |
2457 | showlast = [] |
|
2463 | showlast = [] | |
2458 | for alias in aliases: |
|
2464 | for alias in aliases: | |
2459 | tgt = atab[alias][1] |
|
2465 | tgt = atab[alias][1] | |
2460 | # 'interesting' aliases |
|
2466 | # 'interesting' aliases | |
2461 | if (alias in stored or |
|
2467 | if (alias in stored or | |
2462 | alias != os.path.splitext(tgt)[0] or |
|
2468 | alias != os.path.splitext(tgt)[0] or | |
2463 | ' ' in tgt): |
|
2469 | ' ' in tgt): | |
2464 | showlast.append((alias, tgt)) |
|
2470 | showlast.append((alias, tgt)) | |
2465 | else: |
|
2471 | else: | |
2466 | res.append((alias, tgt )) |
|
2472 | res.append((alias, tgt )) | |
2467 |
|
2473 | |||
2468 | # show most interesting aliases last |
|
2474 | # show most interesting aliases last | |
2469 | res.extend(showlast) |
|
2475 | res.extend(showlast) | |
2470 | print "Total number of aliases:",len(aliases) |
|
2476 | print "Total number of aliases:",len(aliases) | |
2471 | return res |
|
2477 | return res | |
2472 | try: |
|
2478 | try: | |
2473 | alias,cmd = par.split(None,1) |
|
2479 | alias,cmd = par.split(None,1) | |
2474 | except: |
|
2480 | except: | |
2475 | print OInspect.getdoc(self.magic_alias) |
|
2481 | print OInspect.getdoc(self.magic_alias) | |
2476 | else: |
|
2482 | else: | |
2477 | nargs = cmd.count('%s') |
|
2483 | nargs = cmd.count('%s') | |
2478 | if nargs>0 and cmd.find('%l')>=0: |
|
2484 | if nargs>0 and cmd.find('%l')>=0: | |
2479 | error('The %s and %l specifiers are mutually exclusive ' |
|
2485 | error('The %s and %l specifiers are mutually exclusive ' | |
2480 | 'in alias definitions.') |
|
2486 | 'in alias definitions.') | |
2481 | else: # all looks OK |
|
2487 | else: # all looks OK | |
2482 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2488 | self.shell.alias_table[alias] = (nargs,cmd) | |
2483 | self.shell.alias_table_validate(verbose=0) |
|
2489 | self.shell.alias_table_validate(verbose=0) | |
2484 | # end magic_alias |
|
2490 | # end magic_alias | |
2485 |
|
2491 | |||
2486 | def magic_unalias(self, parameter_s = ''): |
|
2492 | def magic_unalias(self, parameter_s = ''): | |
2487 | """Remove an alias""" |
|
2493 | """Remove an alias""" | |
2488 |
|
2494 | |||
2489 | aname = parameter_s.strip() |
|
2495 | aname = parameter_s.strip() | |
2490 | if aname in self.shell.alias_table: |
|
2496 | if aname in self.shell.alias_table: | |
2491 | del self.shell.alias_table[aname] |
|
2497 | del self.shell.alias_table[aname] | |
2492 | stored = self.db.get('stored_aliases', {} ) |
|
2498 | stored = self.db.get('stored_aliases', {} ) | |
2493 | if aname in stored: |
|
2499 | if aname in stored: | |
2494 | print "Removing %stored alias",aname |
|
2500 | print "Removing %stored alias",aname | |
2495 | del stored[aname] |
|
2501 | del stored[aname] | |
2496 | self.db['stored_aliases'] = stored |
|
2502 | self.db['stored_aliases'] = stored | |
2497 |
|
2503 | |||
2498 | def magic_rehash(self, parameter_s = ''): |
|
2504 | def magic_rehash(self, parameter_s = ''): | |
2499 | """Update the alias table with all entries in $PATH. |
|
2505 | """Update the alias table with all entries in $PATH. | |
2500 |
|
2506 | |||
2501 | This version does no checks on execute permissions or whether the |
|
2507 | This version does no checks on execute permissions or whether the | |
2502 | contents of $PATH are truly files (instead of directories or something |
|
2508 | contents of $PATH are truly files (instead of directories or something | |
2503 | else). For such a safer (but slower) version, use %rehashx.""" |
|
2509 | else). For such a safer (but slower) version, use %rehashx.""" | |
2504 |
|
2510 | |||
2505 | # This function (and rehashx) manipulate the alias_table directly |
|
2511 | # This function (and rehashx) manipulate the alias_table directly | |
2506 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
2512 | # rather than calling magic_alias, for speed reasons. A rehash on a | |
2507 | # typical Linux box involves several thousand entries, so efficiency |
|
2513 | # typical Linux box involves several thousand entries, so efficiency | |
2508 | # here is a top concern. |
|
2514 | # here is a top concern. | |
2509 |
|
2515 | |||
2510 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) |
|
2516 | path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep)) | |
2511 | alias_table = self.shell.alias_table |
|
2517 | alias_table = self.shell.alias_table | |
2512 | for pdir in path: |
|
2518 | for pdir in path: | |
2513 | for ff in os.listdir(pdir): |
|
2519 | for ff in os.listdir(pdir): | |
2514 | # each entry in the alias table must be (N,name), where |
|
2520 | # each entry in the alias table must be (N,name), where | |
2515 | # N is the number of positional arguments of the alias. |
|
2521 | # N is the number of positional arguments of the alias. | |
2516 | alias_table[ff] = (0,ff) |
|
2522 | alias_table[ff] = (0,ff) | |
2517 | # Make sure the alias table doesn't contain keywords or builtins |
|
2523 | # Make sure the alias table doesn't contain keywords or builtins | |
2518 | self.shell.alias_table_validate() |
|
2524 | self.shell.alias_table_validate() | |
2519 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
2525 | # Call again init_auto_alias() so we get 'rm -i' and other modified | |
2520 | # aliases since %rehash will probably clobber them |
|
2526 | # aliases since %rehash will probably clobber them | |
2521 | self.shell.init_auto_alias() |
|
2527 | self.shell.init_auto_alias() | |
2522 |
|
2528 | |||
2523 | def magic_rehashx(self, parameter_s = ''): |
|
2529 | def magic_rehashx(self, parameter_s = ''): | |
2524 | """Update the alias table with all executable files in $PATH. |
|
2530 | """Update the alias table with all executable files in $PATH. | |
2525 |
|
2531 | |||
2526 | This version explicitly checks that every entry in $PATH is a file |
|
2532 | This version explicitly checks that every entry in $PATH is a file | |
2527 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2533 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2528 |
|
2534 | |||
2529 | Under Windows, it checks executability as a match agains a |
|
2535 | Under Windows, it checks executability as a match agains a | |
2530 | '|'-separated string of extensions, stored in the IPython config |
|
2536 | '|'-separated string of extensions, stored in the IPython config | |
2531 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ |
|
2537 | variable win_exec_ext. This defaults to 'exe|com|bat'. """ | |
2532 |
|
2538 | |||
2533 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2539 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2534 | os.environ['PATH'].split(os.pathsep)] |
|
2540 | os.environ['PATH'].split(os.pathsep)] | |
2535 | path = filter(os.path.isdir,path) |
|
2541 | path = filter(os.path.isdir,path) | |
2536 |
|
2542 | |||
2537 | alias_table = self.shell.alias_table |
|
2543 | alias_table = self.shell.alias_table | |
2538 | syscmdlist = [] |
|
2544 | syscmdlist = [] | |
2539 | if os.name == 'posix': |
|
2545 | if os.name == 'posix': | |
2540 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2546 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2541 | os.access(fname,os.X_OK) |
|
2547 | os.access(fname,os.X_OK) | |
2542 | else: |
|
2548 | else: | |
2543 |
|
2549 | |||
2544 | try: |
|
2550 | try: | |
2545 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2551 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2546 | except KeyError: |
|
2552 | except KeyError: | |
2547 | winext = 'exe|com|bat|py' |
|
2553 | winext = 'exe|com|bat|py' | |
2548 | if 'py' not in winext: |
|
2554 | if 'py' not in winext: | |
2549 | winext += '|py' |
|
2555 | winext += '|py' | |
2550 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2556 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2551 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2557 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2552 | savedir = os.getcwd() |
|
2558 | savedir = os.getcwd() | |
2553 | try: |
|
2559 | try: | |
2554 | # write the whole loop for posix/Windows so we don't have an if in |
|
2560 | # write the whole loop for posix/Windows so we don't have an if in | |
2555 | # the innermost part |
|
2561 | # the innermost part | |
2556 | if os.name == 'posix': |
|
2562 | if os.name == 'posix': | |
2557 | for pdir in path: |
|
2563 | for pdir in path: | |
2558 | os.chdir(pdir) |
|
2564 | os.chdir(pdir) | |
2559 | for ff in os.listdir(pdir): |
|
2565 | for ff in os.listdir(pdir): | |
2560 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2566 | if isexec(ff) and ff not in self.shell.no_alias: | |
2561 | # each entry in the alias table must be (N,name), |
|
2567 | # each entry in the alias table must be (N,name), | |
2562 | # where N is the number of positional arguments of the |
|
2568 | # where N is the number of positional arguments of the | |
2563 | # alias. |
|
2569 | # alias. | |
2564 | alias_table[ff] = (0,ff) |
|
2570 | alias_table[ff] = (0,ff) | |
2565 | syscmdlist.append(ff) |
|
2571 | syscmdlist.append(ff) | |
2566 | else: |
|
2572 | else: | |
2567 | for pdir in path: |
|
2573 | for pdir in path: | |
2568 | os.chdir(pdir) |
|
2574 | os.chdir(pdir) | |
2569 | for ff in os.listdir(pdir): |
|
2575 | for ff in os.listdir(pdir): | |
2570 | base, ext = os.path.splitext(ff) |
|
2576 | base, ext = os.path.splitext(ff) | |
2571 | if isexec(ff) and base not in self.shell.no_alias: |
|
2577 | if isexec(ff) and base not in self.shell.no_alias: | |
2572 | if ext.lower() == '.exe': |
|
2578 | if ext.lower() == '.exe': | |
2573 | ff = base |
|
2579 | ff = base | |
2574 | alias_table[base] = (0,ff) |
|
2580 | alias_table[base] = (0,ff) | |
2575 | syscmdlist.append(ff) |
|
2581 | syscmdlist.append(ff) | |
2576 | # Make sure the alias table doesn't contain keywords or builtins |
|
2582 | # Make sure the alias table doesn't contain keywords or builtins | |
2577 | self.shell.alias_table_validate() |
|
2583 | self.shell.alias_table_validate() | |
2578 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2584 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2579 | # modified aliases since %rehashx will probably clobber them |
|
2585 | # modified aliases since %rehashx will probably clobber them | |
2580 | self.shell.init_auto_alias() |
|
2586 | self.shell.init_auto_alias() | |
2581 | db = self.getapi().db |
|
2587 | db = self.getapi().db | |
2582 | db['syscmdlist'] = syscmdlist |
|
2588 | db['syscmdlist'] = syscmdlist | |
2583 | finally: |
|
2589 | finally: | |
2584 | os.chdir(savedir) |
|
2590 | os.chdir(savedir) | |
2585 |
|
2591 | |||
2586 | def magic_pwd(self, parameter_s = ''): |
|
2592 | def magic_pwd(self, parameter_s = ''): | |
2587 | """Return the current working directory path.""" |
|
2593 | """Return the current working directory path.""" | |
2588 | return os.getcwd() |
|
2594 | return os.getcwd() | |
2589 |
|
2595 | |||
2590 | def magic_cd(self, parameter_s=''): |
|
2596 | def magic_cd(self, parameter_s=''): | |
2591 | """Change the current working directory. |
|
2597 | """Change the current working directory. | |
2592 |
|
2598 | |||
2593 | This command automatically maintains an internal list of directories |
|
2599 | This command automatically maintains an internal list of directories | |
2594 | you visit during your IPython session, in the variable _dh. The |
|
2600 | you visit during your IPython session, in the variable _dh. The | |
2595 | command %dhist shows this history nicely formatted. You can also |
|
2601 | command %dhist shows this history nicely formatted. You can also | |
2596 | do 'cd -<tab>' to see directory history conveniently. |
|
2602 | do 'cd -<tab>' to see directory history conveniently. | |
2597 |
|
2603 | |||
2598 | Usage: |
|
2604 | Usage: | |
2599 |
|
2605 | |||
2600 | cd 'dir': changes to directory 'dir'. |
|
2606 | cd 'dir': changes to directory 'dir'. | |
2601 |
|
2607 | |||
2602 | cd -: changes to the last visited directory. |
|
2608 | cd -: changes to the last visited directory. | |
2603 |
|
2609 | |||
2604 | cd -<n>: changes to the n-th directory in the directory history. |
|
2610 | cd -<n>: changes to the n-th directory in the directory history. | |
2605 |
|
2611 | |||
2606 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2612 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2607 | (note: cd <bookmark_name> is enough if there is no |
|
2613 | (note: cd <bookmark_name> is enough if there is no | |
2608 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2614 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2609 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2615 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2610 |
|
2616 | |||
2611 | Options: |
|
2617 | Options: | |
2612 |
|
2618 | |||
2613 | -q: quiet. Do not print the working directory after the cd command is |
|
2619 | -q: quiet. Do not print the working directory after the cd command is | |
2614 | executed. By default IPython's cd command does print this directory, |
|
2620 | executed. By default IPython's cd command does print this directory, | |
2615 | since the default prompts do not display path information. |
|
2621 | since the default prompts do not display path information. | |
2616 |
|
2622 | |||
2617 | Note that !cd doesn't work for this purpose because the shell where |
|
2623 | Note that !cd doesn't work for this purpose because the shell where | |
2618 | !command runs is immediately discarded after executing 'command'.""" |
|
2624 | !command runs is immediately discarded after executing 'command'.""" | |
2619 |
|
2625 | |||
2620 | parameter_s = parameter_s.strip() |
|
2626 | parameter_s = parameter_s.strip() | |
2621 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2627 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2622 |
|
2628 | |||
2623 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2629 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2624 | # jump in directory history by number |
|
2630 | # jump in directory history by number | |
2625 | if numcd: |
|
2631 | if numcd: | |
2626 | nn = int(numcd.group(2)) |
|
2632 | nn = int(numcd.group(2)) | |
2627 | try: |
|
2633 | try: | |
2628 | ps = self.shell.user_ns['_dh'][nn] |
|
2634 | ps = self.shell.user_ns['_dh'][nn] | |
2629 | except IndexError: |
|
2635 | except IndexError: | |
2630 | print 'The requested directory does not exist in history.' |
|
2636 | print 'The requested directory does not exist in history.' | |
2631 | return |
|
2637 | return | |
2632 | else: |
|
2638 | else: | |
2633 | opts = {} |
|
2639 | opts = {} | |
2634 | else: |
|
2640 | else: | |
2635 | #turn all non-space-escaping backslashes to slashes, |
|
2641 | #turn all non-space-escaping backslashes to slashes, | |
2636 | # for c:\windows\directory\names\ |
|
2642 | # for c:\windows\directory\names\ | |
2637 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2643 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2638 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2644 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2639 | # jump to previous |
|
2645 | # jump to previous | |
2640 | if ps == '-': |
|
2646 | if ps == '-': | |
2641 | try: |
|
2647 | try: | |
2642 | ps = self.shell.user_ns['_dh'][-2] |
|
2648 | ps = self.shell.user_ns['_dh'][-2] | |
2643 | except IndexError: |
|
2649 | except IndexError: | |
2644 | print 'No previous directory to change to.' |
|
2650 | print 'No previous directory to change to.' | |
2645 | return |
|
2651 | return | |
2646 | # jump to bookmark if needed |
|
2652 | # jump to bookmark if needed | |
2647 | else: |
|
2653 | else: | |
2648 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2654 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2649 | bkms = self.db.get('bookmarks', {}) |
|
2655 | bkms = self.db.get('bookmarks', {}) | |
2650 |
|
2656 | |||
2651 | if bkms.has_key(ps): |
|
2657 | if bkms.has_key(ps): | |
2652 | target = bkms[ps] |
|
2658 | target = bkms[ps] | |
2653 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2659 | print '(bookmark:%s) -> %s' % (ps,target) | |
2654 | ps = target |
|
2660 | ps = target | |
2655 | else: |
|
2661 | else: | |
2656 | if opts.has_key('b'): |
|
2662 | if opts.has_key('b'): | |
2657 | error("Bookmark '%s' not found. " |
|
2663 | error("Bookmark '%s' not found. " | |
2658 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2664 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2659 | return |
|
2665 | return | |
2660 |
|
2666 | |||
2661 | # at this point ps should point to the target dir |
|
2667 | # at this point ps should point to the target dir | |
2662 | if ps: |
|
2668 | if ps: | |
2663 | try: |
|
2669 | try: | |
2664 | os.chdir(os.path.expanduser(ps)) |
|
2670 | os.chdir(os.path.expanduser(ps)) | |
2665 | if self.shell.rc.term_title: |
|
2671 | if self.shell.rc.term_title: | |
2666 | #print 'set term title:',self.shell.rc.term_title # dbg |
|
2672 | #print 'set term title:',self.shell.rc.term_title # dbg | |
2667 | ttitle = ("IPy:" + ( |
|
2673 | ttitle = ("IPy:" + ( | |
2668 | os.getcwd() == '/' and '/' or \ |
|
2674 | os.getcwd() == '/' and '/' or \ | |
2669 | os.path.basename(os.getcwd()))) |
|
2675 | os.path.basename(os.getcwd()))) | |
2670 | platutils.set_term_title(ttitle) |
|
2676 | platutils.set_term_title(ttitle) | |
2671 | except OSError: |
|
2677 | except OSError: | |
2672 | print sys.exc_info()[1] |
|
2678 | print sys.exc_info()[1] | |
2673 | else: |
|
2679 | else: | |
2674 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2680 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2675 | else: |
|
2681 | else: | |
2676 | os.chdir(self.shell.home_dir) |
|
2682 | os.chdir(self.shell.home_dir) | |
2677 | if self.shell.rc.term_title: |
|
2683 | if self.shell.rc.term_title: | |
2678 | platutils.set_term_title("IPy:~") |
|
2684 | platutils.set_term_title("IPy:~") | |
2679 | self.shell.user_ns['_dh'].append(os.getcwd()) |
|
2685 | self.shell.user_ns['_dh'].append(os.getcwd()) | |
2680 | if not 'q' in opts: |
|
2686 | if not 'q' in opts: | |
2681 | print self.shell.user_ns['_dh'][-1] |
|
2687 | print self.shell.user_ns['_dh'][-1] | |
2682 |
|
2688 | |||
2683 | def magic_dhist(self, parameter_s=''): |
|
2689 | def magic_dhist(self, parameter_s=''): | |
2684 | """Print your history of visited directories. |
|
2690 | """Print your history of visited directories. | |
2685 |
|
2691 | |||
2686 | %dhist -> print full history\\ |
|
2692 | %dhist -> print full history\\ | |
2687 | %dhist n -> print last n entries only\\ |
|
2693 | %dhist n -> print last n entries only\\ | |
2688 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2694 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2689 |
|
2695 | |||
2690 | This history is automatically maintained by the %cd command, and |
|
2696 | This history is automatically maintained by the %cd command, and | |
2691 | always available as the global list variable _dh. You can use %cd -<n> |
|
2697 | always available as the global list variable _dh. You can use %cd -<n> | |
2692 | to go to directory number <n>.""" |
|
2698 | to go to directory number <n>.""" | |
2693 |
|
2699 | |||
2694 | dh = self.shell.user_ns['_dh'] |
|
2700 | dh = self.shell.user_ns['_dh'] | |
2695 | if parameter_s: |
|
2701 | if parameter_s: | |
2696 | try: |
|
2702 | try: | |
2697 | args = map(int,parameter_s.split()) |
|
2703 | args = map(int,parameter_s.split()) | |
2698 | except: |
|
2704 | except: | |
2699 | self.arg_err(Magic.magic_dhist) |
|
2705 | self.arg_err(Magic.magic_dhist) | |
2700 | return |
|
2706 | return | |
2701 | if len(args) == 1: |
|
2707 | if len(args) == 1: | |
2702 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2708 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2703 | elif len(args) == 2: |
|
2709 | elif len(args) == 2: | |
2704 | ini,fin = args |
|
2710 | ini,fin = args | |
2705 | else: |
|
2711 | else: | |
2706 | self.arg_err(Magic.magic_dhist) |
|
2712 | self.arg_err(Magic.magic_dhist) | |
2707 | return |
|
2713 | return | |
2708 | else: |
|
2714 | else: | |
2709 | ini,fin = 0,len(dh) |
|
2715 | ini,fin = 0,len(dh) | |
2710 | nlprint(dh, |
|
2716 | nlprint(dh, | |
2711 | header = 'Directory history (kept in _dh)', |
|
2717 | header = 'Directory history (kept in _dh)', | |
2712 | start=ini,stop=fin) |
|
2718 | start=ini,stop=fin) | |
2713 |
|
2719 | |||
2714 | def magic_env(self, parameter_s=''): |
|
2720 | def magic_env(self, parameter_s=''): | |
2715 | """List environment variables.""" |
|
2721 | """List environment variables.""" | |
2716 |
|
2722 | |||
2717 | return os.environ.data |
|
2723 | return os.environ.data | |
2718 |
|
2724 | |||
2719 | def magic_pushd(self, parameter_s=''): |
|
2725 | def magic_pushd(self, parameter_s=''): | |
2720 | """Place the current dir on stack and change directory. |
|
2726 | """Place the current dir on stack and change directory. | |
2721 |
|
2727 | |||
2722 | Usage:\\ |
|
2728 | Usage:\\ | |
2723 | %pushd ['dirname'] |
|
2729 | %pushd ['dirname'] | |
2724 |
|
2730 | |||
2725 | %pushd with no arguments does a %pushd to your home directory. |
|
2731 | %pushd with no arguments does a %pushd to your home directory. | |
2726 | """ |
|
2732 | """ | |
2727 | if parameter_s == '': parameter_s = '~' |
|
2733 | if parameter_s == '': parameter_s = '~' | |
2728 | dir_s = self.shell.dir_stack |
|
2734 | dir_s = self.shell.dir_stack | |
2729 | if len(dir_s)>0 and os.path.expanduser(parameter_s) != \ |
|
2735 | if len(dir_s)>0 and os.path.expanduser(parameter_s) != \ | |
2730 | os.path.expanduser(self.shell.dir_stack[0]): |
|
2736 | os.path.expanduser(self.shell.dir_stack[0]): | |
2731 | try: |
|
2737 | try: | |
2732 | self.magic_cd(parameter_s) |
|
2738 | self.magic_cd(parameter_s) | |
2733 | dir_s.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2739 | dir_s.insert(0,os.getcwd().replace(self.home_dir,'~')) | |
2734 | self.magic_dirs() |
|
2740 | self.magic_dirs() | |
2735 | except: |
|
2741 | except: | |
2736 | print 'Invalid directory' |
|
2742 | print 'Invalid directory' | |
2737 | else: |
|
2743 | else: | |
2738 | print 'You are already there!' |
|
2744 | print 'You are already there!' | |
2739 |
|
2745 | |||
2740 | def magic_popd(self, parameter_s=''): |
|
2746 | def magic_popd(self, parameter_s=''): | |
2741 | """Change to directory popped off the top of the stack. |
|
2747 | """Change to directory popped off the top of the stack. | |
2742 | """ |
|
2748 | """ | |
2743 | if len (self.shell.dir_stack) > 1: |
|
2749 | if len (self.shell.dir_stack) > 1: | |
2744 | self.shell.dir_stack.pop(0) |
|
2750 | self.shell.dir_stack.pop(0) | |
2745 | self.magic_cd(self.shell.dir_stack[0]) |
|
2751 | self.magic_cd(self.shell.dir_stack[0]) | |
2746 | print self.shell.dir_stack[0] |
|
2752 | print self.shell.dir_stack[0] | |
2747 | else: |
|
2753 | else: | |
2748 | print "You can't remove the starting directory from the stack:",\ |
|
2754 | print "You can't remove the starting directory from the stack:",\ | |
2749 | self.shell.dir_stack |
|
2755 | self.shell.dir_stack | |
2750 |
|
2756 | |||
2751 | def magic_dirs(self, parameter_s=''): |
|
2757 | def magic_dirs(self, parameter_s=''): | |
2752 | """Return the current directory stack.""" |
|
2758 | """Return the current directory stack.""" | |
2753 |
|
2759 | |||
2754 | return self.shell.dir_stack[:] |
|
2760 | return self.shell.dir_stack[:] | |
2755 |
|
2761 | |||
2756 | def magic_sc(self, parameter_s=''): |
|
2762 | def magic_sc(self, parameter_s=''): | |
2757 | """Shell capture - execute a shell command and capture its output. |
|
2763 | """Shell capture - execute a shell command and capture its output. | |
2758 |
|
2764 | |||
2759 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2765 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2760 |
|
2766 | |||
2761 | You should use the form 'var = !command' instead. Example: |
|
2767 | You should use the form 'var = !command' instead. Example: | |
2762 |
|
2768 | |||
2763 | "%sc -l myfiles = ls ~" should now be written as |
|
2769 | "%sc -l myfiles = ls ~" should now be written as | |
2764 |
|
2770 | |||
2765 | "myfiles = !ls ~" |
|
2771 | "myfiles = !ls ~" | |
2766 |
|
2772 | |||
2767 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2773 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2768 | below. |
|
2774 | below. | |
2769 |
|
2775 | |||
2770 | -- |
|
2776 | -- | |
2771 | %sc [options] varname=command |
|
2777 | %sc [options] varname=command | |
2772 |
|
2778 | |||
2773 | IPython will run the given command using commands.getoutput(), and |
|
2779 | IPython will run the given command using commands.getoutput(), and | |
2774 | will then update the user's interactive namespace with a variable |
|
2780 | will then update the user's interactive namespace with a variable | |
2775 | called varname, containing the value of the call. Your command can |
|
2781 | called varname, containing the value of the call. Your command can | |
2776 | contain shell wildcards, pipes, etc. |
|
2782 | contain shell wildcards, pipes, etc. | |
2777 |
|
2783 | |||
2778 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2784 | The '=' sign in the syntax is mandatory, and the variable name you | |
2779 | supply must follow Python's standard conventions for valid names. |
|
2785 | supply must follow Python's standard conventions for valid names. | |
2780 |
|
2786 | |||
2781 | (A special format without variable name exists for internal use) |
|
2787 | (A special format without variable name exists for internal use) | |
2782 |
|
2788 | |||
2783 | Options: |
|
2789 | Options: | |
2784 |
|
2790 | |||
2785 | -l: list output. Split the output on newlines into a list before |
|
2791 | -l: list output. Split the output on newlines into a list before | |
2786 | assigning it to the given variable. By default the output is stored |
|
2792 | assigning it to the given variable. By default the output is stored | |
2787 | as a single string. |
|
2793 | as a single string. | |
2788 |
|
2794 | |||
2789 | -v: verbose. Print the contents of the variable. |
|
2795 | -v: verbose. Print the contents of the variable. | |
2790 |
|
2796 | |||
2791 | In most cases you should not need to split as a list, because the |
|
2797 | In most cases you should not need to split as a list, because the | |
2792 | returned value is a special type of string which can automatically |
|
2798 | returned value is a special type of string which can automatically | |
2793 | provide its contents either as a list (split on newlines) or as a |
|
2799 | provide its contents either as a list (split on newlines) or as a | |
2794 | space-separated string. These are convenient, respectively, either |
|
2800 | space-separated string. These are convenient, respectively, either | |
2795 | for sequential processing or to be passed to a shell command. |
|
2801 | for sequential processing or to be passed to a shell command. | |
2796 |
|
2802 | |||
2797 | For example: |
|
2803 | For example: | |
2798 |
|
2804 | |||
2799 | # Capture into variable a |
|
2805 | # Capture into variable a | |
2800 | In [9]: sc a=ls *py |
|
2806 | In [9]: sc a=ls *py | |
2801 |
|
2807 | |||
2802 | # a is a string with embedded newlines |
|
2808 | # a is a string with embedded newlines | |
2803 | In [10]: a |
|
2809 | In [10]: a | |
2804 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2810 | Out[10]: 'setup.py\nwin32_manual_post_install.py' | |
2805 |
|
2811 | |||
2806 | # which can be seen as a list: |
|
2812 | # which can be seen as a list: | |
2807 | In [11]: a.l |
|
2813 | In [11]: a.l | |
2808 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2814 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] | |
2809 |
|
2815 | |||
2810 | # or as a whitespace-separated string: |
|
2816 | # or as a whitespace-separated string: | |
2811 | In [12]: a.s |
|
2817 | In [12]: a.s | |
2812 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2818 | Out[12]: 'setup.py win32_manual_post_install.py' | |
2813 |
|
2819 | |||
2814 | # a.s is useful to pass as a single command line: |
|
2820 | # a.s is useful to pass as a single command line: | |
2815 | In [13]: !wc -l $a.s |
|
2821 | In [13]: !wc -l $a.s | |
2816 | 146 setup.py |
|
2822 | 146 setup.py | |
2817 | 130 win32_manual_post_install.py |
|
2823 | 130 win32_manual_post_install.py | |
2818 | 276 total |
|
2824 | 276 total | |
2819 |
|
2825 | |||
2820 | # while the list form is useful to loop over: |
|
2826 | # while the list form is useful to loop over: | |
2821 | In [14]: for f in a.l: |
|
2827 | In [14]: for f in a.l: | |
2822 | ....: !wc -l $f |
|
2828 | ....: !wc -l $f | |
2823 | ....: |
|
2829 | ....: | |
2824 | 146 setup.py |
|
2830 | 146 setup.py | |
2825 | 130 win32_manual_post_install.py |
|
2831 | 130 win32_manual_post_install.py | |
2826 |
|
2832 | |||
2827 | Similiarly, the lists returned by the -l option are also special, in |
|
2833 | Similiarly, the lists returned by the -l option are also special, in | |
2828 | the sense that you can equally invoke the .s attribute on them to |
|
2834 | the sense that you can equally invoke the .s attribute on them to | |
2829 | automatically get a whitespace-separated string from their contents: |
|
2835 | automatically get a whitespace-separated string from their contents: | |
2830 |
|
2836 | |||
2831 | In [1]: sc -l b=ls *py |
|
2837 | In [1]: sc -l b=ls *py | |
2832 |
|
2838 | |||
2833 | In [2]: b |
|
2839 | In [2]: b | |
2834 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2840 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] | |
2835 |
|
2841 | |||
2836 | In [3]: b.s |
|
2842 | In [3]: b.s | |
2837 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2843 | Out[3]: 'setup.py win32_manual_post_install.py' | |
2838 |
|
2844 | |||
2839 | In summary, both the lists and strings used for ouptut capture have |
|
2845 | In summary, both the lists and strings used for ouptut capture have | |
2840 | the following special attributes: |
|
2846 | the following special attributes: | |
2841 |
|
2847 | |||
2842 | .l (or .list) : value as list. |
|
2848 | .l (or .list) : value as list. | |
2843 | .n (or .nlstr): value as newline-separated string. |
|
2849 | .n (or .nlstr): value as newline-separated string. | |
2844 | .s (or .spstr): value as space-separated string. |
|
2850 | .s (or .spstr): value as space-separated string. | |
2845 | """ |
|
2851 | """ | |
2846 |
|
2852 | |||
2847 | opts,args = self.parse_options(parameter_s,'lv') |
|
2853 | opts,args = self.parse_options(parameter_s,'lv') | |
2848 | # Try to get a variable name and command to run |
|
2854 | # Try to get a variable name and command to run | |
2849 | try: |
|
2855 | try: | |
2850 | # the variable name must be obtained from the parse_options |
|
2856 | # the variable name must be obtained from the parse_options | |
2851 | # output, which uses shlex.split to strip options out. |
|
2857 | # output, which uses shlex.split to strip options out. | |
2852 | var,_ = args.split('=',1) |
|
2858 | var,_ = args.split('=',1) | |
2853 | var = var.strip() |
|
2859 | var = var.strip() | |
2854 | # But the the command has to be extracted from the original input |
|
2860 | # But the the command has to be extracted from the original input | |
2855 | # parameter_s, not on what parse_options returns, to avoid the |
|
2861 | # parameter_s, not on what parse_options returns, to avoid the | |
2856 | # quote stripping which shlex.split performs on it. |
|
2862 | # quote stripping which shlex.split performs on it. | |
2857 | _,cmd = parameter_s.split('=',1) |
|
2863 | _,cmd = parameter_s.split('=',1) | |
2858 | except ValueError: |
|
2864 | except ValueError: | |
2859 | var,cmd = '','' |
|
2865 | var,cmd = '','' | |
2860 | # If all looks ok, proceed |
|
2866 | # If all looks ok, proceed | |
2861 | out,err = self.shell.getoutputerror(cmd) |
|
2867 | out,err = self.shell.getoutputerror(cmd) | |
2862 | if err: |
|
2868 | if err: | |
2863 | print >> Term.cerr,err |
|
2869 | print >> Term.cerr,err | |
2864 | if opts.has_key('l'): |
|
2870 | if opts.has_key('l'): | |
2865 | out = SList(out.split('\n')) |
|
2871 | out = SList(out.split('\n')) | |
2866 | else: |
|
2872 | else: | |
2867 | out = LSString(out) |
|
2873 | out = LSString(out) | |
2868 | if opts.has_key('v'): |
|
2874 | if opts.has_key('v'): | |
2869 | print '%s ==\n%s' % (var,pformat(out)) |
|
2875 | print '%s ==\n%s' % (var,pformat(out)) | |
2870 | if var: |
|
2876 | if var: | |
2871 | self.shell.user_ns.update({var:out}) |
|
2877 | self.shell.user_ns.update({var:out}) | |
2872 | else: |
|
2878 | else: | |
2873 | return out |
|
2879 | return out | |
2874 |
|
2880 | |||
2875 | def magic_sx(self, parameter_s=''): |
|
2881 | def magic_sx(self, parameter_s=''): | |
2876 | """Shell execute - run a shell command and capture its output. |
|
2882 | """Shell execute - run a shell command and capture its output. | |
2877 |
|
2883 | |||
2878 | %sx command |
|
2884 | %sx command | |
2879 |
|
2885 | |||
2880 | IPython will run the given command using commands.getoutput(), and |
|
2886 | IPython will run the given command using commands.getoutput(), and | |
2881 | return the result formatted as a list (split on '\\n'). Since the |
|
2887 | return the result formatted as a list (split on '\\n'). Since the | |
2882 | output is _returned_, it will be stored in ipython's regular output |
|
2888 | output is _returned_, it will be stored in ipython's regular output | |
2883 | cache Out[N] and in the '_N' automatic variables. |
|
2889 | cache Out[N] and in the '_N' automatic variables. | |
2884 |
|
2890 | |||
2885 | Notes: |
|
2891 | Notes: | |
2886 |
|
2892 | |||
2887 | 1) If an input line begins with '!!', then %sx is automatically |
|
2893 | 1) If an input line begins with '!!', then %sx is automatically | |
2888 | invoked. That is, while: |
|
2894 | invoked. That is, while: | |
2889 | !ls |
|
2895 | !ls | |
2890 | causes ipython to simply issue system('ls'), typing |
|
2896 | causes ipython to simply issue system('ls'), typing | |
2891 | !!ls |
|
2897 | !!ls | |
2892 | is a shorthand equivalent to: |
|
2898 | is a shorthand equivalent to: | |
2893 | %sx ls |
|
2899 | %sx ls | |
2894 |
|
2900 | |||
2895 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2901 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2896 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2902 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2897 | to process line-oriented shell output via further python commands. |
|
2903 | to process line-oriented shell output via further python commands. | |
2898 | %sc is meant to provide much finer control, but requires more |
|
2904 | %sc is meant to provide much finer control, but requires more | |
2899 | typing. |
|
2905 | typing. | |
2900 |
|
2906 | |||
2901 | 3) Just like %sc -l, this is a list with special attributes: |
|
2907 | 3) Just like %sc -l, this is a list with special attributes: | |
2902 |
|
2908 | |||
2903 | .l (or .list) : value as list. |
|
2909 | .l (or .list) : value as list. | |
2904 | .n (or .nlstr): value as newline-separated string. |
|
2910 | .n (or .nlstr): value as newline-separated string. | |
2905 | .s (or .spstr): value as whitespace-separated string. |
|
2911 | .s (or .spstr): value as whitespace-separated string. | |
2906 |
|
2912 | |||
2907 | This is very useful when trying to use such lists as arguments to |
|
2913 | This is very useful when trying to use such lists as arguments to | |
2908 | system commands.""" |
|
2914 | system commands.""" | |
2909 |
|
2915 | |||
2910 | if parameter_s: |
|
2916 | if parameter_s: | |
2911 | out,err = self.shell.getoutputerror(parameter_s) |
|
2917 | out,err = self.shell.getoutputerror(parameter_s) | |
2912 | if err: |
|
2918 | if err: | |
2913 | print >> Term.cerr,err |
|
2919 | print >> Term.cerr,err | |
2914 | return SList(out.split('\n')) |
|
2920 | return SList(out.split('\n')) | |
2915 |
|
2921 | |||
2916 | def magic_bg(self, parameter_s=''): |
|
2922 | def magic_bg(self, parameter_s=''): | |
2917 | """Run a job in the background, in a separate thread. |
|
2923 | """Run a job in the background, in a separate thread. | |
2918 |
|
2924 | |||
2919 | For example, |
|
2925 | For example, | |
2920 |
|
2926 | |||
2921 | %bg myfunc(x,y,z=1) |
|
2927 | %bg myfunc(x,y,z=1) | |
2922 |
|
2928 | |||
2923 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2929 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
2924 | execution starts, a message will be printed indicating the job |
|
2930 | execution starts, a message will be printed indicating the job | |
2925 | number. If your job number is 5, you can use |
|
2931 | number. If your job number is 5, you can use | |
2926 |
|
2932 | |||
2927 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2933 | myvar = jobs.result(5) or myvar = jobs[5].result | |
2928 |
|
2934 | |||
2929 | to assign this result to variable 'myvar'. |
|
2935 | to assign this result to variable 'myvar'. | |
2930 |
|
2936 | |||
2931 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2937 | IPython has a job manager, accessible via the 'jobs' object. You can | |
2932 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2938 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
2933 | its attributes. All attributes not starting with an underscore are |
|
2939 | its attributes. All attributes not starting with an underscore are | |
2934 | meant for public use. |
|
2940 | meant for public use. | |
2935 |
|
2941 | |||
2936 | In particular, look at the jobs.new() method, which is used to create |
|
2942 | In particular, look at the jobs.new() method, which is used to create | |
2937 | new jobs. This magic %bg function is just a convenience wrapper |
|
2943 | new jobs. This magic %bg function is just a convenience wrapper | |
2938 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2944 | around jobs.new(), for expression-based jobs. If you want to create a | |
2939 | new job with an explicit function object and arguments, you must call |
|
2945 | new job with an explicit function object and arguments, you must call | |
2940 | jobs.new() directly. |
|
2946 | jobs.new() directly. | |
2941 |
|
2947 | |||
2942 | The jobs.new docstring also describes in detail several important |
|
2948 | The jobs.new docstring also describes in detail several important | |
2943 | caveats associated with a thread-based model for background job |
|
2949 | caveats associated with a thread-based model for background job | |
2944 | execution. Type jobs.new? for details. |
|
2950 | execution. Type jobs.new? for details. | |
2945 |
|
2951 | |||
2946 | You can check the status of all jobs with jobs.status(). |
|
2952 | You can check the status of all jobs with jobs.status(). | |
2947 |
|
2953 | |||
2948 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2954 | The jobs variable is set by IPython into the Python builtin namespace. | |
2949 | If you ever declare a variable named 'jobs', you will shadow this |
|
2955 | If you ever declare a variable named 'jobs', you will shadow this | |
2950 | name. You can either delete your global jobs variable to regain |
|
2956 | name. You can either delete your global jobs variable to regain | |
2951 | access to the job manager, or make a new name and assign it manually |
|
2957 | access to the job manager, or make a new name and assign it manually | |
2952 | to the manager (stored in IPython's namespace). For example, to |
|
2958 | to the manager (stored in IPython's namespace). For example, to | |
2953 | assign the job manager to the Jobs name, use: |
|
2959 | assign the job manager to the Jobs name, use: | |
2954 |
|
2960 | |||
2955 | Jobs = __builtins__.jobs""" |
|
2961 | Jobs = __builtins__.jobs""" | |
2956 |
|
2962 | |||
2957 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2963 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
2958 |
|
2964 | |||
2959 |
|
2965 | |||
2960 | def magic_bookmark(self, parameter_s=''): |
|
2966 | def magic_bookmark(self, parameter_s=''): | |
2961 | """Manage IPython's bookmark system. |
|
2967 | """Manage IPython's bookmark system. | |
2962 |
|
2968 | |||
2963 | %bookmark <name> - set bookmark to current dir |
|
2969 | %bookmark <name> - set bookmark to current dir | |
2964 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2970 | %bookmark <name> <dir> - set bookmark to <dir> | |
2965 | %bookmark -l - list all bookmarks |
|
2971 | %bookmark -l - list all bookmarks | |
2966 | %bookmark -d <name> - remove bookmark |
|
2972 | %bookmark -d <name> - remove bookmark | |
2967 | %bookmark -r - remove all bookmarks |
|
2973 | %bookmark -r - remove all bookmarks | |
2968 |
|
2974 | |||
2969 | You can later on access a bookmarked folder with: |
|
2975 | You can later on access a bookmarked folder with: | |
2970 | %cd -b <name> |
|
2976 | %cd -b <name> | |
2971 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2977 | or simply '%cd <name>' if there is no directory called <name> AND | |
2972 | there is such a bookmark defined. |
|
2978 | there is such a bookmark defined. | |
2973 |
|
2979 | |||
2974 | Your bookmarks persist through IPython sessions, but they are |
|
2980 | Your bookmarks persist through IPython sessions, but they are | |
2975 | associated with each profile.""" |
|
2981 | associated with each profile.""" | |
2976 |
|
2982 | |||
2977 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2983 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
2978 | if len(args) > 2: |
|
2984 | if len(args) > 2: | |
2979 | error('You can only give at most two arguments') |
|
2985 | error('You can only give at most two arguments') | |
2980 | return |
|
2986 | return | |
2981 |
|
2987 | |||
2982 | bkms = self.db.get('bookmarks',{}) |
|
2988 | bkms = self.db.get('bookmarks',{}) | |
2983 |
|
2989 | |||
2984 | if opts.has_key('d'): |
|
2990 | if opts.has_key('d'): | |
2985 | try: |
|
2991 | try: | |
2986 | todel = args[0] |
|
2992 | todel = args[0] | |
2987 | except IndexError: |
|
2993 | except IndexError: | |
2988 | error('You must provide a bookmark to delete') |
|
2994 | error('You must provide a bookmark to delete') | |
2989 | else: |
|
2995 | else: | |
2990 | try: |
|
2996 | try: | |
2991 | del bkms[todel] |
|
2997 | del bkms[todel] | |
2992 | except: |
|
2998 | except: | |
2993 | error("Can't delete bookmark '%s'" % todel) |
|
2999 | error("Can't delete bookmark '%s'" % todel) | |
2994 | elif opts.has_key('r'): |
|
3000 | elif opts.has_key('r'): | |
2995 | bkms = {} |
|
3001 | bkms = {} | |
2996 | elif opts.has_key('l'): |
|
3002 | elif opts.has_key('l'): | |
2997 | bks = bkms.keys() |
|
3003 | bks = bkms.keys() | |
2998 | bks.sort() |
|
3004 | bks.sort() | |
2999 | if bks: |
|
3005 | if bks: | |
3000 | size = max(map(len,bks)) |
|
3006 | size = max(map(len,bks)) | |
3001 | else: |
|
3007 | else: | |
3002 | size = 0 |
|
3008 | size = 0 | |
3003 | fmt = '%-'+str(size)+'s -> %s' |
|
3009 | fmt = '%-'+str(size)+'s -> %s' | |
3004 | print 'Current bookmarks:' |
|
3010 | print 'Current bookmarks:' | |
3005 | for bk in bks: |
|
3011 | for bk in bks: | |
3006 | print fmt % (bk,bkms[bk]) |
|
3012 | print fmt % (bk,bkms[bk]) | |
3007 | else: |
|
3013 | else: | |
3008 | if not args: |
|
3014 | if not args: | |
3009 | error("You must specify the bookmark name") |
|
3015 | error("You must specify the bookmark name") | |
3010 | elif len(args)==1: |
|
3016 | elif len(args)==1: | |
3011 | bkms[args[0]] = os.getcwd() |
|
3017 | bkms[args[0]] = os.getcwd() | |
3012 | elif len(args)==2: |
|
3018 | elif len(args)==2: | |
3013 | bkms[args[0]] = args[1] |
|
3019 | bkms[args[0]] = args[1] | |
3014 | self.db['bookmarks'] = bkms |
|
3020 | self.db['bookmarks'] = bkms | |
3015 |
|
3021 | |||
3016 | def magic_pycat(self, parameter_s=''): |
|
3022 | def magic_pycat(self, parameter_s=''): | |
3017 | """Show a syntax-highlighted file through a pager. |
|
3023 | """Show a syntax-highlighted file through a pager. | |
3018 |
|
3024 | |||
3019 | This magic is similar to the cat utility, but it will assume the file |
|
3025 | This magic is similar to the cat utility, but it will assume the file | |
3020 | to be Python source and will show it with syntax highlighting. """ |
|
3026 | to be Python source and will show it with syntax highlighting. """ | |
3021 |
|
3027 | |||
3022 | try: |
|
3028 | try: | |
3023 | filename = get_py_filename(parameter_s) |
|
3029 | filename = get_py_filename(parameter_s) | |
3024 | cont = file_read(filename) |
|
3030 | cont = file_read(filename) | |
3025 | except IOError: |
|
3031 | except IOError: | |
3026 | try: |
|
3032 | try: | |
3027 | cont = eval(parameter_s,self.user_ns) |
|
3033 | cont = eval(parameter_s,self.user_ns) | |
3028 | except NameError: |
|
3034 | except NameError: | |
3029 | cont = None |
|
3035 | cont = None | |
3030 | if cont is None: |
|
3036 | if cont is None: | |
3031 | print "Error: no such file or variable" |
|
3037 | print "Error: no such file or variable" | |
3032 | return |
|
3038 | return | |
3033 |
|
3039 | |||
3034 | page(self.shell.pycolorize(cont), |
|
3040 | page(self.shell.pycolorize(cont), | |
3035 | screen_lines=self.shell.rc.screen_length) |
|
3041 | screen_lines=self.shell.rc.screen_length) | |
3036 |
|
3042 | |||
3037 | def magic_cpaste(self, parameter_s=''): |
|
3043 | def magic_cpaste(self, parameter_s=''): | |
3038 | """Allows you to paste & execute a pre-formatted code block from clipboard |
|
3044 | """Allows you to paste & execute a pre-formatted code block from clipboard | |
3039 |
|
3045 | |||
3040 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3046 | You must terminate the block with '--' (two minus-signs) alone on the | |
3041 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3047 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
3042 | is the new sentinel for this operation) |
|
3048 | is the new sentinel for this operation) | |
3043 |
|
3049 | |||
3044 | The block is dedented prior to execution to enable execution of |
|
3050 | The block is dedented prior to execution to enable execution of | |
3045 | method definitions. '>' characters at the beginning of a line is |
|
3051 | method definitions. '>' characters at the beginning of a line is | |
3046 | ignored, to allow pasting directly from e-mails. The executed block |
|
3052 | ignored, to allow pasting directly from e-mails. The executed block | |
3047 | is also assigned to variable named 'pasted_block' for later editing |
|
3053 | is also assigned to variable named 'pasted_block' for later editing | |
3048 | with '%edit pasted_block'. |
|
3054 | with '%edit pasted_block'. | |
3049 |
|
3055 | |||
3050 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3056 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
3051 | This assigns the pasted block to variable 'foo' as string, without |
|
3057 | This assigns the pasted block to variable 'foo' as string, without | |
3052 | dedenting or executing it. |
|
3058 | dedenting or executing it. | |
3053 |
|
3059 | |||
3054 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3060 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
3055 | Just press enter and type -- (and press enter again) and the block |
|
3061 | Just press enter and type -- (and press enter again) and the block | |
3056 | will be what was just pasted. |
|
3062 | will be what was just pasted. | |
3057 |
|
3063 | |||
3058 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3064 | IPython statements (magics, shell escapes) are not supported (yet). | |
3059 | """ |
|
3065 | """ | |
3060 | opts,args = self.parse_options(parameter_s,'s:',mode='string') |
|
3066 | opts,args = self.parse_options(parameter_s,'s:',mode='string') | |
3061 | par = args.strip() |
|
3067 | par = args.strip() | |
3062 | sentinel = opts.get('s','--') |
|
3068 | sentinel = opts.get('s','--') | |
3063 |
|
3069 | |||
3064 | from IPython import iplib |
|
3070 | from IPython import iplib | |
3065 | lines = [] |
|
3071 | lines = [] | |
3066 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3072 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3067 | while 1: |
|
3073 | while 1: | |
3068 | l = iplib.raw_input_original(':') |
|
3074 | l = iplib.raw_input_original(':') | |
3069 | if l ==sentinel: |
|
3075 | if l ==sentinel: | |
3070 | break |
|
3076 | break | |
3071 | lines.append(l.lstrip('>')) |
|
3077 | lines.append(l.lstrip('>')) | |
3072 | block = "\n".join(lines) + '\n' |
|
3078 | block = "\n".join(lines) + '\n' | |
3073 | #print "block:\n",block |
|
3079 | #print "block:\n",block | |
3074 | if not par: |
|
3080 | if not par: | |
3075 | b = textwrap.dedent(block) |
|
3081 | b = textwrap.dedent(block) | |
3076 | exec b in self.user_ns |
|
3082 | exec b in self.user_ns | |
3077 | self.user_ns['pasted_block'] = b |
|
3083 | self.user_ns['pasted_block'] = b | |
3078 | else: |
|
3084 | else: | |
3079 | self.user_ns[par] = block |
|
3085 | self.user_ns[par] = block | |
3080 | print "Block assigned to '%s'" % par |
|
3086 | print "Block assigned to '%s'" % par | |
3081 |
|
3087 | |||
3082 | def magic_quickref(self,arg): |
|
3088 | def magic_quickref(self,arg): | |
3083 | """ Show a quick reference sheet """ |
|
3089 | """ Show a quick reference sheet """ | |
3084 | import IPython.usage |
|
3090 | import IPython.usage | |
3085 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
3091 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') | |
3086 |
|
3092 | |||
3087 | page(qr) |
|
3093 | page(qr) | |
3088 |
|
3094 | |||
3089 | def magic_upgrade(self,arg): |
|
3095 | def magic_upgrade(self,arg): | |
3090 | """ Upgrade your IPython installation |
|
3096 | """ Upgrade your IPython installation | |
3091 |
|
3097 | |||
3092 | This will copy the config files that don't yet exist in your |
|
3098 | This will copy the config files that don't yet exist in your | |
3093 | ipython dir from the system config dir. Use this after upgrading |
|
3099 | ipython dir from the system config dir. Use this after upgrading | |
3094 | IPython if you don't wish to delete your .ipython dir. |
|
3100 | IPython if you don't wish to delete your .ipython dir. | |
3095 |
|
3101 | |||
3096 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3102 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
3097 | new users) |
|
3103 | new users) | |
3098 |
|
3104 | |||
3099 | """ |
|
3105 | """ | |
3100 | ip = self.getapi() |
|
3106 | ip = self.getapi() | |
3101 | ipinstallation = path(IPython.__file__).dirname() |
|
3107 | ipinstallation = path(IPython.__file__).dirname() | |
3102 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') |
|
3108 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') | |
3103 | src_config = ipinstallation / 'UserConfig' |
|
3109 | src_config = ipinstallation / 'UserConfig' | |
3104 | userdir = path(ip.options.ipythondir) |
|
3110 | userdir = path(ip.options.ipythondir) | |
3105 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3111 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
3106 | print ">",cmd |
|
3112 | print ">",cmd | |
3107 | shell(cmd) |
|
3113 | shell(cmd) | |
3108 | if arg == '-nolegacy': |
|
3114 | if arg == '-nolegacy': | |
3109 | legacy = userdir.files('ipythonrc*') |
|
3115 | legacy = userdir.files('ipythonrc*') | |
3110 | print "Nuking legacy files:",legacy |
|
3116 | print "Nuking legacy files:",legacy | |
3111 |
|
3117 | |||
3112 | [p.remove() for p in legacy] |
|
3118 | [p.remove() for p in legacy] | |
3113 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3119 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
3114 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3120 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
3115 |
|
3121 | |||
3116 | # end Magic |
|
3122 | # end Magic |
@@ -1,84 +1,84 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Release data for the IPython project. |
|
2 | """Release data for the IPython project. | |
3 |
|
3 | |||
4 |
$Id: Release.py 221 |
|
4 | $Id: Release.py 2221 2007-04-06 02:58:37Z fperez $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
8 | # |
|
8 | # | |
9 | # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray |
|
9 | # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray | |
10 | # <n8gray@caltech.edu> |
|
10 | # <n8gray@caltech.edu> | |
11 | # |
|
11 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #***************************************************************************** |
|
14 | #***************************************************************************** | |
15 |
|
15 | |||
16 | # Name of the package for release purposes. This is the name which labels |
|
16 | # Name of the package for release purposes. This is the name which labels | |
17 | # the tarballs and RPMs made by distutils, so it's best to lowercase it. |
|
17 | # the tarballs and RPMs made by distutils, so it's best to lowercase it. | |
18 | name = 'ipython' |
|
18 | name = 'ipython' | |
19 |
|
19 | |||
20 | # For versions with substrings (like 0.6.16.svn), use an extra . to separate |
|
20 | # For versions with substrings (like 0.6.16.svn), use an extra . to separate | |
21 | # the new substring. We have to avoid using either dashes or underscores, |
|
21 | # the new substring. We have to avoid using either dashes or underscores, | |
22 | # because bdist_rpm does not accept dashes (an RPM) convention, and |
|
22 | # because bdist_rpm does not accept dashes (an RPM) convention, and | |
23 | # bdist_deb does not accept underscores (a Debian convention). |
|
23 | # bdist_deb does not accept underscores (a Debian convention). | |
24 |
|
24 | |||
25 | revision = '2191' |
|
25 | revision = '2191' | |
26 |
|
26 | |||
27 | #version = '0.7.4.svn.r' + revision.rstrip('M') |
|
27 | #version = '0.7.4.svn.r' + revision.rstrip('M') | |
28 |
version = '0. |
|
28 | version = '0.8.0' | |
29 |
|
29 | |||
30 | description = "An enhanced interactive Python shell." |
|
30 | description = "An enhanced interactive Python shell." | |
31 |
|
31 | |||
32 | long_description = \ |
|
32 | long_description = \ | |
33 | """ |
|
33 | """ | |
34 | IPython provides a replacement for the interactive Python interpreter with |
|
34 | IPython provides a replacement for the interactive Python interpreter with | |
35 | extra functionality. |
|
35 | extra functionality. | |
36 |
|
36 | |||
37 | Main features: |
|
37 | Main features: | |
38 |
|
38 | |||
39 | * Comprehensive object introspection. |
|
39 | * Comprehensive object introspection. | |
40 |
|
40 | |||
41 | * Input history, persistent across sessions. |
|
41 | * Input history, persistent across sessions. | |
42 |
|
42 | |||
43 | * Caching of output results during a session with automatically generated |
|
43 | * Caching of output results during a session with automatically generated | |
44 | references. |
|
44 | references. | |
45 |
|
45 | |||
46 | * Readline based name completion. |
|
46 | * Readline based name completion. | |
47 |
|
47 | |||
48 | * Extensible system of 'magic' commands for controlling the environment and |
|
48 | * Extensible system of 'magic' commands for controlling the environment and | |
49 | performing many tasks related either to IPython or the operating system. |
|
49 | performing many tasks related either to IPython or the operating system. | |
50 |
|
50 | |||
51 | * Configuration system with easy switching between different setups (simpler |
|
51 | * Configuration system with easy switching between different setups (simpler | |
52 | than changing $PYTHONSTARTUP environment variables every time). |
|
52 | than changing $PYTHONSTARTUP environment variables every time). | |
53 |
|
53 | |||
54 | * Session logging and reloading. |
|
54 | * Session logging and reloading. | |
55 |
|
55 | |||
56 | * Extensible syntax processing for special purpose situations. |
|
56 | * Extensible syntax processing for special purpose situations. | |
57 |
|
57 | |||
58 | * Access to the system shell with user-extensible alias system. |
|
58 | * Access to the system shell with user-extensible alias system. | |
59 |
|
59 | |||
60 | * Easily embeddable in other Python programs. |
|
60 | * Easily embeddable in other Python programs. | |
61 |
|
61 | |||
62 | * Integrated access to the pdb debugger and the Python profiler. |
|
62 | * Integrated access to the pdb debugger and the Python profiler. | |
63 |
|
63 | |||
64 | The latest development version is always available at the IPython subversion |
|
64 | The latest development version is always available at the IPython subversion | |
65 | repository_. |
|
65 | repository_. | |
66 |
|
66 | |||
67 | .. _repository: http://ipython.scipy.org/svn/ipython/ipython/trunk#egg=ipython-dev |
|
67 | .. _repository: http://ipython.scipy.org/svn/ipython/ipython/trunk#egg=ipython-dev | |
68 | """ |
|
68 | """ | |
69 |
|
69 | |||
70 | license = 'BSD' |
|
70 | license = 'BSD' | |
71 |
|
71 | |||
72 | authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'), |
|
72 | authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'), | |
73 | 'Janko' : ('Janko Hauser','jhauser@zscout.de'), |
|
73 | 'Janko' : ('Janko Hauser','jhauser@zscout.de'), | |
74 | 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'), |
|
74 | 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'), | |
75 | 'Ville' : ('Ville Vainio','vivainio@gmail.com') |
|
75 | 'Ville' : ('Ville Vainio','vivainio@gmail.com') | |
76 | } |
|
76 | } | |
77 |
|
77 | |||
78 | url = 'http://ipython.scipy.org' |
|
78 | url = 'http://ipython.scipy.org' | |
79 |
|
79 | |||
80 | download_url = 'http://ipython.scipy.org/dist' |
|
80 | download_url = 'http://ipython.scipy.org/dist' | |
81 |
|
81 | |||
82 | platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME'] |
|
82 | platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME'] | |
83 |
|
83 | |||
84 | keywords = ['Interactive','Interpreter','Shell'] |
|
84 | keywords = ['Interactive','Interpreter','Shell'] |
@@ -1,1134 +1,1123 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """IPython Shell classes. |
|
2 | """IPython Shell classes. | |
3 |
|
3 | |||
4 | All the matplotlib support code was co-developed with John Hunter, |
|
4 | All the matplotlib support code was co-developed with John Hunter, | |
5 | matplotlib's author. |
|
5 | matplotlib's author. | |
6 |
|
6 | |||
7 |
$Id: Shell.py 221 |
|
7 | $Id: Shell.py 2221 2007-04-06 02:58:37Z fperez $""" | |
8 |
|
8 | |||
9 | #***************************************************************************** |
|
9 | #***************************************************************************** | |
10 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
10 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
11 | # |
|
11 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #***************************************************************************** |
|
14 | #***************************************************************************** | |
15 |
|
15 | |||
16 | from IPython import Release |
|
16 | from IPython import Release | |
17 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
17 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
18 | __license__ = Release.license |
|
18 | __license__ = Release.license | |
19 |
|
19 | |||
20 | # Code begins |
|
20 | # Code begins | |
21 | # Stdlib imports |
|
21 | # Stdlib imports | |
22 | import __builtin__ |
|
22 | import __builtin__ | |
23 | import __main__ |
|
23 | import __main__ | |
24 | import Queue |
|
24 | import Queue | |
25 | import inspect |
|
25 | import inspect | |
26 | import os |
|
26 | import os | |
27 | import sys |
|
27 | import sys | |
|
28 | import thread | |||
28 | import threading |
|
29 | import threading | |
29 | import time |
|
30 | import time | |
30 |
|
31 | |||
31 | from signal import signal, SIGINT |
|
32 | from signal import signal, SIGINT | |
32 |
|
33 | |||
33 | try: |
|
34 | try: | |
34 | import ctypes |
|
35 | import ctypes | |
35 | HAS_CTYPES = True |
|
36 | HAS_CTYPES = True | |
36 | except ImportError: |
|
37 | except ImportError: | |
37 | HAS_CTYPES = False |
|
38 | HAS_CTYPES = False | |
38 |
|
39 | |||
39 |
|
||||
40 | # IPython imports |
|
40 | # IPython imports | |
41 | import IPython |
|
41 | import IPython | |
42 | from IPython import ultraTB |
|
42 | from IPython import ultraTB | |
43 | from IPython.genutils import Term,warn,error,flag_calls |
|
43 | from IPython.genutils import Term,warn,error,flag_calls | |
44 | from IPython.iplib import InteractiveShell |
|
44 | from IPython.iplib import InteractiveShell | |
45 | from IPython.ipmaker import make_IPython |
|
45 | from IPython.ipmaker import make_IPython | |
46 | from IPython.Magic import Magic |
|
46 | from IPython.Magic import Magic | |
47 | from IPython.ipstruct import Struct |
|
47 | from IPython.ipstruct import Struct | |
48 |
|
48 | |||
49 | # Globals |
|
49 | # Globals | |
50 | # global flag to pass around information about Ctrl-C without exceptions |
|
50 | # global flag to pass around information about Ctrl-C without exceptions | |
51 | KBINT = False |
|
51 | KBINT = False | |
52 |
|
52 | |||
53 | # global flag to turn on/off Tk support. |
|
53 | # global flag to turn on/off Tk support. | |
54 | USE_TK = False |
|
54 | USE_TK = False | |
55 |
|
55 | |||
56 | # ID for the main thread, used for cross-thread exceptions |
|
56 | # ID for the main thread, used for cross-thread exceptions | |
57 |
MAIN_THREAD_ID = |
|
57 | MAIN_THREAD_ID = thread.get_ident() | |
58 |
|
58 | |||
59 | # Tag when runcode() is active, for exception handling |
|
59 | # Tag when runcode() is active, for exception handling | |
60 | CODE_RUN = None |
|
60 | CODE_RUN = None | |
61 |
|
61 | |||
62 | #----------------------------------------------------------------------------- |
|
62 | #----------------------------------------------------------------------------- | |
63 | # This class is trivial now, but I want to have it in to publish a clean |
|
63 | # This class is trivial now, but I want to have it in to publish a clean | |
64 | # interface. Later when the internals are reorganized, code that uses this |
|
64 | # interface. Later when the internals are reorganized, code that uses this | |
65 | # shouldn't have to change. |
|
65 | # shouldn't have to change. | |
66 |
|
66 | |||
67 | class IPShell: |
|
67 | class IPShell: | |
68 | """Create an IPython instance.""" |
|
68 | """Create an IPython instance.""" | |
69 |
|
69 | |||
70 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
70 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, | |
71 | debug=1,shell_class=InteractiveShell): |
|
71 | debug=1,shell_class=InteractiveShell): | |
72 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
72 | self.IP = make_IPython(argv,user_ns=user_ns, | |
73 | user_global_ns=user_global_ns, |
|
73 | user_global_ns=user_global_ns, | |
74 | debug=debug,shell_class=shell_class) |
|
74 | debug=debug,shell_class=shell_class) | |
75 |
|
75 | |||
76 | def mainloop(self,sys_exit=0,banner=None): |
|
76 | def mainloop(self,sys_exit=0,banner=None): | |
77 | self.IP.mainloop(banner) |
|
77 | self.IP.mainloop(banner) | |
78 | if sys_exit: |
|
78 | if sys_exit: | |
79 | sys.exit() |
|
79 | sys.exit() | |
80 |
|
80 | |||
81 | #----------------------------------------------------------------------------- |
|
81 | #----------------------------------------------------------------------------- | |
82 | class IPShellEmbed: |
|
82 | class IPShellEmbed: | |
83 | """Allow embedding an IPython shell into a running program. |
|
83 | """Allow embedding an IPython shell into a running program. | |
84 |
|
84 | |||
85 | Instances of this class are callable, with the __call__ method being an |
|
85 | Instances of this class are callable, with the __call__ method being an | |
86 | alias to the embed() method of an InteractiveShell instance. |
|
86 | alias to the embed() method of an InteractiveShell instance. | |
87 |
|
87 | |||
88 | Usage (see also the example-embed.py file for a running example): |
|
88 | Usage (see also the example-embed.py file for a running example): | |
89 |
|
89 | |||
90 | ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override]) |
|
90 | ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override]) | |
91 |
|
91 | |||
92 | - argv: list containing valid command-line options for IPython, as they |
|
92 | - argv: list containing valid command-line options for IPython, as they | |
93 | would appear in sys.argv[1:]. |
|
93 | would appear in sys.argv[1:]. | |
94 |
|
94 | |||
95 | For example, the following command-line options: |
|
95 | For example, the following command-line options: | |
96 |
|
96 | |||
97 | $ ipython -prompt_in1 'Input <\\#>' -colors LightBG |
|
97 | $ ipython -prompt_in1 'Input <\\#>' -colors LightBG | |
98 |
|
98 | |||
99 | would be passed in the argv list as: |
|
99 | would be passed in the argv list as: | |
100 |
|
100 | |||
101 | ['-prompt_in1','Input <\\#>','-colors','LightBG'] |
|
101 | ['-prompt_in1','Input <\\#>','-colors','LightBG'] | |
102 |
|
102 | |||
103 | - banner: string which gets printed every time the interpreter starts. |
|
103 | - banner: string which gets printed every time the interpreter starts. | |
104 |
|
104 | |||
105 | - exit_msg: string which gets printed every time the interpreter exits. |
|
105 | - exit_msg: string which gets printed every time the interpreter exits. | |
106 |
|
106 | |||
107 | - rc_override: a dict or Struct of configuration options such as those |
|
107 | - rc_override: a dict or Struct of configuration options such as those | |
108 | used by IPython. These options are read from your ~/.ipython/ipythonrc |
|
108 | used by IPython. These options are read from your ~/.ipython/ipythonrc | |
109 | file when the Shell object is created. Passing an explicit rc_override |
|
109 | file when the Shell object is created. Passing an explicit rc_override | |
110 | dict with any options you want allows you to override those values at |
|
110 | dict with any options you want allows you to override those values at | |
111 | creation time without having to modify the file. This way you can create |
|
111 | creation time without having to modify the file. This way you can create | |
112 | embeddable instances configured in any way you want without editing any |
|
112 | embeddable instances configured in any way you want without editing any | |
113 | global files (thus keeping your interactive IPython configuration |
|
113 | global files (thus keeping your interactive IPython configuration | |
114 | unchanged). |
|
114 | unchanged). | |
115 |
|
115 | |||
116 | Then the ipshell instance can be called anywhere inside your code: |
|
116 | Then the ipshell instance can be called anywhere inside your code: | |
117 |
|
117 | |||
118 | ipshell(header='') -> Opens up an IPython shell. |
|
118 | ipshell(header='') -> Opens up an IPython shell. | |
119 |
|
119 | |||
120 | - header: string printed by the IPython shell upon startup. This can let |
|
120 | - header: string printed by the IPython shell upon startup. This can let | |
121 | you know where in your code you are when dropping into the shell. Note |
|
121 | you know where in your code you are when dropping into the shell. Note | |
122 | that 'banner' gets prepended to all calls, so header is used for |
|
122 | that 'banner' gets prepended to all calls, so header is used for | |
123 | location-specific information. |
|
123 | location-specific information. | |
124 |
|
124 | |||
125 | For more details, see the __call__ method below. |
|
125 | For more details, see the __call__ method below. | |
126 |
|
126 | |||
127 | When the IPython shell is exited with Ctrl-D, normal program execution |
|
127 | When the IPython shell is exited with Ctrl-D, normal program execution | |
128 | resumes. |
|
128 | resumes. | |
129 |
|
129 | |||
130 | This functionality was inspired by a posting on comp.lang.python by cmkl |
|
130 | This functionality was inspired by a posting on comp.lang.python by cmkl | |
131 | <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and |
|
131 | <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and | |
132 | by the IDL stop/continue commands.""" |
|
132 | by the IDL stop/continue commands.""" | |
133 |
|
133 | |||
134 | def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None, |
|
134 | def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None, | |
135 | user_ns=None): |
|
135 | user_ns=None): | |
136 | """Note that argv here is a string, NOT a list.""" |
|
136 | """Note that argv here is a string, NOT a list.""" | |
137 | self.set_banner(banner) |
|
137 | self.set_banner(banner) | |
138 | self.set_exit_msg(exit_msg) |
|
138 | self.set_exit_msg(exit_msg) | |
139 | self.set_dummy_mode(0) |
|
139 | self.set_dummy_mode(0) | |
140 |
|
140 | |||
141 | # sys.displayhook is a global, we need to save the user's original |
|
141 | # sys.displayhook is a global, we need to save the user's original | |
142 | # Don't rely on __displayhook__, as the user may have changed that. |
|
142 | # Don't rely on __displayhook__, as the user may have changed that. | |
143 | self.sys_displayhook_ori = sys.displayhook |
|
143 | self.sys_displayhook_ori = sys.displayhook | |
144 |
|
144 | |||
145 | # save readline completer status |
|
145 | # save readline completer status | |
146 | try: |
|
146 | try: | |
147 | #print 'Save completer',sys.ipcompleter # dbg |
|
147 | #print 'Save completer',sys.ipcompleter # dbg | |
148 | self.sys_ipcompleter_ori = sys.ipcompleter |
|
148 | self.sys_ipcompleter_ori = sys.ipcompleter | |
149 | except: |
|
149 | except: | |
150 | pass # not nested with IPython |
|
150 | pass # not nested with IPython | |
151 |
|
151 | |||
152 | self.IP = make_IPython(argv,rc_override=rc_override, |
|
152 | self.IP = make_IPython(argv,rc_override=rc_override, | |
153 | embedded=True, |
|
153 | embedded=True, | |
154 | user_ns=user_ns) |
|
154 | user_ns=user_ns) | |
155 |
|
155 | |||
156 | # copy our own displayhook also |
|
156 | # copy our own displayhook also | |
157 | self.sys_displayhook_embed = sys.displayhook |
|
157 | self.sys_displayhook_embed = sys.displayhook | |
158 | # and leave the system's display hook clean |
|
158 | # and leave the system's display hook clean | |
159 | sys.displayhook = self.sys_displayhook_ori |
|
159 | sys.displayhook = self.sys_displayhook_ori | |
160 | # don't use the ipython crash handler so that user exceptions aren't |
|
160 | # don't use the ipython crash handler so that user exceptions aren't | |
161 | # trapped |
|
161 | # trapped | |
162 | sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors, |
|
162 | sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors, | |
163 | mode = self.IP.rc.xmode, |
|
163 | mode = self.IP.rc.xmode, | |
164 | call_pdb = self.IP.rc.pdb) |
|
164 | call_pdb = self.IP.rc.pdb) | |
165 | self.restore_system_completer() |
|
165 | self.restore_system_completer() | |
166 |
|
166 | |||
167 | def restore_system_completer(self): |
|
167 | def restore_system_completer(self): | |
168 | """Restores the readline completer which was in place. |
|
168 | """Restores the readline completer which was in place. | |
169 |
|
169 | |||
170 | This allows embedded IPython within IPython not to disrupt the |
|
170 | This allows embedded IPython within IPython not to disrupt the | |
171 | parent's completion. |
|
171 | parent's completion. | |
172 | """ |
|
172 | """ | |
173 |
|
173 | |||
174 | try: |
|
174 | try: | |
175 | self.IP.readline.set_completer(self.sys_ipcompleter_ori) |
|
175 | self.IP.readline.set_completer(self.sys_ipcompleter_ori) | |
176 | sys.ipcompleter = self.sys_ipcompleter_ori |
|
176 | sys.ipcompleter = self.sys_ipcompleter_ori | |
177 | except: |
|
177 | except: | |
178 | pass |
|
178 | pass | |
179 |
|
179 | |||
180 | def __call__(self,header='',local_ns=None,global_ns=None,dummy=None): |
|
180 | def __call__(self,header='',local_ns=None,global_ns=None,dummy=None): | |
181 | """Activate the interactive interpreter. |
|
181 | """Activate the interactive interpreter. | |
182 |
|
182 | |||
183 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start |
|
183 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start | |
184 | the interpreter shell with the given local and global namespaces, and |
|
184 | the interpreter shell with the given local and global namespaces, and | |
185 | optionally print a header string at startup. |
|
185 | optionally print a header string at startup. | |
186 |
|
186 | |||
187 | The shell can be globally activated/deactivated using the |
|
187 | The shell can be globally activated/deactivated using the | |
188 | set/get_dummy_mode methods. This allows you to turn off a shell used |
|
188 | set/get_dummy_mode methods. This allows you to turn off a shell used | |
189 | for debugging globally. |
|
189 | for debugging globally. | |
190 |
|
190 | |||
191 | However, *each* time you call the shell you can override the current |
|
191 | However, *each* time you call the shell you can override the current | |
192 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
192 | state of dummy_mode with the optional keyword parameter 'dummy'. For | |
193 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you |
|
193 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you | |
194 | can still have a specific call work by making it as IPShell(dummy=0). |
|
194 | can still have a specific call work by making it as IPShell(dummy=0). | |
195 |
|
195 | |||
196 | The optional keyword parameter dummy controls whether the call |
|
196 | The optional keyword parameter dummy controls whether the call | |
197 | actually does anything. """ |
|
197 | actually does anything. """ | |
198 |
|
198 | |||
199 | # Allow the dummy parameter to override the global __dummy_mode |
|
199 | # Allow the dummy parameter to override the global __dummy_mode | |
200 | if dummy or (dummy != 0 and self.__dummy_mode): |
|
200 | if dummy or (dummy != 0 and self.__dummy_mode): | |
201 | return |
|
201 | return | |
202 |
|
202 | |||
203 | # Set global subsystems (display,completions) to our values |
|
203 | # Set global subsystems (display,completions) to our values | |
204 | sys.displayhook = self.sys_displayhook_embed |
|
204 | sys.displayhook = self.sys_displayhook_embed | |
205 | if self.IP.has_readline: |
|
205 | if self.IP.has_readline: | |
206 |
self.IP. |
|
206 | self.IP.set_completer() | |
207 |
|
207 | |||
208 | if self.banner and header: |
|
208 | if self.banner and header: | |
209 | format = '%s\n%s\n' |
|
209 | format = '%s\n%s\n' | |
210 | else: |
|
210 | else: | |
211 | format = '%s%s\n' |
|
211 | format = '%s%s\n' | |
212 | banner = format % (self.banner,header) |
|
212 | banner = format % (self.banner,header) | |
213 |
|
213 | |||
214 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
214 | # Call the embedding code with a stack depth of 1 so it can skip over | |
215 | # our call and get the original caller's namespaces. |
|
215 | # our call and get the original caller's namespaces. | |
216 | self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1) |
|
216 | self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1) | |
217 |
|
217 | |||
218 | if self.exit_msg: |
|
218 | if self.exit_msg: | |
219 | print self.exit_msg |
|
219 | print self.exit_msg | |
220 |
|
220 | |||
221 | # Restore global systems (display, completion) |
|
221 | # Restore global systems (display, completion) | |
222 | sys.displayhook = self.sys_displayhook_ori |
|
222 | sys.displayhook = self.sys_displayhook_ori | |
223 | self.restore_system_completer() |
|
223 | self.restore_system_completer() | |
224 |
|
224 | |||
225 | def set_dummy_mode(self,dummy): |
|
225 | def set_dummy_mode(self,dummy): | |
226 | """Sets the embeddable shell's dummy mode parameter. |
|
226 | """Sets the embeddable shell's dummy mode parameter. | |
227 |
|
227 | |||
228 | set_dummy_mode(dummy): dummy = 0 or 1. |
|
228 | set_dummy_mode(dummy): dummy = 0 or 1. | |
229 |
|
229 | |||
230 | This parameter is persistent and makes calls to the embeddable shell |
|
230 | This parameter is persistent and makes calls to the embeddable shell | |
231 | silently return without performing any action. This allows you to |
|
231 | silently return without performing any action. This allows you to | |
232 | globally activate or deactivate a shell you're using with a single call. |
|
232 | globally activate or deactivate a shell you're using with a single call. | |
233 |
|
233 | |||
234 | If you need to manually""" |
|
234 | If you need to manually""" | |
235 |
|
235 | |||
236 | if dummy not in [0,1,False,True]: |
|
236 | if dummy not in [0,1,False,True]: | |
237 | raise ValueError,'dummy parameter must be boolean' |
|
237 | raise ValueError,'dummy parameter must be boolean' | |
238 | self.__dummy_mode = dummy |
|
238 | self.__dummy_mode = dummy | |
239 |
|
239 | |||
240 | def get_dummy_mode(self): |
|
240 | def get_dummy_mode(self): | |
241 | """Return the current value of the dummy mode parameter. |
|
241 | """Return the current value of the dummy mode parameter. | |
242 | """ |
|
242 | """ | |
243 | return self.__dummy_mode |
|
243 | return self.__dummy_mode | |
244 |
|
244 | |||
245 | def set_banner(self,banner): |
|
245 | def set_banner(self,banner): | |
246 | """Sets the global banner. |
|
246 | """Sets the global banner. | |
247 |
|
247 | |||
248 | This banner gets prepended to every header printed when the shell |
|
248 | This banner gets prepended to every header printed when the shell | |
249 | instance is called.""" |
|
249 | instance is called.""" | |
250 |
|
250 | |||
251 | self.banner = banner |
|
251 | self.banner = banner | |
252 |
|
252 | |||
253 | def set_exit_msg(self,exit_msg): |
|
253 | def set_exit_msg(self,exit_msg): | |
254 | """Sets the global exit_msg. |
|
254 | """Sets the global exit_msg. | |
255 |
|
255 | |||
256 | This exit message gets printed upon exiting every time the embedded |
|
256 | This exit message gets printed upon exiting every time the embedded | |
257 | shell is called. It is None by default. """ |
|
257 | shell is called. It is None by default. """ | |
258 |
|
258 | |||
259 | self.exit_msg = exit_msg |
|
259 | self.exit_msg = exit_msg | |
260 |
|
260 | |||
261 | #----------------------------------------------------------------------------- |
|
261 | #----------------------------------------------------------------------------- | |
262 | if HAS_CTYPES: |
|
262 | if HAS_CTYPES: | |
263 | # Add async exception support. Trick taken from: |
|
263 | # Add async exception support. Trick taken from: | |
264 | # http://sebulba.wikispaces.com/recipe+thread2 |
|
264 | # http://sebulba.wikispaces.com/recipe+thread2 | |
265 | def _async_raise(tid, exctype): |
|
265 | def _async_raise(tid, exctype): | |
266 | """raises the exception, performs cleanup if needed""" |
|
266 | """raises the exception, performs cleanup if needed""" | |
267 | if not inspect.isclass(exctype): |
|
267 | if not inspect.isclass(exctype): | |
268 | raise TypeError("Only types can be raised (not instances)") |
|
268 | raise TypeError("Only types can be raised (not instances)") | |
269 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, |
|
269 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, | |
270 | ctypes.py_object(exctype)) |
|
270 | ctypes.py_object(exctype)) | |
271 | if res == 0: |
|
271 | if res == 0: | |
272 | raise ValueError("invalid thread id") |
|
272 | raise ValueError("invalid thread id") | |
273 | elif res != 1: |
|
273 | elif res != 1: | |
274 | # """if it returns a number greater than one, you're in trouble, |
|
274 | # """if it returns a number greater than one, you're in trouble, | |
275 | # and you should call it again with exc=NULL to revert the effect""" |
|
275 | # and you should call it again with exc=NULL to revert the effect""" | |
276 | ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) |
|
276 | ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) | |
277 | raise SystemError("PyThreadState_SetAsyncExc failed") |
|
277 | raise SystemError("PyThreadState_SetAsyncExc failed") | |
278 |
|
278 | |||
279 | def sigint_handler (signum,stack_frame): |
|
279 | def sigint_handler (signum,stack_frame): | |
280 | """Sigint handler for threaded apps. |
|
280 | """Sigint handler for threaded apps. | |
281 |
|
281 | |||
282 | This is a horrible hack to pass information about SIGINT _without_ |
|
282 | This is a horrible hack to pass information about SIGINT _without_ | |
283 | using exceptions, since I haven't been able to properly manage |
|
283 | using exceptions, since I haven't been able to properly manage | |
284 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be |
|
284 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be | |
285 | done (or at least that's my understanding from a c.l.py thread where |
|
285 | done (or at least that's my understanding from a c.l.py thread where | |
286 | this was discussed).""" |
|
286 | this was discussed).""" | |
287 |
|
287 | |||
288 | global KBINT |
|
288 | global KBINT | |
289 |
|
289 | |||
290 | if CODE_RUN: |
|
290 | if CODE_RUN: | |
291 | _async_raise(MAIN_THREAD_ID,KeyboardInterrupt) |
|
291 | _async_raise(MAIN_THREAD_ID,KeyboardInterrupt) | |
292 | else: |
|
292 | else: | |
293 | KBINT = True |
|
293 | KBINT = True | |
294 | print '\nKeyboardInterrupt - Press <Enter> to continue.', |
|
294 | print '\nKeyboardInterrupt - Press <Enter> to continue.', | |
295 | Term.cout.flush() |
|
295 | Term.cout.flush() | |
296 |
|
296 | |||
297 | else: |
|
297 | else: | |
298 | def sigint_handler (signum,stack_frame): |
|
298 | def sigint_handler (signum,stack_frame): | |
299 | """Sigint handler for threaded apps. |
|
299 | """Sigint handler for threaded apps. | |
300 |
|
300 | |||
301 | This is a horrible hack to pass information about SIGINT _without_ |
|
301 | This is a horrible hack to pass information about SIGINT _without_ | |
302 | using exceptions, since I haven't been able to properly manage |
|
302 | using exceptions, since I haven't been able to properly manage | |
303 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be |
|
303 | cross-thread exceptions in GTK/WX. In fact, I don't think it can be | |
304 | done (or at least that's my understanding from a c.l.py thread where |
|
304 | done (or at least that's my understanding from a c.l.py thread where | |
305 | this was discussed).""" |
|
305 | this was discussed).""" | |
306 |
|
306 | |||
307 | global KBINT |
|
307 | global KBINT | |
308 |
|
308 | |||
309 | print '\nKeyboardInterrupt - Press <Enter> to continue.', |
|
309 | print '\nKeyboardInterrupt - Press <Enter> to continue.', | |
310 | Term.cout.flush() |
|
310 | Term.cout.flush() | |
311 | # Set global flag so that runsource can know that Ctrl-C was hit |
|
311 | # Set global flag so that runsource can know that Ctrl-C was hit | |
312 | KBINT = True |
|
312 | KBINT = True | |
313 |
|
313 | |||
314 |
|
314 | |||
315 | def _set_main_thread_id(): |
|
|||
316 | """Ugly hack to find the main thread's ID. |
|
|||
317 | """ |
|
|||
318 | global MAIN_THREAD_ID |
|
|||
319 | for tid, tobj in threading._active.items(): |
|
|||
320 | # There must be a better way to do this than looking at the str() for |
|
|||
321 | # each thread object... |
|
|||
322 | if 'MainThread' in str(tobj): |
|
|||
323 | #print 'main tid:',tid # dbg |
|
|||
324 | MAIN_THREAD_ID = tid |
|
|||
325 | break |
|
|||
326 |
|
||||
327 | class MTInteractiveShell(InteractiveShell): |
|
315 | class MTInteractiveShell(InteractiveShell): | |
328 | """Simple multi-threaded shell.""" |
|
316 | """Simple multi-threaded shell.""" | |
329 |
|
317 | |||
330 | # Threading strategy taken from: |
|
318 | # Threading strategy taken from: | |
331 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian |
|
319 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian | |
332 | # McErlean and John Finlay. Modified with corrections by Antoon Pardon, |
|
320 | # McErlean and John Finlay. Modified with corrections by Antoon Pardon, | |
333 | # from the pygtk mailing list, to avoid lockups with system calls. |
|
321 | # from the pygtk mailing list, to avoid lockups with system calls. | |
334 |
|
322 | |||
335 | # class attribute to indicate whether the class supports threads or not. |
|
323 | # class attribute to indicate whether the class supports threads or not. | |
336 | # Subclasses with thread support should override this as needed. |
|
324 | # Subclasses with thread support should override this as needed. | |
337 | isthreaded = True |
|
325 | isthreaded = True | |
338 |
|
326 | |||
339 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
327 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
340 | user_ns=None,user_global_ns=None,banner2='',**kw): |
|
328 | user_ns=None,user_global_ns=None,banner2='',**kw): | |
341 | """Similar to the normal InteractiveShell, but with threading control""" |
|
329 | """Similar to the normal InteractiveShell, but with threading control""" | |
342 |
|
330 | |||
343 | InteractiveShell.__init__(self,name,usage,rc,user_ns, |
|
331 | InteractiveShell.__init__(self,name,usage,rc,user_ns, | |
344 | user_global_ns,banner2) |
|
332 | user_global_ns,banner2) | |
345 |
|
333 | |||
346 | # Locking control variable. We need to use a norma lock, not an RLock |
|
334 | # Locking control variable. We need to use a norma lock, not an RLock | |
347 | # here. I'm not exactly sure why, it seems to me like it should be |
|
335 | # here. I'm not exactly sure why, it seems to me like it should be | |
348 | # the opposite, but we deadlock with an RLock. Puzzled... |
|
336 | # the opposite, but we deadlock with an RLock. Puzzled... | |
349 | self.thread_ready = threading.Condition(threading.Lock()) |
|
337 | self.thread_ready = threading.Condition(threading.Lock()) | |
350 |
|
338 | |||
351 | # A queue to hold the code to be executed. A scalar variable is NOT |
|
339 | # A queue to hold the code to be executed. A scalar variable is NOT | |
352 | # enough, because uses like macros cause reentrancy. |
|
340 | # enough, because uses like macros cause reentrancy. | |
353 | self.code_queue = Queue.Queue() |
|
341 | self.code_queue = Queue.Queue() | |
|
342 | ||||
|
343 | # Track once we properly install our special sigint handler | |||
|
344 | self._sigint_handler_not_ready = True | |||
354 |
|
345 | |||
355 | # Stuff to do at closing time |
|
346 | # Stuff to do at closing time | |
356 | self._kill = False |
|
347 | self._kill = False | |
357 | on_kill = kw.get('on_kill') |
|
348 | on_kill = kw.get('on_kill') | |
358 | if on_kill is None: |
|
349 | if on_kill is None: | |
359 | on_kill = [] |
|
350 | on_kill = [] | |
360 | # Check that all things to kill are callable: |
|
351 | # Check that all things to kill are callable: | |
361 | for t in on_kill: |
|
352 | for t in on_kill: | |
362 | if not callable(t): |
|
353 | if not callable(t): | |
363 | raise TypeError,'on_kill must be a list of callables' |
|
354 | raise TypeError,'on_kill must be a list of callables' | |
364 | self.on_kill = on_kill |
|
355 | self.on_kill = on_kill | |
365 |
|
356 | |||
366 | def runsource(self, source, filename="<input>", symbol="single"): |
|
357 | def runsource(self, source, filename="<input>", symbol="single"): | |
367 | """Compile and run some source in the interpreter. |
|
358 | """Compile and run some source in the interpreter. | |
368 |
|
359 | |||
369 | Modified version of code.py's runsource(), to handle threading issues. |
|
360 | Modified version of code.py's runsource(), to handle threading issues. | |
370 | See the original for full docstring details.""" |
|
361 | See the original for full docstring details.""" | |
371 |
|
362 | |||
372 | global KBINT |
|
363 | global KBINT | |
373 |
|
364 | |||
374 | # If Ctrl-C was typed, we reset the flag and return right away |
|
365 | # If Ctrl-C was typed, we reset the flag and return right away | |
375 | if KBINT: |
|
366 | if KBINT: | |
376 | KBINT = False |
|
367 | KBINT = False | |
377 | return False |
|
368 | return False | |
378 |
|
369 | |||
379 | try: |
|
370 | try: | |
380 | code = self.compile(source, filename, symbol) |
|
371 | code = self.compile(source, filename, symbol) | |
381 | except (OverflowError, SyntaxError, ValueError): |
|
372 | except (OverflowError, SyntaxError, ValueError): | |
382 | # Case 1 |
|
373 | # Case 1 | |
383 | self.showsyntaxerror(filename) |
|
374 | self.showsyntaxerror(filename) | |
384 | return False |
|
375 | return False | |
385 |
|
376 | |||
386 | if code is None: |
|
377 | if code is None: | |
387 | # Case 2 |
|
378 | # Case 2 | |
388 | return True |
|
379 | return True | |
389 |
|
380 | |||
390 | # Case 3 |
|
381 | # Case 3 | |
391 | # Store code in queue, so the execution thread can handle it. |
|
382 | # Store code in queue, so the execution thread can handle it. | |
392 |
|
383 | |||
393 | # Note that with macros and other applications, we MAY re-enter this |
|
384 | # Note that with macros and other applications, we MAY re-enter this | |
394 | # section, so we have to acquire the lock with non-blocking semantics, |
|
385 | # section, so we have to acquire the lock with non-blocking semantics, | |
395 | # else we deadlock. |
|
386 | # else we deadlock. | |
396 | got_lock = self.thread_ready.acquire(False) |
|
387 | got_lock = self.thread_ready.acquire(False) | |
397 | self.code_queue.put(code) |
|
388 | self.code_queue.put(code) | |
398 | if got_lock: |
|
389 | if got_lock: | |
399 | self.thread_ready.wait() # Wait until processed in timeout interval |
|
390 | self.thread_ready.wait() # Wait until processed in timeout interval | |
400 | self.thread_ready.release() |
|
391 | self.thread_ready.release() | |
401 |
|
392 | |||
402 | return False |
|
393 | return False | |
403 |
|
394 | |||
404 | def runcode(self): |
|
395 | def runcode(self): | |
405 | """Execute a code object. |
|
396 | """Execute a code object. | |
406 |
|
397 | |||
407 | Multithreaded wrapper around IPython's runcode().""" |
|
398 | Multithreaded wrapper around IPython's runcode().""" | |
408 |
|
399 | |||
409 |
|
||||
410 | global CODE_RUN |
|
400 | global CODE_RUN | |
411 |
|
401 | |||
412 | # Exceptions need to be raised differently depending on which thread is |
|
402 | # Exceptions need to be raised differently depending on which thread is | |
413 | # active |
|
403 | # active | |
414 | CODE_RUN = True |
|
404 | CODE_RUN = True | |
415 |
|
405 | |||
416 | # lock thread-protected stuff |
|
406 | # lock thread-protected stuff | |
417 | got_lock = self.thread_ready.acquire(False) |
|
407 | got_lock = self.thread_ready.acquire(False) | |
418 |
|
408 | |||
419 | if self._kill: |
|
409 | if self._kill: | |
420 | print >>Term.cout, 'Closing threads...', |
|
410 | print >>Term.cout, 'Closing threads...', | |
421 | Term.cout.flush() |
|
411 | Term.cout.flush() | |
422 | for tokill in self.on_kill: |
|
412 | for tokill in self.on_kill: | |
423 | tokill() |
|
413 | tokill() | |
424 | print >>Term.cout, 'Done.' |
|
414 | print >>Term.cout, 'Done.' | |
425 |
|
415 | |||
426 |
# Install sigint handler. It feels stupid to |
|
416 | # Install sigint handler. It feels stupid to test this on every single | |
427 | # pass |
|
417 | # pass. At least we keep track of having done it before... We use a | |
428 | try: |
|
418 | # negative variable so we don't have to call 'not' every time | |
429 |
|
|
419 | if self._sigint_handler_not_ready: | |
430 | except SystemError: |
|
420 | # Try only once... | |
431 | # This happens under Windows, which seems to have all sorts |
|
421 | self._sigint_handler_not_ready = False | |
432 | # of problems with signal handling. Oh well... |
|
422 | try: | |
433 | pass |
|
423 | signal(SIGINT,sigint_handler) | |
|
424 | except SystemError: | |||
|
425 | # This happens under Windows, which seems to have all sorts | |||
|
426 | # of problems with signal handling. Oh well... | |||
|
427 | pass | |||
434 |
|
428 | |||
435 | # Flush queue of pending code by calling the run methood of the parent |
|
429 | # Flush queue of pending code by calling the run methood of the parent | |
436 | # class with all items which may be in the queue. |
|
430 | # class with all items which may be in the queue. | |
437 | while 1: |
|
431 | while 1: | |
438 | try: |
|
432 | try: | |
439 | code_to_run = self.code_queue.get_nowait() |
|
433 | code_to_run = self.code_queue.get_nowait() | |
440 | except Queue.Empty: |
|
434 | except Queue.Empty: | |
441 | break |
|
435 | break | |
442 | if got_lock: |
|
436 | if got_lock: | |
443 | self.thread_ready.notify() |
|
437 | self.thread_ready.notify() | |
444 | InteractiveShell.runcode(self,code_to_run) |
|
438 | InteractiveShell.runcode(self,code_to_run) | |
445 | else: |
|
439 | else: | |
446 | break |
|
440 | break | |
447 |
|
441 | |||
448 | # We're done with thread-protected variables |
|
442 | # We're done with thread-protected variables | |
449 | if got_lock: |
|
443 | if got_lock: | |
450 | self.thread_ready.release() |
|
444 | self.thread_ready.release() | |
451 |
|
445 | |||
452 | # We're done... |
|
446 | # We're done... | |
453 | CODE_RUN = False |
|
447 | CODE_RUN = False | |
454 | # This MUST return true for gtk threading to work |
|
448 | # This MUST return true for gtk threading to work | |
455 | return True |
|
449 | return True | |
456 |
|
450 | |||
457 | def kill(self): |
|
451 | def kill(self): | |
458 | """Kill the thread, returning when it has been shut down.""" |
|
452 | """Kill the thread, returning when it has been shut down.""" | |
459 | got_lock = self.thread_ready.acquire(False) |
|
453 | got_lock = self.thread_ready.acquire(False) | |
460 | self._kill = True |
|
454 | self._kill = True | |
461 | if got_lock: |
|
455 | if got_lock: | |
462 | self.thread_ready.release() |
|
456 | self.thread_ready.release() | |
463 |
|
457 | |||
464 | class MatplotlibShellBase: |
|
458 | class MatplotlibShellBase: | |
465 | """Mixin class to provide the necessary modifications to regular IPython |
|
459 | """Mixin class to provide the necessary modifications to regular IPython | |
466 | shell classes for matplotlib support. |
|
460 | shell classes for matplotlib support. | |
467 |
|
461 | |||
468 | Given Python's MRO, this should be used as the FIRST class in the |
|
462 | Given Python's MRO, this should be used as the FIRST class in the | |
469 | inheritance hierarchy, so that it overrides the relevant methods.""" |
|
463 | inheritance hierarchy, so that it overrides the relevant methods.""" | |
470 |
|
464 | |||
471 | def _matplotlib_config(self,name,user_ns): |
|
465 | def _matplotlib_config(self,name,user_ns): | |
472 | """Return items needed to setup the user's shell with matplotlib""" |
|
466 | """Return items needed to setup the user's shell with matplotlib""" | |
473 |
|
467 | |||
474 | # Initialize matplotlib to interactive mode always |
|
468 | # Initialize matplotlib to interactive mode always | |
475 | import matplotlib |
|
469 | import matplotlib | |
476 | from matplotlib import backends |
|
470 | from matplotlib import backends | |
477 | matplotlib.interactive(True) |
|
471 | matplotlib.interactive(True) | |
478 |
|
472 | |||
479 | def use(arg): |
|
473 | def use(arg): | |
480 | """IPython wrapper for matplotlib's backend switcher. |
|
474 | """IPython wrapper for matplotlib's backend switcher. | |
481 |
|
475 | |||
482 | In interactive use, we can not allow switching to a different |
|
476 | In interactive use, we can not allow switching to a different | |
483 | interactive backend, since thread conflicts will most likely crash |
|
477 | interactive backend, since thread conflicts will most likely crash | |
484 | the python interpreter. This routine does a safety check first, |
|
478 | the python interpreter. This routine does a safety check first, | |
485 | and refuses to perform a dangerous switch. It still allows |
|
479 | and refuses to perform a dangerous switch. It still allows | |
486 | switching to non-interactive backends.""" |
|
480 | switching to non-interactive backends.""" | |
487 |
|
481 | |||
488 | if arg in backends.interactive_bk and arg != self.mpl_backend: |
|
482 | if arg in backends.interactive_bk and arg != self.mpl_backend: | |
489 | m=('invalid matplotlib backend switch.\n' |
|
483 | m=('invalid matplotlib backend switch.\n' | |
490 | 'This script attempted to switch to the interactive ' |
|
484 | 'This script attempted to switch to the interactive ' | |
491 | 'backend: `%s`\n' |
|
485 | 'backend: `%s`\n' | |
492 | 'Your current choice of interactive backend is: `%s`\n\n' |
|
486 | 'Your current choice of interactive backend is: `%s`\n\n' | |
493 | 'Switching interactive matplotlib backends at runtime\n' |
|
487 | 'Switching interactive matplotlib backends at runtime\n' | |
494 | 'would crash the python interpreter, ' |
|
488 | 'would crash the python interpreter, ' | |
495 | 'and IPython has blocked it.\n\n' |
|
489 | 'and IPython has blocked it.\n\n' | |
496 | 'You need to either change your choice of matplotlib backend\n' |
|
490 | 'You need to either change your choice of matplotlib backend\n' | |
497 | 'by editing your .matplotlibrc file, or run this script as a \n' |
|
491 | 'by editing your .matplotlibrc file, or run this script as a \n' | |
498 | 'standalone file from the command line, not using IPython.\n' % |
|
492 | 'standalone file from the command line, not using IPython.\n' % | |
499 | (arg,self.mpl_backend) ) |
|
493 | (arg,self.mpl_backend) ) | |
500 | raise RuntimeError, m |
|
494 | raise RuntimeError, m | |
501 | else: |
|
495 | else: | |
502 | self.mpl_use(arg) |
|
496 | self.mpl_use(arg) | |
503 | self.mpl_use._called = True |
|
497 | self.mpl_use._called = True | |
504 |
|
498 | |||
505 | self.matplotlib = matplotlib |
|
499 | self.matplotlib = matplotlib | |
506 | self.mpl_backend = matplotlib.rcParams['backend'] |
|
500 | self.mpl_backend = matplotlib.rcParams['backend'] | |
507 |
|
501 | |||
508 | # we also need to block switching of interactive backends by use() |
|
502 | # we also need to block switching of interactive backends by use() | |
509 | self.mpl_use = matplotlib.use |
|
503 | self.mpl_use = matplotlib.use | |
510 | self.mpl_use._called = False |
|
504 | self.mpl_use._called = False | |
511 | # overwrite the original matplotlib.use with our wrapper |
|
505 | # overwrite the original matplotlib.use with our wrapper | |
512 | matplotlib.use = use |
|
506 | matplotlib.use = use | |
513 |
|
507 | |||
514 | # This must be imported last in the matplotlib series, after |
|
508 | # This must be imported last in the matplotlib series, after | |
515 | # backend/interactivity choices have been made |
|
509 | # backend/interactivity choices have been made | |
516 | import matplotlib.pylab as pylab |
|
510 | import matplotlib.pylab as pylab | |
517 | self.pylab = pylab |
|
511 | self.pylab = pylab | |
518 |
|
512 | |||
519 | self.pylab.show._needmain = False |
|
513 | self.pylab.show._needmain = False | |
520 | # We need to detect at runtime whether show() is called by the user. |
|
514 | # We need to detect at runtime whether show() is called by the user. | |
521 | # For this, we wrap it into a decorator which adds a 'called' flag. |
|
515 | # For this, we wrap it into a decorator which adds a 'called' flag. | |
522 | self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive) |
|
516 | self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive) | |
523 |
|
517 | |||
524 | # Build a user namespace initialized with matplotlib/matlab features. |
|
518 | # Build a user namespace initialized with matplotlib/matlab features. | |
525 | user_ns = IPython.ipapi.make_user_ns(user_ns) |
|
519 | user_ns = IPython.ipapi.make_user_ns(user_ns) | |
526 |
|
520 | |||
527 | exec ("import matplotlib\n" |
|
521 | exec ("import matplotlib\n" | |
528 | "import matplotlib.pylab as pylab\n") in user_ns |
|
522 | "import matplotlib.pylab as pylab\n") in user_ns | |
529 |
|
523 | |||
530 | # Build matplotlib info banner |
|
524 | # Build matplotlib info banner | |
531 | b=""" |
|
525 | b=""" | |
532 | Welcome to pylab, a matplotlib-based Python environment. |
|
526 | Welcome to pylab, a matplotlib-based Python environment. | |
533 | For more information, type 'help(pylab)'. |
|
527 | For more information, type 'help(pylab)'. | |
534 | """ |
|
528 | """ | |
535 | return user_ns,b |
|
529 | return user_ns,b | |
536 |
|
530 | |||
537 | def mplot_exec(self,fname,*where,**kw): |
|
531 | def mplot_exec(self,fname,*where,**kw): | |
538 | """Execute a matplotlib script. |
|
532 | """Execute a matplotlib script. | |
539 |
|
533 | |||
540 | This is a call to execfile(), but wrapped in safeties to properly |
|
534 | This is a call to execfile(), but wrapped in safeties to properly | |
541 | handle interactive rendering and backend switching.""" |
|
535 | handle interactive rendering and backend switching.""" | |
542 |
|
536 | |||
543 | #print '*** Matplotlib runner ***' # dbg |
|
537 | #print '*** Matplotlib runner ***' # dbg | |
544 | # turn off rendering until end of script |
|
538 | # turn off rendering until end of script | |
545 | isInteractive = self.matplotlib.rcParams['interactive'] |
|
539 | isInteractive = self.matplotlib.rcParams['interactive'] | |
546 | self.matplotlib.interactive(False) |
|
540 | self.matplotlib.interactive(False) | |
547 | self.safe_execfile(fname,*where,**kw) |
|
541 | self.safe_execfile(fname,*where,**kw) | |
548 | self.matplotlib.interactive(isInteractive) |
|
542 | self.matplotlib.interactive(isInteractive) | |
549 | # make rendering call now, if the user tried to do it |
|
543 | # make rendering call now, if the user tried to do it | |
550 | if self.pylab.draw_if_interactive.called: |
|
544 | if self.pylab.draw_if_interactive.called: | |
551 | self.pylab.draw() |
|
545 | self.pylab.draw() | |
552 | self.pylab.draw_if_interactive.called = False |
|
546 | self.pylab.draw_if_interactive.called = False | |
553 |
|
547 | |||
554 | # if a backend switch was performed, reverse it now |
|
548 | # if a backend switch was performed, reverse it now | |
555 | if self.mpl_use._called: |
|
549 | if self.mpl_use._called: | |
556 | self.matplotlib.rcParams['backend'] = self.mpl_backend |
|
550 | self.matplotlib.rcParams['backend'] = self.mpl_backend | |
557 |
|
551 | |||
558 | def magic_run(self,parameter_s=''): |
|
552 | def magic_run(self,parameter_s=''): | |
559 | Magic.magic_run(self,parameter_s,runner=self.mplot_exec) |
|
553 | Magic.magic_run(self,parameter_s,runner=self.mplot_exec) | |
560 |
|
554 | |||
561 | # Fix the docstring so users see the original as well |
|
555 | # Fix the docstring so users see the original as well | |
562 | magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__, |
|
556 | magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__, | |
563 | "\n *** Modified %run for Matplotlib," |
|
557 | "\n *** Modified %run for Matplotlib," | |
564 | " with proper interactive handling ***") |
|
558 | " with proper interactive handling ***") | |
565 |
|
559 | |||
566 | # Now we provide 2 versions of a matplotlib-aware IPython base shells, single |
|
560 | # Now we provide 2 versions of a matplotlib-aware IPython base shells, single | |
567 | # and multithreaded. Note that these are meant for internal use, the IPShell* |
|
561 | # and multithreaded. Note that these are meant for internal use, the IPShell* | |
568 | # classes below are the ones meant for public consumption. |
|
562 | # classes below are the ones meant for public consumption. | |
569 |
|
563 | |||
570 | class MatplotlibShell(MatplotlibShellBase,InteractiveShell): |
|
564 | class MatplotlibShell(MatplotlibShellBase,InteractiveShell): | |
571 | """Single-threaded shell with matplotlib support.""" |
|
565 | """Single-threaded shell with matplotlib support.""" | |
572 |
|
566 | |||
573 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
567 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
574 | user_ns=None,user_global_ns=None,**kw): |
|
568 | user_ns=None,user_global_ns=None,**kw): | |
575 | user_ns,b2 = self._matplotlib_config(name,user_ns) |
|
569 | user_ns,b2 = self._matplotlib_config(name,user_ns) | |
576 | InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, |
|
570 | InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, | |
577 | banner2=b2,**kw) |
|
571 | banner2=b2,**kw) | |
578 |
|
572 | |||
579 | class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell): |
|
573 | class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell): | |
580 | """Multi-threaded shell with matplotlib support.""" |
|
574 | """Multi-threaded shell with matplotlib support.""" | |
581 |
|
575 | |||
582 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
576 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
583 | user_ns=None,user_global_ns=None, **kw): |
|
577 | user_ns=None,user_global_ns=None, **kw): | |
584 | user_ns,b2 = self._matplotlib_config(name,user_ns) |
|
578 | user_ns,b2 = self._matplotlib_config(name,user_ns) | |
585 | MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, |
|
579 | MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns, | |
586 | banner2=b2,**kw) |
|
580 | banner2=b2,**kw) | |
587 |
|
581 | |||
588 | #----------------------------------------------------------------------------- |
|
582 | #----------------------------------------------------------------------------- | |
589 | # Utility functions for the different GUI enabled IPShell* classes. |
|
583 | # Utility functions for the different GUI enabled IPShell* classes. | |
590 |
|
584 | |||
591 | def get_tk(): |
|
585 | def get_tk(): | |
592 | """Tries to import Tkinter and returns a withdrawn Tkinter root |
|
586 | """Tries to import Tkinter and returns a withdrawn Tkinter root | |
593 | window. If Tkinter is already imported or not available, this |
|
587 | window. If Tkinter is already imported or not available, this | |
594 | returns None. This function calls `hijack_tk` underneath. |
|
588 | returns None. This function calls `hijack_tk` underneath. | |
595 | """ |
|
589 | """ | |
596 | if not USE_TK or sys.modules.has_key('Tkinter'): |
|
590 | if not USE_TK or sys.modules.has_key('Tkinter'): | |
597 | return None |
|
591 | return None | |
598 | else: |
|
592 | else: | |
599 | try: |
|
593 | try: | |
600 | import Tkinter |
|
594 | import Tkinter | |
601 | except ImportError: |
|
595 | except ImportError: | |
602 | return None |
|
596 | return None | |
603 | else: |
|
597 | else: | |
604 | hijack_tk() |
|
598 | hijack_tk() | |
605 | r = Tkinter.Tk() |
|
599 | r = Tkinter.Tk() | |
606 | r.withdraw() |
|
600 | r.withdraw() | |
607 | return r |
|
601 | return r | |
608 |
|
602 | |||
609 | def hijack_tk(): |
|
603 | def hijack_tk(): | |
610 | """Modifies Tkinter's mainloop with a dummy so when a module calls |
|
604 | """Modifies Tkinter's mainloop with a dummy so when a module calls | |
611 | mainloop, it does not block. |
|
605 | mainloop, it does not block. | |
612 |
|
606 | |||
613 | """ |
|
607 | """ | |
614 | def misc_mainloop(self, n=0): |
|
608 | def misc_mainloop(self, n=0): | |
615 | pass |
|
609 | pass | |
616 | def tkinter_mainloop(n=0): |
|
610 | def tkinter_mainloop(n=0): | |
617 | pass |
|
611 | pass | |
618 |
|
612 | |||
619 | import Tkinter |
|
613 | import Tkinter | |
620 | Tkinter.Misc.mainloop = misc_mainloop |
|
614 | Tkinter.Misc.mainloop = misc_mainloop | |
621 | Tkinter.mainloop = tkinter_mainloop |
|
615 | Tkinter.mainloop = tkinter_mainloop | |
622 |
|
616 | |||
623 | def update_tk(tk): |
|
617 | def update_tk(tk): | |
624 | """Updates the Tkinter event loop. This is typically called from |
|
618 | """Updates the Tkinter event loop. This is typically called from | |
625 | the respective WX or GTK mainloops. |
|
619 | the respective WX or GTK mainloops. | |
626 | """ |
|
620 | """ | |
627 | if tk: |
|
621 | if tk: | |
628 | tk.update() |
|
622 | tk.update() | |
629 |
|
623 | |||
630 | def hijack_wx(): |
|
624 | def hijack_wx(): | |
631 | """Modifies wxPython's MainLoop with a dummy so user code does not |
|
625 | """Modifies wxPython's MainLoop with a dummy so user code does not | |
632 | block IPython. The hijacked mainloop function is returned. |
|
626 | block IPython. The hijacked mainloop function is returned. | |
633 | """ |
|
627 | """ | |
634 | def dummy_mainloop(*args, **kw): |
|
628 | def dummy_mainloop(*args, **kw): | |
635 | pass |
|
629 | pass | |
636 |
|
630 | |||
637 | try: |
|
631 | try: | |
638 | import wx |
|
632 | import wx | |
639 | except ImportError: |
|
633 | except ImportError: | |
640 | # For very old versions of WX |
|
634 | # For very old versions of WX | |
641 | import wxPython as wx |
|
635 | import wxPython as wx | |
642 |
|
636 | |||
643 | ver = wx.__version__ |
|
637 | ver = wx.__version__ | |
644 | orig_mainloop = None |
|
638 | orig_mainloop = None | |
645 | if ver[:3] >= '2.5': |
|
639 | if ver[:3] >= '2.5': | |
646 | import wx |
|
640 | import wx | |
647 | if hasattr(wx, '_core_'): core = getattr(wx, '_core_') |
|
641 | if hasattr(wx, '_core_'): core = getattr(wx, '_core_') | |
648 | elif hasattr(wx, '_core'): core = getattr(wx, '_core') |
|
642 | elif hasattr(wx, '_core'): core = getattr(wx, '_core') | |
649 | else: raise AttributeError('Could not find wx core module') |
|
643 | else: raise AttributeError('Could not find wx core module') | |
650 | orig_mainloop = core.PyApp_MainLoop |
|
644 | orig_mainloop = core.PyApp_MainLoop | |
651 | core.PyApp_MainLoop = dummy_mainloop |
|
645 | core.PyApp_MainLoop = dummy_mainloop | |
652 | elif ver[:3] == '2.4': |
|
646 | elif ver[:3] == '2.4': | |
653 | orig_mainloop = wx.wxc.wxPyApp_MainLoop |
|
647 | orig_mainloop = wx.wxc.wxPyApp_MainLoop | |
654 | wx.wxc.wxPyApp_MainLoop = dummy_mainloop |
|
648 | wx.wxc.wxPyApp_MainLoop = dummy_mainloop | |
655 | else: |
|
649 | else: | |
656 | warn("Unable to find either wxPython version 2.4 or >= 2.5.") |
|
650 | warn("Unable to find either wxPython version 2.4 or >= 2.5.") | |
657 | return orig_mainloop |
|
651 | return orig_mainloop | |
658 |
|
652 | |||
659 | def hijack_gtk(): |
|
653 | def hijack_gtk(): | |
660 | """Modifies pyGTK's mainloop with a dummy so user code does not |
|
654 | """Modifies pyGTK's mainloop with a dummy so user code does not | |
661 | block IPython. This function returns the original `gtk.mainloop` |
|
655 | block IPython. This function returns the original `gtk.mainloop` | |
662 | function that has been hijacked. |
|
656 | function that has been hijacked. | |
663 | """ |
|
657 | """ | |
664 | def dummy_mainloop(*args, **kw): |
|
658 | def dummy_mainloop(*args, **kw): | |
665 | pass |
|
659 | pass | |
666 | import gtk |
|
660 | import gtk | |
667 | if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main |
|
661 | if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main | |
668 | else: orig_mainloop = gtk.mainloop |
|
662 | else: orig_mainloop = gtk.mainloop | |
669 | gtk.mainloop = dummy_mainloop |
|
663 | gtk.mainloop = dummy_mainloop | |
670 | gtk.main = dummy_mainloop |
|
664 | gtk.main = dummy_mainloop | |
671 | return orig_mainloop |
|
665 | return orig_mainloop | |
672 |
|
666 | |||
673 | #----------------------------------------------------------------------------- |
|
667 | #----------------------------------------------------------------------------- | |
674 | # The IPShell* classes below are the ones meant to be run by external code as |
|
668 | # The IPShell* classes below are the ones meant to be run by external code as | |
675 | # IPython instances. Note that unless a specific threading strategy is |
|
669 | # IPython instances. Note that unless a specific threading strategy is | |
676 | # desired, the factory function start() below should be used instead (it |
|
670 | # desired, the factory function start() below should be used instead (it | |
677 | # selects the proper threaded class). |
|
671 | # selects the proper threaded class). | |
678 |
|
672 | |||
679 | class IPThread(threading.Thread): |
|
673 | class IPThread(threading.Thread): | |
680 | def run(self): |
|
674 | def run(self): | |
681 | self.IP.mainloop(self._banner) |
|
675 | self.IP.mainloop(self._banner) | |
682 | self.IP.kill() |
|
676 | self.IP.kill() | |
683 |
|
677 | |||
684 | def start(self): |
|
|||
685 | threading.Thread.start(self) |
|
|||
686 | _set_main_thread_id() |
|
|||
687 |
|
||||
688 | class IPShellGTK(IPThread): |
|
678 | class IPShellGTK(IPThread): | |
689 | """Run a gtk mainloop() in a separate thread. |
|
679 | """Run a gtk mainloop() in a separate thread. | |
690 |
|
680 | |||
691 | Python commands can be passed to the thread where they will be executed. |
|
681 | Python commands can be passed to the thread where they will be executed. | |
692 | This is implemented by periodically checking for passed code using a |
|
682 | This is implemented by periodically checking for passed code using a | |
693 | GTK timeout callback.""" |
|
683 | GTK timeout callback.""" | |
694 |
|
684 | |||
695 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
685 | TIMEOUT = 100 # Millisecond interval between timeouts. | |
696 |
|
686 | |||
697 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
687 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, | |
698 | debug=1,shell_class=MTInteractiveShell): |
|
688 | debug=1,shell_class=MTInteractiveShell): | |
699 |
|
689 | |||
700 | import gtk |
|
690 | import gtk | |
701 |
|
691 | |||
702 | self.gtk = gtk |
|
692 | self.gtk = gtk | |
703 | self.gtk_mainloop = hijack_gtk() |
|
693 | self.gtk_mainloop = hijack_gtk() | |
704 |
|
694 | |||
705 | # Allows us to use both Tk and GTK. |
|
695 | # Allows us to use both Tk and GTK. | |
706 | self.tk = get_tk() |
|
696 | self.tk = get_tk() | |
707 |
|
697 | |||
708 | if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit |
|
698 | if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit | |
709 | else: mainquit = self.gtk.mainquit |
|
699 | else: mainquit = self.gtk.mainquit | |
710 |
|
700 | |||
711 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
701 | self.IP = make_IPython(argv,user_ns=user_ns, | |
712 | user_global_ns=user_global_ns, |
|
702 | user_global_ns=user_global_ns, | |
713 | debug=debug, |
|
703 | debug=debug, | |
714 | shell_class=shell_class, |
|
704 | shell_class=shell_class, | |
715 | on_kill=[mainquit]) |
|
705 | on_kill=[mainquit]) | |
716 |
|
706 | |||
717 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
707 | # HACK: slot for banner in self; it will be passed to the mainloop | |
718 | # method only and .run() needs it. The actual value will be set by |
|
708 | # method only and .run() needs it. The actual value will be set by | |
719 | # .mainloop(). |
|
709 | # .mainloop(). | |
720 | self._banner = None |
|
710 | self._banner = None | |
721 |
|
711 | |||
722 | threading.Thread.__init__(self) |
|
712 | threading.Thread.__init__(self) | |
723 |
|
713 | |||
724 | def mainloop(self,sys_exit=0,banner=None): |
|
714 | def mainloop(self,sys_exit=0,banner=None): | |
725 |
|
715 | |||
726 | self._banner = banner |
|
716 | self._banner = banner | |
727 |
|
717 | |||
728 | if self.gtk.pygtk_version >= (2,4,0): |
|
718 | if self.gtk.pygtk_version >= (2,4,0): | |
729 | import gobject |
|
719 | import gobject | |
730 | gobject.idle_add(self.on_timer) |
|
720 | gobject.idle_add(self.on_timer) | |
731 | else: |
|
721 | else: | |
732 | self.gtk.idle_add(self.on_timer) |
|
722 | self.gtk.idle_add(self.on_timer) | |
733 |
|
723 | |||
734 | if sys.platform != 'win32': |
|
724 | if sys.platform != 'win32': | |
735 | try: |
|
725 | try: | |
736 | if self.gtk.gtk_version[0] >= 2: |
|
726 | if self.gtk.gtk_version[0] >= 2: | |
737 | self.gtk.gdk.threads_init() |
|
727 | self.gtk.gdk.threads_init() | |
738 | except AttributeError: |
|
728 | except AttributeError: | |
739 | pass |
|
729 | pass | |
740 | except RuntimeError: |
|
730 | except RuntimeError: | |
741 | error('Your pyGTK likely has not been compiled with ' |
|
731 | error('Your pyGTK likely has not been compiled with ' | |
742 | 'threading support.\n' |
|
732 | 'threading support.\n' | |
743 | 'The exception printout is below.\n' |
|
733 | 'The exception printout is below.\n' | |
744 | 'You can either rebuild pyGTK with threads, or ' |
|
734 | 'You can either rebuild pyGTK with threads, or ' | |
745 | 'try using \n' |
|
735 | 'try using \n' | |
746 | 'matplotlib with a different backend (like Tk or WX).\n' |
|
736 | 'matplotlib with a different backend (like Tk or WX).\n' | |
747 | 'Note that matplotlib will most likely not work in its ' |
|
737 | 'Note that matplotlib will most likely not work in its ' | |
748 | 'current state!') |
|
738 | 'current state!') | |
749 | self.IP.InteractiveTB() |
|
739 | self.IP.InteractiveTB() | |
750 |
|
740 | |||
751 | self.start() |
|
741 | self.start() | |
752 | self.gtk.gdk.threads_enter() |
|
742 | self.gtk.gdk.threads_enter() | |
753 | self.gtk_mainloop() |
|
743 | self.gtk_mainloop() | |
754 | self.gtk.gdk.threads_leave() |
|
744 | self.gtk.gdk.threads_leave() | |
755 | self.join() |
|
745 | self.join() | |
756 |
|
746 | |||
757 | def on_timer(self): |
|
747 | def on_timer(self): | |
758 | """Called when GTK is idle. |
|
748 | """Called when GTK is idle. | |
759 |
|
749 | |||
760 | Must return True always, otherwise GTK stops calling it""" |
|
750 | Must return True always, otherwise GTK stops calling it""" | |
761 |
|
751 | |||
762 | update_tk(self.tk) |
|
752 | update_tk(self.tk) | |
763 | self.IP.runcode() |
|
753 | self.IP.runcode() | |
764 | time.sleep(0.01) |
|
754 | time.sleep(0.01) | |
765 | return True |
|
755 | return True | |
766 |
|
756 | |||
767 |
|
757 | |||
768 | class IPShellWX(IPThread): |
|
758 | class IPShellWX(IPThread): | |
769 | """Run a wx mainloop() in a separate thread. |
|
759 | """Run a wx mainloop() in a separate thread. | |
770 |
|
760 | |||
771 | Python commands can be passed to the thread where they will be executed. |
|
761 | Python commands can be passed to the thread where they will be executed. | |
772 | This is implemented by periodically checking for passed code using a |
|
762 | This is implemented by periodically checking for passed code using a | |
773 | GTK timeout callback.""" |
|
763 | GTK timeout callback.""" | |
774 |
|
764 | |||
775 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
765 | TIMEOUT = 100 # Millisecond interval between timeouts. | |
776 |
|
766 | |||
777 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
767 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, | |
778 | debug=1,shell_class=MTInteractiveShell): |
|
768 | debug=1,shell_class=MTInteractiveShell): | |
779 |
|
769 | |||
780 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
770 | self.IP = make_IPython(argv,user_ns=user_ns, | |
781 | user_global_ns=user_global_ns, |
|
771 | user_global_ns=user_global_ns, | |
782 | debug=debug, |
|
772 | debug=debug, | |
783 | shell_class=shell_class, |
|
773 | shell_class=shell_class, | |
784 | on_kill=[self.wxexit]) |
|
774 | on_kill=[self.wxexit]) | |
785 |
|
775 | |||
786 | wantedwxversion=self.IP.rc.wxversion |
|
776 | wantedwxversion=self.IP.rc.wxversion | |
787 | if wantedwxversion!="0": |
|
777 | if wantedwxversion!="0": | |
788 | try: |
|
778 | try: | |
789 | import wxversion |
|
779 | import wxversion | |
790 | except ImportError: |
|
780 | except ImportError: | |
791 | error('The wxversion module is needed for WX version selection') |
|
781 | error('The wxversion module is needed for WX version selection') | |
792 | else: |
|
782 | else: | |
793 | try: |
|
783 | try: | |
794 | wxversion.select(wantedwxversion) |
|
784 | wxversion.select(wantedwxversion) | |
795 | except: |
|
785 | except: | |
796 | self.IP.InteractiveTB() |
|
786 | self.IP.InteractiveTB() | |
797 | error('Requested wxPython version %s could not be loaded' % |
|
787 | error('Requested wxPython version %s could not be loaded' % | |
798 | wantedwxversion) |
|
788 | wantedwxversion) | |
799 |
|
789 | |||
800 | import wx |
|
790 | import wx | |
801 |
|
791 | |||
802 | threading.Thread.__init__(self) |
|
792 | threading.Thread.__init__(self) | |
803 | self.wx = wx |
|
793 | self.wx = wx | |
804 | self.wx_mainloop = hijack_wx() |
|
794 | self.wx_mainloop = hijack_wx() | |
805 |
|
795 | |||
806 | # Allows us to use both Tk and GTK. |
|
796 | # Allows us to use both Tk and GTK. | |
807 | self.tk = get_tk() |
|
797 | self.tk = get_tk() | |
808 |
|
798 | |||
809 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
799 | # HACK: slot for banner in self; it will be passed to the mainloop | |
810 | # method only and .run() needs it. The actual value will be set by |
|
800 | # method only and .run() needs it. The actual value will be set by | |
811 | # .mainloop(). |
|
801 | # .mainloop(). | |
812 | self._banner = None |
|
802 | self._banner = None | |
813 |
|
803 | |||
814 | self.app = None |
|
804 | self.app = None | |
815 |
|
805 | |||
816 | def wxexit(self, *args): |
|
806 | def wxexit(self, *args): | |
817 | if self.app is not None: |
|
807 | if self.app is not None: | |
818 | self.app.agent.timer.Stop() |
|
808 | self.app.agent.timer.Stop() | |
819 | self.app.ExitMainLoop() |
|
809 | self.app.ExitMainLoop() | |
820 |
|
810 | |||
821 | def mainloop(self,sys_exit=0,banner=None): |
|
811 | def mainloop(self,sys_exit=0,banner=None): | |
822 |
|
812 | |||
823 | self._banner = banner |
|
813 | self._banner = banner | |
824 |
|
814 | |||
825 | self.start() |
|
815 | self.start() | |
826 |
|
816 | |||
827 | class TimerAgent(self.wx.MiniFrame): |
|
817 | class TimerAgent(self.wx.MiniFrame): | |
828 | wx = self.wx |
|
818 | wx = self.wx | |
829 | IP = self.IP |
|
819 | IP = self.IP | |
830 | tk = self.tk |
|
820 | tk = self.tk | |
831 | def __init__(self, parent, interval): |
|
821 | def __init__(self, parent, interval): | |
832 | style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ |
|
822 | style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ | |
833 | self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200), |
|
823 | self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200), | |
834 | size=(100, 100),style=style) |
|
824 | size=(100, 100),style=style) | |
835 | self.Show(False) |
|
825 | self.Show(False) | |
836 | self.interval = interval |
|
826 | self.interval = interval | |
837 | self.timerId = self.wx.NewId() |
|
827 | self.timerId = self.wx.NewId() | |
838 |
|
828 | |||
839 | def StartWork(self): |
|
829 | def StartWork(self): | |
840 | self.timer = self.wx.Timer(self, self.timerId) |
|
830 | self.timer = self.wx.Timer(self, self.timerId) | |
841 | self.wx.EVT_TIMER(self, self.timerId, self.OnTimer) |
|
831 | self.wx.EVT_TIMER(self, self.timerId, self.OnTimer) | |
842 | self.timer.Start(self.interval) |
|
832 | self.timer.Start(self.interval) | |
843 |
|
833 | |||
844 | def OnTimer(self, event): |
|
834 | def OnTimer(self, event): | |
845 | update_tk(self.tk) |
|
835 | update_tk(self.tk) | |
846 | self.IP.runcode() |
|
836 | self.IP.runcode() | |
847 |
|
837 | |||
848 | class App(self.wx.App): |
|
838 | class App(self.wx.App): | |
849 | wx = self.wx |
|
839 | wx = self.wx | |
850 | TIMEOUT = self.TIMEOUT |
|
840 | TIMEOUT = self.TIMEOUT | |
851 | def OnInit(self): |
|
841 | def OnInit(self): | |
852 | 'Create the main window and insert the custom frame' |
|
842 | 'Create the main window and insert the custom frame' | |
853 | self.agent = TimerAgent(None, self.TIMEOUT) |
|
843 | self.agent = TimerAgent(None, self.TIMEOUT) | |
854 | self.agent.Show(False) |
|
844 | self.agent.Show(False) | |
855 | self.agent.StartWork() |
|
845 | self.agent.StartWork() | |
856 | return True |
|
846 | return True | |
857 |
|
847 | |||
858 | _set_main_thread_id() |
|
|||
859 | self.app = App(redirect=False) |
|
848 | self.app = App(redirect=False) | |
860 | self.wx_mainloop(self.app) |
|
849 | self.wx_mainloop(self.app) | |
861 | self.join() |
|
850 | self.join() | |
862 |
|
851 | |||
863 |
|
852 | |||
864 | class IPShellQt(IPThread): |
|
853 | class IPShellQt(IPThread): | |
865 | """Run a Qt event loop in a separate thread. |
|
854 | """Run a Qt event loop in a separate thread. | |
866 |
|
855 | |||
867 | Python commands can be passed to the thread where they will be executed. |
|
856 | Python commands can be passed to the thread where they will be executed. | |
868 | This is implemented by periodically checking for passed code using a |
|
857 | This is implemented by periodically checking for passed code using a | |
869 | Qt timer / slot.""" |
|
858 | Qt timer / slot.""" | |
870 |
|
859 | |||
871 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
860 | TIMEOUT = 100 # Millisecond interval between timeouts. | |
872 |
|
861 | |||
873 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
862 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, | |
874 | debug=0,shell_class=MTInteractiveShell): |
|
863 | debug=0,shell_class=MTInteractiveShell): | |
875 |
|
864 | |||
876 | import qt |
|
865 | import qt | |
877 |
|
866 | |||
878 | class newQApplication: |
|
867 | class newQApplication: | |
879 | def __init__( self ): |
|
868 | def __init__( self ): | |
880 | self.QApplication = qt.QApplication |
|
869 | self.QApplication = qt.QApplication | |
881 |
|
870 | |||
882 | def __call__( *args, **kwargs ): |
|
871 | def __call__( *args, **kwargs ): | |
883 | return qt.qApp |
|
872 | return qt.qApp | |
884 |
|
873 | |||
885 | def exec_loop( *args, **kwargs ): |
|
874 | def exec_loop( *args, **kwargs ): | |
886 | pass |
|
875 | pass | |
887 |
|
876 | |||
888 | def __getattr__( self, name ): |
|
877 | def __getattr__( self, name ): | |
889 | return getattr( self.QApplication, name ) |
|
878 | return getattr( self.QApplication, name ) | |
890 |
|
879 | |||
891 | qt.QApplication = newQApplication() |
|
880 | qt.QApplication = newQApplication() | |
892 |
|
881 | |||
893 | # Allows us to use both Tk and QT. |
|
882 | # Allows us to use both Tk and QT. | |
894 | self.tk = get_tk() |
|
883 | self.tk = get_tk() | |
895 |
|
884 | |||
896 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
885 | self.IP = make_IPython(argv,user_ns=user_ns, | |
897 | user_global_ns=user_global_ns, |
|
886 | user_global_ns=user_global_ns, | |
898 | debug=debug, |
|
887 | debug=debug, | |
899 | shell_class=shell_class, |
|
888 | shell_class=shell_class, | |
900 | on_kill=[qt.qApp.exit]) |
|
889 | on_kill=[qt.qApp.exit]) | |
901 |
|
890 | |||
902 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
891 | # HACK: slot for banner in self; it will be passed to the mainloop | |
903 | # method only and .run() needs it. The actual value will be set by |
|
892 | # method only and .run() needs it. The actual value will be set by | |
904 | # .mainloop(). |
|
893 | # .mainloop(). | |
905 | self._banner = None |
|
894 | self._banner = None | |
906 |
|
895 | |||
907 | threading.Thread.__init__(self) |
|
896 | threading.Thread.__init__(self) | |
908 |
|
897 | |||
909 | def mainloop(self,sys_exit=0,banner=None): |
|
898 | def mainloop(self,sys_exit=0,banner=None): | |
910 |
|
899 | |||
911 | import qt |
|
900 | import qt | |
912 |
|
901 | |||
913 | self._banner = banner |
|
902 | self._banner = banner | |
914 |
|
903 | |||
915 | if qt.QApplication.startingUp(): |
|
904 | if qt.QApplication.startingUp(): | |
916 | a = qt.QApplication.QApplication(sys.argv) |
|
905 | a = qt.QApplication.QApplication(sys.argv) | |
917 | self.timer = qt.QTimer() |
|
906 | self.timer = qt.QTimer() | |
918 | qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer ) |
|
907 | qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer ) | |
919 |
|
908 | |||
920 | self.start() |
|
909 | self.start() | |
921 | self.timer.start( self.TIMEOUT, True ) |
|
910 | self.timer.start( self.TIMEOUT, True ) | |
922 | while True: |
|
911 | while True: | |
923 | if self.IP._kill: break |
|
912 | if self.IP._kill: break | |
924 | qt.qApp.exec_loop() |
|
913 | qt.qApp.exec_loop() | |
925 | self.join() |
|
914 | self.join() | |
926 |
|
915 | |||
927 | def on_timer(self): |
|
916 | def on_timer(self): | |
928 | update_tk(self.tk) |
|
917 | update_tk(self.tk) | |
929 | result = self.IP.runcode() |
|
918 | result = self.IP.runcode() | |
930 | self.timer.start( self.TIMEOUT, True ) |
|
919 | self.timer.start( self.TIMEOUT, True ) | |
931 | return result |
|
920 | return result | |
932 |
|
921 | |||
933 |
|
922 | |||
934 | class IPShellQt4(IPThread): |
|
923 | class IPShellQt4(IPThread): | |
935 | """Run a Qt event loop in a separate thread. |
|
924 | """Run a Qt event loop in a separate thread. | |
936 |
|
925 | |||
937 | Python commands can be passed to the thread where they will be executed. |
|
926 | Python commands can be passed to the thread where they will be executed. | |
938 | This is implemented by periodically checking for passed code using a |
|
927 | This is implemented by periodically checking for passed code using a | |
939 | Qt timer / slot.""" |
|
928 | Qt timer / slot.""" | |
940 |
|
929 | |||
941 | TIMEOUT = 100 # Millisecond interval between timeouts. |
|
930 | TIMEOUT = 100 # Millisecond interval between timeouts. | |
942 |
|
931 | |||
943 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, |
|
932 | def __init__(self,argv=None,user_ns=None,user_global_ns=None, | |
944 | debug=0,shell_class=MTInteractiveShell): |
|
933 | debug=0,shell_class=MTInteractiveShell): | |
945 |
|
934 | |||
946 | from PyQt4 import QtCore, QtGui |
|
935 | from PyQt4 import QtCore, QtGui | |
947 |
|
936 | |||
948 | class newQApplication: |
|
937 | class newQApplication: | |
949 | def __init__( self ): |
|
938 | def __init__( self ): | |
950 | self.QApplication = QtGui.QApplication |
|
939 | self.QApplication = QtGui.QApplication | |
951 |
|
940 | |||
952 | def __call__( *args, **kwargs ): |
|
941 | def __call__( *args, **kwargs ): | |
953 | return QtGui.qApp |
|
942 | return QtGui.qApp | |
954 |
|
943 | |||
955 | def exec_loop( *args, **kwargs ): |
|
944 | def exec_loop( *args, **kwargs ): | |
956 | pass |
|
945 | pass | |
957 |
|
946 | |||
958 | def __getattr__( self, name ): |
|
947 | def __getattr__( self, name ): | |
959 | return getattr( self.QApplication, name ) |
|
948 | return getattr( self.QApplication, name ) | |
960 |
|
949 | |||
961 | QtGui.QApplication = newQApplication() |
|
950 | QtGui.QApplication = newQApplication() | |
962 |
|
951 | |||
963 | # Allows us to use both Tk and QT. |
|
952 | # Allows us to use both Tk and QT. | |
964 | self.tk = get_tk() |
|
953 | self.tk = get_tk() | |
965 |
|
954 | |||
966 | self.IP = make_IPython(argv,user_ns=user_ns, |
|
955 | self.IP = make_IPython(argv,user_ns=user_ns, | |
967 | user_global_ns=user_global_ns, |
|
956 | user_global_ns=user_global_ns, | |
968 | debug=debug, |
|
957 | debug=debug, | |
969 | shell_class=shell_class, |
|
958 | shell_class=shell_class, | |
970 | on_kill=[QtGui.qApp.exit]) |
|
959 | on_kill=[QtGui.qApp.exit]) | |
971 |
|
960 | |||
972 | # HACK: slot for banner in self; it will be passed to the mainloop |
|
961 | # HACK: slot for banner in self; it will be passed to the mainloop | |
973 | # method only and .run() needs it. The actual value will be set by |
|
962 | # method only and .run() needs it. The actual value will be set by | |
974 | # .mainloop(). |
|
963 | # .mainloop(). | |
975 | self._banner = None |
|
964 | self._banner = None | |
976 |
|
965 | |||
977 | threading.Thread.__init__(self) |
|
966 | threading.Thread.__init__(self) | |
978 |
|
967 | |||
979 | def mainloop(self,sys_exit=0,banner=None): |
|
968 | def mainloop(self,sys_exit=0,banner=None): | |
980 |
|
969 | |||
981 | from PyQt4 import QtCore, QtGui |
|
970 | from PyQt4 import QtCore, QtGui | |
982 |
|
971 | |||
983 | self._banner = banner |
|
972 | self._banner = banner | |
984 |
|
973 | |||
985 | if QtGui.QApplication.startingUp(): |
|
974 | if QtGui.QApplication.startingUp(): | |
986 | a = QtGui.QApplication.QApplication(sys.argv) |
|
975 | a = QtGui.QApplication.QApplication(sys.argv) | |
987 | self.timer = QtCore.QTimer() |
|
976 | self.timer = QtCore.QTimer() | |
988 | QtCore.QObject.connect( self.timer, QtCore.SIGNAL( 'timeout()' ), self.on_timer ) |
|
977 | QtCore.QObject.connect( self.timer, QtCore.SIGNAL( 'timeout()' ), self.on_timer ) | |
989 |
|
978 | |||
990 | self.start() |
|
979 | self.start() | |
991 | self.timer.start( self.TIMEOUT ) |
|
980 | self.timer.start( self.TIMEOUT ) | |
992 | while True: |
|
981 | while True: | |
993 | if self.IP._kill: break |
|
982 | if self.IP._kill: break | |
994 | QtGui.qApp.exec_() |
|
983 | QtGui.qApp.exec_() | |
995 | self.join() |
|
984 | self.join() | |
996 |
|
985 | |||
997 | def on_timer(self): |
|
986 | def on_timer(self): | |
998 | update_tk(self.tk) |
|
987 | update_tk(self.tk) | |
999 | result = self.IP.runcode() |
|
988 | result = self.IP.runcode() | |
1000 | self.timer.start( self.TIMEOUT ) |
|
989 | self.timer.start( self.TIMEOUT ) | |
1001 | return result |
|
990 | return result | |
1002 |
|
991 | |||
1003 |
|
992 | |||
1004 | # A set of matplotlib public IPython shell classes, for single-threaded |
|
993 | # A set of matplotlib public IPython shell classes, for single-threaded (Tk* | |
1005 |
# |
|
994 | # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use. | |
1006 | def _load_pylab(user_ns): |
|
995 | def _load_pylab(user_ns): | |
1007 | """Allow users to disable pulling all of pylab into the top-level |
|
996 | """Allow users to disable pulling all of pylab into the top-level | |
1008 | namespace. |
|
997 | namespace. | |
1009 |
|
998 | |||
1010 | This little utility must be called AFTER the actual ipython instance is |
|
999 | This little utility must be called AFTER the actual ipython instance is | |
1011 | running, since only then will the options file have been fully parsed.""" |
|
1000 | running, since only then will the options file have been fully parsed.""" | |
1012 |
|
1001 | |||
1013 | ip = IPython.ipapi.get() |
|
1002 | ip = IPython.ipapi.get() | |
1014 | if ip.options.pylab_import_all: |
|
1003 | if ip.options.pylab_import_all: | |
1015 | exec "from matplotlib.pylab import *" in user_ns |
|
1004 | exec "from matplotlib.pylab import *" in user_ns | |
1016 |
|
1005 | |||
1017 | class IPShellMatplotlib(IPShell): |
|
1006 | class IPShellMatplotlib(IPShell): | |
1018 | """Subclass IPShell with MatplotlibShell as the internal shell. |
|
1007 | """Subclass IPShell with MatplotlibShell as the internal shell. | |
1019 |
|
1008 | |||
1020 | Single-threaded class, meant for the Tk* and FLTK* backends. |
|
1009 | Single-threaded class, meant for the Tk* and FLTK* backends. | |
1021 |
|
1010 | |||
1022 | Having this on a separate class simplifies the external driver code.""" |
|
1011 | Having this on a separate class simplifies the external driver code.""" | |
1023 |
|
1012 | |||
1024 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1013 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |
1025 | IPShell.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1014 | IPShell.__init__(self,argv,user_ns,user_global_ns,debug, | |
1026 | shell_class=MatplotlibShell) |
|
1015 | shell_class=MatplotlibShell) | |
1027 | _load_pylab(self.IP.user_ns) |
|
1016 | _load_pylab(self.IP.user_ns) | |
1028 |
|
1017 | |||
1029 | class IPShellMatplotlibGTK(IPShellGTK): |
|
1018 | class IPShellMatplotlibGTK(IPShellGTK): | |
1030 | """Subclass IPShellGTK with MatplotlibMTShell as the internal shell. |
|
1019 | """Subclass IPShellGTK with MatplotlibMTShell as the internal shell. | |
1031 |
|
1020 | |||
1032 | Multi-threaded class, meant for the GTK* backends.""" |
|
1021 | Multi-threaded class, meant for the GTK* backends.""" | |
1033 |
|
1022 | |||
1034 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1023 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |
1035 | IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1024 | IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug, | |
1036 | shell_class=MatplotlibMTShell) |
|
1025 | shell_class=MatplotlibMTShell) | |
1037 | _load_pylab(self.IP.user_ns) |
|
1026 | _load_pylab(self.IP.user_ns) | |
1038 |
|
1027 | |||
1039 | class IPShellMatplotlibWX(IPShellWX): |
|
1028 | class IPShellMatplotlibWX(IPShellWX): | |
1040 | """Subclass IPShellWX with MatplotlibMTShell as the internal shell. |
|
1029 | """Subclass IPShellWX with MatplotlibMTShell as the internal shell. | |
1041 |
|
1030 | |||
1042 | Multi-threaded class, meant for the WX* backends.""" |
|
1031 | Multi-threaded class, meant for the WX* backends.""" | |
1043 |
|
1032 | |||
1044 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1033 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |
1045 | IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1034 | IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug, | |
1046 | shell_class=MatplotlibMTShell) |
|
1035 | shell_class=MatplotlibMTShell) | |
1047 | _load_pylab(self.IP.user_ns) |
|
1036 | _load_pylab(self.IP.user_ns) | |
1048 |
|
1037 | |||
1049 | class IPShellMatplotlibQt(IPShellQt): |
|
1038 | class IPShellMatplotlibQt(IPShellQt): | |
1050 | """Subclass IPShellQt with MatplotlibMTShell as the internal shell. |
|
1039 | """Subclass IPShellQt with MatplotlibMTShell as the internal shell. | |
1051 |
|
1040 | |||
1052 | Multi-threaded class, meant for the Qt* backends.""" |
|
1041 | Multi-threaded class, meant for the Qt* backends.""" | |
1053 |
|
1042 | |||
1054 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1043 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |
1055 | IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1044 | IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug, | |
1056 | shell_class=MatplotlibMTShell) |
|
1045 | shell_class=MatplotlibMTShell) | |
1057 | _load_pylab(self.IP.user_ns) |
|
1046 | _load_pylab(self.IP.user_ns) | |
1058 |
|
1047 | |||
1059 | class IPShellMatplotlibQt4(IPShellQt4): |
|
1048 | class IPShellMatplotlibQt4(IPShellQt4): | |
1060 | """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell. |
|
1049 | """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell. | |
1061 |
|
1050 | |||
1062 | Multi-threaded class, meant for the Qt4* backends.""" |
|
1051 | Multi-threaded class, meant for the Qt4* backends.""" | |
1063 |
|
1052 | |||
1064 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): |
|
1053 | def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1): | |
1065 | IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug, |
|
1054 | IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug, | |
1066 | shell_class=MatplotlibMTShell) |
|
1055 | shell_class=MatplotlibMTShell) | |
1067 | _load_pylab(self.IP.user_ns) |
|
1056 | _load_pylab(self.IP.user_ns) | |
1068 |
|
1057 | |||
1069 | #----------------------------------------------------------------------------- |
|
1058 | #----------------------------------------------------------------------------- | |
1070 | # Factory functions to actually start the proper thread-aware shell |
|
1059 | # Factory functions to actually start the proper thread-aware shell | |
1071 |
|
1060 | |||
1072 | def _matplotlib_shell_class(): |
|
1061 | def _matplotlib_shell_class(): | |
1073 | """Factory function to handle shell class selection for matplotlib. |
|
1062 | """Factory function to handle shell class selection for matplotlib. | |
1074 |
|
1063 | |||
1075 | The proper shell class to use depends on the matplotlib backend, since |
|
1064 | The proper shell class to use depends on the matplotlib backend, since | |
1076 | each backend requires a different threading strategy.""" |
|
1065 | each backend requires a different threading strategy.""" | |
1077 |
|
1066 | |||
1078 | try: |
|
1067 | try: | |
1079 | import matplotlib |
|
1068 | import matplotlib | |
1080 | except ImportError: |
|
1069 | except ImportError: | |
1081 | error('matplotlib could NOT be imported! Starting normal IPython.') |
|
1070 | error('matplotlib could NOT be imported! Starting normal IPython.') | |
1082 | sh_class = IPShell |
|
1071 | sh_class = IPShell | |
1083 | else: |
|
1072 | else: | |
1084 | backend = matplotlib.rcParams['backend'] |
|
1073 | backend = matplotlib.rcParams['backend'] | |
1085 | if backend.startswith('GTK'): |
|
1074 | if backend.startswith('GTK'): | |
1086 | sh_class = IPShellMatplotlibGTK |
|
1075 | sh_class = IPShellMatplotlibGTK | |
1087 | elif backend.startswith('WX'): |
|
1076 | elif backend.startswith('WX'): | |
1088 | sh_class = IPShellMatplotlibWX |
|
1077 | sh_class = IPShellMatplotlibWX | |
1089 | elif backend.startswith('Qt4'): |
|
1078 | elif backend.startswith('Qt4'): | |
1090 | sh_class = IPShellMatplotlibQt4 |
|
1079 | sh_class = IPShellMatplotlibQt4 | |
1091 | elif backend.startswith('Qt'): |
|
1080 | elif backend.startswith('Qt'): | |
1092 | sh_class = IPShellMatplotlibQt |
|
1081 | sh_class = IPShellMatplotlibQt | |
1093 | else: |
|
1082 | else: | |
1094 | sh_class = IPShellMatplotlib |
|
1083 | sh_class = IPShellMatplotlib | |
1095 | #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg |
|
1084 | #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg | |
1096 | return sh_class |
|
1085 | return sh_class | |
1097 |
|
1086 | |||
1098 | # This is the one which should be called by external code. |
|
1087 | # This is the one which should be called by external code. | |
1099 | def start(user_ns = None): |
|
1088 | def start(user_ns = None): | |
1100 | """Return a running shell instance, dealing with threading options. |
|
1089 | """Return a running shell instance, dealing with threading options. | |
1101 |
|
1090 | |||
1102 | This is a factory function which will instantiate the proper IPython shell |
|
1091 | This is a factory function which will instantiate the proper IPython shell | |
1103 | based on the user's threading choice. Such a selector is needed because |
|
1092 | based on the user's threading choice. Such a selector is needed because | |
1104 | different GUI toolkits require different thread handling details.""" |
|
1093 | different GUI toolkits require different thread handling details.""" | |
1105 |
|
1094 | |||
1106 | global USE_TK |
|
1095 | global USE_TK | |
1107 | # Crude sys.argv hack to extract the threading options. |
|
1096 | # Crude sys.argv hack to extract the threading options. | |
1108 | argv = sys.argv |
|
1097 | argv = sys.argv | |
1109 | if len(argv) > 1: |
|
1098 | if len(argv) > 1: | |
1110 | if len(argv) > 2: |
|
1099 | if len(argv) > 2: | |
1111 | arg2 = argv[2] |
|
1100 | arg2 = argv[2] | |
1112 | if arg2.endswith('-tk'): |
|
1101 | if arg2.endswith('-tk'): | |
1113 | USE_TK = True |
|
1102 | USE_TK = True | |
1114 | arg1 = argv[1] |
|
1103 | arg1 = argv[1] | |
1115 | if arg1.endswith('-gthread'): |
|
1104 | if arg1.endswith('-gthread'): | |
1116 | shell = IPShellGTK |
|
1105 | shell = IPShellGTK | |
1117 | elif arg1.endswith( '-qthread' ): |
|
1106 | elif arg1.endswith( '-qthread' ): | |
1118 | shell = IPShellQt |
|
1107 | shell = IPShellQt | |
1119 | elif arg1.endswith( '-q4thread' ): |
|
1108 | elif arg1.endswith( '-q4thread' ): | |
1120 | shell = IPShellQt4 |
|
1109 | shell = IPShellQt4 | |
1121 | elif arg1.endswith('-wthread'): |
|
1110 | elif arg1.endswith('-wthread'): | |
1122 | shell = IPShellWX |
|
1111 | shell = IPShellWX | |
1123 | elif arg1.endswith('-pylab'): |
|
1112 | elif arg1.endswith('-pylab'): | |
1124 | shell = _matplotlib_shell_class() |
|
1113 | shell = _matplotlib_shell_class() | |
1125 | else: |
|
1114 | else: | |
1126 | shell = IPShell |
|
1115 | shell = IPShell | |
1127 | else: |
|
1116 | else: | |
1128 | shell = IPShell |
|
1117 | shell = IPShell | |
1129 | return shell(user_ns = user_ns) |
|
1118 | return shell(user_ns = user_ns) | |
1130 |
|
1119 | |||
1131 | # Some aliases for backwards compatibility |
|
1120 | # Some aliases for backwards compatibility | |
1132 | IPythonShell = IPShell |
|
1121 | IPythonShell = IPShell | |
1133 | IPythonShellEmbed = IPShellEmbed |
|
1122 | IPythonShellEmbed = IPShellEmbed | |
1134 | #************************ End of file <Shell.py> *************************** |
|
1123 | #************************ End of file <Shell.py> *************************** |
@@ -1,2597 +1,2599 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | Requires Python 2.3 or newer. |
|
5 | Requires Python 2.3 or newer. | |
6 |
|
6 | |||
7 | This file contains all the classes and helper functions specific to IPython. |
|
7 | This file contains all the classes and helper functions specific to IPython. | |
8 |
|
8 | |||
9 |
$Id: iplib.py 22 |
|
9 | $Id: iplib.py 2221 2007-04-06 02:58:37Z fperez $ | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
14 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
14 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
15 | # |
|
15 | # | |
16 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | # Distributed under the terms of the BSD License. The full license is in | |
17 | # the file COPYING, distributed as part of this software. |
|
17 | # the file COPYING, distributed as part of this software. | |
18 | # |
|
18 | # | |
19 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
19 | # Note: this code originally subclassed code.InteractiveConsole from the | |
20 | # Python standard library. Over time, all of that class has been copied |
|
20 | # Python standard library. Over time, all of that class has been copied | |
21 | # verbatim here for modifications which could not be accomplished by |
|
21 | # verbatim here for modifications which could not be accomplished by | |
22 | # subclassing. At this point, there are no dependencies at all on the code |
|
22 | # subclassing. At this point, there are no dependencies at all on the code | |
23 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
23 | # module anymore (it is not even imported). The Python License (sec. 2) | |
24 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
24 | # allows for this, but it's always nice to acknowledge credit where credit is | |
25 | # due. |
|
25 | # due. | |
26 | #***************************************************************************** |
|
26 | #***************************************************************************** | |
27 |
|
27 | |||
28 | #**************************************************************************** |
|
28 | #**************************************************************************** | |
29 | # Modules and globals |
|
29 | # Modules and globals | |
30 |
|
30 | |||
31 | from IPython import Release |
|
31 | from IPython import Release | |
32 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
32 | __author__ = '%s <%s>\n%s <%s>' % \ | |
33 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
33 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
34 | __license__ = Release.license |
|
34 | __license__ = Release.license | |
35 | __version__ = Release.version |
|
35 | __version__ = Release.version | |
36 |
|
36 | |||
37 | # Python standard modules |
|
37 | # Python standard modules | |
38 | import __main__ |
|
38 | import __main__ | |
39 | import __builtin__ |
|
39 | import __builtin__ | |
40 | import StringIO |
|
40 | import StringIO | |
41 | import bdb |
|
41 | import bdb | |
42 | import cPickle as pickle |
|
42 | import cPickle as pickle | |
43 | import codeop |
|
43 | import codeop | |
44 | import exceptions |
|
44 | import exceptions | |
45 | import glob |
|
45 | import glob | |
46 | import inspect |
|
46 | import inspect | |
47 | import keyword |
|
47 | import keyword | |
48 | import new |
|
48 | import new | |
49 | import os |
|
49 | import os | |
50 | import pydoc |
|
50 | import pydoc | |
51 | import re |
|
51 | import re | |
52 | import shutil |
|
52 | import shutil | |
53 | import string |
|
53 | import string | |
54 | import sys |
|
54 | import sys | |
55 | import tempfile |
|
55 | import tempfile | |
56 | import traceback |
|
56 | import traceback | |
57 | import types |
|
57 | import types | |
58 | import pickleshare |
|
58 | import pickleshare | |
59 | from sets import Set |
|
59 | from sets import Set | |
60 | from pprint import pprint, pformat |
|
60 | from pprint import pprint, pformat | |
61 |
|
61 | |||
62 | # IPython's own modules |
|
62 | # IPython's own modules | |
63 | import IPython |
|
63 | import IPython | |
64 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
64 | from IPython import Debugger,OInspect,PyColorize,ultraTB | |
65 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
65 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names | |
66 | from IPython.FakeModule import FakeModule |
|
66 | from IPython.FakeModule import FakeModule | |
67 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
67 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
68 | from IPython.Logger import Logger |
|
68 | from IPython.Logger import Logger | |
69 | from IPython.Magic import Magic |
|
69 | from IPython.Magic import Magic | |
70 | from IPython.Prompts import CachedOutput |
|
70 | from IPython.Prompts import CachedOutput | |
71 | from IPython.ipstruct import Struct |
|
71 | from IPython.ipstruct import Struct | |
72 | from IPython.background_jobs import BackgroundJobManager |
|
72 | from IPython.background_jobs import BackgroundJobManager | |
73 | from IPython.usage import cmd_line_usage,interactive_usage |
|
73 | from IPython.usage import cmd_line_usage,interactive_usage | |
74 | from IPython.genutils import * |
|
74 | from IPython.genutils import * | |
75 | from IPython.strdispatch import StrDispatch |
|
75 | from IPython.strdispatch import StrDispatch | |
76 | import IPython.ipapi |
|
76 | import IPython.ipapi | |
77 |
|
77 | |||
78 | # Globals |
|
78 | # Globals | |
79 |
|
79 | |||
80 | # store the builtin raw_input globally, and use this always, in case user code |
|
80 | # store the builtin raw_input globally, and use this always, in case user code | |
81 | # overwrites it (like wx.py.PyShell does) |
|
81 | # overwrites it (like wx.py.PyShell does) | |
82 | raw_input_original = raw_input |
|
82 | raw_input_original = raw_input | |
83 |
|
83 | |||
84 | # compiled regexps for autoindent management |
|
84 | # compiled regexps for autoindent management | |
85 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
85 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
86 |
|
86 | |||
87 |
|
87 | |||
88 | #**************************************************************************** |
|
88 | #**************************************************************************** | |
89 | # Some utility function definitions |
|
89 | # Some utility function definitions | |
90 |
|
90 | |||
91 | ini_spaces_re = re.compile(r'^(\s+)') |
|
91 | ini_spaces_re = re.compile(r'^(\s+)') | |
92 |
|
92 | |||
93 | def num_ini_spaces(strng): |
|
93 | def num_ini_spaces(strng): | |
94 | """Return the number of initial spaces in a string""" |
|
94 | """Return the number of initial spaces in a string""" | |
95 |
|
95 | |||
96 | ini_spaces = ini_spaces_re.match(strng) |
|
96 | ini_spaces = ini_spaces_re.match(strng) | |
97 | if ini_spaces: |
|
97 | if ini_spaces: | |
98 | return ini_spaces.end() |
|
98 | return ini_spaces.end() | |
99 | else: |
|
99 | else: | |
100 | return 0 |
|
100 | return 0 | |
101 |
|
101 | |||
102 | def softspace(file, newvalue): |
|
102 | def softspace(file, newvalue): | |
103 | """Copied from code.py, to remove the dependency""" |
|
103 | """Copied from code.py, to remove the dependency""" | |
104 |
|
104 | |||
105 | oldvalue = 0 |
|
105 | oldvalue = 0 | |
106 | try: |
|
106 | try: | |
107 | oldvalue = file.softspace |
|
107 | oldvalue = file.softspace | |
108 | except AttributeError: |
|
108 | except AttributeError: | |
109 | pass |
|
109 | pass | |
110 | try: |
|
110 | try: | |
111 | file.softspace = newvalue |
|
111 | file.softspace = newvalue | |
112 | except (AttributeError, TypeError): |
|
112 | except (AttributeError, TypeError): | |
113 | # "attribute-less object" or "read-only attributes" |
|
113 | # "attribute-less object" or "read-only attributes" | |
114 | pass |
|
114 | pass | |
115 | return oldvalue |
|
115 | return oldvalue | |
116 |
|
116 | |||
117 |
|
117 | |||
118 | #**************************************************************************** |
|
118 | #**************************************************************************** | |
119 | # Local use exceptions |
|
119 | # Local use exceptions | |
120 | class SpaceInInput(exceptions.Exception): pass |
|
120 | class SpaceInInput(exceptions.Exception): pass | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | #**************************************************************************** |
|
123 | #**************************************************************************** | |
124 | # Local use classes |
|
124 | # Local use classes | |
125 | class Bunch: pass |
|
125 | class Bunch: pass | |
126 |
|
126 | |||
127 | class Undefined: pass |
|
127 | class Undefined: pass | |
128 |
|
128 | |||
129 | class Quitter(object): |
|
129 | class Quitter(object): | |
130 | """Simple class to handle exit, similar to Python 2.5's. |
|
130 | """Simple class to handle exit, similar to Python 2.5's. | |
131 |
|
131 | |||
132 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
132 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 | |
133 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
133 | doesn't do (obviously, since it doesn't know about ipython).""" | |
134 |
|
134 | |||
135 | def __init__(self,shell,name): |
|
135 | def __init__(self,shell,name): | |
136 | self.shell = shell |
|
136 | self.shell = shell | |
137 | self.name = name |
|
137 | self.name = name | |
138 |
|
138 | |||
139 | def __repr__(self): |
|
139 | def __repr__(self): | |
140 | return 'Type %s() to exit.' % self.name |
|
140 | return 'Type %s() to exit.' % self.name | |
141 | __str__ = __repr__ |
|
141 | __str__ = __repr__ | |
142 |
|
142 | |||
143 | def __call__(self): |
|
143 | def __call__(self): | |
144 | self.shell.exit() |
|
144 | self.shell.exit() | |
145 |
|
145 | |||
146 | class InputList(list): |
|
146 | class InputList(list): | |
147 | """Class to store user input. |
|
147 | """Class to store user input. | |
148 |
|
148 | |||
149 | It's basically a list, but slices return a string instead of a list, thus |
|
149 | It's basically a list, but slices return a string instead of a list, thus | |
150 | allowing things like (assuming 'In' is an instance): |
|
150 | allowing things like (assuming 'In' is an instance): | |
151 |
|
151 | |||
152 | exec In[4:7] |
|
152 | exec In[4:7] | |
153 |
|
153 | |||
154 | or |
|
154 | or | |
155 |
|
155 | |||
156 | exec In[5:9] + In[14] + In[21:25]""" |
|
156 | exec In[5:9] + In[14] + In[21:25]""" | |
157 |
|
157 | |||
158 | def __getslice__(self,i,j): |
|
158 | def __getslice__(self,i,j): | |
159 | return ''.join(list.__getslice__(self,i,j)) |
|
159 | return ''.join(list.__getslice__(self,i,j)) | |
160 |
|
160 | |||
161 | class SyntaxTB(ultraTB.ListTB): |
|
161 | class SyntaxTB(ultraTB.ListTB): | |
162 | """Extension which holds some state: the last exception value""" |
|
162 | """Extension which holds some state: the last exception value""" | |
163 |
|
163 | |||
164 | def __init__(self,color_scheme = 'NoColor'): |
|
164 | def __init__(self,color_scheme = 'NoColor'): | |
165 | ultraTB.ListTB.__init__(self,color_scheme) |
|
165 | ultraTB.ListTB.__init__(self,color_scheme) | |
166 | self.last_syntax_error = None |
|
166 | self.last_syntax_error = None | |
167 |
|
167 | |||
168 | def __call__(self, etype, value, elist): |
|
168 | def __call__(self, etype, value, elist): | |
169 | self.last_syntax_error = value |
|
169 | self.last_syntax_error = value | |
170 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
170 | ultraTB.ListTB.__call__(self,etype,value,elist) | |
171 |
|
171 | |||
172 | def clear_err_state(self): |
|
172 | def clear_err_state(self): | |
173 | """Return the current error state and clear it""" |
|
173 | """Return the current error state and clear it""" | |
174 | e = self.last_syntax_error |
|
174 | e = self.last_syntax_error | |
175 | self.last_syntax_error = None |
|
175 | self.last_syntax_error = None | |
176 | return e |
|
176 | return e | |
177 |
|
177 | |||
178 | #**************************************************************************** |
|
178 | #**************************************************************************** | |
179 | # Main IPython class |
|
179 | # Main IPython class | |
180 |
|
180 | |||
181 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
181 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |
182 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
182 | # until a full rewrite is made. I've cleaned all cross-class uses of | |
183 | # attributes and methods, but too much user code out there relies on the |
|
183 | # attributes and methods, but too much user code out there relies on the | |
184 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
184 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |
185 | # |
|
185 | # | |
186 | # But at least now, all the pieces have been separated and we could, in |
|
186 | # But at least now, all the pieces have been separated and we could, in | |
187 | # principle, stop using the mixin. This will ease the transition to the |
|
187 | # principle, stop using the mixin. This will ease the transition to the | |
188 | # chainsaw branch. |
|
188 | # chainsaw branch. | |
189 |
|
189 | |||
190 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
190 | # For reference, the following is the list of 'self.foo' uses in the Magic | |
191 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
191 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |
192 | # class, to prevent clashes. |
|
192 | # class, to prevent clashes. | |
193 |
|
193 | |||
194 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
194 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |
195 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
195 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |
196 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
196 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |
197 | # 'self.value'] |
|
197 | # 'self.value'] | |
198 |
|
198 | |||
199 | class InteractiveShell(object,Magic): |
|
199 | class InteractiveShell(object,Magic): | |
200 | """An enhanced console for Python.""" |
|
200 | """An enhanced console for Python.""" | |
201 |
|
201 | |||
202 | # class attribute to indicate whether the class supports threads or not. |
|
202 | # class attribute to indicate whether the class supports threads or not. | |
203 | # Subclasses with thread support should override this as needed. |
|
203 | # Subclasses with thread support should override this as needed. | |
204 | isthreaded = False |
|
204 | isthreaded = False | |
205 |
|
205 | |||
206 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
206 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
207 | user_ns = None,user_global_ns=None,banner2='', |
|
207 | user_ns = None,user_global_ns=None,banner2='', | |
208 | custom_exceptions=((),None),embedded=False): |
|
208 | custom_exceptions=((),None),embedded=False): | |
209 |
|
209 | |||
210 | # log system |
|
210 | # log system | |
211 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
211 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
212 |
|
212 | |||
213 | # some minimal strict typechecks. For some core data structures, I |
|
213 | # some minimal strict typechecks. For some core data structures, I | |
214 | # want actual basic python types, not just anything that looks like |
|
214 | # want actual basic python types, not just anything that looks like | |
215 | # one. This is especially true for namespaces. |
|
215 | # one. This is especially true for namespaces. | |
216 | for ns in (user_ns,user_global_ns): |
|
216 | for ns in (user_ns,user_global_ns): | |
217 | if ns is not None and type(ns) != types.DictType: |
|
217 | if ns is not None and type(ns) != types.DictType: | |
218 | raise TypeError,'namespace must be a dictionary' |
|
218 | raise TypeError,'namespace must be a dictionary' | |
219 |
|
219 | |||
220 | # Job manager (for jobs run as background threads) |
|
220 | # Job manager (for jobs run as background threads) | |
221 | self.jobs = BackgroundJobManager() |
|
221 | self.jobs = BackgroundJobManager() | |
222 |
|
222 | |||
223 | # Store the actual shell's name |
|
223 | # Store the actual shell's name | |
224 | self.name = name |
|
224 | self.name = name | |
225 |
|
225 | |||
226 | # We need to know whether the instance is meant for embedding, since |
|
226 | # We need to know whether the instance is meant for embedding, since | |
227 | # global/local namespaces need to be handled differently in that case |
|
227 | # global/local namespaces need to be handled differently in that case | |
228 | self.embedded = embedded |
|
228 | self.embedded = embedded | |
229 |
|
229 | |||
230 | # command compiler |
|
230 | # command compiler | |
231 | self.compile = codeop.CommandCompiler() |
|
231 | self.compile = codeop.CommandCompiler() | |
232 |
|
232 | |||
233 | # User input buffer |
|
233 | # User input buffer | |
234 | self.buffer = [] |
|
234 | self.buffer = [] | |
235 |
|
235 | |||
236 | # Default name given in compilation of code |
|
236 | # Default name given in compilation of code | |
237 | self.filename = '<ipython console>' |
|
237 | self.filename = '<ipython console>' | |
238 |
|
238 | |||
239 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
239 | # Install our own quitter instead of the builtins. For python2.3-2.4, | |
240 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
240 | # this brings in behavior like 2.5, and for 2.5 it's identical. | |
241 | __builtin__.exit = Quitter(self,'exit') |
|
241 | __builtin__.exit = Quitter(self,'exit') | |
242 | __builtin__.quit = Quitter(self,'quit') |
|
242 | __builtin__.quit = Quitter(self,'quit') | |
243 |
|
243 | |||
244 | # Make an empty namespace, which extension writers can rely on both |
|
244 | # Make an empty namespace, which extension writers can rely on both | |
245 | # existing and NEVER being used by ipython itself. This gives them a |
|
245 | # existing and NEVER being used by ipython itself. This gives them a | |
246 | # convenient location for storing additional information and state |
|
246 | # convenient location for storing additional information and state | |
247 | # their extensions may require, without fear of collisions with other |
|
247 | # their extensions may require, without fear of collisions with other | |
248 | # ipython names that may develop later. |
|
248 | # ipython names that may develop later. | |
249 | self.meta = Struct() |
|
249 | self.meta = Struct() | |
250 |
|
250 | |||
251 | # Create the namespace where the user will operate. user_ns is |
|
251 | # Create the namespace where the user will operate. user_ns is | |
252 | # normally the only one used, and it is passed to the exec calls as |
|
252 | # normally the only one used, and it is passed to the exec calls as | |
253 | # the locals argument. But we do carry a user_global_ns namespace |
|
253 | # the locals argument. But we do carry a user_global_ns namespace | |
254 | # given as the exec 'globals' argument, This is useful in embedding |
|
254 | # given as the exec 'globals' argument, This is useful in embedding | |
255 | # situations where the ipython shell opens in a context where the |
|
255 | # situations where the ipython shell opens in a context where the | |
256 | # distinction between locals and globals is meaningful. |
|
256 | # distinction between locals and globals is meaningful. | |
257 |
|
257 | |||
258 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
258 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
259 | # level as a dict instead of a module. This is a manual fix, but I |
|
259 | # level as a dict instead of a module. This is a manual fix, but I | |
260 | # should really track down where the problem is coming from. Alex |
|
260 | # should really track down where the problem is coming from. Alex | |
261 | # Schmolck reported this problem first. |
|
261 | # Schmolck reported this problem first. | |
262 |
|
262 | |||
263 | # A useful post by Alex Martelli on this topic: |
|
263 | # A useful post by Alex Martelli on this topic: | |
264 | # Re: inconsistent value from __builtins__ |
|
264 | # Re: inconsistent value from __builtins__ | |
265 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
265 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
266 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
266 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
267 | # Gruppen: comp.lang.python |
|
267 | # Gruppen: comp.lang.python | |
268 |
|
268 | |||
269 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
269 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
270 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
270 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
271 | # > <type 'dict'> |
|
271 | # > <type 'dict'> | |
272 | # > >>> print type(__builtins__) |
|
272 | # > >>> print type(__builtins__) | |
273 | # > <type 'module'> |
|
273 | # > <type 'module'> | |
274 | # > Is this difference in return value intentional? |
|
274 | # > Is this difference in return value intentional? | |
275 |
|
275 | |||
276 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
276 | # Well, it's documented that '__builtins__' can be either a dictionary | |
277 | # or a module, and it's been that way for a long time. Whether it's |
|
277 | # or a module, and it's been that way for a long time. Whether it's | |
278 | # intentional (or sensible), I don't know. In any case, the idea is |
|
278 | # intentional (or sensible), I don't know. In any case, the idea is | |
279 | # that if you need to access the built-in namespace directly, you |
|
279 | # that if you need to access the built-in namespace directly, you | |
280 | # should start with "import __builtin__" (note, no 's') which will |
|
280 | # should start with "import __builtin__" (note, no 's') which will | |
281 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
281 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
282 |
|
282 | |||
283 | # These routines return properly built dicts as needed by the rest of |
|
283 | # These routines return properly built dicts as needed by the rest of | |
284 | # the code, and can also be used by extension writers to generate |
|
284 | # the code, and can also be used by extension writers to generate | |
285 | # properly initialized namespaces. |
|
285 | # properly initialized namespaces. | |
286 | user_ns = IPython.ipapi.make_user_ns(user_ns) |
|
286 | user_ns = IPython.ipapi.make_user_ns(user_ns) | |
287 | user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns) |
|
287 | user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns) | |
288 |
|
288 | |||
289 | # Assign namespaces |
|
289 | # Assign namespaces | |
290 | # This is the namespace where all normal user variables live |
|
290 | # This is the namespace where all normal user variables live | |
291 | self.user_ns = user_ns |
|
291 | self.user_ns = user_ns | |
292 | # Embedded instances require a separate namespace for globals. |
|
292 | # Embedded instances require a separate namespace for globals. | |
293 | # Normally this one is unused by non-embedded instances. |
|
293 | # Normally this one is unused by non-embedded instances. | |
294 | self.user_global_ns = user_global_ns |
|
294 | self.user_global_ns = user_global_ns | |
295 | # A namespace to keep track of internal data structures to prevent |
|
295 | # A namespace to keep track of internal data structures to prevent | |
296 | # them from cluttering user-visible stuff. Will be updated later |
|
296 | # them from cluttering user-visible stuff. Will be updated later | |
297 | self.internal_ns = {} |
|
297 | self.internal_ns = {} | |
298 |
|
298 | |||
299 | # Namespace of system aliases. Each entry in the alias |
|
299 | # Namespace of system aliases. Each entry in the alias | |
300 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
300 | # table must be a 2-tuple of the form (N,name), where N is the number | |
301 | # of positional arguments of the alias. |
|
301 | # of positional arguments of the alias. | |
302 | self.alias_table = {} |
|
302 | self.alias_table = {} | |
303 |
|
303 | |||
304 | # A table holding all the namespaces IPython deals with, so that |
|
304 | # A table holding all the namespaces IPython deals with, so that | |
305 | # introspection facilities can search easily. |
|
305 | # introspection facilities can search easily. | |
306 | self.ns_table = {'user':user_ns, |
|
306 | self.ns_table = {'user':user_ns, | |
307 | 'user_global':user_global_ns, |
|
307 | 'user_global':user_global_ns, | |
308 | 'alias':self.alias_table, |
|
308 | 'alias':self.alias_table, | |
309 | 'internal':self.internal_ns, |
|
309 | 'internal':self.internal_ns, | |
310 | 'builtin':__builtin__.__dict__ |
|
310 | 'builtin':__builtin__.__dict__ | |
311 | } |
|
311 | } | |
312 |
|
312 | |||
313 | # The user namespace MUST have a pointer to the shell itself. |
|
313 | # The user namespace MUST have a pointer to the shell itself. | |
314 | self.user_ns[name] = self |
|
314 | self.user_ns[name] = self | |
315 |
|
315 | |||
316 | # We need to insert into sys.modules something that looks like a |
|
316 | # We need to insert into sys.modules something that looks like a | |
317 | # module but which accesses the IPython namespace, for shelve and |
|
317 | # module but which accesses the IPython namespace, for shelve and | |
318 | # pickle to work interactively. Normally they rely on getting |
|
318 | # pickle to work interactively. Normally they rely on getting | |
319 | # everything out of __main__, but for embedding purposes each IPython |
|
319 | # everything out of __main__, but for embedding purposes each IPython | |
320 | # instance has its own private namespace, so we can't go shoving |
|
320 | # instance has its own private namespace, so we can't go shoving | |
321 | # everything into __main__. |
|
321 | # everything into __main__. | |
322 |
|
322 | |||
323 | # note, however, that we should only do this for non-embedded |
|
323 | # note, however, that we should only do this for non-embedded | |
324 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
324 | # ipythons, which really mimic the __main__.__dict__ with their own | |
325 | # namespace. Embedded instances, on the other hand, should not do |
|
325 | # namespace. Embedded instances, on the other hand, should not do | |
326 | # this because they need to manage the user local/global namespaces |
|
326 | # this because they need to manage the user local/global namespaces | |
327 | # only, but they live within a 'normal' __main__ (meaning, they |
|
327 | # only, but they live within a 'normal' __main__ (meaning, they | |
328 | # shouldn't overtake the execution environment of the script they're |
|
328 | # shouldn't overtake the execution environment of the script they're | |
329 | # embedded in). |
|
329 | # embedded in). | |
330 |
|
330 | |||
331 | if not embedded: |
|
331 | if not embedded: | |
332 | try: |
|
332 | try: | |
333 | main_name = self.user_ns['__name__'] |
|
333 | main_name = self.user_ns['__name__'] | |
334 | except KeyError: |
|
334 | except KeyError: | |
335 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
335 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
336 | else: |
|
336 | else: | |
337 | #print "pickle hack in place" # dbg |
|
337 | #print "pickle hack in place" # dbg | |
338 | #print 'main_name:',main_name # dbg |
|
338 | #print 'main_name:',main_name # dbg | |
339 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
339 | sys.modules[main_name] = FakeModule(self.user_ns) | |
340 |
|
340 | |||
341 | # List of input with multi-line handling. |
|
341 | # List of input with multi-line handling. | |
342 | # Fill its zero entry, user counter starts at 1 |
|
342 | # Fill its zero entry, user counter starts at 1 | |
343 | self.input_hist = InputList(['\n']) |
|
343 | self.input_hist = InputList(['\n']) | |
344 | # This one will hold the 'raw' input history, without any |
|
344 | # This one will hold the 'raw' input history, without any | |
345 | # pre-processing. This will allow users to retrieve the input just as |
|
345 | # pre-processing. This will allow users to retrieve the input just as | |
346 | # it was exactly typed in by the user, with %hist -r. |
|
346 | # it was exactly typed in by the user, with %hist -r. | |
347 | self.input_hist_raw = InputList(['\n']) |
|
347 | self.input_hist_raw = InputList(['\n']) | |
348 |
|
348 | |||
349 | # list of visited directories |
|
349 | # list of visited directories | |
350 | try: |
|
350 | try: | |
351 | self.dir_hist = [os.getcwd()] |
|
351 | self.dir_hist = [os.getcwd()] | |
352 | except IOError, e: |
|
352 | except IOError, e: | |
353 | self.dir_hist = [] |
|
353 | self.dir_hist = [] | |
354 |
|
354 | |||
355 | # dict of output history |
|
355 | # dict of output history | |
356 | self.output_hist = {} |
|
356 | self.output_hist = {} | |
357 |
|
357 | |||
358 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
358 | # dict of things NOT to alias (keywords, builtins and some magics) | |
359 | no_alias = {} |
|
359 | no_alias = {} | |
360 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
360 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
361 | for key in keyword.kwlist + no_alias_magics: |
|
361 | for key in keyword.kwlist + no_alias_magics: | |
362 | no_alias[key] = 1 |
|
362 | no_alias[key] = 1 | |
363 | no_alias.update(__builtin__.__dict__) |
|
363 | no_alias.update(__builtin__.__dict__) | |
364 | self.no_alias = no_alias |
|
364 | self.no_alias = no_alias | |
365 |
|
365 | |||
366 | # make global variables for user access to these |
|
366 | # make global variables for user access to these | |
367 | self.user_ns['_ih'] = self.input_hist |
|
367 | self.user_ns['_ih'] = self.input_hist | |
368 | self.user_ns['_oh'] = self.output_hist |
|
368 | self.user_ns['_oh'] = self.output_hist | |
369 | self.user_ns['_dh'] = self.dir_hist |
|
369 | self.user_ns['_dh'] = self.dir_hist | |
370 |
|
370 | |||
371 | # user aliases to input and output histories |
|
371 | # user aliases to input and output histories | |
372 | self.user_ns['In'] = self.input_hist |
|
372 | self.user_ns['In'] = self.input_hist | |
373 | self.user_ns['Out'] = self.output_hist |
|
373 | self.user_ns['Out'] = self.output_hist | |
374 |
|
374 | |||
375 | # Object variable to store code object waiting execution. This is |
|
375 | # Object variable to store code object waiting execution. This is | |
376 | # used mainly by the multithreaded shells, but it can come in handy in |
|
376 | # used mainly by the multithreaded shells, but it can come in handy in | |
377 | # other situations. No need to use a Queue here, since it's a single |
|
377 | # other situations. No need to use a Queue here, since it's a single | |
378 | # item which gets cleared once run. |
|
378 | # item which gets cleared once run. | |
379 | self.code_to_run = None |
|
379 | self.code_to_run = None | |
380 |
|
380 | |||
381 | # escapes for automatic behavior on the command line |
|
381 | # escapes for automatic behavior on the command line | |
382 | self.ESC_SHELL = '!' |
|
382 | self.ESC_SHELL = '!' | |
383 | self.ESC_HELP = '?' |
|
383 | self.ESC_HELP = '?' | |
384 | self.ESC_MAGIC = '%' |
|
384 | self.ESC_MAGIC = '%' | |
385 | self.ESC_QUOTE = ',' |
|
385 | self.ESC_QUOTE = ',' | |
386 | self.ESC_QUOTE2 = ';' |
|
386 | self.ESC_QUOTE2 = ';' | |
387 | self.ESC_PAREN = '/' |
|
387 | self.ESC_PAREN = '/' | |
388 |
|
388 | |||
389 | # And their associated handlers |
|
389 | # And their associated handlers | |
390 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
390 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
391 | self.ESC_QUOTE : self.handle_auto, |
|
391 | self.ESC_QUOTE : self.handle_auto, | |
392 | self.ESC_QUOTE2 : self.handle_auto, |
|
392 | self.ESC_QUOTE2 : self.handle_auto, | |
393 | self.ESC_MAGIC : self.handle_magic, |
|
393 | self.ESC_MAGIC : self.handle_magic, | |
394 | self.ESC_HELP : self.handle_help, |
|
394 | self.ESC_HELP : self.handle_help, | |
395 | self.ESC_SHELL : self.handle_shell_escape, |
|
395 | self.ESC_SHELL : self.handle_shell_escape, | |
396 | } |
|
396 | } | |
397 |
|
397 | |||
398 | # class initializations |
|
398 | # class initializations | |
399 | Magic.__init__(self,self) |
|
399 | Magic.__init__(self,self) | |
400 |
|
400 | |||
401 | # Python source parser/formatter for syntax highlighting |
|
401 | # Python source parser/formatter for syntax highlighting | |
402 | pyformat = PyColorize.Parser().format |
|
402 | pyformat = PyColorize.Parser().format | |
403 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
403 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |
404 |
|
404 | |||
405 | # hooks holds pointers used for user-side customizations |
|
405 | # hooks holds pointers used for user-side customizations | |
406 | self.hooks = Struct() |
|
406 | self.hooks = Struct() | |
407 |
|
407 | |||
408 | self.strdispatchers = {} |
|
408 | self.strdispatchers = {} | |
409 |
|
409 | |||
410 | # Set all default hooks, defined in the IPython.hooks module. |
|
410 | # Set all default hooks, defined in the IPython.hooks module. | |
411 | hooks = IPython.hooks |
|
411 | hooks = IPython.hooks | |
412 | for hook_name in hooks.__all__: |
|
412 | for hook_name in hooks.__all__: | |
413 | # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority |
|
413 | # default hooks have priority 100, i.e. low; user hooks should have 0-100 priority | |
414 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
414 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
415 | #print "bound hook",hook_name |
|
415 | #print "bound hook",hook_name | |
416 |
|
416 | |||
417 | # Flag to mark unconditional exit |
|
417 | # Flag to mark unconditional exit | |
418 | self.exit_now = False |
|
418 | self.exit_now = False | |
419 |
|
419 | |||
420 | self.usage_min = """\ |
|
420 | self.usage_min = """\ | |
421 | An enhanced console for Python. |
|
421 | An enhanced console for Python. | |
422 | Some of its features are: |
|
422 | Some of its features are: | |
423 | - Readline support if the readline library is present. |
|
423 | - Readline support if the readline library is present. | |
424 | - Tab completion in the local namespace. |
|
424 | - Tab completion in the local namespace. | |
425 | - Logging of input, see command-line options. |
|
425 | - Logging of input, see command-line options. | |
426 | - System shell escape via ! , eg !ls. |
|
426 | - System shell escape via ! , eg !ls. | |
427 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
427 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
428 | - Keeps track of locally defined variables via %who, %whos. |
|
428 | - Keeps track of locally defined variables via %who, %whos. | |
429 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
429 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
430 | """ |
|
430 | """ | |
431 | if usage: self.usage = usage |
|
431 | if usage: self.usage = usage | |
432 | else: self.usage = self.usage_min |
|
432 | else: self.usage = self.usage_min | |
433 |
|
433 | |||
434 | # Storage |
|
434 | # Storage | |
435 | self.rc = rc # This will hold all configuration information |
|
435 | self.rc = rc # This will hold all configuration information | |
436 | self.pager = 'less' |
|
436 | self.pager = 'less' | |
437 | # temporary files used for various purposes. Deleted at exit. |
|
437 | # temporary files used for various purposes. Deleted at exit. | |
438 | self.tempfiles = [] |
|
438 | self.tempfiles = [] | |
439 |
|
439 | |||
440 | # Keep track of readline usage (later set by init_readline) |
|
440 | # Keep track of readline usage (later set by init_readline) | |
441 | self.has_readline = False |
|
441 | self.has_readline = False | |
442 |
|
442 | |||
443 | # template for logfile headers. It gets resolved at runtime by the |
|
443 | # template for logfile headers. It gets resolved at runtime by the | |
444 | # logstart method. |
|
444 | # logstart method. | |
445 | self.loghead_tpl = \ |
|
445 | self.loghead_tpl = \ | |
446 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
446 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
447 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
447 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
448 | #log# opts = %s |
|
448 | #log# opts = %s | |
449 | #log# args = %s |
|
449 | #log# args = %s | |
450 | #log# It is safe to make manual edits below here. |
|
450 | #log# It is safe to make manual edits below here. | |
451 | #log#----------------------------------------------------------------------- |
|
451 | #log#----------------------------------------------------------------------- | |
452 | """ |
|
452 | """ | |
453 | # for pushd/popd management |
|
453 | # for pushd/popd management | |
454 | try: |
|
454 | try: | |
455 | self.home_dir = get_home_dir() |
|
455 | self.home_dir = get_home_dir() | |
456 | except HomeDirError,msg: |
|
456 | except HomeDirError,msg: | |
457 | fatal(msg) |
|
457 | fatal(msg) | |
458 |
|
458 | |||
459 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] |
|
459 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] | |
460 |
|
460 | |||
461 | # Functions to call the underlying shell. |
|
461 | # Functions to call the underlying shell. | |
462 |
|
462 | |||
463 | # The first is similar to os.system, but it doesn't return a value, |
|
463 | # The first is similar to os.system, but it doesn't return a value, | |
464 | # and it allows interpolation of variables in the user's namespace. |
|
464 | # and it allows interpolation of variables in the user's namespace. | |
465 | self.system = lambda cmd: \ |
|
465 | self.system = lambda cmd: \ | |
466 | shell(self.var_expand(cmd,depth=2), |
|
466 | shell(self.var_expand(cmd,depth=2), | |
467 | header=self.rc.system_header, |
|
467 | header=self.rc.system_header, | |
468 | verbose=self.rc.system_verbose) |
|
468 | verbose=self.rc.system_verbose) | |
469 |
|
469 | |||
470 | # These are for getoutput and getoutputerror: |
|
470 | # These are for getoutput and getoutputerror: | |
471 | self.getoutput = lambda cmd: \ |
|
471 | self.getoutput = lambda cmd: \ | |
472 | getoutput(self.var_expand(cmd,depth=2), |
|
472 | getoutput(self.var_expand(cmd,depth=2), | |
473 | header=self.rc.system_header, |
|
473 | header=self.rc.system_header, | |
474 | verbose=self.rc.system_verbose) |
|
474 | verbose=self.rc.system_verbose) | |
475 |
|
475 | |||
476 | self.getoutputerror = lambda cmd: \ |
|
476 | self.getoutputerror = lambda cmd: \ | |
477 | getoutputerror(self.var_expand(cmd,depth=2), |
|
477 | getoutputerror(self.var_expand(cmd,depth=2), | |
478 | header=self.rc.system_header, |
|
478 | header=self.rc.system_header, | |
479 | verbose=self.rc.system_verbose) |
|
479 | verbose=self.rc.system_verbose) | |
480 |
|
480 | |||
481 | # RegExp for splitting line contents into pre-char//first |
|
481 | # RegExp for splitting line contents into pre-char//first | |
482 | # word-method//rest. For clarity, each group in on one line. |
|
482 | # word-method//rest. For clarity, each group in on one line. | |
483 |
|
483 | |||
484 | # WARNING: update the regexp if the above escapes are changed, as they |
|
484 | # WARNING: update the regexp if the above escapes are changed, as they | |
485 | # are hardwired in. |
|
485 | # are hardwired in. | |
486 |
|
486 | |||
487 | # Don't get carried away with trying to make the autocalling catch too |
|
487 | # Don't get carried away with trying to make the autocalling catch too | |
488 | # much: it's better to be conservative rather than to trigger hidden |
|
488 | # much: it's better to be conservative rather than to trigger hidden | |
489 | # evals() somewhere and end up causing side effects. |
|
489 | # evals() somewhere and end up causing side effects. | |
490 | self.line_split = re.compile(r'^(\s*[,;/]?\s*)' |
|
490 | self.line_split = re.compile(r'^(\s*[,;/]?\s*)' | |
491 | r'([\?\w\.]+\w*\s*)' |
|
491 | r'([\?\w\.]+\w*\s*)' | |
492 | r'(\(?.*$)') |
|
492 | r'(\(?.*$)') | |
493 |
|
493 | |||
494 | self.shell_line_split = re.compile(r'^(\s*)' |
|
494 | self.shell_line_split = re.compile(r'^(\s*)' | |
495 | r'(\S*\s*)' |
|
495 | r'(\S*\s*)' | |
496 | r'(\(?.*$)') |
|
496 | r'(\(?.*$)') | |
497 |
|
497 | |||
498 |
|
498 | |||
499 | # A simpler regexp used as a fallback if the above doesn't work. This |
|
499 | # A simpler regexp used as a fallback if the above doesn't work. This | |
500 | # one is more conservative in how it partitions the input. This code |
|
500 | # one is more conservative in how it partitions the input. This code | |
501 | # can probably be cleaned up to do everything with just one regexp, but |
|
501 | # can probably be cleaned up to do everything with just one regexp, but | |
502 | # I'm afraid of breaking something; do it once the unit tests are in |
|
502 | # I'm afraid of breaking something; do it once the unit tests are in | |
503 | # place. |
|
503 | # place. | |
504 | self.line_split_fallback = re.compile(r'^(\s*)' |
|
504 | self.line_split_fallback = re.compile(r'^(\s*)' | |
505 | r'([%\!\?\w\.]*)' |
|
505 | r'([%\!\?\w\.]*)' | |
506 | r'(.*)') |
|
506 | r'(.*)') | |
507 |
|
507 | |||
508 | # Original re, keep around for a while in case changes break something |
|
508 | # Original re, keep around for a while in case changes break something | |
509 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' |
|
509 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' | |
510 | # r'(\s*[\?\w\.]+\w*\s*)' |
|
510 | # r'(\s*[\?\w\.]+\w*\s*)' | |
511 | # r'(\(?.*$)') |
|
511 | # r'(\(?.*$)') | |
512 |
|
512 | |||
513 | # RegExp to identify potential function names |
|
513 | # RegExp to identify potential function names | |
514 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
514 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
515 |
|
515 | |||
516 | # RegExp to exclude strings with this start from autocalling. In |
|
516 | # RegExp to exclude strings with this start from autocalling. In | |
517 | # particular, all binary operators should be excluded, so that if foo |
|
517 | # particular, all binary operators should be excluded, so that if foo | |
518 | # is callable, foo OP bar doesn't become foo(OP bar), which is |
|
518 | # is callable, foo OP bar doesn't become foo(OP bar), which is | |
519 | # invalid. The characters '!=()' don't need to be checked for, as the |
|
519 | # invalid. The characters '!=()' don't need to be checked for, as the | |
520 | # _prefilter routine explicitely does so, to catch direct calls and |
|
520 | # _prefilter routine explicitely does so, to catch direct calls and | |
521 | # rebindings of existing names. |
|
521 | # rebindings of existing names. | |
522 |
|
522 | |||
523 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
523 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise | |
524 | # it affects the rest of the group in square brackets. |
|
524 | # it affects the rest of the group in square brackets. | |
525 | self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]' |
|
525 | self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]' | |
526 | '|^is |^not |^in |^and |^or ') |
|
526 | '|^is |^not |^in |^and |^or ') | |
527 |
|
527 | |||
528 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
528 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
529 | # (experimental). For this to work, the line_split regexp would need |
|
529 | # (experimental). For this to work, the line_split regexp would need | |
530 | # to be modified so it wouldn't break things at '['. That line is |
|
530 | # to be modified so it wouldn't break things at '['. That line is | |
531 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
531 | # nasty enough that I shouldn't change it until I can test it _well_. | |
532 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
532 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
533 |
|
533 | |||
534 | # keep track of where we started running (mainly for crash post-mortem) |
|
534 | # keep track of where we started running (mainly for crash post-mortem) | |
535 | self.starting_dir = os.getcwd() |
|
535 | self.starting_dir = os.getcwd() | |
536 |
|
536 | |||
537 | # Various switches which can be set |
|
537 | # Various switches which can be set | |
538 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
538 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
539 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
539 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
540 | self.banner2 = banner2 |
|
540 | self.banner2 = banner2 | |
541 |
|
541 | |||
542 | # TraceBack handlers: |
|
542 | # TraceBack handlers: | |
543 |
|
543 | |||
544 | # Syntax error handler. |
|
544 | # Syntax error handler. | |
545 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
545 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
546 |
|
546 | |||
547 | # The interactive one is initialized with an offset, meaning we always |
|
547 | # The interactive one is initialized with an offset, meaning we always | |
548 | # want to remove the topmost item in the traceback, which is our own |
|
548 | # want to remove the topmost item in the traceback, which is our own | |
549 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
549 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
550 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
550 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
551 | color_scheme='NoColor', |
|
551 | color_scheme='NoColor', | |
552 | tb_offset = 1) |
|
552 | tb_offset = 1) | |
553 |
|
553 | |||
554 | # IPython itself shouldn't crash. This will produce a detailed |
|
554 | # IPython itself shouldn't crash. This will produce a detailed | |
555 | # post-mortem if it does. But we only install the crash handler for |
|
555 | # post-mortem if it does. But we only install the crash handler for | |
556 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
556 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
557 | # and lose the crash handler. This is because exceptions in the main |
|
557 | # and lose the crash handler. This is because exceptions in the main | |
558 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
558 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
559 | # and there's no point in printing crash dumps for every user exception. |
|
559 | # and there's no point in printing crash dumps for every user exception. | |
560 | if self.isthreaded: |
|
560 | if self.isthreaded: | |
561 | ipCrashHandler = ultraTB.FormattedTB() |
|
561 | ipCrashHandler = ultraTB.FormattedTB() | |
562 | else: |
|
562 | else: | |
563 | from IPython import CrashHandler |
|
563 | from IPython import CrashHandler | |
564 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
564 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) | |
565 | self.set_crash_handler(ipCrashHandler) |
|
565 | self.set_crash_handler(ipCrashHandler) | |
566 |
|
566 | |||
567 | # and add any custom exception handlers the user may have specified |
|
567 | # and add any custom exception handlers the user may have specified | |
568 | self.set_custom_exc(*custom_exceptions) |
|
568 | self.set_custom_exc(*custom_exceptions) | |
569 |
|
569 | |||
570 | # indentation management |
|
570 | # indentation management | |
571 | self.autoindent = False |
|
571 | self.autoindent = False | |
572 | self.indent_current_nsp = 0 |
|
572 | self.indent_current_nsp = 0 | |
573 |
|
573 | |||
574 | # Make some aliases automatically |
|
574 | # Make some aliases automatically | |
575 | # Prepare list of shell aliases to auto-define |
|
575 | # Prepare list of shell aliases to auto-define | |
576 | if os.name == 'posix': |
|
576 | if os.name == 'posix': | |
577 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
577 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
578 | 'mv mv -i','rm rm -i','cp cp -i', |
|
578 | 'mv mv -i','rm rm -i','cp cp -i', | |
579 | 'cat cat','less less','clear clear', |
|
579 | 'cat cat','less less','clear clear', | |
580 | # a better ls |
|
580 | # a better ls | |
581 | 'ls ls -F', |
|
581 | 'ls ls -F', | |
582 | # long ls |
|
582 | # long ls | |
583 | 'll ls -lF') |
|
583 | 'll ls -lF') | |
584 | # Extra ls aliases with color, which need special treatment on BSD |
|
584 | # Extra ls aliases with color, which need special treatment on BSD | |
585 | # variants |
|
585 | # variants | |
586 | ls_extra = ( # color ls |
|
586 | ls_extra = ( # color ls | |
587 | 'lc ls -F -o --color', |
|
587 | 'lc ls -F -o --color', | |
588 | # ls normal files only |
|
588 | # ls normal files only | |
589 | 'lf ls -F -o --color %l | grep ^-', |
|
589 | 'lf ls -F -o --color %l | grep ^-', | |
590 | # ls symbolic links |
|
590 | # ls symbolic links | |
591 | 'lk ls -F -o --color %l | grep ^l', |
|
591 | 'lk ls -F -o --color %l | grep ^l', | |
592 | # directories or links to directories, |
|
592 | # directories or links to directories, | |
593 | 'ldir ls -F -o --color %l | grep /$', |
|
593 | 'ldir ls -F -o --color %l | grep /$', | |
594 | # things which are executable |
|
594 | # things which are executable | |
595 | 'lx ls -F -o --color %l | grep ^-..x', |
|
595 | 'lx ls -F -o --color %l | grep ^-..x', | |
596 | ) |
|
596 | ) | |
597 | # The BSDs don't ship GNU ls, so they don't understand the |
|
597 | # The BSDs don't ship GNU ls, so they don't understand the | |
598 | # --color switch out of the box |
|
598 | # --color switch out of the box | |
599 | if 'bsd' in sys.platform: |
|
599 | if 'bsd' in sys.platform: | |
600 | ls_extra = ( # ls normal files only |
|
600 | ls_extra = ( # ls normal files only | |
601 | 'lf ls -lF | grep ^-', |
|
601 | 'lf ls -lF | grep ^-', | |
602 | # ls symbolic links |
|
602 | # ls symbolic links | |
603 | 'lk ls -lF | grep ^l', |
|
603 | 'lk ls -lF | grep ^l', | |
604 | # directories or links to directories, |
|
604 | # directories or links to directories, | |
605 | 'ldir ls -lF | grep /$', |
|
605 | 'ldir ls -lF | grep /$', | |
606 | # things which are executable |
|
606 | # things which are executable | |
607 | 'lx ls -lF | grep ^-..x', |
|
607 | 'lx ls -lF | grep ^-..x', | |
608 | ) |
|
608 | ) | |
609 | auto_alias = auto_alias + ls_extra |
|
609 | auto_alias = auto_alias + ls_extra | |
610 | elif os.name in ['nt','dos']: |
|
610 | elif os.name in ['nt','dos']: | |
611 | auto_alias = ('dir dir /on', 'ls dir /on', |
|
611 | auto_alias = ('dir dir /on', 'ls dir /on', | |
612 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
612 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
613 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
613 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
614 | 'ren ren','cls cls','copy copy') |
|
614 | 'ren ren','cls cls','copy copy') | |
615 | else: |
|
615 | else: | |
616 | auto_alias = () |
|
616 | auto_alias = () | |
617 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
617 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |
618 | # Call the actual (public) initializer |
|
618 | # Call the actual (public) initializer | |
619 | self.init_auto_alias() |
|
619 | self.init_auto_alias() | |
620 |
|
620 | |||
621 | # Produce a public API instance |
|
621 | # Produce a public API instance | |
622 | self.api = IPython.ipapi.IPApi(self) |
|
622 | self.api = IPython.ipapi.IPApi(self) | |
623 |
|
623 | |||
624 | # track which builtins we add, so we can clean up later |
|
624 | # track which builtins we add, so we can clean up later | |
625 | self.builtins_added = {} |
|
625 | self.builtins_added = {} | |
626 | # This method will add the necessary builtins for operation, but |
|
626 | # This method will add the necessary builtins for operation, but | |
627 | # tracking what it did via the builtins_added dict. |
|
627 | # tracking what it did via the builtins_added dict. | |
628 | self.add_builtins() |
|
628 | self.add_builtins() | |
629 |
|
629 | |||
630 | # end __init__ |
|
630 | # end __init__ | |
631 |
|
631 | |||
632 | def var_expand(self,cmd,depth=0): |
|
632 | def var_expand(self,cmd,depth=0): | |
633 | """Expand python variables in a string. |
|
633 | """Expand python variables in a string. | |
634 |
|
634 | |||
635 | The depth argument indicates how many frames above the caller should |
|
635 | The depth argument indicates how many frames above the caller should | |
636 | be walked to look for the local namespace where to expand variables. |
|
636 | be walked to look for the local namespace where to expand variables. | |
637 |
|
637 | |||
638 | The global namespace for expansion is always the user's interactive |
|
638 | The global namespace for expansion is always the user's interactive | |
639 | namespace. |
|
639 | namespace. | |
640 | """ |
|
640 | """ | |
641 |
|
641 | |||
642 | return str(ItplNS(cmd.replace('#','\#'), |
|
642 | return str(ItplNS(cmd.replace('#','\#'), | |
643 | self.user_ns, # globals |
|
643 | self.user_ns, # globals | |
644 | # Skip our own frame in searching for locals: |
|
644 | # Skip our own frame in searching for locals: | |
645 | sys._getframe(depth+1).f_locals # locals |
|
645 | sys._getframe(depth+1).f_locals # locals | |
646 | )) |
|
646 | )) | |
647 |
|
647 | |||
648 | def pre_config_initialization(self): |
|
648 | def pre_config_initialization(self): | |
649 | """Pre-configuration init method |
|
649 | """Pre-configuration init method | |
650 |
|
650 | |||
651 | This is called before the configuration files are processed to |
|
651 | This is called before the configuration files are processed to | |
652 | prepare the services the config files might need. |
|
652 | prepare the services the config files might need. | |
653 |
|
653 | |||
654 | self.rc already has reasonable default values at this point. |
|
654 | self.rc already has reasonable default values at this point. | |
655 | """ |
|
655 | """ | |
656 | rc = self.rc |
|
656 | rc = self.rc | |
657 |
|
657 | |||
658 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
658 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") | |
659 |
|
659 | |||
660 | def post_config_initialization(self): |
|
660 | def post_config_initialization(self): | |
661 | """Post configuration init method |
|
661 | """Post configuration init method | |
662 |
|
662 | |||
663 | This is called after the configuration files have been processed to |
|
663 | This is called after the configuration files have been processed to | |
664 | 'finalize' the initialization.""" |
|
664 | 'finalize' the initialization.""" | |
665 |
|
665 | |||
666 | rc = self.rc |
|
666 | rc = self.rc | |
667 |
|
667 | |||
668 | # Object inspector |
|
668 | # Object inspector | |
669 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
669 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
670 | PyColorize.ANSICodeColors, |
|
670 | PyColorize.ANSICodeColors, | |
671 | 'NoColor', |
|
671 | 'NoColor', | |
672 | rc.object_info_string_level) |
|
672 | rc.object_info_string_level) | |
673 |
|
673 | |||
674 | # Load readline proper |
|
674 | # Load readline proper | |
675 | if rc.readline: |
|
675 | if rc.readline: | |
676 | self.init_readline() |
|
676 | self.init_readline() | |
677 |
|
677 | |||
678 | # local shortcut, this is used a LOT |
|
678 | # local shortcut, this is used a LOT | |
679 | self.log = self.logger.log |
|
679 | self.log = self.logger.log | |
680 |
|
680 | |||
681 | # Initialize cache, set in/out prompts and printing system |
|
681 | # Initialize cache, set in/out prompts and printing system | |
682 | self.outputcache = CachedOutput(self, |
|
682 | self.outputcache = CachedOutput(self, | |
683 | rc.cache_size, |
|
683 | rc.cache_size, | |
684 | rc.pprint, |
|
684 | rc.pprint, | |
685 | input_sep = rc.separate_in, |
|
685 | input_sep = rc.separate_in, | |
686 | output_sep = rc.separate_out, |
|
686 | output_sep = rc.separate_out, | |
687 | output_sep2 = rc.separate_out2, |
|
687 | output_sep2 = rc.separate_out2, | |
688 | ps1 = rc.prompt_in1, |
|
688 | ps1 = rc.prompt_in1, | |
689 | ps2 = rc.prompt_in2, |
|
689 | ps2 = rc.prompt_in2, | |
690 | ps_out = rc.prompt_out, |
|
690 | ps_out = rc.prompt_out, | |
691 | pad_left = rc.prompts_pad_left) |
|
691 | pad_left = rc.prompts_pad_left) | |
692 |
|
692 | |||
693 | # user may have over-ridden the default print hook: |
|
693 | # user may have over-ridden the default print hook: | |
694 | try: |
|
694 | try: | |
695 | self.outputcache.__class__.display = self.hooks.display |
|
695 | self.outputcache.__class__.display = self.hooks.display | |
696 | except AttributeError: |
|
696 | except AttributeError: | |
697 | pass |
|
697 | pass | |
698 |
|
698 | |||
699 | # I don't like assigning globally to sys, because it means when |
|
699 | # I don't like assigning globally to sys, because it means when | |
700 | # embedding instances, each embedded instance overrides the previous |
|
700 | # embedding instances, each embedded instance overrides the previous | |
701 | # choice. But sys.displayhook seems to be called internally by exec, |
|
701 | # choice. But sys.displayhook seems to be called internally by exec, | |
702 | # so I don't see a way around it. We first save the original and then |
|
702 | # so I don't see a way around it. We first save the original and then | |
703 | # overwrite it. |
|
703 | # overwrite it. | |
704 | self.sys_displayhook = sys.displayhook |
|
704 | self.sys_displayhook = sys.displayhook | |
705 | sys.displayhook = self.outputcache |
|
705 | sys.displayhook = self.outputcache | |
706 |
|
706 | |||
707 | # Set user colors (don't do it in the constructor above so that it |
|
707 | # Set user colors (don't do it in the constructor above so that it | |
708 | # doesn't crash if colors option is invalid) |
|
708 | # doesn't crash if colors option is invalid) | |
709 | self.magic_colors(rc.colors) |
|
709 | self.magic_colors(rc.colors) | |
710 |
|
710 | |||
711 | # Set calling of pdb on exceptions |
|
711 | # Set calling of pdb on exceptions | |
712 | self.call_pdb = rc.pdb |
|
712 | self.call_pdb = rc.pdb | |
713 |
|
713 | |||
714 | # Load user aliases |
|
714 | # Load user aliases | |
715 | for alias in rc.alias: |
|
715 | for alias in rc.alias: | |
716 | self.magic_alias(alias) |
|
716 | self.magic_alias(alias) | |
717 | self.hooks.late_startup_hook() |
|
717 | self.hooks.late_startup_hook() | |
718 |
|
718 | |||
719 | batchrun = False |
|
719 | batchrun = False | |
720 | for batchfile in [path(arg) for arg in self.rc.args |
|
720 | for batchfile in [path(arg) for arg in self.rc.args | |
721 | if arg.lower().endswith('.ipy')]: |
|
721 | if arg.lower().endswith('.ipy')]: | |
722 | if not batchfile.isfile(): |
|
722 | if not batchfile.isfile(): | |
723 | print "No such batch file:", batchfile |
|
723 | print "No such batch file:", batchfile | |
724 | continue |
|
724 | continue | |
725 | self.api.runlines(batchfile.text()) |
|
725 | self.api.runlines(batchfile.text()) | |
726 | batchrun = True |
|
726 | batchrun = True | |
727 | if batchrun: |
|
727 | if batchrun: | |
728 | self.exit_now = True |
|
728 | self.exit_now = True | |
729 |
|
729 | |||
730 | def add_builtins(self): |
|
730 | def add_builtins(self): | |
731 | """Store ipython references into the builtin namespace. |
|
731 | """Store ipython references into the builtin namespace. | |
732 |
|
732 | |||
733 | Some parts of ipython operate via builtins injected here, which hold a |
|
733 | Some parts of ipython operate via builtins injected here, which hold a | |
734 | reference to IPython itself.""" |
|
734 | reference to IPython itself.""" | |
735 |
|
735 | |||
736 | # TODO: deprecate all except _ip; 'jobs' should be installed |
|
736 | # TODO: deprecate all except _ip; 'jobs' should be installed | |
737 | # by an extension and the rest are under _ip, ipalias is redundant |
|
737 | # by an extension and the rest are under _ip, ipalias is redundant | |
738 | builtins_new = dict(__IPYTHON__ = self, |
|
738 | builtins_new = dict(__IPYTHON__ = self, | |
739 | ip_set_hook = self.set_hook, |
|
739 | ip_set_hook = self.set_hook, | |
740 | jobs = self.jobs, |
|
740 | jobs = self.jobs, | |
741 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
741 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), | |
742 | ipalias = wrap_deprecated(self.ipalias), |
|
742 | ipalias = wrap_deprecated(self.ipalias), | |
743 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
743 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), | |
744 | _ip = self.api |
|
744 | _ip = self.api | |
745 | ) |
|
745 | ) | |
746 | for biname,bival in builtins_new.items(): |
|
746 | for biname,bival in builtins_new.items(): | |
747 | try: |
|
747 | try: | |
748 | # store the orignal value so we can restore it |
|
748 | # store the orignal value so we can restore it | |
749 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
749 | self.builtins_added[biname] = __builtin__.__dict__[biname] | |
750 | except KeyError: |
|
750 | except KeyError: | |
751 | # or mark that it wasn't defined, and we'll just delete it at |
|
751 | # or mark that it wasn't defined, and we'll just delete it at | |
752 | # cleanup |
|
752 | # cleanup | |
753 | self.builtins_added[biname] = Undefined |
|
753 | self.builtins_added[biname] = Undefined | |
754 | __builtin__.__dict__[biname] = bival |
|
754 | __builtin__.__dict__[biname] = bival | |
755 |
|
755 | |||
756 | # Keep in the builtins a flag for when IPython is active. We set it |
|
756 | # Keep in the builtins a flag for when IPython is active. We set it | |
757 | # with setdefault so that multiple nested IPythons don't clobber one |
|
757 | # with setdefault so that multiple nested IPythons don't clobber one | |
758 | # another. Each will increase its value by one upon being activated, |
|
758 | # another. Each will increase its value by one upon being activated, | |
759 | # which also gives us a way to determine the nesting level. |
|
759 | # which also gives us a way to determine the nesting level. | |
760 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
760 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
761 |
|
761 | |||
762 | def clean_builtins(self): |
|
762 | def clean_builtins(self): | |
763 | """Remove any builtins which might have been added by add_builtins, or |
|
763 | """Remove any builtins which might have been added by add_builtins, or | |
764 | restore overwritten ones to their previous values.""" |
|
764 | restore overwritten ones to their previous values.""" | |
765 | for biname,bival in self.builtins_added.items(): |
|
765 | for biname,bival in self.builtins_added.items(): | |
766 | if bival is Undefined: |
|
766 | if bival is Undefined: | |
767 | del __builtin__.__dict__[biname] |
|
767 | del __builtin__.__dict__[biname] | |
768 | else: |
|
768 | else: | |
769 | __builtin__.__dict__[biname] = bival |
|
769 | __builtin__.__dict__[biname] = bival | |
770 | self.builtins_added.clear() |
|
770 | self.builtins_added.clear() | |
771 |
|
771 | |||
772 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
772 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
773 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
773 | """set_hook(name,hook) -> sets an internal IPython hook. | |
774 |
|
774 | |||
775 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
775 | IPython exposes some of its internal API as user-modifiable hooks. By | |
776 | adding your function to one of these hooks, you can modify IPython's |
|
776 | adding your function to one of these hooks, you can modify IPython's | |
777 | behavior to call at runtime your own routines.""" |
|
777 | behavior to call at runtime your own routines.""" | |
778 |
|
778 | |||
779 | # At some point in the future, this should validate the hook before it |
|
779 | # At some point in the future, this should validate the hook before it | |
780 | # accepts it. Probably at least check that the hook takes the number |
|
780 | # accepts it. Probably at least check that the hook takes the number | |
781 | # of args it's supposed to. |
|
781 | # of args it's supposed to. | |
782 |
|
782 | |||
783 | f = new.instancemethod(hook,self,self.__class__) |
|
783 | f = new.instancemethod(hook,self,self.__class__) | |
784 |
|
784 | |||
785 | # check if the hook is for strdispatcher first |
|
785 | # check if the hook is for strdispatcher first | |
786 | if str_key is not None: |
|
786 | if str_key is not None: | |
787 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
787 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
788 | sdp.add_s(str_key, f, priority ) |
|
788 | sdp.add_s(str_key, f, priority ) | |
789 | self.strdispatchers[name] = sdp |
|
789 | self.strdispatchers[name] = sdp | |
790 | return |
|
790 | return | |
791 | if re_key is not None: |
|
791 | if re_key is not None: | |
792 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
792 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
793 | sdp.add_re(re.compile(re_key), f, priority ) |
|
793 | sdp.add_re(re.compile(re_key), f, priority ) | |
794 | self.strdispatchers[name] = sdp |
|
794 | self.strdispatchers[name] = sdp | |
795 | return |
|
795 | return | |
796 |
|
796 | |||
797 | dp = getattr(self.hooks, name, None) |
|
797 | dp = getattr(self.hooks, name, None) | |
798 | if name not in IPython.hooks.__all__: |
|
798 | if name not in IPython.hooks.__all__: | |
799 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
799 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) | |
800 | if not dp: |
|
800 | if not dp: | |
801 | dp = IPython.hooks.CommandChainDispatcher() |
|
801 | dp = IPython.hooks.CommandChainDispatcher() | |
802 |
|
802 | |||
803 | try: |
|
803 | try: | |
804 | dp.add(f,priority) |
|
804 | dp.add(f,priority) | |
805 | except AttributeError: |
|
805 | except AttributeError: | |
806 | # it was not commandchain, plain old func - replace |
|
806 | # it was not commandchain, plain old func - replace | |
807 | dp = f |
|
807 | dp = f | |
808 |
|
808 | |||
809 | setattr(self.hooks,name, dp) |
|
809 | setattr(self.hooks,name, dp) | |
810 |
|
810 | |||
811 |
|
811 | |||
812 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
812 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
813 |
|
813 | |||
814 | def set_crash_handler(self,crashHandler): |
|
814 | def set_crash_handler(self,crashHandler): | |
815 | """Set the IPython crash handler. |
|
815 | """Set the IPython crash handler. | |
816 |
|
816 | |||
817 | This must be a callable with a signature suitable for use as |
|
817 | This must be a callable with a signature suitable for use as | |
818 | sys.excepthook.""" |
|
818 | sys.excepthook.""" | |
819 |
|
819 | |||
820 | # Install the given crash handler as the Python exception hook |
|
820 | # Install the given crash handler as the Python exception hook | |
821 | sys.excepthook = crashHandler |
|
821 | sys.excepthook = crashHandler | |
822 |
|
822 | |||
823 | # The instance will store a pointer to this, so that runtime code |
|
823 | # The instance will store a pointer to this, so that runtime code | |
824 | # (such as magics) can access it. This is because during the |
|
824 | # (such as magics) can access it. This is because during the | |
825 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
825 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
826 | # frameworks). |
|
826 | # frameworks). | |
827 | self.sys_excepthook = sys.excepthook |
|
827 | self.sys_excepthook = sys.excepthook | |
828 |
|
828 | |||
829 |
|
829 | |||
830 | def set_custom_exc(self,exc_tuple,handler): |
|
830 | def set_custom_exc(self,exc_tuple,handler): | |
831 | """set_custom_exc(exc_tuple,handler) |
|
831 | """set_custom_exc(exc_tuple,handler) | |
832 |
|
832 | |||
833 | Set a custom exception handler, which will be called if any of the |
|
833 | Set a custom exception handler, which will be called if any of the | |
834 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
834 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
835 | runcode() method. |
|
835 | runcode() method. | |
836 |
|
836 | |||
837 | Inputs: |
|
837 | Inputs: | |
838 |
|
838 | |||
839 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
839 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
840 | handler for. It is very important that you use a tuple, and NOT A |
|
840 | handler for. It is very important that you use a tuple, and NOT A | |
841 | LIST here, because of the way Python's except statement works. If |
|
841 | LIST here, because of the way Python's except statement works. If | |
842 | you only want to trap a single exception, use a singleton tuple: |
|
842 | you only want to trap a single exception, use a singleton tuple: | |
843 |
|
843 | |||
844 | exc_tuple == (MyCustomException,) |
|
844 | exc_tuple == (MyCustomException,) | |
845 |
|
845 | |||
846 | - handler: this must be defined as a function with the following |
|
846 | - handler: this must be defined as a function with the following | |
847 | basic interface: def my_handler(self,etype,value,tb). |
|
847 | basic interface: def my_handler(self,etype,value,tb). | |
848 |
|
848 | |||
849 | This will be made into an instance method (via new.instancemethod) |
|
849 | This will be made into an instance method (via new.instancemethod) | |
850 | of IPython itself, and it will be called if any of the exceptions |
|
850 | of IPython itself, and it will be called if any of the exceptions | |
851 | listed in the exc_tuple are caught. If the handler is None, an |
|
851 | listed in the exc_tuple are caught. If the handler is None, an | |
852 | internal basic one is used, which just prints basic info. |
|
852 | internal basic one is used, which just prints basic info. | |
853 |
|
853 | |||
854 | WARNING: by putting in your own exception handler into IPython's main |
|
854 | WARNING: by putting in your own exception handler into IPython's main | |
855 | execution loop, you run a very good chance of nasty crashes. This |
|
855 | execution loop, you run a very good chance of nasty crashes. This | |
856 | facility should only be used if you really know what you are doing.""" |
|
856 | facility should only be used if you really know what you are doing.""" | |
857 |
|
857 | |||
858 | assert type(exc_tuple)==type(()) , \ |
|
858 | assert type(exc_tuple)==type(()) , \ | |
859 | "The custom exceptions must be given AS A TUPLE." |
|
859 | "The custom exceptions must be given AS A TUPLE." | |
860 |
|
860 | |||
861 | def dummy_handler(self,etype,value,tb): |
|
861 | def dummy_handler(self,etype,value,tb): | |
862 | print '*** Simple custom exception handler ***' |
|
862 | print '*** Simple custom exception handler ***' | |
863 | print 'Exception type :',etype |
|
863 | print 'Exception type :',etype | |
864 | print 'Exception value:',value |
|
864 | print 'Exception value:',value | |
865 | print 'Traceback :',tb |
|
865 | print 'Traceback :',tb | |
866 | print 'Source code :','\n'.join(self.buffer) |
|
866 | print 'Source code :','\n'.join(self.buffer) | |
867 |
|
867 | |||
868 | if handler is None: handler = dummy_handler |
|
868 | if handler is None: handler = dummy_handler | |
869 |
|
869 | |||
870 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
870 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
871 | self.custom_exceptions = exc_tuple |
|
871 | self.custom_exceptions = exc_tuple | |
872 |
|
872 | |||
873 | def set_custom_completer(self,completer,pos=0): |
|
873 | def set_custom_completer(self,completer,pos=0): | |
874 | """set_custom_completer(completer,pos=0) |
|
874 | """set_custom_completer(completer,pos=0) | |
875 |
|
875 | |||
876 | Adds a new custom completer function. |
|
876 | Adds a new custom completer function. | |
877 |
|
877 | |||
878 | The position argument (defaults to 0) is the index in the completers |
|
878 | The position argument (defaults to 0) is the index in the completers | |
879 | list where you want the completer to be inserted.""" |
|
879 | list where you want the completer to be inserted.""" | |
880 |
|
880 | |||
881 | newcomp = new.instancemethod(completer,self.Completer, |
|
881 | newcomp = new.instancemethod(completer,self.Completer, | |
882 | self.Completer.__class__) |
|
882 | self.Completer.__class__) | |
883 | self.Completer.matchers.insert(pos,newcomp) |
|
883 | self.Completer.matchers.insert(pos,newcomp) | |
884 |
|
884 | |||
|
885 | def set_completer(self): | |||
|
886 | """reset readline's completer to be our own.""" | |||
|
887 | self.readline.set_completer(self.Completer.complete) | |||
|
888 | ||||
885 | def _get_call_pdb(self): |
|
889 | def _get_call_pdb(self): | |
886 | return self._call_pdb |
|
890 | return self._call_pdb | |
887 |
|
891 | |||
888 | def _set_call_pdb(self,val): |
|
892 | def _set_call_pdb(self,val): | |
889 |
|
893 | |||
890 | if val not in (0,1,False,True): |
|
894 | if val not in (0,1,False,True): | |
891 | raise ValueError,'new call_pdb value must be boolean' |
|
895 | raise ValueError,'new call_pdb value must be boolean' | |
892 |
|
896 | |||
893 | # store value in instance |
|
897 | # store value in instance | |
894 | self._call_pdb = val |
|
898 | self._call_pdb = val | |
895 |
|
899 | |||
896 | # notify the actual exception handlers |
|
900 | # notify the actual exception handlers | |
897 | self.InteractiveTB.call_pdb = val |
|
901 | self.InteractiveTB.call_pdb = val | |
898 | if self.isthreaded: |
|
902 | if self.isthreaded: | |
899 | try: |
|
903 | try: | |
900 | self.sys_excepthook.call_pdb = val |
|
904 | self.sys_excepthook.call_pdb = val | |
901 | except: |
|
905 | except: | |
902 | warn('Failed to activate pdb for threaded exception handler') |
|
906 | warn('Failed to activate pdb for threaded exception handler') | |
903 |
|
907 | |||
904 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
908 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
905 | 'Control auto-activation of pdb at exceptions') |
|
909 | 'Control auto-activation of pdb at exceptions') | |
906 |
|
910 | |||
907 |
|
911 | |||
908 | # These special functions get installed in the builtin namespace, to |
|
912 | # These special functions get installed in the builtin namespace, to | |
909 | # provide programmatic (pure python) access to magics, aliases and system |
|
913 | # provide programmatic (pure python) access to magics, aliases and system | |
910 | # calls. This is important for logging, user scripting, and more. |
|
914 | # calls. This is important for logging, user scripting, and more. | |
911 |
|
915 | |||
912 | # We are basically exposing, via normal python functions, the three |
|
916 | # We are basically exposing, via normal python functions, the three | |
913 | # mechanisms in which ipython offers special call modes (magics for |
|
917 | # mechanisms in which ipython offers special call modes (magics for | |
914 | # internal control, aliases for direct system access via pre-selected |
|
918 | # internal control, aliases for direct system access via pre-selected | |
915 | # names, and !cmd for calling arbitrary system commands). |
|
919 | # names, and !cmd for calling arbitrary system commands). | |
916 |
|
920 | |||
917 | def ipmagic(self,arg_s): |
|
921 | def ipmagic(self,arg_s): | |
918 | """Call a magic function by name. |
|
922 | """Call a magic function by name. | |
919 |
|
923 | |||
920 | Input: a string containing the name of the magic function to call and any |
|
924 | Input: a string containing the name of the magic function to call and any | |
921 | additional arguments to be passed to the magic. |
|
925 | additional arguments to be passed to the magic. | |
922 |
|
926 | |||
923 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
927 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
924 | prompt: |
|
928 | prompt: | |
925 |
|
929 | |||
926 | In[1]: %name -opt foo bar |
|
930 | In[1]: %name -opt foo bar | |
927 |
|
931 | |||
928 | To call a magic without arguments, simply use ipmagic('name'). |
|
932 | To call a magic without arguments, simply use ipmagic('name'). | |
929 |
|
933 | |||
930 | This provides a proper Python function to call IPython's magics in any |
|
934 | This provides a proper Python function to call IPython's magics in any | |
931 | valid Python code you can type at the interpreter, including loops and |
|
935 | valid Python code you can type at the interpreter, including loops and | |
932 | compound statements. It is added by IPython to the Python builtin |
|
936 | compound statements. It is added by IPython to the Python builtin | |
933 | namespace upon initialization.""" |
|
937 | namespace upon initialization.""" | |
934 |
|
938 | |||
935 | args = arg_s.split(' ',1) |
|
939 | args = arg_s.split(' ',1) | |
936 | magic_name = args[0] |
|
940 | magic_name = args[0] | |
937 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
941 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
938 |
|
942 | |||
939 | try: |
|
943 | try: | |
940 | magic_args = args[1] |
|
944 | magic_args = args[1] | |
941 | except IndexError: |
|
945 | except IndexError: | |
942 | magic_args = '' |
|
946 | magic_args = '' | |
943 | fn = getattr(self,'magic_'+magic_name,None) |
|
947 | fn = getattr(self,'magic_'+magic_name,None) | |
944 | if fn is None: |
|
948 | if fn is None: | |
945 | error("Magic function `%s` not found." % magic_name) |
|
949 | error("Magic function `%s` not found." % magic_name) | |
946 | else: |
|
950 | else: | |
947 | magic_args = self.var_expand(magic_args,1) |
|
951 | magic_args = self.var_expand(magic_args,1) | |
948 | return fn(magic_args) |
|
952 | return fn(magic_args) | |
949 |
|
953 | |||
950 | def ipalias(self,arg_s): |
|
954 | def ipalias(self,arg_s): | |
951 | """Call an alias by name. |
|
955 | """Call an alias by name. | |
952 |
|
956 | |||
953 | Input: a string containing the name of the alias to call and any |
|
957 | Input: a string containing the name of the alias to call and any | |
954 | additional arguments to be passed to the magic. |
|
958 | additional arguments to be passed to the magic. | |
955 |
|
959 | |||
956 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
960 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
957 | prompt: |
|
961 | prompt: | |
958 |
|
962 | |||
959 | In[1]: name -opt foo bar |
|
963 | In[1]: name -opt foo bar | |
960 |
|
964 | |||
961 | To call an alias without arguments, simply use ipalias('name'). |
|
965 | To call an alias without arguments, simply use ipalias('name'). | |
962 |
|
966 | |||
963 | This provides a proper Python function to call IPython's aliases in any |
|
967 | This provides a proper Python function to call IPython's aliases in any | |
964 | valid Python code you can type at the interpreter, including loops and |
|
968 | valid Python code you can type at the interpreter, including loops and | |
965 | compound statements. It is added by IPython to the Python builtin |
|
969 | compound statements. It is added by IPython to the Python builtin | |
966 | namespace upon initialization.""" |
|
970 | namespace upon initialization.""" | |
967 |
|
971 | |||
968 | args = arg_s.split(' ',1) |
|
972 | args = arg_s.split(' ',1) | |
969 | alias_name = args[0] |
|
973 | alias_name = args[0] | |
970 | try: |
|
974 | try: | |
971 | alias_args = args[1] |
|
975 | alias_args = args[1] | |
972 | except IndexError: |
|
976 | except IndexError: | |
973 | alias_args = '' |
|
977 | alias_args = '' | |
974 | if alias_name in self.alias_table: |
|
978 | if alias_name in self.alias_table: | |
975 | self.call_alias(alias_name,alias_args) |
|
979 | self.call_alias(alias_name,alias_args) | |
976 | else: |
|
980 | else: | |
977 | error("Alias `%s` not found." % alias_name) |
|
981 | error("Alias `%s` not found." % alias_name) | |
978 |
|
982 | |||
979 | def ipsystem(self,arg_s): |
|
983 | def ipsystem(self,arg_s): | |
980 | """Make a system call, using IPython.""" |
|
984 | """Make a system call, using IPython.""" | |
981 |
|
985 | |||
982 | self.system(arg_s) |
|
986 | self.system(arg_s) | |
983 |
|
987 | |||
984 | def complete(self,text): |
|
988 | def complete(self,text): | |
985 | """Return a sorted list of all possible completions on text. |
|
989 | """Return a sorted list of all possible completions on text. | |
986 |
|
990 | |||
987 | Inputs: |
|
991 | Inputs: | |
988 |
|
992 | |||
989 | - text: a string of text to be completed on. |
|
993 | - text: a string of text to be completed on. | |
990 |
|
994 | |||
991 | This is a wrapper around the completion mechanism, similar to what |
|
995 | This is a wrapper around the completion mechanism, similar to what | |
992 | readline does at the command line when the TAB key is hit. By |
|
996 | readline does at the command line when the TAB key is hit. By | |
993 | exposing it as a method, it can be used by other non-readline |
|
997 | exposing it as a method, it can be used by other non-readline | |
994 | environments (such as GUIs) for text completion. |
|
998 | environments (such as GUIs) for text completion. | |
995 |
|
999 | |||
996 | Simple usage example: |
|
1000 | Simple usage example: | |
997 |
|
1001 | |||
998 | In [1]: x = 'hello' |
|
1002 | In [1]: x = 'hello' | |
999 |
|
1003 | |||
1000 | In [2]: __IP.complete('x.l') |
|
1004 | In [2]: __IP.complete('x.l') | |
1001 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
1005 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" | |
1002 |
|
1006 | |||
1003 | complete = self.Completer.complete |
|
1007 | complete = self.Completer.complete | |
1004 | state = 0 |
|
1008 | state = 0 | |
1005 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1009 | # use a dict so we get unique keys, since ipyhton's multiple | |
1006 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1010 | # completers can return duplicates. When we make 2.4 a requirement, | |
1007 | # start using sets instead, which are faster. |
|
1011 | # start using sets instead, which are faster. | |
1008 | comps = {} |
|
1012 | comps = {} | |
1009 | while True: |
|
1013 | while True: | |
1010 | newcomp = complete(text,state,line_buffer=text) |
|
1014 | newcomp = complete(text,state,line_buffer=text) | |
1011 | if newcomp is None: |
|
1015 | if newcomp is None: | |
1012 | break |
|
1016 | break | |
1013 | comps[newcomp] = 1 |
|
1017 | comps[newcomp] = 1 | |
1014 | state += 1 |
|
1018 | state += 1 | |
1015 | outcomps = comps.keys() |
|
1019 | outcomps = comps.keys() | |
1016 | outcomps.sort() |
|
1020 | outcomps.sort() | |
1017 | return outcomps |
|
1021 | return outcomps | |
1018 |
|
1022 | |||
1019 | def set_completer_frame(self, frame=None): |
|
1023 | def set_completer_frame(self, frame=None): | |
1020 | if frame: |
|
1024 | if frame: | |
1021 | self.Completer.namespace = frame.f_locals |
|
1025 | self.Completer.namespace = frame.f_locals | |
1022 | self.Completer.global_namespace = frame.f_globals |
|
1026 | self.Completer.global_namespace = frame.f_globals | |
1023 | else: |
|
1027 | else: | |
1024 | self.Completer.namespace = self.user_ns |
|
1028 | self.Completer.namespace = self.user_ns | |
1025 | self.Completer.global_namespace = self.user_global_ns |
|
1029 | self.Completer.global_namespace = self.user_global_ns | |
1026 |
|
1030 | |||
1027 | def init_auto_alias(self): |
|
1031 | def init_auto_alias(self): | |
1028 | """Define some aliases automatically. |
|
1032 | """Define some aliases automatically. | |
1029 |
|
1033 | |||
1030 | These are ALL parameter-less aliases""" |
|
1034 | These are ALL parameter-less aliases""" | |
1031 |
|
1035 | |||
1032 | for alias,cmd in self.auto_alias: |
|
1036 | for alias,cmd in self.auto_alias: | |
1033 | self.alias_table[alias] = (0,cmd) |
|
1037 | self.alias_table[alias] = (0,cmd) | |
1034 |
|
1038 | |||
1035 | def alias_table_validate(self,verbose=0): |
|
1039 | def alias_table_validate(self,verbose=0): | |
1036 | """Update information about the alias table. |
|
1040 | """Update information about the alias table. | |
1037 |
|
1041 | |||
1038 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1042 | In particular, make sure no Python keywords/builtins are in it.""" | |
1039 |
|
1043 | |||
1040 | no_alias = self.no_alias |
|
1044 | no_alias = self.no_alias | |
1041 | for k in self.alias_table.keys(): |
|
1045 | for k in self.alias_table.keys(): | |
1042 | if k in no_alias: |
|
1046 | if k in no_alias: | |
1043 | del self.alias_table[k] |
|
1047 | del self.alias_table[k] | |
1044 | if verbose: |
|
1048 | if verbose: | |
1045 | print ("Deleting alias <%s>, it's a Python " |
|
1049 | print ("Deleting alias <%s>, it's a Python " | |
1046 | "keyword or builtin." % k) |
|
1050 | "keyword or builtin." % k) | |
1047 |
|
1051 | |||
1048 | def set_autoindent(self,value=None): |
|
1052 | def set_autoindent(self,value=None): | |
1049 | """Set the autoindent flag, checking for readline support. |
|
1053 | """Set the autoindent flag, checking for readline support. | |
1050 |
|
1054 | |||
1051 | If called with no arguments, it acts as a toggle.""" |
|
1055 | If called with no arguments, it acts as a toggle.""" | |
1052 |
|
1056 | |||
1053 | if not self.has_readline: |
|
1057 | if not self.has_readline: | |
1054 | if os.name == 'posix': |
|
1058 | if os.name == 'posix': | |
1055 | warn("The auto-indent feature requires the readline library") |
|
1059 | warn("The auto-indent feature requires the readline library") | |
1056 | self.autoindent = 0 |
|
1060 | self.autoindent = 0 | |
1057 | return |
|
1061 | return | |
1058 | if value is None: |
|
1062 | if value is None: | |
1059 | self.autoindent = not self.autoindent |
|
1063 | self.autoindent = not self.autoindent | |
1060 | else: |
|
1064 | else: | |
1061 | self.autoindent = value |
|
1065 | self.autoindent = value | |
1062 |
|
1066 | |||
1063 | def rc_set_toggle(self,rc_field,value=None): |
|
1067 | def rc_set_toggle(self,rc_field,value=None): | |
1064 | """Set or toggle a field in IPython's rc config. structure. |
|
1068 | """Set or toggle a field in IPython's rc config. structure. | |
1065 |
|
1069 | |||
1066 | If called with no arguments, it acts as a toggle. |
|
1070 | If called with no arguments, it acts as a toggle. | |
1067 |
|
1071 | |||
1068 | If called with a non-existent field, the resulting AttributeError |
|
1072 | If called with a non-existent field, the resulting AttributeError | |
1069 | exception will propagate out.""" |
|
1073 | exception will propagate out.""" | |
1070 |
|
1074 | |||
1071 | rc_val = getattr(self.rc,rc_field) |
|
1075 | rc_val = getattr(self.rc,rc_field) | |
1072 | if value is None: |
|
1076 | if value is None: | |
1073 | value = not rc_val |
|
1077 | value = not rc_val | |
1074 | setattr(self.rc,rc_field,value) |
|
1078 | setattr(self.rc,rc_field,value) | |
1075 |
|
1079 | |||
1076 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1080 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
1077 | """Install the user configuration directory. |
|
1081 | """Install the user configuration directory. | |
1078 |
|
1082 | |||
1079 | Can be called when running for the first time or to upgrade the user's |
|
1083 | Can be called when running for the first time or to upgrade the user's | |
1080 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
1084 | .ipython/ directory with the mode parameter. Valid modes are 'install' | |
1081 | and 'upgrade'.""" |
|
1085 | and 'upgrade'.""" | |
1082 |
|
1086 | |||
1083 | def wait(): |
|
1087 | def wait(): | |
1084 | try: |
|
1088 | try: | |
1085 | raw_input("Please press <RETURN> to start IPython.") |
|
1089 | raw_input("Please press <RETURN> to start IPython.") | |
1086 | except EOFError: |
|
1090 | except EOFError: | |
1087 | print >> Term.cout |
|
1091 | print >> Term.cout | |
1088 | print '*'*70 |
|
1092 | print '*'*70 | |
1089 |
|
1093 | |||
1090 | cwd = os.getcwd() # remember where we started |
|
1094 | cwd = os.getcwd() # remember where we started | |
1091 | glb = glob.glob |
|
1095 | glb = glob.glob | |
1092 | print '*'*70 |
|
1096 | print '*'*70 | |
1093 | if mode == 'install': |
|
1097 | if mode == 'install': | |
1094 | print \ |
|
1098 | print \ | |
1095 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1099 | """Welcome to IPython. I will try to create a personal configuration directory | |
1096 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1100 | where you can customize many aspects of IPython's functionality in:\n""" | |
1097 | else: |
|
1101 | else: | |
1098 | print 'I am going to upgrade your configuration in:' |
|
1102 | print 'I am going to upgrade your configuration in:' | |
1099 |
|
1103 | |||
1100 | print ipythondir |
|
1104 | print ipythondir | |
1101 |
|
1105 | |||
1102 | rcdirend = os.path.join('IPython','UserConfig') |
|
1106 | rcdirend = os.path.join('IPython','UserConfig') | |
1103 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1107 | cfg = lambda d: os.path.join(d,rcdirend) | |
1104 | try: |
|
1108 | try: | |
1105 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1109 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
1106 | except IOError: |
|
1110 | except IOError: | |
1107 | warning = """ |
|
1111 | warning = """ | |
1108 | Installation error. IPython's directory was not found. |
|
1112 | Installation error. IPython's directory was not found. | |
1109 |
|
1113 | |||
1110 | Check the following: |
|
1114 | Check the following: | |
1111 |
|
1115 | |||
1112 | The ipython/IPython directory should be in a directory belonging to your |
|
1116 | The ipython/IPython directory should be in a directory belonging to your | |
1113 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1117 | PYTHONPATH environment variable (that is, it should be in a directory | |
1114 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1118 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
1115 |
|
1119 | |||
1116 | IPython will proceed with builtin defaults. |
|
1120 | IPython will proceed with builtin defaults. | |
1117 | """ |
|
1121 | """ | |
1118 | warn(warning) |
|
1122 | warn(warning) | |
1119 | wait() |
|
1123 | wait() | |
1120 | return |
|
1124 | return | |
1121 |
|
1125 | |||
1122 | if mode == 'install': |
|
1126 | if mode == 'install': | |
1123 | try: |
|
1127 | try: | |
1124 | shutil.copytree(rcdir,ipythondir) |
|
1128 | shutil.copytree(rcdir,ipythondir) | |
1125 | os.chdir(ipythondir) |
|
1129 | os.chdir(ipythondir) | |
1126 | rc_files = glb("ipythonrc*") |
|
1130 | rc_files = glb("ipythonrc*") | |
1127 | for rc_file in rc_files: |
|
1131 | for rc_file in rc_files: | |
1128 | os.rename(rc_file,rc_file+rc_suffix) |
|
1132 | os.rename(rc_file,rc_file+rc_suffix) | |
1129 | except: |
|
1133 | except: | |
1130 | warning = """ |
|
1134 | warning = """ | |
1131 |
|
1135 | |||
1132 | There was a problem with the installation: |
|
1136 | There was a problem with the installation: | |
1133 | %s |
|
1137 | %s | |
1134 | Try to correct it or contact the developers if you think it's a bug. |
|
1138 | Try to correct it or contact the developers if you think it's a bug. | |
1135 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1139 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
1136 | warn(warning) |
|
1140 | warn(warning) | |
1137 | wait() |
|
1141 | wait() | |
1138 | return |
|
1142 | return | |
1139 |
|
1143 | |||
1140 | elif mode == 'upgrade': |
|
1144 | elif mode == 'upgrade': | |
1141 | try: |
|
1145 | try: | |
1142 | os.chdir(ipythondir) |
|
1146 | os.chdir(ipythondir) | |
1143 | except: |
|
1147 | except: | |
1144 | print """ |
|
1148 | print """ | |
1145 | Can not upgrade: changing to directory %s failed. Details: |
|
1149 | Can not upgrade: changing to directory %s failed. Details: | |
1146 | %s |
|
1150 | %s | |
1147 | """ % (ipythondir,sys.exc_info()[1]) |
|
1151 | """ % (ipythondir,sys.exc_info()[1]) | |
1148 | wait() |
|
1152 | wait() | |
1149 | return |
|
1153 | return | |
1150 | else: |
|
1154 | else: | |
1151 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1155 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
1152 | for new_full_path in sources: |
|
1156 | for new_full_path in sources: | |
1153 | new_filename = os.path.basename(new_full_path) |
|
1157 | new_filename = os.path.basename(new_full_path) | |
1154 | if new_filename.startswith('ipythonrc'): |
|
1158 | if new_filename.startswith('ipythonrc'): | |
1155 | new_filename = new_filename + rc_suffix |
|
1159 | new_filename = new_filename + rc_suffix | |
1156 | # The config directory should only contain files, skip any |
|
1160 | # The config directory should only contain files, skip any | |
1157 | # directories which may be there (like CVS) |
|
1161 | # directories which may be there (like CVS) | |
1158 | if os.path.isdir(new_full_path): |
|
1162 | if os.path.isdir(new_full_path): | |
1159 | continue |
|
1163 | continue | |
1160 | if os.path.exists(new_filename): |
|
1164 | if os.path.exists(new_filename): | |
1161 | old_file = new_filename+'.old' |
|
1165 | old_file = new_filename+'.old' | |
1162 | if os.path.exists(old_file): |
|
1166 | if os.path.exists(old_file): | |
1163 | os.remove(old_file) |
|
1167 | os.remove(old_file) | |
1164 | os.rename(new_filename,old_file) |
|
1168 | os.rename(new_filename,old_file) | |
1165 | shutil.copy(new_full_path,new_filename) |
|
1169 | shutil.copy(new_full_path,new_filename) | |
1166 | else: |
|
1170 | else: | |
1167 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1171 | raise ValueError,'unrecognized mode for install:',`mode` | |
1168 |
|
1172 | |||
1169 | # Fix line-endings to those native to each platform in the config |
|
1173 | # Fix line-endings to those native to each platform in the config | |
1170 | # directory. |
|
1174 | # directory. | |
1171 | try: |
|
1175 | try: | |
1172 | os.chdir(ipythondir) |
|
1176 | os.chdir(ipythondir) | |
1173 | except: |
|
1177 | except: | |
1174 | print """ |
|
1178 | print """ | |
1175 | Problem: changing to directory %s failed. |
|
1179 | Problem: changing to directory %s failed. | |
1176 | Details: |
|
1180 | Details: | |
1177 | %s |
|
1181 | %s | |
1178 |
|
1182 | |||
1179 | Some configuration files may have incorrect line endings. This should not |
|
1183 | Some configuration files may have incorrect line endings. This should not | |
1180 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1184 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) | |
1181 | wait() |
|
1185 | wait() | |
1182 | else: |
|
1186 | else: | |
1183 | for fname in glb('ipythonrc*'): |
|
1187 | for fname in glb('ipythonrc*'): | |
1184 | try: |
|
1188 | try: | |
1185 | native_line_ends(fname,backup=0) |
|
1189 | native_line_ends(fname,backup=0) | |
1186 | except IOError: |
|
1190 | except IOError: | |
1187 | pass |
|
1191 | pass | |
1188 |
|
1192 | |||
1189 | if mode == 'install': |
|
1193 | if mode == 'install': | |
1190 | print """ |
|
1194 | print """ | |
1191 | Successful installation! |
|
1195 | Successful installation! | |
1192 |
|
1196 | |||
1193 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1197 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
1194 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1198 | IPython manual (there are both HTML and PDF versions supplied with the | |
1195 | distribution) to make sure that your system environment is properly configured |
|
1199 | distribution) to make sure that your system environment is properly configured | |
1196 | to take advantage of IPython's features. |
|
1200 | to take advantage of IPython's features. | |
1197 |
|
1201 | |||
1198 | Important note: the configuration system has changed! The old system is |
|
1202 | Important note: the configuration system has changed! The old system is | |
1199 | still in place, but its setting may be partly overridden by the settings in |
|
1203 | still in place, but its setting may be partly overridden by the settings in | |
1200 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1204 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
1201 | if some of the new settings bother you. |
|
1205 | if some of the new settings bother you. | |
1202 |
|
1206 | |||
1203 | """ |
|
1207 | """ | |
1204 | else: |
|
1208 | else: | |
1205 | print """ |
|
1209 | print """ | |
1206 | Successful upgrade! |
|
1210 | Successful upgrade! | |
1207 |
|
1211 | |||
1208 | All files in your directory: |
|
1212 | All files in your directory: | |
1209 | %(ipythondir)s |
|
1213 | %(ipythondir)s | |
1210 | which would have been overwritten by the upgrade were backed up with a .old |
|
1214 | which would have been overwritten by the upgrade were backed up with a .old | |
1211 | extension. If you had made particular customizations in those files you may |
|
1215 | extension. If you had made particular customizations in those files you may | |
1212 | want to merge them back into the new files.""" % locals() |
|
1216 | want to merge them back into the new files.""" % locals() | |
1213 | wait() |
|
1217 | wait() | |
1214 | os.chdir(cwd) |
|
1218 | os.chdir(cwd) | |
1215 | # end user_setup() |
|
1219 | # end user_setup() | |
1216 |
|
1220 | |||
1217 | def atexit_operations(self): |
|
1221 | def atexit_operations(self): | |
1218 | """This will be executed at the time of exit. |
|
1222 | """This will be executed at the time of exit. | |
1219 |
|
1223 | |||
1220 | Saving of persistent data should be performed here. """ |
|
1224 | Saving of persistent data should be performed here. """ | |
1221 |
|
1225 | |||
1222 | #print '*** IPython exit cleanup ***' # dbg |
|
1226 | #print '*** IPython exit cleanup ***' # dbg | |
1223 | # input history |
|
1227 | # input history | |
1224 | self.savehist() |
|
1228 | self.savehist() | |
1225 |
|
1229 | |||
1226 | # Cleanup all tempfiles left around |
|
1230 | # Cleanup all tempfiles left around | |
1227 | for tfile in self.tempfiles: |
|
1231 | for tfile in self.tempfiles: | |
1228 | try: |
|
1232 | try: | |
1229 | os.unlink(tfile) |
|
1233 | os.unlink(tfile) | |
1230 | except OSError: |
|
1234 | except OSError: | |
1231 | pass |
|
1235 | pass | |
1232 |
|
1236 | |||
1233 | # save the "persistent data" catch-all dictionary |
|
1237 | # save the "persistent data" catch-all dictionary | |
1234 | self.hooks.shutdown_hook() |
|
1238 | self.hooks.shutdown_hook() | |
1235 |
|
1239 | |||
1236 | def savehist(self): |
|
1240 | def savehist(self): | |
1237 | """Save input history to a file (via readline library).""" |
|
1241 | """Save input history to a file (via readline library).""" | |
1238 | try: |
|
1242 | try: | |
1239 | self.readline.write_history_file(self.histfile) |
|
1243 | self.readline.write_history_file(self.histfile) | |
1240 | except: |
|
1244 | except: | |
1241 | print 'Unable to save IPython command history to file: ' + \ |
|
1245 | print 'Unable to save IPython command history to file: ' + \ | |
1242 | `self.histfile` |
|
1246 | `self.histfile` | |
1243 |
|
1247 | |||
1244 | def history_saving_wrapper(self, func): |
|
1248 | def history_saving_wrapper(self, func): | |
1245 | """ Wrap func for readline history saving |
|
1249 | """ Wrap func for readline history saving | |
1246 |
|
1250 | |||
1247 | Convert func into callable that saves & restores |
|
1251 | Convert func into callable that saves & restores | |
1248 | history around the call """ |
|
1252 | history around the call """ | |
1249 |
|
1253 | |||
1250 | if not self.has_readline: |
|
1254 | if not self.has_readline: | |
1251 | return func |
|
1255 | return func | |
1252 |
|
1256 | |||
1253 | def wrapper(): |
|
1257 | def wrapper(): | |
1254 | self.savehist() |
|
1258 | self.savehist() | |
1255 | try: |
|
1259 | try: | |
1256 | func() |
|
1260 | func() | |
1257 | finally: |
|
1261 | finally: | |
1258 | readline.read_history_file(self.histfile) |
|
1262 | readline.read_history_file(self.histfile) | |
1259 | return wrapper |
|
1263 | return wrapper | |
1260 |
|
1264 | |||
1261 |
|
1265 | |||
1262 | def pre_readline(self): |
|
1266 | def pre_readline(self): | |
1263 | """readline hook to be used at the start of each line. |
|
1267 | """readline hook to be used at the start of each line. | |
1264 |
|
1268 | |||
1265 | Currently it handles auto-indent only.""" |
|
1269 | Currently it handles auto-indent only.""" | |
1266 |
|
1270 | |||
1267 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1271 | #debugx('self.indent_current_nsp','pre_readline:') | |
1268 | self.readline.insert_text(self.indent_current_str()) |
|
1272 | self.readline.insert_text(self.indent_current_str()) | |
1269 |
|
1273 | |||
1270 | def init_readline(self): |
|
1274 | def init_readline(self): | |
1271 | """Command history completion/saving/reloading.""" |
|
1275 | """Command history completion/saving/reloading.""" | |
1272 |
|
1276 | |||
1273 | import IPython.rlineimpl as readline |
|
1277 | import IPython.rlineimpl as readline | |
1274 | if not readline.have_readline: |
|
1278 | if not readline.have_readline: | |
1275 | self.has_readline = 0 |
|
1279 | self.has_readline = 0 | |
1276 | self.readline = None |
|
1280 | self.readline = None | |
1277 | # no point in bugging windows users with this every time: |
|
1281 | # no point in bugging windows users with this every time: | |
1278 | warn('Readline services not available on this platform.') |
|
1282 | warn('Readline services not available on this platform.') | |
1279 | else: |
|
1283 | else: | |
1280 | sys.modules['readline'] = readline |
|
1284 | sys.modules['readline'] = readline | |
1281 | import atexit |
|
1285 | import atexit | |
1282 | from IPython.completer import IPCompleter |
|
1286 | from IPython.completer import IPCompleter | |
1283 | self.Completer = IPCompleter(self, |
|
1287 | self.Completer = IPCompleter(self, | |
1284 | self.user_ns, |
|
1288 | self.user_ns, | |
1285 | self.user_global_ns, |
|
1289 | self.user_global_ns, | |
1286 | self.rc.readline_omit__names, |
|
1290 | self.rc.readline_omit__names, | |
1287 | self.alias_table) |
|
1291 | self.alias_table) | |
1288 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1292 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1289 | self.strdispatchers['complete_command'] = sdisp |
|
1293 | self.strdispatchers['complete_command'] = sdisp | |
1290 | self.Completer.custom_completers = sdisp |
|
1294 | self.Completer.custom_completers = sdisp | |
1291 | # Platform-specific configuration |
|
1295 | # Platform-specific configuration | |
1292 | if os.name == 'nt': |
|
1296 | if os.name == 'nt': | |
1293 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1297 | self.readline_startup_hook = readline.set_pre_input_hook | |
1294 | else: |
|
1298 | else: | |
1295 | self.readline_startup_hook = readline.set_startup_hook |
|
1299 | self.readline_startup_hook = readline.set_startup_hook | |
1296 |
|
1300 | |||
1297 | # Load user's initrc file (readline config) |
|
1301 | # Load user's initrc file (readline config) | |
1298 | inputrc_name = os.environ.get('INPUTRC') |
|
1302 | inputrc_name = os.environ.get('INPUTRC') | |
1299 | if inputrc_name is None: |
|
1303 | if inputrc_name is None: | |
1300 | home_dir = get_home_dir() |
|
1304 | home_dir = get_home_dir() | |
1301 | if home_dir is not None: |
|
1305 | if home_dir is not None: | |
1302 | inputrc_name = os.path.join(home_dir,'.inputrc') |
|
1306 | inputrc_name = os.path.join(home_dir,'.inputrc') | |
1303 | if os.path.isfile(inputrc_name): |
|
1307 | if os.path.isfile(inputrc_name): | |
1304 | try: |
|
1308 | try: | |
1305 | readline.read_init_file(inputrc_name) |
|
1309 | readline.read_init_file(inputrc_name) | |
1306 | except: |
|
1310 | except: | |
1307 | warn('Problems reading readline initialization file <%s>' |
|
1311 | warn('Problems reading readline initialization file <%s>' | |
1308 | % inputrc_name) |
|
1312 | % inputrc_name) | |
1309 |
|
1313 | |||
1310 | self.has_readline = 1 |
|
1314 | self.has_readline = 1 | |
1311 | self.readline = readline |
|
1315 | self.readline = readline | |
1312 | # save this in sys so embedded copies can restore it properly |
|
1316 | # save this in sys so embedded copies can restore it properly | |
1313 | sys.ipcompleter = self.Completer.complete |
|
1317 | sys.ipcompleter = self.Completer.complete | |
1314 |
|
|
1318 | self.set_completer() | |
1315 |
|
1319 | |||
1316 | # Configure readline according to user's prefs |
|
1320 | # Configure readline according to user's prefs | |
1317 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1321 | for rlcommand in self.rc.readline_parse_and_bind: | |
1318 | readline.parse_and_bind(rlcommand) |
|
1322 | readline.parse_and_bind(rlcommand) | |
1319 |
|
1323 | |||
1320 | # remove some chars from the delimiters list |
|
1324 | # remove some chars from the delimiters list | |
1321 | delims = readline.get_completer_delims() |
|
1325 | delims = readline.get_completer_delims() | |
1322 | delims = delims.translate(string._idmap, |
|
1326 | delims = delims.translate(string._idmap, | |
1323 | self.rc.readline_remove_delims) |
|
1327 | self.rc.readline_remove_delims) | |
1324 | readline.set_completer_delims(delims) |
|
1328 | readline.set_completer_delims(delims) | |
1325 | # otherwise we end up with a monster history after a while: |
|
1329 | # otherwise we end up with a monster history after a while: | |
1326 | readline.set_history_length(1000) |
|
1330 | readline.set_history_length(1000) | |
1327 | try: |
|
1331 | try: | |
1328 | #print '*** Reading readline history' # dbg |
|
1332 | #print '*** Reading readline history' # dbg | |
1329 | readline.read_history_file(self.histfile) |
|
1333 | readline.read_history_file(self.histfile) | |
1330 | except IOError: |
|
1334 | except IOError: | |
1331 | pass # It doesn't exist yet. |
|
1335 | pass # It doesn't exist yet. | |
1332 |
|
1336 | |||
1333 | atexit.register(self.atexit_operations) |
|
1337 | atexit.register(self.atexit_operations) | |
1334 | del atexit |
|
1338 | del atexit | |
1335 |
|
1339 | |||
1336 | # Configure auto-indent for all platforms |
|
1340 | # Configure auto-indent for all platforms | |
1337 | self.set_autoindent(self.rc.autoindent) |
|
1341 | self.set_autoindent(self.rc.autoindent) | |
1338 |
|
1342 | |||
1339 | def ask_yes_no(self,prompt,default=True): |
|
1343 | def ask_yes_no(self,prompt,default=True): | |
1340 | if self.rc.quiet: |
|
1344 | if self.rc.quiet: | |
1341 | return True |
|
1345 | return True | |
1342 | return ask_yes_no(prompt,default) |
|
1346 | return ask_yes_no(prompt,default) | |
1343 |
|
1347 | |||
1344 | def _should_recompile(self,e): |
|
1348 | def _should_recompile(self,e): | |
1345 | """Utility routine for edit_syntax_error""" |
|
1349 | """Utility routine for edit_syntax_error""" | |
1346 |
|
1350 | |||
1347 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1351 | if e.filename in ('<ipython console>','<input>','<string>', | |
1348 | '<console>','<BackgroundJob compilation>', |
|
1352 | '<console>','<BackgroundJob compilation>', | |
1349 | None): |
|
1353 | None): | |
1350 |
|
1354 | |||
1351 | return False |
|
1355 | return False | |
1352 | try: |
|
1356 | try: | |
1353 | if (self.rc.autoedit_syntax and |
|
1357 | if (self.rc.autoedit_syntax and | |
1354 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1358 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1355 | '[Y/n] ','y')): |
|
1359 | '[Y/n] ','y')): | |
1356 | return False |
|
1360 | return False | |
1357 | except EOFError: |
|
1361 | except EOFError: | |
1358 | return False |
|
1362 | return False | |
1359 |
|
1363 | |||
1360 | def int0(x): |
|
1364 | def int0(x): | |
1361 | try: |
|
1365 | try: | |
1362 | return int(x) |
|
1366 | return int(x) | |
1363 | except TypeError: |
|
1367 | except TypeError: | |
1364 | return 0 |
|
1368 | return 0 | |
1365 | # always pass integer line and offset values to editor hook |
|
1369 | # always pass integer line and offset values to editor hook | |
1366 | self.hooks.fix_error_editor(e.filename, |
|
1370 | self.hooks.fix_error_editor(e.filename, | |
1367 | int0(e.lineno),int0(e.offset),e.msg) |
|
1371 | int0(e.lineno),int0(e.offset),e.msg) | |
1368 | return True |
|
1372 | return True | |
1369 |
|
1373 | |||
1370 | def edit_syntax_error(self): |
|
1374 | def edit_syntax_error(self): | |
1371 | """The bottom half of the syntax error handler called in the main loop. |
|
1375 | """The bottom half of the syntax error handler called in the main loop. | |
1372 |
|
1376 | |||
1373 | Loop until syntax error is fixed or user cancels. |
|
1377 | Loop until syntax error is fixed or user cancels. | |
1374 | """ |
|
1378 | """ | |
1375 |
|
1379 | |||
1376 | while self.SyntaxTB.last_syntax_error: |
|
1380 | while self.SyntaxTB.last_syntax_error: | |
1377 | # copy and clear last_syntax_error |
|
1381 | # copy and clear last_syntax_error | |
1378 | err = self.SyntaxTB.clear_err_state() |
|
1382 | err = self.SyntaxTB.clear_err_state() | |
1379 | if not self._should_recompile(err): |
|
1383 | if not self._should_recompile(err): | |
1380 | return |
|
1384 | return | |
1381 | try: |
|
1385 | try: | |
1382 | # may set last_syntax_error again if a SyntaxError is raised |
|
1386 | # may set last_syntax_error again if a SyntaxError is raised | |
1383 | self.safe_execfile(err.filename,self.user_ns) |
|
1387 | self.safe_execfile(err.filename,self.user_ns) | |
1384 | except: |
|
1388 | except: | |
1385 | self.showtraceback() |
|
1389 | self.showtraceback() | |
1386 | else: |
|
1390 | else: | |
1387 | try: |
|
1391 | try: | |
1388 | f = file(err.filename) |
|
1392 | f = file(err.filename) | |
1389 | try: |
|
1393 | try: | |
1390 | sys.displayhook(f.read()) |
|
1394 | sys.displayhook(f.read()) | |
1391 | finally: |
|
1395 | finally: | |
1392 | f.close() |
|
1396 | f.close() | |
1393 | except: |
|
1397 | except: | |
1394 | self.showtraceback() |
|
1398 | self.showtraceback() | |
1395 |
|
1399 | |||
1396 | def showsyntaxerror(self, filename=None): |
|
1400 | def showsyntaxerror(self, filename=None): | |
1397 | """Display the syntax error that just occurred. |
|
1401 | """Display the syntax error that just occurred. | |
1398 |
|
1402 | |||
1399 | This doesn't display a stack trace because there isn't one. |
|
1403 | This doesn't display a stack trace because there isn't one. | |
1400 |
|
1404 | |||
1401 | If a filename is given, it is stuffed in the exception instead |
|
1405 | If a filename is given, it is stuffed in the exception instead | |
1402 | of what was there before (because Python's parser always uses |
|
1406 | of what was there before (because Python's parser always uses | |
1403 | "<string>" when reading from a string). |
|
1407 | "<string>" when reading from a string). | |
1404 | """ |
|
1408 | """ | |
1405 | etype, value, last_traceback = sys.exc_info() |
|
1409 | etype, value, last_traceback = sys.exc_info() | |
1406 |
|
1410 | |||
1407 | # See note about these variables in showtraceback() below |
|
1411 | # See note about these variables in showtraceback() below | |
1408 | sys.last_type = etype |
|
1412 | sys.last_type = etype | |
1409 | sys.last_value = value |
|
1413 | sys.last_value = value | |
1410 | sys.last_traceback = last_traceback |
|
1414 | sys.last_traceback = last_traceback | |
1411 |
|
1415 | |||
1412 | if filename and etype is SyntaxError: |
|
1416 | if filename and etype is SyntaxError: | |
1413 | # Work hard to stuff the correct filename in the exception |
|
1417 | # Work hard to stuff the correct filename in the exception | |
1414 | try: |
|
1418 | try: | |
1415 | msg, (dummy_filename, lineno, offset, line) = value |
|
1419 | msg, (dummy_filename, lineno, offset, line) = value | |
1416 | except: |
|
1420 | except: | |
1417 | # Not the format we expect; leave it alone |
|
1421 | # Not the format we expect; leave it alone | |
1418 | pass |
|
1422 | pass | |
1419 | else: |
|
1423 | else: | |
1420 | # Stuff in the right filename |
|
1424 | # Stuff in the right filename | |
1421 | try: |
|
1425 | try: | |
1422 | # Assume SyntaxError is a class exception |
|
1426 | # Assume SyntaxError is a class exception | |
1423 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1427 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1424 | except: |
|
1428 | except: | |
1425 | # If that failed, assume SyntaxError is a string |
|
1429 | # If that failed, assume SyntaxError is a string | |
1426 | value = msg, (filename, lineno, offset, line) |
|
1430 | value = msg, (filename, lineno, offset, line) | |
1427 | self.SyntaxTB(etype,value,[]) |
|
1431 | self.SyntaxTB(etype,value,[]) | |
1428 |
|
1432 | |||
1429 | def debugger(self,force=False): |
|
1433 | def debugger(self,force=False): | |
1430 | """Call the pydb/pdb debugger. |
|
1434 | """Call the pydb/pdb debugger. | |
1431 |
|
1435 | |||
1432 | Keywords: |
|
1436 | Keywords: | |
1433 |
|
1437 | |||
1434 | - force(False): by default, this routine checks the instance call_pdb |
|
1438 | - force(False): by default, this routine checks the instance call_pdb | |
1435 | flag and does not actually invoke the debugger if the flag is false. |
|
1439 | flag and does not actually invoke the debugger if the flag is false. | |
1436 | The 'force' option forces the debugger to activate even if the flag |
|
1440 | The 'force' option forces the debugger to activate even if the flag | |
1437 | is false. |
|
1441 | is false. | |
1438 | """ |
|
1442 | """ | |
1439 |
|
1443 | |||
1440 | if not (force or self.call_pdb): |
|
1444 | if not (force or self.call_pdb): | |
1441 | return |
|
1445 | return | |
1442 |
|
1446 | |||
1443 | if not hasattr(sys,'last_traceback'): |
|
1447 | if not hasattr(sys,'last_traceback'): | |
1444 | error('No traceback has been produced, nothing to debug.') |
|
1448 | error('No traceback has been produced, nothing to debug.') | |
1445 | return |
|
1449 | return | |
1446 |
|
1450 | |||
1447 | # use pydb if available |
|
1451 | # use pydb if available | |
1448 | if Debugger.has_pydb: |
|
1452 | if Debugger.has_pydb: | |
1449 | from pydb import pm |
|
1453 | from pydb import pm | |
1450 | else: |
|
1454 | else: | |
1451 | # fallback to our internal debugger |
|
1455 | # fallback to our internal debugger | |
1452 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1456 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
1453 | self.history_saving_wrapper(pm)() |
|
1457 | self.history_saving_wrapper(pm)() | |
1454 |
|
1458 | |||
1455 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1459 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1456 | """Display the exception that just occurred. |
|
1460 | """Display the exception that just occurred. | |
1457 |
|
1461 | |||
1458 | If nothing is known about the exception, this is the method which |
|
1462 | If nothing is known about the exception, this is the method which | |
1459 | should be used throughout the code for presenting user tracebacks, |
|
1463 | should be used throughout the code for presenting user tracebacks, | |
1460 | rather than directly invoking the InteractiveTB object. |
|
1464 | rather than directly invoking the InteractiveTB object. | |
1461 |
|
1465 | |||
1462 | A specific showsyntaxerror() also exists, but this method can take |
|
1466 | A specific showsyntaxerror() also exists, but this method can take | |
1463 | care of calling it if needed, so unless you are explicitly catching a |
|
1467 | care of calling it if needed, so unless you are explicitly catching a | |
1464 | SyntaxError exception, don't try to analyze the stack manually and |
|
1468 | SyntaxError exception, don't try to analyze the stack manually and | |
1465 | simply call this method.""" |
|
1469 | simply call this method.""" | |
1466 |
|
1470 | |||
1467 | # Though this won't be called by syntax errors in the input line, |
|
1471 | # Though this won't be called by syntax errors in the input line, | |
1468 | # there may be SyntaxError cases whith imported code. |
|
1472 | # there may be SyntaxError cases whith imported code. | |
1469 | if exc_tuple is None: |
|
1473 | if exc_tuple is None: | |
1470 | etype, value, tb = sys.exc_info() |
|
1474 | etype, value, tb = sys.exc_info() | |
1471 | else: |
|
1475 | else: | |
1472 | etype, value, tb = exc_tuple |
|
1476 | etype, value, tb = exc_tuple | |
1473 |
|
1477 | |||
1474 | if etype is SyntaxError: |
|
1478 | if etype is SyntaxError: | |
1475 | self.showsyntaxerror(filename) |
|
1479 | self.showsyntaxerror(filename) | |
1476 | else: |
|
1480 | else: | |
1477 | # WARNING: these variables are somewhat deprecated and not |
|
1481 | # WARNING: these variables are somewhat deprecated and not | |
1478 | # necessarily safe to use in a threaded environment, but tools |
|
1482 | # necessarily safe to use in a threaded environment, but tools | |
1479 | # like pdb depend on their existence, so let's set them. If we |
|
1483 | # like pdb depend on their existence, so let's set them. If we | |
1480 | # find problems in the field, we'll need to revisit their use. |
|
1484 | # find problems in the field, we'll need to revisit their use. | |
1481 | sys.last_type = etype |
|
1485 | sys.last_type = etype | |
1482 | sys.last_value = value |
|
1486 | sys.last_value = value | |
1483 | sys.last_traceback = tb |
|
1487 | sys.last_traceback = tb | |
1484 |
|
1488 | |||
1485 | if etype in self.custom_exceptions: |
|
1489 | if etype in self.custom_exceptions: | |
1486 | self.CustomTB(etype,value,tb) |
|
1490 | self.CustomTB(etype,value,tb) | |
1487 | else: |
|
1491 | else: | |
1488 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1492 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1489 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1493 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1490 | # pdb mucks up readline, fix it back |
|
1494 | # pdb mucks up readline, fix it back | |
1491 |
self. |
|
1495 | self.set_completer() | |
1492 |
|
1496 | |||
1493 | def mainloop(self,banner=None): |
|
1497 | def mainloop(self,banner=None): | |
1494 | """Creates the local namespace and starts the mainloop. |
|
1498 | """Creates the local namespace and starts the mainloop. | |
1495 |
|
1499 | |||
1496 | If an optional banner argument is given, it will override the |
|
1500 | If an optional banner argument is given, it will override the | |
1497 | internally created default banner.""" |
|
1501 | internally created default banner.""" | |
1498 |
|
1502 | |||
1499 | if self.rc.c: # Emulate Python's -c option |
|
1503 | if self.rc.c: # Emulate Python's -c option | |
1500 | self.exec_init_cmd() |
|
1504 | self.exec_init_cmd() | |
1501 | if banner is None: |
|
1505 | if banner is None: | |
1502 | if not self.rc.banner: |
|
1506 | if not self.rc.banner: | |
1503 | banner = '' |
|
1507 | banner = '' | |
1504 | # banner is string? Use it directly! |
|
1508 | # banner is string? Use it directly! | |
1505 | elif isinstance(self.rc.banner,basestring): |
|
1509 | elif isinstance(self.rc.banner,basestring): | |
1506 | banner = self.rc.banner |
|
1510 | banner = self.rc.banner | |
1507 | else: |
|
1511 | else: | |
1508 | banner = self.BANNER+self.banner2 |
|
1512 | banner = self.BANNER+self.banner2 | |
1509 |
|
1513 | |||
1510 | self.interact(banner) |
|
1514 | self.interact(banner) | |
1511 |
|
1515 | |||
1512 | def exec_init_cmd(self): |
|
1516 | def exec_init_cmd(self): | |
1513 | """Execute a command given at the command line. |
|
1517 | """Execute a command given at the command line. | |
1514 |
|
1518 | |||
1515 | This emulates Python's -c option.""" |
|
1519 | This emulates Python's -c option.""" | |
1516 |
|
1520 | |||
1517 | #sys.argv = ['-c'] |
|
1521 | #sys.argv = ['-c'] | |
1518 | self.push(self.rc.c) |
|
1522 | self.push(self.rc.c) | |
1519 |
|
1523 | |||
1520 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1524 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1521 | """Embeds IPython into a running python program. |
|
1525 | """Embeds IPython into a running python program. | |
1522 |
|
1526 | |||
1523 | Input: |
|
1527 | Input: | |
1524 |
|
1528 | |||
1525 | - header: An optional header message can be specified. |
|
1529 | - header: An optional header message can be specified. | |
1526 |
|
1530 | |||
1527 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1531 | - local_ns, global_ns: working namespaces. If given as None, the | |
1528 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1532 | IPython-initialized one is updated with __main__.__dict__, so that | |
1529 | program variables become visible but user-specific configuration |
|
1533 | program variables become visible but user-specific configuration | |
1530 | remains possible. |
|
1534 | remains possible. | |
1531 |
|
1535 | |||
1532 | - stack_depth: specifies how many levels in the stack to go to |
|
1536 | - stack_depth: specifies how many levels in the stack to go to | |
1533 | looking for namespaces (when local_ns and global_ns are None). This |
|
1537 | looking for namespaces (when local_ns and global_ns are None). This | |
1534 | allows an intermediate caller to make sure that this function gets |
|
1538 | allows an intermediate caller to make sure that this function gets | |
1535 | the namespace from the intended level in the stack. By default (0) |
|
1539 | the namespace from the intended level in the stack. By default (0) | |
1536 | it will get its locals and globals from the immediate caller. |
|
1540 | it will get its locals and globals from the immediate caller. | |
1537 |
|
1541 | |||
1538 | Warning: it's possible to use this in a program which is being run by |
|
1542 | Warning: it's possible to use this in a program which is being run by | |
1539 | IPython itself (via %run), but some funny things will happen (a few |
|
1543 | IPython itself (via %run), but some funny things will happen (a few | |
1540 | globals get overwritten). In the future this will be cleaned up, as |
|
1544 | globals get overwritten). In the future this will be cleaned up, as | |
1541 | there is no fundamental reason why it can't work perfectly.""" |
|
1545 | there is no fundamental reason why it can't work perfectly.""" | |
1542 |
|
1546 | |||
1543 | # Get locals and globals from caller |
|
1547 | # Get locals and globals from caller | |
1544 | if local_ns is None or global_ns is None: |
|
1548 | if local_ns is None or global_ns is None: | |
1545 | call_frame = sys._getframe(stack_depth).f_back |
|
1549 | call_frame = sys._getframe(stack_depth).f_back | |
1546 |
|
1550 | |||
1547 | if local_ns is None: |
|
1551 | if local_ns is None: | |
1548 | local_ns = call_frame.f_locals |
|
1552 | local_ns = call_frame.f_locals | |
1549 | if global_ns is None: |
|
1553 | if global_ns is None: | |
1550 | global_ns = call_frame.f_globals |
|
1554 | global_ns = call_frame.f_globals | |
1551 |
|
1555 | |||
1552 | # Update namespaces and fire up interpreter |
|
1556 | # Update namespaces and fire up interpreter | |
1553 |
|
1557 | |||
1554 | # The global one is easy, we can just throw it in |
|
1558 | # The global one is easy, we can just throw it in | |
1555 | self.user_global_ns = global_ns |
|
1559 | self.user_global_ns = global_ns | |
1556 |
|
1560 | |||
1557 | # but the user/local one is tricky: ipython needs it to store internal |
|
1561 | # but the user/local one is tricky: ipython needs it to store internal | |
1558 | # data, but we also need the locals. We'll copy locals in the user |
|
1562 | # data, but we also need the locals. We'll copy locals in the user | |
1559 | # one, but will track what got copied so we can delete them at exit. |
|
1563 | # one, but will track what got copied so we can delete them at exit. | |
1560 | # This is so that a later embedded call doesn't see locals from a |
|
1564 | # This is so that a later embedded call doesn't see locals from a | |
1561 | # previous call (which most likely existed in a separate scope). |
|
1565 | # previous call (which most likely existed in a separate scope). | |
1562 | local_varnames = local_ns.keys() |
|
1566 | local_varnames = local_ns.keys() | |
1563 | self.user_ns.update(local_ns) |
|
1567 | self.user_ns.update(local_ns) | |
1564 |
|
1568 | |||
1565 | # Patch for global embedding to make sure that things don't overwrite |
|
1569 | # Patch for global embedding to make sure that things don't overwrite | |
1566 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1570 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1567 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1571 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1568 | if local_ns is None and global_ns is None: |
|
1572 | if local_ns is None and global_ns is None: | |
1569 | self.user_global_ns.update(__main__.__dict__) |
|
1573 | self.user_global_ns.update(__main__.__dict__) | |
1570 |
|
1574 | |||
1571 | # make sure the tab-completer has the correct frame information, so it |
|
1575 | # make sure the tab-completer has the correct frame information, so it | |
1572 | # actually completes using the frame's locals/globals |
|
1576 | # actually completes using the frame's locals/globals | |
1573 | self.set_completer_frame() |
|
1577 | self.set_completer_frame() | |
1574 |
|
1578 | |||
1575 | # before activating the interactive mode, we need to make sure that |
|
1579 | # before activating the interactive mode, we need to make sure that | |
1576 | # all names in the builtin namespace needed by ipython point to |
|
1580 | # all names in the builtin namespace needed by ipython point to | |
1577 | # ourselves, and not to other instances. |
|
1581 | # ourselves, and not to other instances. | |
1578 | self.add_builtins() |
|
1582 | self.add_builtins() | |
1579 |
|
1583 | |||
1580 | self.interact(header) |
|
1584 | self.interact(header) | |
1581 |
|
1585 | |||
1582 | # now, purge out the user namespace from anything we might have added |
|
1586 | # now, purge out the user namespace from anything we might have added | |
1583 | # from the caller's local namespace |
|
1587 | # from the caller's local namespace | |
1584 | delvar = self.user_ns.pop |
|
1588 | delvar = self.user_ns.pop | |
1585 | for var in local_varnames: |
|
1589 | for var in local_varnames: | |
1586 | delvar(var,None) |
|
1590 | delvar(var,None) | |
1587 | # and clean builtins we may have overridden |
|
1591 | # and clean builtins we may have overridden | |
1588 | self.clean_builtins() |
|
1592 | self.clean_builtins() | |
1589 |
|
1593 | |||
1590 | def interact(self, banner=None): |
|
1594 | def interact(self, banner=None): | |
1591 | """Closely emulate the interactive Python console. |
|
1595 | """Closely emulate the interactive Python console. | |
1592 |
|
1596 | |||
1593 | The optional banner argument specify the banner to print |
|
1597 | The optional banner argument specify the banner to print | |
1594 | before the first interaction; by default it prints a banner |
|
1598 | before the first interaction; by default it prints a banner | |
1595 | similar to the one printed by the real Python interpreter, |
|
1599 | similar to the one printed by the real Python interpreter, | |
1596 | followed by the current class name in parentheses (so as not |
|
1600 | followed by the current class name in parentheses (so as not | |
1597 | to confuse this with the real interpreter -- since it's so |
|
1601 | to confuse this with the real interpreter -- since it's so | |
1598 | close!). |
|
1602 | close!). | |
1599 |
|
1603 | |||
1600 | """ |
|
1604 | """ | |
1601 |
|
1605 | |||
1602 | if self.exit_now: |
|
1606 | if self.exit_now: | |
1603 | # batch run -> do not interact |
|
1607 | # batch run -> do not interact | |
1604 | return |
|
1608 | return | |
1605 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1609 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1606 | if banner is None: |
|
1610 | if banner is None: | |
1607 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1611 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1608 | (sys.version, sys.platform, cprt, |
|
1612 | (sys.version, sys.platform, cprt, | |
1609 | self.__class__.__name__)) |
|
1613 | self.__class__.__name__)) | |
1610 | else: |
|
1614 | else: | |
1611 | self.write(banner) |
|
1615 | self.write(banner) | |
1612 |
|
1616 | |||
1613 | more = 0 |
|
1617 | more = 0 | |
1614 |
|
1618 | |||
1615 | # Mark activity in the builtins |
|
1619 | # Mark activity in the builtins | |
1616 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1620 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1617 |
|
1621 | |||
1618 | # exit_now is set by a call to %Exit or %Quit |
|
1622 | # exit_now is set by a call to %Exit or %Quit | |
1619 | while not self.exit_now: |
|
1623 | while not self.exit_now: | |
1620 | if more: |
|
1624 | if more: | |
1621 | prompt = self.hooks.generate_prompt(True) |
|
1625 | prompt = self.hooks.generate_prompt(True) | |
1622 | if self.autoindent: |
|
1626 | if self.autoindent: | |
1623 | self.readline_startup_hook(self.pre_readline) |
|
1627 | self.readline_startup_hook(self.pre_readline) | |
1624 | else: |
|
1628 | else: | |
1625 | prompt = self.hooks.generate_prompt(False) |
|
1629 | prompt = self.hooks.generate_prompt(False) | |
1626 | try: |
|
1630 | try: | |
1627 | line = self.raw_input(prompt,more) |
|
1631 | line = self.raw_input(prompt,more) | |
1628 | if self.exit_now: |
|
1632 | if self.exit_now: | |
1629 | # quick exit on sys.std[in|out] close |
|
1633 | # quick exit on sys.std[in|out] close | |
1630 | break |
|
1634 | break | |
1631 | if self.autoindent: |
|
1635 | if self.autoindent: | |
1632 | self.readline_startup_hook(None) |
|
1636 | self.readline_startup_hook(None) | |
1633 | except KeyboardInterrupt: |
|
1637 | except KeyboardInterrupt: | |
1634 | self.write('\nKeyboardInterrupt\n') |
|
1638 | self.write('\nKeyboardInterrupt\n') | |
1635 | self.resetbuffer() |
|
1639 | self.resetbuffer() | |
1636 | # keep cache in sync with the prompt counter: |
|
1640 | # keep cache in sync with the prompt counter: | |
1637 | self.outputcache.prompt_count -= 1 |
|
1641 | self.outputcache.prompt_count -= 1 | |
1638 |
|
1642 | |||
1639 | if self.autoindent: |
|
1643 | if self.autoindent: | |
1640 | self.indent_current_nsp = 0 |
|
1644 | self.indent_current_nsp = 0 | |
1641 | more = 0 |
|
1645 | more = 0 | |
1642 | except EOFError: |
|
1646 | except EOFError: | |
1643 | if self.autoindent: |
|
1647 | if self.autoindent: | |
1644 | self.readline_startup_hook(None) |
|
1648 | self.readline_startup_hook(None) | |
1645 | self.write('\n') |
|
1649 | self.write('\n') | |
1646 | self.exit() |
|
1650 | self.exit() | |
1647 | except bdb.BdbQuit: |
|
1651 | except bdb.BdbQuit: | |
1648 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1652 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1649 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1653 | 'Because of how pdb handles the stack, it is impossible\n' | |
1650 | 'for IPython to properly format this particular exception.\n' |
|
1654 | 'for IPython to properly format this particular exception.\n' | |
1651 | 'IPython will resume normal operation.') |
|
1655 | 'IPython will resume normal operation.') | |
1652 | except: |
|
1656 | except: | |
1653 | # exceptions here are VERY RARE, but they can be triggered |
|
1657 | # exceptions here are VERY RARE, but they can be triggered | |
1654 | # asynchronously by signal handlers, for example. |
|
1658 | # asynchronously by signal handlers, for example. | |
1655 | self.showtraceback() |
|
1659 | self.showtraceback() | |
1656 | else: |
|
1660 | else: | |
1657 | more = self.push(line) |
|
1661 | more = self.push(line) | |
1658 | if (self.SyntaxTB.last_syntax_error and |
|
1662 | if (self.SyntaxTB.last_syntax_error and | |
1659 | self.rc.autoedit_syntax): |
|
1663 | self.rc.autoedit_syntax): | |
1660 | self.edit_syntax_error() |
|
1664 | self.edit_syntax_error() | |
1661 |
|
1665 | |||
1662 | # We are off again... |
|
1666 | # We are off again... | |
1663 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1667 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1664 |
|
1668 | |||
1665 | def excepthook(self, etype, value, tb): |
|
1669 | def excepthook(self, etype, value, tb): | |
1666 | """One more defense for GUI apps that call sys.excepthook. |
|
1670 | """One more defense for GUI apps that call sys.excepthook. | |
1667 |
|
1671 | |||
1668 | GUI frameworks like wxPython trap exceptions and call |
|
1672 | GUI frameworks like wxPython trap exceptions and call | |
1669 | sys.excepthook themselves. I guess this is a feature that |
|
1673 | sys.excepthook themselves. I guess this is a feature that | |
1670 | enables them to keep running after exceptions that would |
|
1674 | enables them to keep running after exceptions that would | |
1671 | otherwise kill their mainloop. This is a bother for IPython |
|
1675 | otherwise kill their mainloop. This is a bother for IPython | |
1672 | which excepts to catch all of the program exceptions with a try: |
|
1676 | which excepts to catch all of the program exceptions with a try: | |
1673 | except: statement. |
|
1677 | except: statement. | |
1674 |
|
1678 | |||
1675 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1679 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1676 | any app directly invokes sys.excepthook, it will look to the user like |
|
1680 | any app directly invokes sys.excepthook, it will look to the user like | |
1677 | IPython crashed. In order to work around this, we can disable the |
|
1681 | IPython crashed. In order to work around this, we can disable the | |
1678 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1682 | CrashHandler and replace it with this excepthook instead, which prints a | |
1679 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1683 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1680 | call sys.excepthook will generate a regular-looking exception from |
|
1684 | call sys.excepthook will generate a regular-looking exception from | |
1681 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1685 | IPython, and the CrashHandler will only be triggered by real IPython | |
1682 | crashes. |
|
1686 | crashes. | |
1683 |
|
1687 | |||
1684 | This hook should be used sparingly, only in places which are not likely |
|
1688 | This hook should be used sparingly, only in places which are not likely | |
1685 | to be true IPython errors. |
|
1689 | to be true IPython errors. | |
1686 | """ |
|
1690 | """ | |
1687 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1691 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1688 |
|
1692 | |||
1689 | def expand_aliases(self,fn,rest): |
|
1693 | def expand_aliases(self,fn,rest): | |
1690 | """ Expand multiple levels of aliases: |
|
1694 | """ Expand multiple levels of aliases: | |
1691 |
|
1695 | |||
1692 | if: |
|
1696 | if: | |
1693 |
|
1697 | |||
1694 | alias foo bar /tmp |
|
1698 | alias foo bar /tmp | |
1695 | alias baz foo |
|
1699 | alias baz foo | |
1696 |
|
1700 | |||
1697 | then: |
|
1701 | then: | |
1698 |
|
1702 | |||
1699 | baz huhhahhei -> bar /tmp huhhahhei |
|
1703 | baz huhhahhei -> bar /tmp huhhahhei | |
1700 |
|
1704 | |||
1701 | """ |
|
1705 | """ | |
1702 | line = fn + " " + rest |
|
1706 | line = fn + " " + rest | |
1703 |
|
1707 | |||
1704 | done = Set() |
|
1708 | done = Set() | |
1705 | while 1: |
|
1709 | while 1: | |
1706 | pre,fn,rest = self.split_user_input(line, pattern = self.shell_line_split) |
|
1710 | pre,fn,rest = self.split_user_input(line, pattern = self.shell_line_split) | |
1707 | # print "!",fn,"!",rest # dbg |
|
1711 | # print "!",fn,"!",rest # dbg | |
1708 | if fn in self.alias_table: |
|
1712 | if fn in self.alias_table: | |
1709 | if fn in done: |
|
1713 | if fn in done: | |
1710 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1714 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
1711 | return "" |
|
1715 | return "" | |
1712 | done.add(fn) |
|
1716 | done.add(fn) | |
1713 |
|
1717 | |||
1714 | l2 = self.transform_alias(fn,rest) |
|
1718 | l2 = self.transform_alias(fn,rest) | |
1715 | # dir -> dir |
|
1719 | # dir -> dir | |
1716 | # print "alias",line, "->",l2 #dbg |
|
1720 | # print "alias",line, "->",l2 #dbg | |
1717 | if l2 == line: |
|
1721 | if l2 == line: | |
1718 | break |
|
1722 | break | |
1719 | # ls -> ls -F should not recurse forever |
|
1723 | # ls -> ls -F should not recurse forever | |
1720 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1724 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
1721 | line = l2 |
|
1725 | line = l2 | |
1722 | break |
|
1726 | break | |
1723 |
|
1727 | |||
1724 | line=l2 |
|
1728 | line=l2 | |
1725 |
|
1729 | |||
1726 |
|
1730 | |||
1727 | # print "al expand to",line #dbg |
|
1731 | # print "al expand to",line #dbg | |
1728 | else: |
|
1732 | else: | |
1729 | break |
|
1733 | break | |
1730 |
|
1734 | |||
1731 | return line |
|
1735 | return line | |
1732 |
|
1736 | |||
1733 | def transform_alias(self, alias,rest=''): |
|
1737 | def transform_alias(self, alias,rest=''): | |
1734 | """ Transform alias to system command string. |
|
1738 | """ Transform alias to system command string. | |
1735 | """ |
|
1739 | """ | |
1736 | nargs,cmd = self.alias_table[alias] |
|
1740 | nargs,cmd = self.alias_table[alias] | |
1737 | if ' ' in cmd and os.path.isfile(cmd): |
|
1741 | if ' ' in cmd and os.path.isfile(cmd): | |
1738 | cmd = '"%s"' % cmd |
|
1742 | cmd = '"%s"' % cmd | |
1739 |
|
1743 | |||
1740 | # Expand the %l special to be the user's input line |
|
1744 | # Expand the %l special to be the user's input line | |
1741 | if cmd.find('%l') >= 0: |
|
1745 | if cmd.find('%l') >= 0: | |
1742 | cmd = cmd.replace('%l',rest) |
|
1746 | cmd = cmd.replace('%l',rest) | |
1743 | rest = '' |
|
1747 | rest = '' | |
1744 | if nargs==0: |
|
1748 | if nargs==0: | |
1745 | # Simple, argument-less aliases |
|
1749 | # Simple, argument-less aliases | |
1746 | cmd = '%s %s' % (cmd,rest) |
|
1750 | cmd = '%s %s' % (cmd,rest) | |
1747 | else: |
|
1751 | else: | |
1748 | # Handle aliases with positional arguments |
|
1752 | # Handle aliases with positional arguments | |
1749 | args = rest.split(None,nargs) |
|
1753 | args = rest.split(None,nargs) | |
1750 | if len(args)< nargs: |
|
1754 | if len(args)< nargs: | |
1751 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1755 | error('Alias <%s> requires %s arguments, %s given.' % | |
1752 | (alias,nargs,len(args))) |
|
1756 | (alias,nargs,len(args))) | |
1753 | return None |
|
1757 | return None | |
1754 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1758 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
1755 | # Now call the macro, evaluating in the user's namespace |
|
1759 | # Now call the macro, evaluating in the user's namespace | |
1756 | #print 'new command: <%r>' % cmd # dbg |
|
1760 | #print 'new command: <%r>' % cmd # dbg | |
1757 | return cmd |
|
1761 | return cmd | |
1758 |
|
1762 | |||
1759 | def call_alias(self,alias,rest=''): |
|
1763 | def call_alias(self,alias,rest=''): | |
1760 | """Call an alias given its name and the rest of the line. |
|
1764 | """Call an alias given its name and the rest of the line. | |
1761 |
|
1765 | |||
1762 | This is only used to provide backwards compatibility for users of |
|
1766 | This is only used to provide backwards compatibility for users of | |
1763 | ipalias(), use of which is not recommended for anymore.""" |
|
1767 | ipalias(), use of which is not recommended for anymore.""" | |
1764 |
|
1768 | |||
1765 | # Now call the macro, evaluating in the user's namespace |
|
1769 | # Now call the macro, evaluating in the user's namespace | |
1766 | cmd = self.transform_alias(alias, rest) |
|
1770 | cmd = self.transform_alias(alias, rest) | |
1767 | try: |
|
1771 | try: | |
1768 | self.system(cmd) |
|
1772 | self.system(cmd) | |
1769 | except: |
|
1773 | except: | |
1770 | self.showtraceback() |
|
1774 | self.showtraceback() | |
1771 |
|
1775 | |||
1772 | def indent_current_str(self): |
|
1776 | def indent_current_str(self): | |
1773 | """return the current level of indentation as a string""" |
|
1777 | """return the current level of indentation as a string""" | |
1774 | return self.indent_current_nsp * ' ' |
|
1778 | return self.indent_current_nsp * ' ' | |
1775 |
|
1779 | |||
1776 | def autoindent_update(self,line): |
|
1780 | def autoindent_update(self,line): | |
1777 | """Keep track of the indent level.""" |
|
1781 | """Keep track of the indent level.""" | |
1778 |
|
1782 | |||
1779 | #debugx('line') |
|
1783 | #debugx('line') | |
1780 | #debugx('self.indent_current_nsp') |
|
1784 | #debugx('self.indent_current_nsp') | |
1781 | if self.autoindent: |
|
1785 | if self.autoindent: | |
1782 | if line: |
|
1786 | if line: | |
1783 | inisp = num_ini_spaces(line) |
|
1787 | inisp = num_ini_spaces(line) | |
1784 | if inisp < self.indent_current_nsp: |
|
1788 | if inisp < self.indent_current_nsp: | |
1785 | self.indent_current_nsp = inisp |
|
1789 | self.indent_current_nsp = inisp | |
1786 |
|
1790 | |||
1787 | if line[-1] == ':': |
|
1791 | if line[-1] == ':': | |
1788 | self.indent_current_nsp += 4 |
|
1792 | self.indent_current_nsp += 4 | |
1789 | elif dedent_re.match(line): |
|
1793 | elif dedent_re.match(line): | |
1790 | self.indent_current_nsp -= 4 |
|
1794 | self.indent_current_nsp -= 4 | |
1791 | else: |
|
1795 | else: | |
1792 | self.indent_current_nsp = 0 |
|
1796 | self.indent_current_nsp = 0 | |
1793 |
|
1797 | |||
1794 | def runlines(self,lines): |
|
1798 | def runlines(self,lines): | |
1795 | """Run a string of one or more lines of source. |
|
1799 | """Run a string of one or more lines of source. | |
1796 |
|
1800 | |||
1797 | This method is capable of running a string containing multiple source |
|
1801 | This method is capable of running a string containing multiple source | |
1798 | lines, as if they had been entered at the IPython prompt. Since it |
|
1802 | lines, as if they had been entered at the IPython prompt. Since it | |
1799 | exposes IPython's processing machinery, the given strings can contain |
|
1803 | exposes IPython's processing machinery, the given strings can contain | |
1800 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1804 | magic calls (%magic), special shell access (!cmd), etc.""" | |
1801 |
|
1805 | |||
1802 | # We must start with a clean buffer, in case this is run from an |
|
1806 | # We must start with a clean buffer, in case this is run from an | |
1803 | # interactive IPython session (via a magic, for example). |
|
1807 | # interactive IPython session (via a magic, for example). | |
1804 | self.resetbuffer() |
|
1808 | self.resetbuffer() | |
1805 | lines = lines.split('\n') |
|
1809 | lines = lines.split('\n') | |
1806 | more = 0 |
|
1810 | more = 0 | |
1807 | for line in lines: |
|
1811 | for line in lines: | |
1808 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1812 | # skip blank lines so we don't mess up the prompt counter, but do | |
1809 | # NOT skip even a blank line if we are in a code block (more is |
|
1813 | # NOT skip even a blank line if we are in a code block (more is | |
1810 | # true) |
|
1814 | # true) | |
1811 | if line or more: |
|
1815 | if line or more: | |
1812 | more = self.push(self.prefilter(line,more)) |
|
1816 | more = self.push(self.prefilter(line,more)) | |
1813 | # IPython's runsource returns None if there was an error |
|
1817 | # IPython's runsource returns None if there was an error | |
1814 | # compiling the code. This allows us to stop processing right |
|
1818 | # compiling the code. This allows us to stop processing right | |
1815 | # away, so the user gets the error message at the right place. |
|
1819 | # away, so the user gets the error message at the right place. | |
1816 | if more is None: |
|
1820 | if more is None: | |
1817 | break |
|
1821 | break | |
1818 | # final newline in case the input didn't have it, so that the code |
|
1822 | # final newline in case the input didn't have it, so that the code | |
1819 | # actually does get executed |
|
1823 | # actually does get executed | |
1820 | if more: |
|
1824 | if more: | |
1821 | self.push('\n') |
|
1825 | self.push('\n') | |
1822 |
|
1826 | |||
1823 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1827 | def runsource(self, source, filename='<input>', symbol='single'): | |
1824 | """Compile and run some source in the interpreter. |
|
1828 | """Compile and run some source in the interpreter. | |
1825 |
|
1829 | |||
1826 | Arguments are as for compile_command(). |
|
1830 | Arguments are as for compile_command(). | |
1827 |
|
1831 | |||
1828 | One several things can happen: |
|
1832 | One several things can happen: | |
1829 |
|
1833 | |||
1830 | 1) The input is incorrect; compile_command() raised an |
|
1834 | 1) The input is incorrect; compile_command() raised an | |
1831 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1835 | exception (SyntaxError or OverflowError). A syntax traceback | |
1832 | will be printed by calling the showsyntaxerror() method. |
|
1836 | will be printed by calling the showsyntaxerror() method. | |
1833 |
|
1837 | |||
1834 | 2) The input is incomplete, and more input is required; |
|
1838 | 2) The input is incomplete, and more input is required; | |
1835 | compile_command() returned None. Nothing happens. |
|
1839 | compile_command() returned None. Nothing happens. | |
1836 |
|
1840 | |||
1837 | 3) The input is complete; compile_command() returned a code |
|
1841 | 3) The input is complete; compile_command() returned a code | |
1838 | object. The code is executed by calling self.runcode() (which |
|
1842 | object. The code is executed by calling self.runcode() (which | |
1839 | also handles run-time exceptions, except for SystemExit). |
|
1843 | also handles run-time exceptions, except for SystemExit). | |
1840 |
|
1844 | |||
1841 | The return value is: |
|
1845 | The return value is: | |
1842 |
|
1846 | |||
1843 | - True in case 2 |
|
1847 | - True in case 2 | |
1844 |
|
1848 | |||
1845 | - False in the other cases, unless an exception is raised, where |
|
1849 | - False in the other cases, unless an exception is raised, where | |
1846 | None is returned instead. This can be used by external callers to |
|
1850 | None is returned instead. This can be used by external callers to | |
1847 | know whether to continue feeding input or not. |
|
1851 | know whether to continue feeding input or not. | |
1848 |
|
1852 | |||
1849 | The return value can be used to decide whether to use sys.ps1 or |
|
1853 | The return value can be used to decide whether to use sys.ps1 or | |
1850 | sys.ps2 to prompt the next line.""" |
|
1854 | sys.ps2 to prompt the next line.""" | |
1851 |
|
1855 | |||
1852 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
1856 | # if the source code has leading blanks, add 'if 1:\n' to it | |
1853 | # this allows execution of indented pasted code. It is tempting |
|
1857 | # this allows execution of indented pasted code. It is tempting | |
1854 | # to add '\n' at the end of source to run commands like ' a=1' |
|
1858 | # to add '\n' at the end of source to run commands like ' a=1' | |
1855 | # directly, but this fails for more complicated scenarios |
|
1859 | # directly, but this fails for more complicated scenarios | |
1856 | if source[:1] in [' ', '\t']: |
|
1860 | if source[:1] in [' ', '\t']: | |
1857 | source = 'if 1:\n%s' % source |
|
1861 | source = 'if 1:\n%s' % source | |
1858 |
|
1862 | |||
1859 | try: |
|
1863 | try: | |
1860 | code = self.compile(source,filename,symbol) |
|
1864 | code = self.compile(source,filename,symbol) | |
1861 | except (OverflowError, SyntaxError, ValueError): |
|
1865 | except (OverflowError, SyntaxError, ValueError): | |
1862 | # Case 1 |
|
1866 | # Case 1 | |
1863 | self.showsyntaxerror(filename) |
|
1867 | self.showsyntaxerror(filename) | |
1864 | return None |
|
1868 | return None | |
1865 |
|
1869 | |||
1866 | if code is None: |
|
1870 | if code is None: | |
1867 | # Case 2 |
|
1871 | # Case 2 | |
1868 | return True |
|
1872 | return True | |
1869 |
|
1873 | |||
1870 | # Case 3 |
|
1874 | # Case 3 | |
1871 | # We store the code object so that threaded shells and |
|
1875 | # We store the code object so that threaded shells and | |
1872 | # custom exception handlers can access all this info if needed. |
|
1876 | # custom exception handlers can access all this info if needed. | |
1873 | # The source corresponding to this can be obtained from the |
|
1877 | # The source corresponding to this can be obtained from the | |
1874 | # buffer attribute as '\n'.join(self.buffer). |
|
1878 | # buffer attribute as '\n'.join(self.buffer). | |
1875 | self.code_to_run = code |
|
1879 | self.code_to_run = code | |
1876 | # now actually execute the code object |
|
1880 | # now actually execute the code object | |
1877 | if self.runcode(code) == 0: |
|
1881 | if self.runcode(code) == 0: | |
1878 | return False |
|
1882 | return False | |
1879 | else: |
|
1883 | else: | |
1880 | return None |
|
1884 | return None | |
1881 |
|
1885 | |||
1882 | def runcode(self,code_obj): |
|
1886 | def runcode(self,code_obj): | |
1883 | """Execute a code object. |
|
1887 | """Execute a code object. | |
1884 |
|
1888 | |||
1885 | When an exception occurs, self.showtraceback() is called to display a |
|
1889 | When an exception occurs, self.showtraceback() is called to display a | |
1886 | traceback. |
|
1890 | traceback. | |
1887 |
|
1891 | |||
1888 | Return value: a flag indicating whether the code to be run completed |
|
1892 | Return value: a flag indicating whether the code to be run completed | |
1889 | successfully: |
|
1893 | successfully: | |
1890 |
|
1894 | |||
1891 | - 0: successful execution. |
|
1895 | - 0: successful execution. | |
1892 | - 1: an error occurred. |
|
1896 | - 1: an error occurred. | |
1893 | """ |
|
1897 | """ | |
1894 |
|
1898 | |||
1895 | # Set our own excepthook in case the user code tries to call it |
|
1899 | # Set our own excepthook in case the user code tries to call it | |
1896 | # directly, so that the IPython crash handler doesn't get triggered |
|
1900 | # directly, so that the IPython crash handler doesn't get triggered | |
1897 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1901 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
1898 |
|
1902 | |||
1899 | # we save the original sys.excepthook in the instance, in case config |
|
1903 | # we save the original sys.excepthook in the instance, in case config | |
1900 | # code (such as magics) needs access to it. |
|
1904 | # code (such as magics) needs access to it. | |
1901 | self.sys_excepthook = old_excepthook |
|
1905 | self.sys_excepthook = old_excepthook | |
1902 | outflag = 1 # happens in more places, so it's easier as default |
|
1906 | outflag = 1 # happens in more places, so it's easier as default | |
1903 | try: |
|
1907 | try: | |
1904 | try: |
|
1908 | try: | |
1905 | # Embedded instances require separate global/local namespaces |
|
1909 | # Embedded instances require separate global/local namespaces | |
1906 | # so they can see both the surrounding (local) namespace and |
|
1910 | # so they can see both the surrounding (local) namespace and | |
1907 | # the module-level globals when called inside another function. |
|
1911 | # the module-level globals when called inside another function. | |
1908 | if self.embedded: |
|
1912 | if self.embedded: | |
1909 | exec code_obj in self.user_global_ns, self.user_ns |
|
1913 | exec code_obj in self.user_global_ns, self.user_ns | |
1910 | # Normal (non-embedded) instances should only have a single |
|
1914 | # Normal (non-embedded) instances should only have a single | |
1911 | # namespace for user code execution, otherwise functions won't |
|
1915 | # namespace for user code execution, otherwise functions won't | |
1912 | # see interactive top-level globals. |
|
1916 | # see interactive top-level globals. | |
1913 | else: |
|
1917 | else: | |
1914 | exec code_obj in self.user_ns |
|
1918 | exec code_obj in self.user_ns | |
1915 | finally: |
|
1919 | finally: | |
1916 | # Reset our crash handler in place |
|
1920 | # Reset our crash handler in place | |
1917 | sys.excepthook = old_excepthook |
|
1921 | sys.excepthook = old_excepthook | |
1918 | except SystemExit: |
|
1922 | except SystemExit: | |
1919 | self.resetbuffer() |
|
1923 | self.resetbuffer() | |
1920 | self.showtraceback() |
|
1924 | self.showtraceback() | |
1921 | warn("Type %exit or %quit to exit IPython " |
|
1925 | warn("Type %exit or %quit to exit IPython " | |
1922 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
1926 | "(%Exit or %Quit do so unconditionally).",level=1) | |
1923 | except self.custom_exceptions: |
|
1927 | except self.custom_exceptions: | |
1924 | etype,value,tb = sys.exc_info() |
|
1928 | etype,value,tb = sys.exc_info() | |
1925 | self.CustomTB(etype,value,tb) |
|
1929 | self.CustomTB(etype,value,tb) | |
1926 | except: |
|
1930 | except: | |
1927 | self.showtraceback() |
|
1931 | self.showtraceback() | |
1928 | else: |
|
1932 | else: | |
1929 | outflag = 0 |
|
1933 | outflag = 0 | |
1930 | if softspace(sys.stdout, 0): |
|
1934 | if softspace(sys.stdout, 0): | |
1931 |
|
1935 | |||
1932 | # Flush out code object which has been run (and source) |
|
1936 | # Flush out code object which has been run (and source) | |
1933 | self.code_to_run = None |
|
1937 | self.code_to_run = None | |
1934 | return outflag |
|
1938 | return outflag | |
1935 |
|
1939 | |||
1936 | def push(self, line): |
|
1940 | def push(self, line): | |
1937 | """Push a line to the interpreter. |
|
1941 | """Push a line to the interpreter. | |
1938 |
|
1942 | |||
1939 | The line should not have a trailing newline; it may have |
|
1943 | The line should not have a trailing newline; it may have | |
1940 | internal newlines. The line is appended to a buffer and the |
|
1944 | internal newlines. The line is appended to a buffer and the | |
1941 | interpreter's runsource() method is called with the |
|
1945 | interpreter's runsource() method is called with the | |
1942 | concatenated contents of the buffer as source. If this |
|
1946 | concatenated contents of the buffer as source. If this | |
1943 | indicates that the command was executed or invalid, the buffer |
|
1947 | indicates that the command was executed or invalid, the buffer | |
1944 | is reset; otherwise, the command is incomplete, and the buffer |
|
1948 | is reset; otherwise, the command is incomplete, and the buffer | |
1945 | is left as it was after the line was appended. The return |
|
1949 | is left as it was after the line was appended. The return | |
1946 | value is 1 if more input is required, 0 if the line was dealt |
|
1950 | value is 1 if more input is required, 0 if the line was dealt | |
1947 | with in some way (this is the same as runsource()). |
|
1951 | with in some way (this is the same as runsource()). | |
1948 | """ |
|
1952 | """ | |
1949 |
|
1953 | |||
1950 | # autoindent management should be done here, and not in the |
|
1954 | # autoindent management should be done here, and not in the | |
1951 | # interactive loop, since that one is only seen by keyboard input. We |
|
1955 | # interactive loop, since that one is only seen by keyboard input. We | |
1952 | # need this done correctly even for code run via runlines (which uses |
|
1956 | # need this done correctly even for code run via runlines (which uses | |
1953 | # push). |
|
1957 | # push). | |
1954 |
|
1958 | |||
1955 | #print 'push line: <%s>' % line # dbg |
|
1959 | #print 'push line: <%s>' % line # dbg | |
1956 | for subline in line.splitlines(): |
|
1960 | for subline in line.splitlines(): | |
1957 | self.autoindent_update(subline) |
|
1961 | self.autoindent_update(subline) | |
1958 | self.buffer.append(line) |
|
1962 | self.buffer.append(line) | |
1959 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
1963 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
1960 | if not more: |
|
1964 | if not more: | |
1961 | self.resetbuffer() |
|
1965 | self.resetbuffer() | |
1962 | return more |
|
1966 | return more | |
1963 |
|
1967 | |||
1964 | def resetbuffer(self): |
|
1968 | def resetbuffer(self): | |
1965 | """Reset the input buffer.""" |
|
1969 | """Reset the input buffer.""" | |
1966 | self.buffer[:] = [] |
|
1970 | self.buffer[:] = [] | |
1967 |
|
1971 | |||
1968 | def raw_input(self,prompt='',continue_prompt=False): |
|
1972 | def raw_input(self,prompt='',continue_prompt=False): | |
1969 | """Write a prompt and read a line. |
|
1973 | """Write a prompt and read a line. | |
1970 |
|
1974 | |||
1971 | The returned line does not include the trailing newline. |
|
1975 | The returned line does not include the trailing newline. | |
1972 | When the user enters the EOF key sequence, EOFError is raised. |
|
1976 | When the user enters the EOF key sequence, EOFError is raised. | |
1973 |
|
1977 | |||
1974 | Optional inputs: |
|
1978 | Optional inputs: | |
1975 |
|
1979 | |||
1976 | - prompt(''): a string to be printed to prompt the user. |
|
1980 | - prompt(''): a string to be printed to prompt the user. | |
1977 |
|
1981 | |||
1978 | - continue_prompt(False): whether this line is the first one or a |
|
1982 | - continue_prompt(False): whether this line is the first one or a | |
1979 | continuation in a sequence of inputs. |
|
1983 | continuation in a sequence of inputs. | |
1980 | """ |
|
1984 | """ | |
1981 |
|
1985 | |||
|
1986 | # Code run by the user may have modified the readline completer state. | |||
|
1987 | # We must ensure that our completer is back in place. | |||
|
1988 | self.set_completer() | |||
|
1989 | ||||
1982 | try: |
|
1990 | try: | |
1983 | line = raw_input_original(prompt).decode(sys.stdin.encoding) |
|
1991 | line = raw_input_original(prompt).decode(sys.stdin.encoding) | |
1984 | #line = raw_input_original(prompt) |
|
|||
1985 | except ValueError: |
|
1992 | except ValueError: | |
1986 |
warn("\n********\nYou or a %run:ed script called sys.stdin.close() |
|
1993 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
|
1994 | " or sys.stdout.close()!\nExiting IPython!") | |||
1987 | self.exit_now = True |
|
1995 | self.exit_now = True | |
1988 | return "" |
|
1996 | return "" | |
1989 |
|
||||
1990 |
|
1997 | |||
1991 | # Try to be reasonably smart about not re-indenting pasted input more |
|
1998 | # Try to be reasonably smart about not re-indenting pasted input more | |
1992 | # than necessary. We do this by trimming out the auto-indent initial |
|
1999 | # than necessary. We do this by trimming out the auto-indent initial | |
1993 | # spaces, if the user's actual input started itself with whitespace. |
|
2000 | # spaces, if the user's actual input started itself with whitespace. | |
1994 | #debugx('self.buffer[-1]') |
|
2001 | #debugx('self.buffer[-1]') | |
1995 |
|
2002 | |||
1996 | if self.autoindent: |
|
2003 | if self.autoindent: | |
1997 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2004 | if num_ini_spaces(line) > self.indent_current_nsp: | |
1998 | line = line[self.indent_current_nsp:] |
|
2005 | line = line[self.indent_current_nsp:] | |
1999 | self.indent_current_nsp = 0 |
|
2006 | self.indent_current_nsp = 0 | |
2000 |
|
2007 | |||
2001 | # store the unfiltered input before the user has any chance to modify |
|
2008 | # store the unfiltered input before the user has any chance to modify | |
2002 | # it. |
|
2009 | # it. | |
2003 | if line.strip(): |
|
2010 | if line.strip(): | |
2004 | if continue_prompt: |
|
2011 | if continue_prompt: | |
2005 | self.input_hist_raw[-1] += '%s\n' % line |
|
2012 | self.input_hist_raw[-1] += '%s\n' % line | |
2006 | if self.has_readline: # and some config option is set? |
|
2013 | if self.has_readline: # and some config option is set? | |
2007 | try: |
|
2014 | try: | |
2008 | histlen = self.readline.get_current_history_length() |
|
2015 | histlen = self.readline.get_current_history_length() | |
2009 | newhist = self.input_hist_raw[-1].rstrip() |
|
2016 | newhist = self.input_hist_raw[-1].rstrip() | |
2010 | self.readline.remove_history_item(histlen-1) |
|
2017 | self.readline.remove_history_item(histlen-1) | |
2011 | self.readline.replace_history_item(histlen-2,newhist) |
|
2018 | self.readline.replace_history_item(histlen-2,newhist) | |
2012 | except AttributeError: |
|
2019 | except AttributeError: | |
2013 | pass # re{move,place}_history_item are new in 2.4. |
|
2020 | pass # re{move,place}_history_item are new in 2.4. | |
2014 | else: |
|
2021 | else: | |
2015 | self.input_hist_raw.append('%s\n' % line) |
|
2022 | self.input_hist_raw.append('%s\n' % line) | |
2016 |
|
2023 | |||
2017 | try: |
|
2024 | try: | |
2018 | lineout = self.prefilter(line,continue_prompt) |
|
2025 | lineout = self.prefilter(line,continue_prompt) | |
2019 | except: |
|
2026 | except: | |
2020 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2027 | # blanket except, in case a user-defined prefilter crashes, so it | |
2021 | # can't take all of ipython with it. |
|
2028 | # can't take all of ipython with it. | |
2022 | self.showtraceback() |
|
2029 | self.showtraceback() | |
2023 | return '' |
|
2030 | return '' | |
2024 | else: |
|
2031 | else: | |
2025 | return lineout |
|
2032 | return lineout | |
2026 |
|
2033 | |||
2027 | def split_user_input(self,line, pattern = None): |
|
2034 | def split_user_input(self,line, pattern = None): | |
2028 | """Split user input into pre-char, function part and rest.""" |
|
2035 | """Split user input into pre-char, function part and rest.""" | |
2029 |
|
2036 | |||
2030 | if pattern is None: |
|
2037 | if pattern is None: | |
2031 | pattern = self.line_split |
|
2038 | pattern = self.line_split | |
2032 |
|
2039 | |||
2033 | lsplit = pattern.match(line) |
|
2040 | lsplit = pattern.match(line) | |
2034 | if lsplit is None: # no regexp match returns None |
|
2041 | if lsplit is None: # no regexp match returns None | |
2035 | #print "match failed for line '%s'" % line # dbg |
|
2042 | #print "match failed for line '%s'" % line # dbg | |
2036 | try: |
|
2043 | try: | |
2037 | iFun,theRest = line.split(None,1) |
|
2044 | iFun,theRest = line.split(None,1) | |
2038 | except ValueError: |
|
2045 | except ValueError: | |
2039 | #print "split failed for line '%s'" % line # dbg |
|
2046 | #print "split failed for line '%s'" % line # dbg | |
2040 | iFun,theRest = line,'' |
|
2047 | iFun,theRest = line,'' | |
2041 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
2048 | pre = re.match('^(\s*)(.*)',line).groups()[0] | |
2042 | else: |
|
2049 | else: | |
2043 | pre,iFun,theRest = lsplit.groups() |
|
2050 | pre,iFun,theRest = lsplit.groups() | |
2044 |
|
2051 | |||
2045 | # iFun has to be a valid python identifier, so it better be only pure |
|
2052 | # iFun has to be a valid python identifier, so it better be only pure | |
2046 | #ascii, no unicode: |
|
2053 | #ascii, no unicode: | |
2047 | try: |
|
2054 | try: | |
2048 | iFun = iFun.encode('ascii') |
|
2055 | iFun = iFun.encode('ascii') | |
2049 | except UnicodeEncodeError: |
|
2056 | except UnicodeEncodeError: | |
2050 | theRest = iFun+u' '+theRest |
|
2057 | theRest = iFun+u' '+theRest | |
2051 | iFun = u'' |
|
2058 | iFun = u'' | |
2052 |
|
2059 | |||
2053 | #print 'line:<%s>' % line # dbg |
|
2060 | #print 'line:<%s>' % line # dbg | |
2054 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
2061 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg | |
2055 | return pre,iFun.strip(),theRest |
|
2062 | return pre,iFun.strip(),theRest | |
2056 |
|
2063 | |||
2057 | # THIS VERSION IS BROKEN!!! It was intended to prevent spurious attribute |
|
2064 | # THIS VERSION IS BROKEN!!! It was intended to prevent spurious attribute | |
2058 | # accesses with a more stringent check of inputs, but it introduced other |
|
2065 | # accesses with a more stringent check of inputs, but it introduced other | |
2059 | # bugs. Disable it for now until I can properly fix it. |
|
2066 | # bugs. Disable it for now until I can properly fix it. | |
2060 | def split_user_inputBROKEN(self,line): |
|
2067 | def split_user_inputBROKEN(self,line): | |
2061 | """Split user input into pre-char, function part and rest.""" |
|
2068 | """Split user input into pre-char, function part and rest.""" | |
2062 |
|
2069 | |||
2063 | lsplit = self.line_split.match(line) |
|
2070 | lsplit = self.line_split.match(line) | |
2064 | if lsplit is None: # no regexp match returns None |
|
2071 | if lsplit is None: # no regexp match returns None | |
2065 | lsplit = self.line_split_fallback.match(line) |
|
2072 | lsplit = self.line_split_fallback.match(line) | |
2066 |
|
2073 | |||
2067 | #pre,iFun,theRest = lsplit.groups() # dbg |
|
2074 | #pre,iFun,theRest = lsplit.groups() # dbg | |
2068 | #print 'line:<%s>' % line # dbg |
|
2075 | #print 'line:<%s>' % line # dbg | |
2069 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
2076 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg | |
2070 | #return pre,iFun.strip(),theRest # dbg |
|
2077 | #return pre,iFun.strip(),theRest # dbg | |
2071 |
|
2078 | |||
2072 | return lsplit.groups() |
|
2079 | return lsplit.groups() | |
2073 |
|
2080 | |||
2074 | def _prefilter(self, line, continue_prompt): |
|
2081 | def _prefilter(self, line, continue_prompt): | |
2075 | """Calls different preprocessors, depending on the form of line.""" |
|
2082 | """Calls different preprocessors, depending on the form of line.""" | |
2076 |
|
2083 | |||
2077 | # All handlers *must* return a value, even if it's blank (''). |
|
2084 | # All handlers *must* return a value, even if it's blank (''). | |
2078 |
|
2085 | |||
2079 | # Lines are NOT logged here. Handlers should process the line as |
|
2086 | # Lines are NOT logged here. Handlers should process the line as | |
2080 | # needed, update the cache AND log it (so that the input cache array |
|
2087 | # needed, update the cache AND log it (so that the input cache array | |
2081 | # stays synced). |
|
2088 | # stays synced). | |
2082 |
|
2089 | |||
2083 | # This function is _very_ delicate, and since it's also the one which |
|
2090 | # This function is _very_ delicate, and since it's also the one which | |
2084 | # determines IPython's response to user input, it must be as efficient |
|
2091 | # determines IPython's response to user input, it must be as efficient | |
2085 | # as possible. For this reason it has _many_ returns in it, trying |
|
2092 | # as possible. For this reason it has _many_ returns in it, trying | |
2086 | # always to exit as quickly as it can figure out what it needs to do. |
|
2093 | # always to exit as quickly as it can figure out what it needs to do. | |
2087 |
|
2094 | |||
2088 | # This function is the main responsible for maintaining IPython's |
|
2095 | # This function is the main responsible for maintaining IPython's | |
2089 | # behavior respectful of Python's semantics. So be _very_ careful if |
|
2096 | # behavior respectful of Python's semantics. So be _very_ careful if | |
2090 | # making changes to anything here. |
|
2097 | # making changes to anything here. | |
2091 |
|
2098 | |||
2092 | #..................................................................... |
|
2099 | #..................................................................... | |
2093 | # Code begins |
|
2100 | # Code begins | |
2094 |
|
2101 | |||
2095 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2102 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
2096 |
|
2103 | |||
2097 | # save the line away in case we crash, so the post-mortem handler can |
|
2104 | # save the line away in case we crash, so the post-mortem handler can | |
2098 | # record it |
|
2105 | # record it | |
2099 | self._last_input_line = line |
|
2106 | self._last_input_line = line | |
2100 |
|
2107 | |||
2101 | #print '***line: <%s>' % line # dbg |
|
2108 | #print '***line: <%s>' % line # dbg | |
2102 |
|
2109 | |||
2103 | # the input history needs to track even empty lines |
|
2110 | # the input history needs to track even empty lines | |
2104 | stripped = line.strip() |
|
2111 | stripped = line.strip() | |
2105 |
|
2112 | |||
2106 | if not stripped: |
|
2113 | if not stripped: | |
2107 | if not continue_prompt: |
|
2114 | if not continue_prompt: | |
2108 | self.outputcache.prompt_count -= 1 |
|
2115 | self.outputcache.prompt_count -= 1 | |
2109 | return self.handle_normal(line,continue_prompt) |
|
2116 | return self.handle_normal(line,continue_prompt) | |
2110 | #return self.handle_normal('',continue_prompt) |
|
2117 | #return self.handle_normal('',continue_prompt) | |
2111 |
|
2118 | |||
2112 | # print '***cont',continue_prompt # dbg |
|
2119 | # print '***cont',continue_prompt # dbg | |
2113 | # special handlers are only allowed for single line statements |
|
2120 | # special handlers are only allowed for single line statements | |
2114 | if continue_prompt and not self.rc.multi_line_specials: |
|
2121 | if continue_prompt and not self.rc.multi_line_specials: | |
2115 | return self.handle_normal(line,continue_prompt) |
|
2122 | return self.handle_normal(line,continue_prompt) | |
2116 |
|
2123 | |||
2117 |
|
2124 | |||
2118 | # For the rest, we need the structure of the input |
|
2125 | # For the rest, we need the structure of the input | |
2119 | pre,iFun,theRest = self.split_user_input(line) |
|
2126 | pre,iFun,theRest = self.split_user_input(line) | |
2120 |
|
2127 | |||
2121 | # See whether any pre-existing handler can take care of it |
|
2128 | # See whether any pre-existing handler can take care of it | |
2122 |
|
2129 | |||
2123 | rewritten = self.hooks.input_prefilter(stripped) |
|
2130 | rewritten = self.hooks.input_prefilter(stripped) | |
2124 | if rewritten != stripped: # ok, some prefilter did something |
|
2131 | if rewritten != stripped: # ok, some prefilter did something | |
2125 | rewritten = pre + rewritten # add indentation |
|
2132 | rewritten = pre + rewritten # add indentation | |
2126 | return self.handle_normal(rewritten) |
|
2133 | return self.handle_normal(rewritten) | |
2127 |
|
2134 | |||
2128 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2135 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2129 |
|
2136 | |||
2130 | # Next, check if we can automatically execute this thing |
|
2137 | # Next, check if we can automatically execute this thing | |
2131 |
|
2138 | |||
2132 | # Allow ! in multi-line statements if multi_line_specials is on: |
|
2139 | # Allow ! in multi-line statements if multi_line_specials is on: | |
2133 | if continue_prompt and self.rc.multi_line_specials and \ |
|
2140 | if continue_prompt and self.rc.multi_line_specials and \ | |
2134 | iFun.startswith(self.ESC_SHELL): |
|
2141 | iFun.startswith(self.ESC_SHELL): | |
2135 | return self.handle_shell_escape(line,continue_prompt, |
|
2142 | return self.handle_shell_escape(line,continue_prompt, | |
2136 | pre=pre,iFun=iFun, |
|
2143 | pre=pre,iFun=iFun, | |
2137 | theRest=theRest) |
|
2144 | theRest=theRest) | |
2138 |
|
2145 | |||
2139 | # First check for explicit escapes in the last/first character |
|
2146 | # First check for explicit escapes in the last/first character | |
2140 | handler = None |
|
2147 | handler = None | |
2141 | if line[-1] == self.ESC_HELP and line[0] != self.ESC_SHELL: |
|
2148 | if line[-1] == self.ESC_HELP and line[0] != self.ESC_SHELL: | |
2142 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end |
|
2149 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end | |
2143 | if handler is None: |
|
2150 | if handler is None: | |
2144 | # look at the first character of iFun, NOT of line, so we skip |
|
2151 | # look at the first character of iFun, NOT of line, so we skip | |
2145 | # leading whitespace in multiline input |
|
2152 | # leading whitespace in multiline input | |
2146 | handler = self.esc_handlers.get(iFun[0:1]) |
|
2153 | handler = self.esc_handlers.get(iFun[0:1]) | |
2147 | if handler is not None: |
|
2154 | if handler is not None: | |
2148 | return handler(line,continue_prompt,pre,iFun,theRest) |
|
2155 | return handler(line,continue_prompt,pre,iFun,theRest) | |
2149 | # Emacs ipython-mode tags certain input lines |
|
2156 | # Emacs ipython-mode tags certain input lines | |
2150 | if line.endswith('# PYTHON-MODE'): |
|
2157 | if line.endswith('# PYTHON-MODE'): | |
2151 | return self.handle_emacs(line,continue_prompt) |
|
2158 | return self.handle_emacs(line,continue_prompt) | |
2152 |
|
2159 | |||
2153 | # Let's try to find if the input line is a magic fn |
|
2160 | # Let's try to find if the input line is a magic fn | |
2154 | oinfo = None |
|
2161 | oinfo = None | |
2155 | if hasattr(self,'magic_'+iFun): |
|
2162 | if hasattr(self,'magic_'+iFun): | |
2156 | # WARNING: _ofind uses getattr(), so it can consume generators and |
|
2163 | # WARNING: _ofind uses getattr(), so it can consume generators and | |
2157 | # cause other side effects. |
|
2164 | # cause other side effects. | |
2158 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
2165 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
2159 | if oinfo['ismagic']: |
|
2166 | if oinfo['ismagic']: | |
2160 | # Be careful not to call magics when a variable assignment is |
|
2167 | # Be careful not to call magics when a variable assignment is | |
2161 | # being made (ls='hi', for example) |
|
2168 | # being made (ls='hi', for example) | |
2162 | if self.rc.automagic and \ |
|
2169 | if self.rc.automagic and \ | |
2163 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ |
|
2170 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ | |
2164 | (self.rc.multi_line_specials or not continue_prompt): |
|
2171 | (self.rc.multi_line_specials or not continue_prompt): | |
2165 | return self.handle_magic(line,continue_prompt, |
|
2172 | return self.handle_magic(line,continue_prompt, | |
2166 | pre,iFun,theRest) |
|
2173 | pre,iFun,theRest) | |
2167 | else: |
|
2174 | else: | |
2168 | return self.handle_normal(line,continue_prompt) |
|
2175 | return self.handle_normal(line,continue_prompt) | |
2169 |
|
2176 | |||
2170 | # If the rest of the line begins with an (in)equality, assginment or |
|
2177 | # If the rest of the line begins with an (in)equality, assginment or | |
2171 | # function call, we should not call _ofind but simply execute it. |
|
2178 | # function call, we should not call _ofind but simply execute it. | |
2172 | # This avoids spurious geattr() accesses on objects upon assignment. |
|
2179 | # This avoids spurious geattr() accesses on objects upon assignment. | |
2173 | # |
|
2180 | # | |
2174 | # It also allows users to assign to either alias or magic names true |
|
2181 | # It also allows users to assign to either alias or magic names true | |
2175 | # python variables (the magic/alias systems always take second seat to |
|
2182 | # python variables (the magic/alias systems always take second seat to | |
2176 | # true python code). |
|
2183 | # true python code). | |
2177 | # |
|
2184 | if theRest and theRest[0] in '!=()': | |
2178 | # We also go to direct execution if there's a binary operator in there, |
|
|||
2179 | # so users get the regular exception. Note that '-' is NOT included, |
|
|||
2180 | # since it is also a unary operator ('+' can also be used as unary, but |
|
|||
2181 | # in practice it rarely is). |
|
|||
2182 | if theRest and theRest[0] in '!=()<>+*/%^&|': |
|
|||
2183 | return self.handle_normal(line,continue_prompt) |
|
2185 | return self.handle_normal(line,continue_prompt) | |
2184 |
|
2186 | |||
2185 | if oinfo is None: |
|
2187 | if oinfo is None: | |
2186 | # let's try to ensure that _oinfo is ONLY called when autocall is |
|
2188 | # let's try to ensure that _oinfo is ONLY called when autocall is | |
2187 | # on. Since it has inevitable potential side effects, at least |
|
2189 | # on. Since it has inevitable potential side effects, at least | |
2188 | # having autocall off should be a guarantee to the user that no |
|
2190 | # having autocall off should be a guarantee to the user that no | |
2189 | # weird things will happen. |
|
2191 | # weird things will happen. | |
2190 |
|
2192 | |||
2191 | if self.rc.autocall: |
|
2193 | if self.rc.autocall: | |
2192 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
2194 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
2193 | else: |
|
2195 | else: | |
2194 | # in this case, all that's left is either an alias or |
|
2196 | # in this case, all that's left is either an alias or | |
2195 | # processing the line normally. |
|
2197 | # processing the line normally. | |
2196 | if iFun in self.alias_table: |
|
2198 | if iFun in self.alias_table: | |
2197 | # if autocall is off, by not running _ofind we won't know |
|
2199 | # if autocall is off, by not running _ofind we won't know | |
2198 | # whether the given name may also exist in one of the |
|
2200 | # whether the given name may also exist in one of the | |
2199 | # user's namespace. At this point, it's best to do a |
|
2201 | # user's namespace. At this point, it's best to do a | |
2200 | # quick check just to be sure that we don't let aliases |
|
2202 | # quick check just to be sure that we don't let aliases | |
2201 | # shadow variables. |
|
2203 | # shadow variables. | |
2202 | head = iFun.split('.',1)[0] |
|
2204 | head = iFun.split('.',1)[0] | |
2203 | if head in self.user_ns or head in self.internal_ns \ |
|
2205 | if head in self.user_ns or head in self.internal_ns \ | |
2204 | or head in __builtin__.__dict__: |
|
2206 | or head in __builtin__.__dict__: | |
2205 | return self.handle_normal(line,continue_prompt) |
|
2207 | return self.handle_normal(line,continue_prompt) | |
2206 | else: |
|
2208 | else: | |
2207 | return self.handle_alias(line,continue_prompt, |
|
2209 | return self.handle_alias(line,continue_prompt, | |
2208 | pre,iFun,theRest) |
|
2210 | pre,iFun,theRest) | |
2209 |
|
2211 | |||
2210 | else: |
|
2212 | else: | |
2211 | return self.handle_normal(line,continue_prompt) |
|
2213 | return self.handle_normal(line,continue_prompt) | |
2212 |
|
2214 | |||
2213 | if not oinfo['found']: |
|
2215 | if not oinfo['found']: | |
2214 | return self.handle_normal(line,continue_prompt) |
|
2216 | return self.handle_normal(line,continue_prompt) | |
2215 | else: |
|
2217 | else: | |
2216 | #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2218 | #print 'pre<%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2217 | if oinfo['isalias']: |
|
2219 | if oinfo['isalias']: | |
2218 | return self.handle_alias(line,continue_prompt, |
|
2220 | return self.handle_alias(line,continue_prompt, | |
2219 | pre,iFun,theRest) |
|
2221 | pre,iFun,theRest) | |
2220 |
|
2222 | |||
2221 | if (self.rc.autocall |
|
2223 | if (self.rc.autocall | |
2222 | and |
|
2224 | and | |
2223 | ( |
|
2225 | ( | |
2224 | #only consider exclusion re if not "," or ";" autoquoting |
|
2226 | #only consider exclusion re if not "," or ";" autoquoting | |
2225 | (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2 |
|
2227 | (pre == self.ESC_QUOTE or pre == self.ESC_QUOTE2 | |
2226 | or pre == self.ESC_PAREN) or |
|
2228 | or pre == self.ESC_PAREN) or | |
2227 | (not self.re_exclude_auto.match(theRest))) |
|
2229 | (not self.re_exclude_auto.match(theRest))) | |
2228 | and |
|
2230 | and | |
2229 | self.re_fun_name.match(iFun) and |
|
2231 | self.re_fun_name.match(iFun) and | |
2230 | callable(oinfo['obj'])) : |
|
2232 | callable(oinfo['obj'])) : | |
2231 | #print 'going auto' # dbg |
|
2233 | #print 'going auto' # dbg | |
2232 | return self.handle_auto(line,continue_prompt, |
|
2234 | return self.handle_auto(line,continue_prompt, | |
2233 | pre,iFun,theRest,oinfo['obj']) |
|
2235 | pre,iFun,theRest,oinfo['obj']) | |
2234 | else: |
|
2236 | else: | |
2235 | #print 'was callable?', callable(oinfo['obj']) # dbg |
|
2237 | #print 'was callable?', callable(oinfo['obj']) # dbg | |
2236 | return self.handle_normal(line,continue_prompt) |
|
2238 | return self.handle_normal(line,continue_prompt) | |
2237 |
|
2239 | |||
2238 | # If we get here, we have a normal Python line. Log and return. |
|
2240 | # If we get here, we have a normal Python line. Log and return. | |
2239 | return self.handle_normal(line,continue_prompt) |
|
2241 | return self.handle_normal(line,continue_prompt) | |
2240 |
|
2242 | |||
2241 | def _prefilter_dumb(self, line, continue_prompt): |
|
2243 | def _prefilter_dumb(self, line, continue_prompt): | |
2242 | """simple prefilter function, for debugging""" |
|
2244 | """simple prefilter function, for debugging""" | |
2243 | return self.handle_normal(line,continue_prompt) |
|
2245 | return self.handle_normal(line,continue_prompt) | |
2244 |
|
2246 | |||
2245 |
|
2247 | |||
2246 | def multiline_prefilter(self, line, continue_prompt): |
|
2248 | def multiline_prefilter(self, line, continue_prompt): | |
2247 | """ Run _prefilter for each line of input |
|
2249 | """ Run _prefilter for each line of input | |
2248 |
|
2250 | |||
2249 | Covers cases where there are multiple lines in the user entry, |
|
2251 | Covers cases where there are multiple lines in the user entry, | |
2250 | which is the case when the user goes back to a multiline history |
|
2252 | which is the case when the user goes back to a multiline history | |
2251 | entry and presses enter. |
|
2253 | entry and presses enter. | |
2252 |
|
2254 | |||
2253 | """ |
|
2255 | """ | |
2254 | out = [] |
|
2256 | out = [] | |
2255 | for l in line.rstrip('\n').split('\n'): |
|
2257 | for l in line.rstrip('\n').split('\n'): | |
2256 | out.append(self._prefilter(l, continue_prompt)) |
|
2258 | out.append(self._prefilter(l, continue_prompt)) | |
2257 | return '\n'.join(out) |
|
2259 | return '\n'.join(out) | |
2258 |
|
2260 | |||
2259 | # Set the default prefilter() function (this can be user-overridden) |
|
2261 | # Set the default prefilter() function (this can be user-overridden) | |
2260 | prefilter = multiline_prefilter |
|
2262 | prefilter = multiline_prefilter | |
2261 |
|
2263 | |||
2262 | def handle_normal(self,line,continue_prompt=None, |
|
2264 | def handle_normal(self,line,continue_prompt=None, | |
2263 | pre=None,iFun=None,theRest=None): |
|
2265 | pre=None,iFun=None,theRest=None): | |
2264 | """Handle normal input lines. Use as a template for handlers.""" |
|
2266 | """Handle normal input lines. Use as a template for handlers.""" | |
2265 |
|
2267 | |||
2266 | # With autoindent on, we need some way to exit the input loop, and I |
|
2268 | # With autoindent on, we need some way to exit the input loop, and I | |
2267 | # don't want to force the user to have to backspace all the way to |
|
2269 | # don't want to force the user to have to backspace all the way to | |
2268 | # clear the line. The rule will be in this case, that either two |
|
2270 | # clear the line. The rule will be in this case, that either two | |
2269 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2271 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2270 | # of a size different to the indent level, will exit the input loop. |
|
2272 | # of a size different to the indent level, will exit the input loop. | |
2271 |
|
2273 | |||
2272 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2274 | if (continue_prompt and self.autoindent and line.isspace() and | |
2273 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2275 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2274 | (self.buffer[-1]).isspace() )): |
|
2276 | (self.buffer[-1]).isspace() )): | |
2275 | line = '' |
|
2277 | line = '' | |
2276 |
|
2278 | |||
2277 | self.log(line,line,continue_prompt) |
|
2279 | self.log(line,line,continue_prompt) | |
2278 | return line |
|
2280 | return line | |
2279 |
|
2281 | |||
2280 | def handle_alias(self,line,continue_prompt=None, |
|
2282 | def handle_alias(self,line,continue_prompt=None, | |
2281 | pre=None,iFun=None,theRest=None): |
|
2283 | pre=None,iFun=None,theRest=None): | |
2282 | """Handle alias input lines. """ |
|
2284 | """Handle alias input lines. """ | |
2283 |
|
2285 | |||
2284 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2286 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2285 | # aliases won't work in indented sections. |
|
2287 | # aliases won't work in indented sections. | |
2286 | transformed = self.expand_aliases(iFun, theRest) |
|
2288 | transformed = self.expand_aliases(iFun, theRest) | |
2287 | line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed )) |
|
2289 | line_out = '%s_ip.system(%s)' % (pre, make_quoted_expr( transformed )) | |
2288 | self.log(line,line_out,continue_prompt) |
|
2290 | self.log(line,line_out,continue_prompt) | |
2289 | #print 'line out:',line_out # dbg |
|
2291 | #print 'line out:',line_out # dbg | |
2290 | return line_out |
|
2292 | return line_out | |
2291 |
|
2293 | |||
2292 | def handle_shell_escape(self, line, continue_prompt=None, |
|
2294 | def handle_shell_escape(self, line, continue_prompt=None, | |
2293 | pre=None,iFun=None,theRest=None): |
|
2295 | pre=None,iFun=None,theRest=None): | |
2294 | """Execute the line in a shell, empty return value""" |
|
2296 | """Execute the line in a shell, empty return value""" | |
2295 |
|
2297 | |||
2296 | #print 'line in :', `line` # dbg |
|
2298 | #print 'line in :', `line` # dbg | |
2297 | # Example of a special handler. Others follow a similar pattern. |
|
2299 | # Example of a special handler. Others follow a similar pattern. | |
2298 | if line.lstrip().startswith('!!'): |
|
2300 | if line.lstrip().startswith('!!'): | |
2299 | # rewrite iFun/theRest to properly hold the call to %sx and |
|
2301 | # rewrite iFun/theRest to properly hold the call to %sx and | |
2300 | # the actual command to be executed, so handle_magic can work |
|
2302 | # the actual command to be executed, so handle_magic can work | |
2301 | # correctly |
|
2303 | # correctly | |
2302 | theRest = '%s %s' % (iFun[2:],theRest) |
|
2304 | theRest = '%s %s' % (iFun[2:],theRest) | |
2303 | iFun = 'sx' |
|
2305 | iFun = 'sx' | |
2304 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC, |
|
2306 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC, | |
2305 | line.lstrip()[2:]), |
|
2307 | line.lstrip()[2:]), | |
2306 | continue_prompt,pre,iFun,theRest) |
|
2308 | continue_prompt,pre,iFun,theRest) | |
2307 | else: |
|
2309 | else: | |
2308 | cmd=line.lstrip().lstrip('!') |
|
2310 | cmd=line.lstrip().lstrip('!') | |
2309 | line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd)) |
|
2311 | line_out = '%s_ip.system(%s)' % (pre,make_quoted_expr(cmd)) | |
2310 | # update cache/log and return |
|
2312 | # update cache/log and return | |
2311 | self.log(line,line_out,continue_prompt) |
|
2313 | self.log(line,line_out,continue_prompt) | |
2312 | return line_out |
|
2314 | return line_out | |
2313 |
|
2315 | |||
2314 | def handle_magic(self, line, continue_prompt=None, |
|
2316 | def handle_magic(self, line, continue_prompt=None, | |
2315 | pre=None,iFun=None,theRest=None): |
|
2317 | pre=None,iFun=None,theRest=None): | |
2316 | """Execute magic functions.""" |
|
2318 | """Execute magic functions.""" | |
2317 |
|
2319 | |||
2318 |
|
2320 | |||
2319 | cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest)) |
|
2321 | cmd = '%s_ip.magic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest)) | |
2320 | self.log(line,cmd,continue_prompt) |
|
2322 | self.log(line,cmd,continue_prompt) | |
2321 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2323 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2322 | return cmd |
|
2324 | return cmd | |
2323 |
|
2325 | |||
2324 | def handle_auto(self, line, continue_prompt=None, |
|
2326 | def handle_auto(self, line, continue_prompt=None, | |
2325 | pre=None,iFun=None,theRest=None,obj=None): |
|
2327 | pre=None,iFun=None,theRest=None,obj=None): | |
2326 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2328 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2327 |
|
2329 | |||
2328 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2330 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2329 |
|
2331 | |||
2330 | # This should only be active for single-line input! |
|
2332 | # This should only be active for single-line input! | |
2331 | if continue_prompt: |
|
2333 | if continue_prompt: | |
2332 | self.log(line,line,continue_prompt) |
|
2334 | self.log(line,line,continue_prompt) | |
2333 | return line |
|
2335 | return line | |
2334 |
|
2336 | |||
2335 | auto_rewrite = True |
|
2337 | auto_rewrite = True | |
2336 |
|
2338 | |||
2337 | if pre == self.ESC_QUOTE: |
|
2339 | if pre == self.ESC_QUOTE: | |
2338 | # Auto-quote splitting on whitespace |
|
2340 | # Auto-quote splitting on whitespace | |
2339 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2341 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2340 | elif pre == self.ESC_QUOTE2: |
|
2342 | elif pre == self.ESC_QUOTE2: | |
2341 | # Auto-quote whole string |
|
2343 | # Auto-quote whole string | |
2342 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2344 | newcmd = '%s("%s")' % (iFun,theRest) | |
2343 | elif pre == self.ESC_PAREN: |
|
2345 | elif pre == self.ESC_PAREN: | |
2344 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2346 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2345 | else: |
|
2347 | else: | |
2346 | # Auto-paren. |
|
2348 | # Auto-paren. | |
2347 | # We only apply it to argument-less calls if the autocall |
|
2349 | # We only apply it to argument-less calls if the autocall | |
2348 | # parameter is set to 2. We only need to check that autocall is < |
|
2350 | # parameter is set to 2. We only need to check that autocall is < | |
2349 | # 2, since this function isn't called unless it's at least 1. |
|
2351 | # 2, since this function isn't called unless it's at least 1. | |
2350 | if not theRest and (self.rc.autocall < 2): |
|
2352 | if not theRest and (self.rc.autocall < 2): | |
2351 | newcmd = '%s %s' % (iFun,theRest) |
|
2353 | newcmd = '%s %s' % (iFun,theRest) | |
2352 | auto_rewrite = False |
|
2354 | auto_rewrite = False | |
2353 | else: |
|
2355 | else: | |
2354 | if theRest.startswith('['): |
|
2356 | if theRest.startswith('['): | |
2355 | if hasattr(obj,'__getitem__'): |
|
2357 | if hasattr(obj,'__getitem__'): | |
2356 | # Don't autocall in this case: item access for an object |
|
2358 | # Don't autocall in this case: item access for an object | |
2357 | # which is BOTH callable and implements __getitem__. |
|
2359 | # which is BOTH callable and implements __getitem__. | |
2358 | newcmd = '%s %s' % (iFun,theRest) |
|
2360 | newcmd = '%s %s' % (iFun,theRest) | |
2359 | auto_rewrite = False |
|
2361 | auto_rewrite = False | |
2360 | else: |
|
2362 | else: | |
2361 | # if the object doesn't support [] access, go ahead and |
|
2363 | # if the object doesn't support [] access, go ahead and | |
2362 | # autocall |
|
2364 | # autocall | |
2363 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2365 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2364 | elif theRest.endswith(';'): |
|
2366 | elif theRest.endswith(';'): | |
2365 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2367 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2366 | else: |
|
2368 | else: | |
2367 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2369 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2368 |
|
2370 | |||
2369 | if auto_rewrite: |
|
2371 | if auto_rewrite: | |
2370 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2372 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd | |
2371 | # log what is now valid Python, not the actual user input (without the |
|
2373 | # log what is now valid Python, not the actual user input (without the | |
2372 | # final newline) |
|
2374 | # final newline) | |
2373 | self.log(line,newcmd,continue_prompt) |
|
2375 | self.log(line,newcmd,continue_prompt) | |
2374 | return newcmd |
|
2376 | return newcmd | |
2375 |
|
2377 | |||
2376 | def handle_help(self, line, continue_prompt=None, |
|
2378 | def handle_help(self, line, continue_prompt=None, | |
2377 | pre=None,iFun=None,theRest=None): |
|
2379 | pre=None,iFun=None,theRest=None): | |
2378 | """Try to get some help for the object. |
|
2380 | """Try to get some help for the object. | |
2379 |
|
2381 | |||
2380 | obj? or ?obj -> basic information. |
|
2382 | obj? or ?obj -> basic information. | |
2381 | obj?? or ??obj -> more details. |
|
2383 | obj?? or ??obj -> more details. | |
2382 | """ |
|
2384 | """ | |
2383 |
|
2385 | |||
2384 | # We need to make sure that we don't process lines which would be |
|
2386 | # We need to make sure that we don't process lines which would be | |
2385 | # otherwise valid python, such as "x=1 # what?" |
|
2387 | # otherwise valid python, such as "x=1 # what?" | |
2386 | try: |
|
2388 | try: | |
2387 | codeop.compile_command(line) |
|
2389 | codeop.compile_command(line) | |
2388 | except SyntaxError: |
|
2390 | except SyntaxError: | |
2389 | # We should only handle as help stuff which is NOT valid syntax |
|
2391 | # We should only handle as help stuff which is NOT valid syntax | |
2390 | if line[0]==self.ESC_HELP: |
|
2392 | if line[0]==self.ESC_HELP: | |
2391 | line = line[1:] |
|
2393 | line = line[1:] | |
2392 | elif line[-1]==self.ESC_HELP: |
|
2394 | elif line[-1]==self.ESC_HELP: | |
2393 | line = line[:-1] |
|
2395 | line = line[:-1] | |
2394 | self.log(line,'#?'+line,continue_prompt) |
|
2396 | self.log(line,'#?'+line,continue_prompt) | |
2395 | if line: |
|
2397 | if line: | |
2396 | #print 'line:<%r>' % line # dbg |
|
2398 | #print 'line:<%r>' % line # dbg | |
2397 | self.magic_pinfo(line) |
|
2399 | self.magic_pinfo(line) | |
2398 | else: |
|
2400 | else: | |
2399 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2401 | page(self.usage,screen_lines=self.rc.screen_length) | |
2400 | return '' # Empty string is needed here! |
|
2402 | return '' # Empty string is needed here! | |
2401 | except: |
|
2403 | except: | |
2402 | # Pass any other exceptions through to the normal handler |
|
2404 | # Pass any other exceptions through to the normal handler | |
2403 | return self.handle_normal(line,continue_prompt) |
|
2405 | return self.handle_normal(line,continue_prompt) | |
2404 | else: |
|
2406 | else: | |
2405 | # If the code compiles ok, we should handle it normally |
|
2407 | # If the code compiles ok, we should handle it normally | |
2406 | return self.handle_normal(line,continue_prompt) |
|
2408 | return self.handle_normal(line,continue_prompt) | |
2407 |
|
2409 | |||
2408 | def getapi(self): |
|
2410 | def getapi(self): | |
2409 | """ Get an IPApi object for this shell instance |
|
2411 | """ Get an IPApi object for this shell instance | |
2410 |
|
2412 | |||
2411 | Getting an IPApi object is always preferable to accessing the shell |
|
2413 | Getting an IPApi object is always preferable to accessing the shell | |
2412 | directly, but this holds true especially for extensions. |
|
2414 | directly, but this holds true especially for extensions. | |
2413 |
|
2415 | |||
2414 | It should always be possible to implement an extension with IPApi |
|
2416 | It should always be possible to implement an extension with IPApi | |
2415 | alone. If not, contact maintainer to request an addition. |
|
2417 | alone. If not, contact maintainer to request an addition. | |
2416 |
|
2418 | |||
2417 | """ |
|
2419 | """ | |
2418 | return self.api |
|
2420 | return self.api | |
2419 |
|
2421 | |||
2420 | def handle_emacs(self,line,continue_prompt=None, |
|
2422 | def handle_emacs(self,line,continue_prompt=None, | |
2421 | pre=None,iFun=None,theRest=None): |
|
2423 | pre=None,iFun=None,theRest=None): | |
2422 | """Handle input lines marked by python-mode.""" |
|
2424 | """Handle input lines marked by python-mode.""" | |
2423 |
|
2425 | |||
2424 | # Currently, nothing is done. Later more functionality can be added |
|
2426 | # Currently, nothing is done. Later more functionality can be added | |
2425 | # here if needed. |
|
2427 | # here if needed. | |
2426 |
|
2428 | |||
2427 | # The input cache shouldn't be updated |
|
2429 | # The input cache shouldn't be updated | |
2428 |
|
2430 | |||
2429 | return line |
|
2431 | return line | |
2430 |
|
2432 | |||
2431 | def mktempfile(self,data=None): |
|
2433 | def mktempfile(self,data=None): | |
2432 | """Make a new tempfile and return its filename. |
|
2434 | """Make a new tempfile and return its filename. | |
2433 |
|
2435 | |||
2434 | This makes a call to tempfile.mktemp, but it registers the created |
|
2436 | This makes a call to tempfile.mktemp, but it registers the created | |
2435 | filename internally so ipython cleans it up at exit time. |
|
2437 | filename internally so ipython cleans it up at exit time. | |
2436 |
|
2438 | |||
2437 | Optional inputs: |
|
2439 | Optional inputs: | |
2438 |
|
2440 | |||
2439 | - data(None): if data is given, it gets written out to the temp file |
|
2441 | - data(None): if data is given, it gets written out to the temp file | |
2440 | immediately, and the file is closed again.""" |
|
2442 | immediately, and the file is closed again.""" | |
2441 |
|
2443 | |||
2442 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2444 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2443 | self.tempfiles.append(filename) |
|
2445 | self.tempfiles.append(filename) | |
2444 |
|
2446 | |||
2445 | if data: |
|
2447 | if data: | |
2446 | tmp_file = open(filename,'w') |
|
2448 | tmp_file = open(filename,'w') | |
2447 | tmp_file.write(data) |
|
2449 | tmp_file.write(data) | |
2448 | tmp_file.close() |
|
2450 | tmp_file.close() | |
2449 | return filename |
|
2451 | return filename | |
2450 |
|
2452 | |||
2451 | def write(self,data): |
|
2453 | def write(self,data): | |
2452 | """Write a string to the default output""" |
|
2454 | """Write a string to the default output""" | |
2453 | Term.cout.write(data) |
|
2455 | Term.cout.write(data) | |
2454 |
|
2456 | |||
2455 | def write_err(self,data): |
|
2457 | def write_err(self,data): | |
2456 | """Write a string to the default error output""" |
|
2458 | """Write a string to the default error output""" | |
2457 | Term.cerr.write(data) |
|
2459 | Term.cerr.write(data) | |
2458 |
|
2460 | |||
2459 | def exit(self): |
|
2461 | def exit(self): | |
2460 | """Handle interactive exit. |
|
2462 | """Handle interactive exit. | |
2461 |
|
2463 | |||
2462 | This method sets the exit_now attribute.""" |
|
2464 | This method sets the exit_now attribute.""" | |
2463 |
|
2465 | |||
2464 | if self.rc.confirm_exit: |
|
2466 | if self.rc.confirm_exit: | |
2465 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2467 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2466 | self.exit_now = True |
|
2468 | self.exit_now = True | |
2467 | else: |
|
2469 | else: | |
2468 | self.exit_now = True |
|
2470 | self.exit_now = True | |
2469 |
|
2471 | |||
2470 | def safe_execfile(self,fname,*where,**kw): |
|
2472 | def safe_execfile(self,fname,*where,**kw): | |
2471 | """A safe version of the builtin execfile(). |
|
2473 | """A safe version of the builtin execfile(). | |
2472 |
|
2474 | |||
2473 | This version will never throw an exception, and knows how to handle |
|
2475 | This version will never throw an exception, and knows how to handle | |
2474 | ipython logs as well.""" |
|
2476 | ipython logs as well.""" | |
2475 |
|
2477 | |||
2476 | def syspath_cleanup(): |
|
2478 | def syspath_cleanup(): | |
2477 | """Internal cleanup routine for sys.path.""" |
|
2479 | """Internal cleanup routine for sys.path.""" | |
2478 | if add_dname: |
|
2480 | if add_dname: | |
2479 | try: |
|
2481 | try: | |
2480 | sys.path.remove(dname) |
|
2482 | sys.path.remove(dname) | |
2481 | except ValueError: |
|
2483 | except ValueError: | |
2482 | # For some reason the user has already removed it, ignore. |
|
2484 | # For some reason the user has already removed it, ignore. | |
2483 | pass |
|
2485 | pass | |
2484 |
|
2486 | |||
2485 | fname = os.path.expanduser(fname) |
|
2487 | fname = os.path.expanduser(fname) | |
2486 |
|
2488 | |||
2487 | # Find things also in current directory. This is needed to mimic the |
|
2489 | # Find things also in current directory. This is needed to mimic the | |
2488 | # behavior of running a script from the system command line, where |
|
2490 | # behavior of running a script from the system command line, where | |
2489 | # Python inserts the script's directory into sys.path |
|
2491 | # Python inserts the script's directory into sys.path | |
2490 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2492 | dname = os.path.dirname(os.path.abspath(fname)) | |
2491 | add_dname = False |
|
2493 | add_dname = False | |
2492 | if dname not in sys.path: |
|
2494 | if dname not in sys.path: | |
2493 | sys.path.insert(0,dname) |
|
2495 | sys.path.insert(0,dname) | |
2494 | add_dname = True |
|
2496 | add_dname = True | |
2495 |
|
2497 | |||
2496 | try: |
|
2498 | try: | |
2497 | xfile = open(fname) |
|
2499 | xfile = open(fname) | |
2498 | except: |
|
2500 | except: | |
2499 | print >> Term.cerr, \ |
|
2501 | print >> Term.cerr, \ | |
2500 | 'Could not open file <%s> for safe execution.' % fname |
|
2502 | 'Could not open file <%s> for safe execution.' % fname | |
2501 | syspath_cleanup() |
|
2503 | syspath_cleanup() | |
2502 | return None |
|
2504 | return None | |
2503 |
|
2505 | |||
2504 | kw.setdefault('islog',0) |
|
2506 | kw.setdefault('islog',0) | |
2505 | kw.setdefault('quiet',1) |
|
2507 | kw.setdefault('quiet',1) | |
2506 | kw.setdefault('exit_ignore',0) |
|
2508 | kw.setdefault('exit_ignore',0) | |
2507 | first = xfile.readline() |
|
2509 | first = xfile.readline() | |
2508 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2510 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2509 | xfile.close() |
|
2511 | xfile.close() | |
2510 | # line by line execution |
|
2512 | # line by line execution | |
2511 | if first.startswith(loghead) or kw['islog']: |
|
2513 | if first.startswith(loghead) or kw['islog']: | |
2512 | print 'Loading log file <%s> one line at a time...' % fname |
|
2514 | print 'Loading log file <%s> one line at a time...' % fname | |
2513 | if kw['quiet']: |
|
2515 | if kw['quiet']: | |
2514 | stdout_save = sys.stdout |
|
2516 | stdout_save = sys.stdout | |
2515 | sys.stdout = StringIO.StringIO() |
|
2517 | sys.stdout = StringIO.StringIO() | |
2516 | try: |
|
2518 | try: | |
2517 | globs,locs = where[0:2] |
|
2519 | globs,locs = where[0:2] | |
2518 | except: |
|
2520 | except: | |
2519 | try: |
|
2521 | try: | |
2520 | globs = locs = where[0] |
|
2522 | globs = locs = where[0] | |
2521 | except: |
|
2523 | except: | |
2522 | globs = locs = globals() |
|
2524 | globs = locs = globals() | |
2523 | badblocks = [] |
|
2525 | badblocks = [] | |
2524 |
|
2526 | |||
2525 | # we also need to identify indented blocks of code when replaying |
|
2527 | # we also need to identify indented blocks of code when replaying | |
2526 | # logs and put them together before passing them to an exec |
|
2528 | # logs and put them together before passing them to an exec | |
2527 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2529 | # statement. This takes a bit of regexp and look-ahead work in the | |
2528 | # file. It's easiest if we swallow the whole thing in memory |
|
2530 | # file. It's easiest if we swallow the whole thing in memory | |
2529 | # first, and manually walk through the lines list moving the |
|
2531 | # first, and manually walk through the lines list moving the | |
2530 | # counter ourselves. |
|
2532 | # counter ourselves. | |
2531 | indent_re = re.compile('\s+\S') |
|
2533 | indent_re = re.compile('\s+\S') | |
2532 | xfile = open(fname) |
|
2534 | xfile = open(fname) | |
2533 | filelines = xfile.readlines() |
|
2535 | filelines = xfile.readlines() | |
2534 | xfile.close() |
|
2536 | xfile.close() | |
2535 | nlines = len(filelines) |
|
2537 | nlines = len(filelines) | |
2536 | lnum = 0 |
|
2538 | lnum = 0 | |
2537 | while lnum < nlines: |
|
2539 | while lnum < nlines: | |
2538 | line = filelines[lnum] |
|
2540 | line = filelines[lnum] | |
2539 | lnum += 1 |
|
2541 | lnum += 1 | |
2540 | # don't re-insert logger status info into cache |
|
2542 | # don't re-insert logger status info into cache | |
2541 | if line.startswith('#log#'): |
|
2543 | if line.startswith('#log#'): | |
2542 | continue |
|
2544 | continue | |
2543 | else: |
|
2545 | else: | |
2544 | # build a block of code (maybe a single line) for execution |
|
2546 | # build a block of code (maybe a single line) for execution | |
2545 | block = line |
|
2547 | block = line | |
2546 | try: |
|
2548 | try: | |
2547 | next = filelines[lnum] # lnum has already incremented |
|
2549 | next = filelines[lnum] # lnum has already incremented | |
2548 | except: |
|
2550 | except: | |
2549 | next = None |
|
2551 | next = None | |
2550 | while next and indent_re.match(next): |
|
2552 | while next and indent_re.match(next): | |
2551 | block += next |
|
2553 | block += next | |
2552 | lnum += 1 |
|
2554 | lnum += 1 | |
2553 | try: |
|
2555 | try: | |
2554 | next = filelines[lnum] |
|
2556 | next = filelines[lnum] | |
2555 | except: |
|
2557 | except: | |
2556 | next = None |
|
2558 | next = None | |
2557 | # now execute the block of one or more lines |
|
2559 | # now execute the block of one or more lines | |
2558 | try: |
|
2560 | try: | |
2559 | exec block in globs,locs |
|
2561 | exec block in globs,locs | |
2560 | except SystemExit: |
|
2562 | except SystemExit: | |
2561 | pass |
|
2563 | pass | |
2562 | except: |
|
2564 | except: | |
2563 | badblocks.append(block.rstrip()) |
|
2565 | badblocks.append(block.rstrip()) | |
2564 | if kw['quiet']: # restore stdout |
|
2566 | if kw['quiet']: # restore stdout | |
2565 | sys.stdout.close() |
|
2567 | sys.stdout.close() | |
2566 | sys.stdout = stdout_save |
|
2568 | sys.stdout = stdout_save | |
2567 | print 'Finished replaying log file <%s>' % fname |
|
2569 | print 'Finished replaying log file <%s>' % fname | |
2568 | if badblocks: |
|
2570 | if badblocks: | |
2569 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2571 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2570 | '<%s> reported errors:' % fname) |
|
2572 | '<%s> reported errors:' % fname) | |
2571 |
|
2573 | |||
2572 | for badline in badblocks: |
|
2574 | for badline in badblocks: | |
2573 | print >> sys.stderr, badline |
|
2575 | print >> sys.stderr, badline | |
2574 | else: # regular file execution |
|
2576 | else: # regular file execution | |
2575 | try: |
|
2577 | try: | |
2576 | if sys.platform == 'win32': |
|
2578 | if sys.platform == 'win32': | |
2577 | # Work around a bug in Python for Windows. The bug was |
|
2579 | # Work around a bug in Python for Windows. The bug was | |
2578 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2580 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |
2579 | # SVN Python as of March/07. For details, see: |
|
2581 | # SVN Python as of March/07. For details, see: | |
2580 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2582 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |
2581 | exec file(fname) in where[0],where[1] |
|
2583 | exec file(fname) in where[0],where[1] | |
2582 | else: |
|
2584 | else: | |
2583 | execfile(fname,*where) |
|
2585 | execfile(fname,*where) | |
2584 | except SyntaxError: |
|
2586 | except SyntaxError: | |
2585 | self.showsyntaxerror() |
|
2587 | self.showsyntaxerror() | |
2586 | warn('Failure executing file: <%s>' % fname) |
|
2588 | warn('Failure executing file: <%s>' % fname) | |
2587 | except SystemExit,status: |
|
2589 | except SystemExit,status: | |
2588 | if not kw['exit_ignore']: |
|
2590 | if not kw['exit_ignore']: | |
2589 | self.showtraceback() |
|
2591 | self.showtraceback() | |
2590 | warn('Failure executing file: <%s>' % fname) |
|
2592 | warn('Failure executing file: <%s>' % fname) | |
2591 | except: |
|
2593 | except: | |
2592 | self.showtraceback() |
|
2594 | self.showtraceback() | |
2593 | warn('Failure executing file: <%s>' % fname) |
|
2595 | warn('Failure executing file: <%s>' % fname) | |
2594 |
|
2596 | |||
2595 | syspath_cleanup() |
|
2597 | syspath_cleanup() | |
2596 |
|
2598 | |||
2597 | #************************* end of file <iplib.py> ***************************** |
|
2599 | #************************* end of file <iplib.py> ***************************** |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now