Show More
@@ -1,2158 +1,2161 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """General purpose utilities. |
|
2 | """General purpose utilities. | |
3 |
|
3 | |||
4 | This is a grab-bag of stuff I find useful in most programs I write. Some of |
|
4 | This is a grab-bag of stuff I find useful in most programs I write. Some of | |
5 | these things are also convenient when working at the command line. |
|
5 | these things are also convenient when working at the command line. | |
6 | """ |
|
6 | """ | |
7 |
|
7 | |||
8 | #***************************************************************************** |
|
8 | #***************************************************************************** | |
9 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
9 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
10 | # |
|
10 | # | |
11 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
12 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
13 | #***************************************************************************** |
|
13 | #***************************************************************************** | |
14 |
|
14 | |||
15 | #**************************************************************************** |
|
15 | #**************************************************************************** | |
16 | # required modules from the Python standard library |
|
16 | # required modules from the Python standard library | |
17 | import __main__ |
|
17 | import __main__ | |
18 | import commands |
|
18 | import commands | |
19 | try: |
|
19 | try: | |
20 | import doctest |
|
20 | import doctest | |
21 | except ImportError: |
|
21 | except ImportError: | |
22 | pass |
|
22 | pass | |
23 | import os |
|
23 | import os | |
24 | import platform |
|
24 | import platform | |
25 | import re |
|
25 | import re | |
26 | import shlex |
|
26 | import shlex | |
27 | import shutil |
|
27 | import shutil | |
28 | import subprocess |
|
28 | import subprocess | |
29 | import sys |
|
29 | import sys | |
30 | import tempfile |
|
30 | import tempfile | |
31 | import time |
|
31 | import time | |
32 | import types |
|
32 | import types | |
33 | import warnings |
|
33 | import warnings | |
34 |
|
34 | |||
35 | # Curses and termios are Unix-only modules |
|
35 | # Curses and termios are Unix-only modules | |
36 | try: |
|
36 | try: | |
37 | import curses |
|
37 | import curses | |
38 | # We need termios as well, so if its import happens to raise, we bail on |
|
38 | # We need termios as well, so if its import happens to raise, we bail on | |
39 | # using curses altogether. |
|
39 | # using curses altogether. | |
40 | import termios |
|
40 | import termios | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | USE_CURSES = False |
|
42 | USE_CURSES = False | |
43 | else: |
|
43 | else: | |
44 | # Curses on Solaris may not be complete, so we can't use it there |
|
44 | # Curses on Solaris may not be complete, so we can't use it there | |
45 | USE_CURSES = hasattr(curses,'initscr') |
|
45 | USE_CURSES = hasattr(curses,'initscr') | |
46 |
|
46 | |||
47 | # Other IPython utilities |
|
47 | # Other IPython utilities | |
48 | import IPython |
|
48 | import IPython | |
49 | from IPython.Itpl import Itpl,itpl,printpl |
|
49 | from IPython.Itpl import Itpl,itpl,printpl | |
50 | from IPython import DPyGetOpt, platutils |
|
50 | from IPython import DPyGetOpt, platutils | |
51 | from IPython.generics import result_display |
|
51 | from IPython.generics import result_display | |
52 | import IPython.ipapi |
|
52 | import IPython.ipapi | |
53 | from IPython.external.path import path |
|
53 | from IPython.external.path import path | |
54 | if os.name == "nt": |
|
54 | if os.name == "nt": | |
55 | from IPython.winconsole import get_console_size |
|
55 | from IPython.winconsole import get_console_size | |
56 |
|
56 | |||
57 | try: |
|
57 | try: | |
58 | set |
|
58 | set | |
59 | except: |
|
59 | except: | |
60 | from sets import Set as set |
|
60 | from sets import Set as set | |
61 |
|
61 | |||
62 |
|
62 | |||
63 | #**************************************************************************** |
|
63 | #**************************************************************************** | |
64 | # Exceptions |
|
64 | # Exceptions | |
65 | class Error(Exception): |
|
65 | class Error(Exception): | |
66 | """Base class for exceptions in this module.""" |
|
66 | """Base class for exceptions in this module.""" | |
67 | pass |
|
67 | pass | |
68 |
|
68 | |||
69 | #---------------------------------------------------------------------------- |
|
69 | #---------------------------------------------------------------------------- | |
70 | class IOStream: |
|
70 | class IOStream: | |
71 | def __init__(self,stream,fallback): |
|
71 | def __init__(self,stream,fallback): | |
72 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
72 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): | |
73 | stream = fallback |
|
73 | stream = fallback | |
74 | self.stream = stream |
|
74 | self.stream = stream | |
75 | self._swrite = stream.write |
|
75 | self._swrite = stream.write | |
76 | self.flush = stream.flush |
|
76 | self.flush = stream.flush | |
77 |
|
77 | |||
78 | def write(self,data): |
|
78 | def write(self,data): | |
79 | try: |
|
79 | try: | |
80 | self._swrite(data) |
|
80 | self._swrite(data) | |
81 | except: |
|
81 | except: | |
82 | try: |
|
82 | try: | |
83 | # print handles some unicode issues which may trip a plain |
|
83 | # print handles some unicode issues which may trip a plain | |
84 | # write() call. Attempt to emulate write() by using a |
|
84 | # write() call. Attempt to emulate write() by using a | |
85 | # trailing comma |
|
85 | # trailing comma | |
86 | print >> self.stream, data, |
|
86 | print >> self.stream, data, | |
87 | except: |
|
87 | except: | |
88 | # if we get here, something is seriously broken. |
|
88 | # if we get here, something is seriously broken. | |
89 | print >> sys.stderr, \ |
|
89 | print >> sys.stderr, \ | |
90 | 'ERROR - failed to write data to stream:', self.stream |
|
90 | 'ERROR - failed to write data to stream:', self.stream | |
91 |
|
91 | |||
92 | def close(self): |
|
92 | def close(self): | |
93 | pass |
|
93 | pass | |
94 |
|
94 | |||
95 |
|
95 | |||
96 | class IOTerm: |
|
96 | class IOTerm: | |
97 | """ Term holds the file or file-like objects for handling I/O operations. |
|
97 | """ Term holds the file or file-like objects for handling I/O operations. | |
98 |
|
98 | |||
99 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
99 | These are normally just sys.stdin, sys.stdout and sys.stderr but for | |
100 | Windows they can can replaced to allow editing the strings before they are |
|
100 | Windows they can can replaced to allow editing the strings before they are | |
101 | displayed.""" |
|
101 | displayed.""" | |
102 |
|
102 | |||
103 | # In the future, having IPython channel all its I/O operations through |
|
103 | # In the future, having IPython channel all its I/O operations through | |
104 | # this class will make it easier to embed it into other environments which |
|
104 | # this class will make it easier to embed it into other environments which | |
105 | # are not a normal terminal (such as a GUI-based shell) |
|
105 | # are not a normal terminal (such as a GUI-based shell) | |
106 | def __init__(self,cin=None,cout=None,cerr=None): |
|
106 | def __init__(self,cin=None,cout=None,cerr=None): | |
107 | self.cin = IOStream(cin,sys.stdin) |
|
107 | self.cin = IOStream(cin,sys.stdin) | |
108 | self.cout = IOStream(cout,sys.stdout) |
|
108 | self.cout = IOStream(cout,sys.stdout) | |
109 | self.cerr = IOStream(cerr,sys.stderr) |
|
109 | self.cerr = IOStream(cerr,sys.stderr) | |
110 |
|
110 | |||
111 | # Global variable to be used for all I/O |
|
111 | # Global variable to be used for all I/O | |
112 | Term = IOTerm() |
|
112 | Term = IOTerm() | |
113 |
|
113 | |||
114 | import IPython.rlineimpl as readline |
|
114 | import IPython.rlineimpl as readline | |
115 | # Remake Term to use the readline i/o facilities |
|
115 | # Remake Term to use the readline i/o facilities | |
116 | if sys.platform == 'win32' and readline.have_readline: |
|
116 | if sys.platform == 'win32' and readline.have_readline: | |
117 |
|
117 | |||
118 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) |
|
118 | Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile) | |
119 |
|
119 | |||
120 |
|
120 | |||
121 | #**************************************************************************** |
|
121 | #**************************************************************************** | |
122 | # Generic warning/error printer, used by everything else |
|
122 | # Generic warning/error printer, used by everything else | |
123 | def warn(msg,level=2,exit_val=1): |
|
123 | def warn(msg,level=2,exit_val=1): | |
124 | """Standard warning printer. Gives formatting consistency. |
|
124 | """Standard warning printer. Gives formatting consistency. | |
125 |
|
125 | |||
126 | Output is sent to Term.cerr (sys.stderr by default). |
|
126 | Output is sent to Term.cerr (sys.stderr by default). | |
127 |
|
127 | |||
128 | Options: |
|
128 | Options: | |
129 |
|
129 | |||
130 | -level(2): allows finer control: |
|
130 | -level(2): allows finer control: | |
131 | 0 -> Do nothing, dummy function. |
|
131 | 0 -> Do nothing, dummy function. | |
132 | 1 -> Print message. |
|
132 | 1 -> Print message. | |
133 | 2 -> Print 'WARNING:' + message. (Default level). |
|
133 | 2 -> Print 'WARNING:' + message. (Default level). | |
134 | 3 -> Print 'ERROR:' + message. |
|
134 | 3 -> Print 'ERROR:' + message. | |
135 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
135 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). | |
136 |
|
136 | |||
137 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
137 | -exit_val (1): exit value returned by sys.exit() for a level 4 | |
138 | warning. Ignored for all other levels.""" |
|
138 | warning. Ignored for all other levels.""" | |
139 |
|
139 | |||
140 | if level>0: |
|
140 | if level>0: | |
141 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
141 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] | |
142 | print >> Term.cerr, '%s%s' % (header[level],msg) |
|
142 | print >> Term.cerr, '%s%s' % (header[level],msg) | |
143 | if level == 4: |
|
143 | if level == 4: | |
144 | print >> Term.cerr,'Exiting.\n' |
|
144 | print >> Term.cerr,'Exiting.\n' | |
145 | sys.exit(exit_val) |
|
145 | sys.exit(exit_val) | |
146 |
|
146 | |||
147 | def info(msg): |
|
147 | def info(msg): | |
148 | """Equivalent to warn(msg,level=1).""" |
|
148 | """Equivalent to warn(msg,level=1).""" | |
149 |
|
149 | |||
150 | warn(msg,level=1) |
|
150 | warn(msg,level=1) | |
151 |
|
151 | |||
152 | def error(msg): |
|
152 | def error(msg): | |
153 | """Equivalent to warn(msg,level=3).""" |
|
153 | """Equivalent to warn(msg,level=3).""" | |
154 |
|
154 | |||
155 | warn(msg,level=3) |
|
155 | warn(msg,level=3) | |
156 |
|
156 | |||
157 | def fatal(msg,exit_val=1): |
|
157 | def fatal(msg,exit_val=1): | |
158 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
158 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" | |
159 |
|
159 | |||
160 | warn(msg,exit_val=exit_val,level=4) |
|
160 | warn(msg,exit_val=exit_val,level=4) | |
161 |
|
161 | |||
162 | #--------------------------------------------------------------------------- |
|
162 | #--------------------------------------------------------------------------- | |
163 | # Debugging routines |
|
163 | # Debugging routines | |
164 | # |
|
164 | # | |
165 | def debugx(expr,pre_msg=''): |
|
165 | def debugx(expr,pre_msg=''): | |
166 | """Print the value of an expression from the caller's frame. |
|
166 | """Print the value of an expression from the caller's frame. | |
167 |
|
167 | |||
168 | Takes an expression, evaluates it in the caller's frame and prints both |
|
168 | Takes an expression, evaluates it in the caller's frame and prints both | |
169 | the given expression and the resulting value (as well as a debug mark |
|
169 | the given expression and the resulting value (as well as a debug mark | |
170 | indicating the name of the calling function. The input must be of a form |
|
170 | indicating the name of the calling function. The input must be of a form | |
171 | suitable for eval(). |
|
171 | suitable for eval(). | |
172 |
|
172 | |||
173 | An optional message can be passed, which will be prepended to the printed |
|
173 | An optional message can be passed, which will be prepended to the printed | |
174 | expr->value pair.""" |
|
174 | expr->value pair.""" | |
175 |
|
175 | |||
176 | cf = sys._getframe(1) |
|
176 | cf = sys._getframe(1) | |
177 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, |
|
177 | print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr, | |
178 | eval(expr,cf.f_globals,cf.f_locals)) |
|
178 | eval(expr,cf.f_globals,cf.f_locals)) | |
179 |
|
179 | |||
180 | # deactivate it by uncommenting the following line, which makes it a no-op |
|
180 | # deactivate it by uncommenting the following line, which makes it a no-op | |
181 | #def debugx(expr,pre_msg=''): pass |
|
181 | #def debugx(expr,pre_msg=''): pass | |
182 |
|
182 | |||
183 | #---------------------------------------------------------------------------- |
|
183 | #---------------------------------------------------------------------------- | |
184 | StringTypes = types.StringTypes |
|
184 | StringTypes = types.StringTypes | |
185 |
|
185 | |||
186 | # Basic timing functionality |
|
186 | # Basic timing functionality | |
187 |
|
187 | |||
188 | # If possible (Unix), use the resource module instead of time.clock() |
|
188 | # If possible (Unix), use the resource module instead of time.clock() | |
189 | try: |
|
189 | try: | |
190 | import resource |
|
190 | import resource | |
191 | def clocku(): |
|
191 | def clocku(): | |
192 | """clocku() -> floating point number |
|
192 | """clocku() -> floating point number | |
193 |
|
193 | |||
194 | Return the *USER* CPU time in seconds since the start of the process. |
|
194 | Return the *USER* CPU time in seconds since the start of the process. | |
195 | This is done via a call to resource.getrusage, so it avoids the |
|
195 | This is done via a call to resource.getrusage, so it avoids the | |
196 | wraparound problems in time.clock().""" |
|
196 | wraparound problems in time.clock().""" | |
197 |
|
197 | |||
198 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
198 | return resource.getrusage(resource.RUSAGE_SELF)[0] | |
199 |
|
199 | |||
200 | def clocks(): |
|
200 | def clocks(): | |
201 | """clocks() -> floating point number |
|
201 | """clocks() -> floating point number | |
202 |
|
202 | |||
203 | Return the *SYSTEM* CPU time in seconds since the start of the process. |
|
203 | Return the *SYSTEM* CPU time in seconds since the start of the process. | |
204 | This is done via a call to resource.getrusage, so it avoids the |
|
204 | This is done via a call to resource.getrusage, so it avoids the | |
205 | wraparound problems in time.clock().""" |
|
205 | wraparound problems in time.clock().""" | |
206 |
|
206 | |||
207 | return resource.getrusage(resource.RUSAGE_SELF)[1] |
|
207 | return resource.getrusage(resource.RUSAGE_SELF)[1] | |
208 |
|
208 | |||
209 | def clock(): |
|
209 | def clock(): | |
210 | """clock() -> floating point number |
|
210 | """clock() -> floating point number | |
211 |
|
211 | |||
212 | Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of |
|
212 | Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of | |
213 | the process. This is done via a call to resource.getrusage, so it |
|
213 | the process. This is done via a call to resource.getrusage, so it | |
214 | avoids the wraparound problems in time.clock().""" |
|
214 | avoids the wraparound problems in time.clock().""" | |
215 |
|
215 | |||
216 | u,s = resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
216 | u,s = resource.getrusage(resource.RUSAGE_SELF)[:2] | |
217 | return u+s |
|
217 | return u+s | |
218 |
|
218 | |||
219 | def clock2(): |
|
219 | def clock2(): | |
220 | """clock2() -> (t_user,t_system) |
|
220 | """clock2() -> (t_user,t_system) | |
221 |
|
221 | |||
222 | Similar to clock(), but return a tuple of user/system times.""" |
|
222 | Similar to clock(), but return a tuple of user/system times.""" | |
223 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
223 | return resource.getrusage(resource.RUSAGE_SELF)[:2] | |
224 |
|
224 | |||
225 | except ImportError: |
|
225 | except ImportError: | |
226 | # There is no distinction of user/system time under windows, so we just use |
|
226 | # There is no distinction of user/system time under windows, so we just use | |
227 | # time.clock() for everything... |
|
227 | # time.clock() for everything... | |
228 | clocku = clocks = clock = time.clock |
|
228 | clocku = clocks = clock = time.clock | |
229 | def clock2(): |
|
229 | def clock2(): | |
230 | """Under windows, system CPU time can't be measured. |
|
230 | """Under windows, system CPU time can't be measured. | |
231 |
|
231 | |||
232 | This just returns clock() and zero.""" |
|
232 | This just returns clock() and zero.""" | |
233 | return time.clock(),0.0 |
|
233 | return time.clock(),0.0 | |
234 |
|
234 | |||
235 | def timings_out(reps,func,*args,**kw): |
|
235 | def timings_out(reps,func,*args,**kw): | |
236 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
236 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) | |
237 |
|
237 | |||
238 | Execute a function reps times, return a tuple with the elapsed total |
|
238 | Execute a function reps times, return a tuple with the elapsed total | |
239 | CPU time in seconds, the time per call and the function's output. |
|
239 | CPU time in seconds, the time per call and the function's output. | |
240 |
|
240 | |||
241 | Under Unix, the return value is the sum of user+system time consumed by |
|
241 | Under Unix, the return value is the sum of user+system time consumed by | |
242 | the process, computed via the resource module. This prevents problems |
|
242 | the process, computed via the resource module. This prevents problems | |
243 | related to the wraparound effect which the time.clock() function has. |
|
243 | related to the wraparound effect which the time.clock() function has. | |
244 |
|
244 | |||
245 | Under Windows the return value is in wall clock seconds. See the |
|
245 | Under Windows the return value is in wall clock seconds. See the | |
246 | documentation for the time module for more details.""" |
|
246 | documentation for the time module for more details.""" | |
247 |
|
247 | |||
248 | reps = int(reps) |
|
248 | reps = int(reps) | |
249 | assert reps >=1, 'reps must be >= 1' |
|
249 | assert reps >=1, 'reps must be >= 1' | |
250 | if reps==1: |
|
250 | if reps==1: | |
251 | start = clock() |
|
251 | start = clock() | |
252 | out = func(*args,**kw) |
|
252 | out = func(*args,**kw) | |
253 | tot_time = clock()-start |
|
253 | tot_time = clock()-start | |
254 | else: |
|
254 | else: | |
255 | rng = xrange(reps-1) # the last time is executed separately to store output |
|
255 | rng = xrange(reps-1) # the last time is executed separately to store output | |
256 | start = clock() |
|
256 | start = clock() | |
257 | for dummy in rng: func(*args,**kw) |
|
257 | for dummy in rng: func(*args,**kw) | |
258 | out = func(*args,**kw) # one last time |
|
258 | out = func(*args,**kw) # one last time | |
259 | tot_time = clock()-start |
|
259 | tot_time = clock()-start | |
260 | av_time = tot_time / reps |
|
260 | av_time = tot_time / reps | |
261 | return tot_time,av_time,out |
|
261 | return tot_time,av_time,out | |
262 |
|
262 | |||
263 | def timings(reps,func,*args,**kw): |
|
263 | def timings(reps,func,*args,**kw): | |
264 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
264 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) | |
265 |
|
265 | |||
266 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
266 | Execute a function reps times, return a tuple with the elapsed total CPU | |
267 | time in seconds and the time per call. These are just the first two values |
|
267 | time in seconds and the time per call. These are just the first two values | |
268 | in timings_out().""" |
|
268 | in timings_out().""" | |
269 |
|
269 | |||
270 | return timings_out(reps,func,*args,**kw)[0:2] |
|
270 | return timings_out(reps,func,*args,**kw)[0:2] | |
271 |
|
271 | |||
272 | def timing(func,*args,**kw): |
|
272 | def timing(func,*args,**kw): | |
273 | """timing(func,*args,**kw) -> t_total |
|
273 | """timing(func,*args,**kw) -> t_total | |
274 |
|
274 | |||
275 | Execute a function once, return the elapsed total CPU time in |
|
275 | Execute a function once, return the elapsed total CPU time in | |
276 | seconds. This is just the first value in timings_out().""" |
|
276 | seconds. This is just the first value in timings_out().""" | |
277 |
|
277 | |||
278 | return timings_out(1,func,*args,**kw)[0] |
|
278 | return timings_out(1,func,*args,**kw)[0] | |
279 |
|
279 | |||
280 | #**************************************************************************** |
|
280 | #**************************************************************************** | |
281 | # file and system |
|
281 | # file and system | |
282 |
|
282 | |||
283 | def arg_split(s,posix=False): |
|
283 | def arg_split(s,posix=False): | |
284 | """Split a command line's arguments in a shell-like manner. |
|
284 | """Split a command line's arguments in a shell-like manner. | |
285 |
|
285 | |||
286 | This is a modified version of the standard library's shlex.split() |
|
286 | This is a modified version of the standard library's shlex.split() | |
287 | function, but with a default of posix=False for splitting, so that quotes |
|
287 | function, but with a default of posix=False for splitting, so that quotes | |
288 | in inputs are respected.""" |
|
288 | in inputs are respected.""" | |
289 |
|
289 | |||
290 | # XXX - there may be unicode-related problems here!!! I'm not sure that |
|
290 | # XXX - there may be unicode-related problems here!!! I'm not sure that | |
291 | # shlex is truly unicode-safe, so it might be necessary to do |
|
291 | # shlex is truly unicode-safe, so it might be necessary to do | |
292 | # |
|
292 | # | |
293 | # s = s.encode(sys.stdin.encoding) |
|
293 | # s = s.encode(sys.stdin.encoding) | |
294 | # |
|
294 | # | |
295 | # first, to ensure that shlex gets a normal string. Input from anyone who |
|
295 | # first, to ensure that shlex gets a normal string. Input from anyone who | |
296 | # knows more about unicode and shlex than I would be good to have here... |
|
296 | # knows more about unicode and shlex than I would be good to have here... | |
297 | lex = shlex.shlex(s, posix=posix) |
|
297 | lex = shlex.shlex(s, posix=posix) | |
298 | lex.whitespace_split = True |
|
298 | lex.whitespace_split = True | |
299 | return list(lex) |
|
299 | return list(lex) | |
300 |
|
300 | |||
301 | def system(cmd,verbose=0,debug=0,header=''): |
|
301 | def system(cmd,verbose=0,debug=0,header=''): | |
302 | """Execute a system command, return its exit status. |
|
302 | """Execute a system command, return its exit status. | |
303 |
|
303 | |||
304 | Options: |
|
304 | Options: | |
305 |
|
305 | |||
306 | - verbose (0): print the command to be executed. |
|
306 | - verbose (0): print the command to be executed. | |
307 |
|
307 | |||
308 | - debug (0): only print, do not actually execute. |
|
308 | - debug (0): only print, do not actually execute. | |
309 |
|
309 | |||
310 | - header (''): Header to print on screen prior to the executed command (it |
|
310 | - header (''): Header to print on screen prior to the executed command (it | |
311 | is only prepended to the command, no newlines are added). |
|
311 | is only prepended to the command, no newlines are added). | |
312 |
|
312 | |||
313 | Note: a stateful version of this function is available through the |
|
313 | Note: a stateful version of this function is available through the | |
314 | SystemExec class.""" |
|
314 | SystemExec class.""" | |
315 |
|
315 | |||
316 | stat = 0 |
|
316 | stat = 0 | |
317 | if verbose or debug: print header+cmd |
|
317 | if verbose or debug: print header+cmd | |
318 | sys.stdout.flush() |
|
318 | sys.stdout.flush() | |
319 | if not debug: stat = os.system(cmd) |
|
319 | if not debug: stat = os.system(cmd) | |
320 | return stat |
|
320 | return stat | |
321 |
|
321 | |||
322 | def abbrev_cwd(): |
|
322 | def abbrev_cwd(): | |
323 | """ Return abbreviated version of cwd, e.g. d:mydir """ |
|
323 | """ Return abbreviated version of cwd, e.g. d:mydir """ | |
324 | cwd = os.getcwd().replace('\\','/') |
|
324 | cwd = os.getcwd().replace('\\','/') | |
325 | drivepart = '' |
|
325 | drivepart = '' | |
326 | tail = cwd |
|
326 | tail = cwd | |
327 | if sys.platform == 'win32': |
|
327 | if sys.platform == 'win32': | |
328 | if len(cwd) < 4: |
|
328 | if len(cwd) < 4: | |
329 | return cwd |
|
329 | return cwd | |
330 | drivepart,tail = os.path.splitdrive(cwd) |
|
330 | drivepart,tail = os.path.splitdrive(cwd) | |
331 |
|
331 | |||
332 |
|
332 | |||
333 | parts = tail.split('/') |
|
333 | parts = tail.split('/') | |
334 | if len(parts) > 2: |
|
334 | if len(parts) > 2: | |
335 | tail = '/'.join(parts[-2:]) |
|
335 | tail = '/'.join(parts[-2:]) | |
336 |
|
336 | |||
337 | return (drivepart + ( |
|
337 | return (drivepart + ( | |
338 | cwd == '/' and '/' or tail)) |
|
338 | cwd == '/' and '/' or tail)) | |
339 |
|
339 | |||
340 |
|
340 | |||
341 | # This function is used by ipython in a lot of places to make system calls. |
|
341 | # This function is used by ipython in a lot of places to make system calls. | |
342 | # We need it to be slightly different under win32, due to the vagaries of |
|
342 | # We need it to be slightly different under win32, due to the vagaries of | |
343 | # 'network shares'. A win32 override is below. |
|
343 | # 'network shares'. A win32 override is below. | |
344 |
|
344 | |||
345 | def shell(cmd,verbose=0,debug=0,header=''): |
|
345 | def shell(cmd,verbose=0,debug=0,header=''): | |
346 | """Execute a command in the system shell, always return None. |
|
346 | """Execute a command in the system shell, always return None. | |
347 |
|
347 | |||
348 | Options: |
|
348 | Options: | |
349 |
|
349 | |||
350 | - verbose (0): print the command to be executed. |
|
350 | - verbose (0): print the command to be executed. | |
351 |
|
351 | |||
352 | - debug (0): only print, do not actually execute. |
|
352 | - debug (0): only print, do not actually execute. | |
353 |
|
353 | |||
354 | - header (''): Header to print on screen prior to the executed command (it |
|
354 | - header (''): Header to print on screen prior to the executed command (it | |
355 | is only prepended to the command, no newlines are added). |
|
355 | is only prepended to the command, no newlines are added). | |
356 |
|
356 | |||
357 | Note: this is similar to genutils.system(), but it returns None so it can |
|
357 | Note: this is similar to genutils.system(), but it returns None so it can | |
358 | be conveniently used in interactive loops without getting the return value |
|
358 | be conveniently used in interactive loops without getting the return value | |
359 | (typically 0) printed many times.""" |
|
359 | (typically 0) printed many times.""" | |
360 |
|
360 | |||
361 | stat = 0 |
|
361 | stat = 0 | |
362 | if verbose or debug: print header+cmd |
|
362 | if verbose or debug: print header+cmd | |
363 | # flush stdout so we don't mangle python's buffering |
|
363 | # flush stdout so we don't mangle python's buffering | |
364 | sys.stdout.flush() |
|
364 | sys.stdout.flush() | |
365 |
|
365 | |||
366 | if not debug: |
|
366 | if not debug: | |
367 | platutils.set_term_title("IPy " + cmd) |
|
367 | platutils.set_term_title("IPy " + cmd) | |
368 | os.system(cmd) |
|
368 | os.system(cmd) | |
369 | platutils.set_term_title("IPy " + abbrev_cwd()) |
|
369 | platutils.set_term_title("IPy " + abbrev_cwd()) | |
370 |
|
370 | |||
371 | # override shell() for win32 to deal with network shares |
|
371 | # override shell() for win32 to deal with network shares | |
372 | if os.name in ('nt','dos'): |
|
372 | if os.name in ('nt','dos'): | |
373 |
|
373 | |||
374 | shell_ori = shell |
|
374 | shell_ori = shell | |
375 |
|
375 | |||
376 | def shell(cmd,verbose=0,debug=0,header=''): |
|
376 | def shell(cmd,verbose=0,debug=0,header=''): | |
377 | if os.getcwd().startswith(r"\\"): |
|
377 | if os.getcwd().startswith(r"\\"): | |
378 | path = os.getcwd() |
|
378 | path = os.getcwd() | |
379 | # change to c drive (cannot be on UNC-share when issuing os.system, |
|
379 | # change to c drive (cannot be on UNC-share when issuing os.system, | |
380 | # as cmd.exe cannot handle UNC addresses) |
|
380 | # as cmd.exe cannot handle UNC addresses) | |
381 | os.chdir("c:") |
|
381 | os.chdir("c:") | |
382 | # issue pushd to the UNC-share and then run the command |
|
382 | # issue pushd to the UNC-share and then run the command | |
383 | try: |
|
383 | try: | |
384 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) |
|
384 | shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header) | |
385 | finally: |
|
385 | finally: | |
386 | os.chdir(path) |
|
386 | os.chdir(path) | |
387 | else: |
|
387 | else: | |
388 | shell_ori(cmd,verbose,debug,header) |
|
388 | shell_ori(cmd,verbose,debug,header) | |
389 |
|
389 | |||
390 | shell.__doc__ = shell_ori.__doc__ |
|
390 | shell.__doc__ = shell_ori.__doc__ | |
391 |
|
391 | |||
392 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): |
|
392 | def getoutput(cmd,verbose=0,debug=0,header='',split=0): | |
393 | """Dummy substitute for perl's backquotes. |
|
393 | """Dummy substitute for perl's backquotes. | |
394 |
|
394 | |||
395 | Executes a command and returns the output. |
|
395 | Executes a command and returns the output. | |
396 |
|
396 | |||
397 | Accepts the same arguments as system(), plus: |
|
397 | Accepts the same arguments as system(), plus: | |
398 |
|
398 | |||
399 | - split(0): if true, the output is returned as a list split on newlines. |
|
399 | - split(0): if true, the output is returned as a list split on newlines. | |
400 |
|
400 | |||
401 | Note: a stateful version of this function is available through the |
|
401 | Note: a stateful version of this function is available through the | |
402 | SystemExec class. |
|
402 | SystemExec class. | |
403 |
|
403 | |||
404 | This is pretty much deprecated and rarely used, |
|
404 | This is pretty much deprecated and rarely used, | |
405 | genutils.getoutputerror may be what you need. |
|
405 | genutils.getoutputerror may be what you need. | |
406 |
|
406 | |||
407 | """ |
|
407 | """ | |
408 |
|
408 | |||
409 | if verbose or debug: print header+cmd |
|
409 | if verbose or debug: print header+cmd | |
410 | if not debug: |
|
410 | if not debug: | |
411 | output = os.popen(cmd).read() |
|
411 | output = os.popen(cmd).read() | |
412 | # stipping last \n is here for backwards compat. |
|
412 | # stipping last \n is here for backwards compat. | |
413 | if output.endswith('\n'): |
|
413 | if output.endswith('\n'): | |
414 | output = output[:-1] |
|
414 | output = output[:-1] | |
415 | if split: |
|
415 | if split: | |
416 | return output.split('\n') |
|
416 | return output.split('\n') | |
417 | else: |
|
417 | else: | |
418 | return output |
|
418 | return output | |
419 |
|
419 | |||
420 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): |
|
420 | def getoutputerror(cmd,verbose=0,debug=0,header='',split=0): | |
421 | """Return (standard output,standard error) of executing cmd in a shell. |
|
421 | """Return (standard output,standard error) of executing cmd in a shell. | |
422 |
|
422 | |||
423 | Accepts the same arguments as system(), plus: |
|
423 | Accepts the same arguments as system(), plus: | |
424 |
|
424 | |||
425 | - split(0): if true, each of stdout/err is returned as a list split on |
|
425 | - split(0): if true, each of stdout/err is returned as a list split on | |
426 | newlines. |
|
426 | newlines. | |
427 |
|
427 | |||
428 | Note: a stateful version of this function is available through the |
|
428 | Note: a stateful version of this function is available through the | |
429 | SystemExec class.""" |
|
429 | SystemExec class.""" | |
430 |
|
430 | |||
431 | if verbose or debug: print header+cmd |
|
431 | if verbose or debug: print header+cmd | |
432 | if not cmd: |
|
432 | if not cmd: | |
433 | if split: |
|
433 | if split: | |
434 | return [],[] |
|
434 | return [],[] | |
435 | else: |
|
435 | else: | |
436 | return '','' |
|
436 | return '','' | |
437 | if not debug: |
|
437 | if not debug: | |
438 | pin,pout,perr = os.popen3(cmd) |
|
438 | pin,pout,perr = os.popen3(cmd) | |
439 | tout = pout.read().rstrip() |
|
439 | tout = pout.read().rstrip() | |
440 | terr = perr.read().rstrip() |
|
440 | terr = perr.read().rstrip() | |
441 | pin.close() |
|
441 | pin.close() | |
442 | pout.close() |
|
442 | pout.close() | |
443 | perr.close() |
|
443 | perr.close() | |
444 | if split: |
|
444 | if split: | |
445 | return tout.split('\n'),terr.split('\n') |
|
445 | return tout.split('\n'),terr.split('\n') | |
446 | else: |
|
446 | else: | |
447 | return tout,terr |
|
447 | return tout,terr | |
448 |
|
448 | |||
449 | # for compatibility with older naming conventions |
|
449 | # for compatibility with older naming conventions | |
450 | xsys = system |
|
450 | xsys = system | |
451 | bq = getoutput |
|
451 | bq = getoutput | |
452 |
|
452 | |||
453 | class SystemExec: |
|
453 | class SystemExec: | |
454 | """Access the system and getoutput functions through a stateful interface. |
|
454 | """Access the system and getoutput functions through a stateful interface. | |
455 |
|
455 | |||
456 | Note: here we refer to the system and getoutput functions from this |
|
456 | Note: here we refer to the system and getoutput functions from this | |
457 | library, not the ones from the standard python library. |
|
457 | library, not the ones from the standard python library. | |
458 |
|
458 | |||
459 | This class offers the system and getoutput functions as methods, but the |
|
459 | This class offers the system and getoutput functions as methods, but the | |
460 | verbose, debug and header parameters can be set for the instance (at |
|
460 | verbose, debug and header parameters can be set for the instance (at | |
461 | creation time or later) so that they don't need to be specified on each |
|
461 | creation time or later) so that they don't need to be specified on each | |
462 | call. |
|
462 | call. | |
463 |
|
463 | |||
464 | For efficiency reasons, there's no way to override the parameters on a |
|
464 | For efficiency reasons, there's no way to override the parameters on a | |
465 | per-call basis other than by setting instance attributes. If you need |
|
465 | per-call basis other than by setting instance attributes. If you need | |
466 | local overrides, it's best to directly call system() or getoutput(). |
|
466 | local overrides, it's best to directly call system() or getoutput(). | |
467 |
|
467 | |||
468 | The following names are provided as alternate options: |
|
468 | The following names are provided as alternate options: | |
469 | - xsys: alias to system |
|
469 | - xsys: alias to system | |
470 | - bq: alias to getoutput |
|
470 | - bq: alias to getoutput | |
471 |
|
471 | |||
472 | An instance can then be created as: |
|
472 | An instance can then be created as: | |
473 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') |
|
473 | >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ') | |
474 | """ |
|
474 | """ | |
475 |
|
475 | |||
476 | def __init__(self,verbose=0,debug=0,header='',split=0): |
|
476 | def __init__(self,verbose=0,debug=0,header='',split=0): | |
477 | """Specify the instance's values for verbose, debug and header.""" |
|
477 | """Specify the instance's values for verbose, debug and header.""" | |
478 | setattr_list(self,'verbose debug header split') |
|
478 | setattr_list(self,'verbose debug header split') | |
479 |
|
479 | |||
480 | def system(self,cmd): |
|
480 | def system(self,cmd): | |
481 | """Stateful interface to system(), with the same keyword parameters.""" |
|
481 | """Stateful interface to system(), with the same keyword parameters.""" | |
482 |
|
482 | |||
483 | system(cmd,self.verbose,self.debug,self.header) |
|
483 | system(cmd,self.verbose,self.debug,self.header) | |
484 |
|
484 | |||
485 | def shell(self,cmd): |
|
485 | def shell(self,cmd): | |
486 | """Stateful interface to shell(), with the same keyword parameters.""" |
|
486 | """Stateful interface to shell(), with the same keyword parameters.""" | |
487 |
|
487 | |||
488 | shell(cmd,self.verbose,self.debug,self.header) |
|
488 | shell(cmd,self.verbose,self.debug,self.header) | |
489 |
|
489 | |||
490 | xsys = system # alias |
|
490 | xsys = system # alias | |
491 |
|
491 | |||
492 | def getoutput(self,cmd): |
|
492 | def getoutput(self,cmd): | |
493 | """Stateful interface to getoutput().""" |
|
493 | """Stateful interface to getoutput().""" | |
494 |
|
494 | |||
495 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) |
|
495 | return getoutput(cmd,self.verbose,self.debug,self.header,self.split) | |
496 |
|
496 | |||
497 | def getoutputerror(self,cmd): |
|
497 | def getoutputerror(self,cmd): | |
498 | """Stateful interface to getoutputerror().""" |
|
498 | """Stateful interface to getoutputerror().""" | |
499 |
|
499 | |||
500 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) |
|
500 | return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split) | |
501 |
|
501 | |||
502 | bq = getoutput # alias |
|
502 | bq = getoutput # alias | |
503 |
|
503 | |||
504 | #----------------------------------------------------------------------------- |
|
504 | #----------------------------------------------------------------------------- | |
505 | def mutex_opts(dict,ex_op): |
|
505 | def mutex_opts(dict,ex_op): | |
506 | """Check for presence of mutually exclusive keys in a dict. |
|
506 | """Check for presence of mutually exclusive keys in a dict. | |
507 |
|
507 | |||
508 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
508 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" | |
509 | for op1,op2 in ex_op: |
|
509 | for op1,op2 in ex_op: | |
510 | if op1 in dict and op2 in dict: |
|
510 | if op1 in dict and op2 in dict: | |
511 | raise ValueError,'\n*** ERROR in Arguments *** '\ |
|
511 | raise ValueError,'\n*** ERROR in Arguments *** '\ | |
512 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
512 | 'Options '+op1+' and '+op2+' are mutually exclusive.' | |
513 |
|
513 | |||
514 | #----------------------------------------------------------------------------- |
|
514 | #----------------------------------------------------------------------------- | |
515 | def get_py_filename(name): |
|
515 | def get_py_filename(name): | |
516 | """Return a valid python filename in the current directory. |
|
516 | """Return a valid python filename in the current directory. | |
517 |
|
517 | |||
518 | If the given name is not a file, it adds '.py' and searches again. |
|
518 | If the given name is not a file, it adds '.py' and searches again. | |
519 | Raises IOError with an informative message if the file isn't found.""" |
|
519 | Raises IOError with an informative message if the file isn't found.""" | |
520 |
|
520 | |||
521 | name = os.path.expanduser(name) |
|
521 | name = os.path.expanduser(name) | |
522 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
522 | if not os.path.isfile(name) and not name.endswith('.py'): | |
523 | name += '.py' |
|
523 | name += '.py' | |
524 | if os.path.isfile(name): |
|
524 | if os.path.isfile(name): | |
525 | return name |
|
525 | return name | |
526 | else: |
|
526 | else: | |
527 | raise IOError,'File `%s` not found.' % name |
|
527 | raise IOError,'File `%s` not found.' % name | |
528 |
|
528 | |||
529 | #----------------------------------------------------------------------------- |
|
529 | #----------------------------------------------------------------------------- | |
530 | def filefind(fname,alt_dirs = None): |
|
530 | def filefind(fname,alt_dirs = None): | |
531 | """Return the given filename either in the current directory, if it |
|
531 | """Return the given filename either in the current directory, if it | |
532 | exists, or in a specified list of directories. |
|
532 | exists, or in a specified list of directories. | |
533 |
|
533 | |||
534 | ~ expansion is done on all file and directory names. |
|
534 | ~ expansion is done on all file and directory names. | |
535 |
|
535 | |||
536 | Upon an unsuccessful search, raise an IOError exception.""" |
|
536 | Upon an unsuccessful search, raise an IOError exception.""" | |
537 |
|
537 | |||
538 | if alt_dirs is None: |
|
538 | if alt_dirs is None: | |
539 | try: |
|
539 | try: | |
540 | alt_dirs = get_home_dir() |
|
540 | alt_dirs = get_home_dir() | |
541 | except HomeDirError: |
|
541 | except HomeDirError: | |
542 | alt_dirs = os.getcwd() |
|
542 | alt_dirs = os.getcwd() | |
543 | search = [fname] + list_strings(alt_dirs) |
|
543 | search = [fname] + list_strings(alt_dirs) | |
544 | search = map(os.path.expanduser,search) |
|
544 | search = map(os.path.expanduser,search) | |
545 | #print 'search list for',fname,'list:',search # dbg |
|
545 | #print 'search list for',fname,'list:',search # dbg | |
546 | fname = search[0] |
|
546 | fname = search[0] | |
547 | if os.path.isfile(fname): |
|
547 | if os.path.isfile(fname): | |
548 | return fname |
|
548 | return fname | |
549 | for direc in search[1:]: |
|
549 | for direc in search[1:]: | |
550 | testname = os.path.join(direc,fname) |
|
550 | testname = os.path.join(direc,fname) | |
551 | #print 'testname',testname # dbg |
|
551 | #print 'testname',testname # dbg | |
552 | if os.path.isfile(testname): |
|
552 | if os.path.isfile(testname): | |
553 | return testname |
|
553 | return testname | |
554 | raise IOError,'File' + `fname` + \ |
|
554 | raise IOError,'File' + `fname` + \ | |
555 | ' not found in current or supplied directories:' + `alt_dirs` |
|
555 | ' not found in current or supplied directories:' + `alt_dirs` | |
556 |
|
556 | |||
557 | #---------------------------------------------------------------------------- |
|
557 | #---------------------------------------------------------------------------- | |
558 | def file_read(filename): |
|
558 | def file_read(filename): | |
559 | """Read a file and close it. Returns the file source.""" |
|
559 | """Read a file and close it. Returns the file source.""" | |
560 | fobj = open(filename,'r'); |
|
560 | fobj = open(filename,'r'); | |
561 | source = fobj.read(); |
|
561 | source = fobj.read(); | |
562 | fobj.close() |
|
562 | fobj.close() | |
563 | return source |
|
563 | return source | |
564 |
|
564 | |||
565 | def file_readlines(filename): |
|
565 | def file_readlines(filename): | |
566 | """Read a file and close it. Returns the file source using readlines().""" |
|
566 | """Read a file and close it. Returns the file source using readlines().""" | |
567 | fobj = open(filename,'r'); |
|
567 | fobj = open(filename,'r'); | |
568 | lines = fobj.readlines(); |
|
568 | lines = fobj.readlines(); | |
569 | fobj.close() |
|
569 | fobj.close() | |
570 | return lines |
|
570 | return lines | |
571 |
|
571 | |||
572 | #---------------------------------------------------------------------------- |
|
572 | #---------------------------------------------------------------------------- | |
573 | def target_outdated(target,deps): |
|
573 | def target_outdated(target,deps): | |
574 | """Determine whether a target is out of date. |
|
574 | """Determine whether a target is out of date. | |
575 |
|
575 | |||
576 | target_outdated(target,deps) -> 1/0 |
|
576 | target_outdated(target,deps) -> 1/0 | |
577 |
|
577 | |||
578 | deps: list of filenames which MUST exist. |
|
578 | deps: list of filenames which MUST exist. | |
579 | target: single filename which may or may not exist. |
|
579 | target: single filename which may or may not exist. | |
580 |
|
580 | |||
581 | If target doesn't exist or is older than any file listed in deps, return |
|
581 | If target doesn't exist or is older than any file listed in deps, return | |
582 | true, otherwise return false. |
|
582 | true, otherwise return false. | |
583 | """ |
|
583 | """ | |
584 | try: |
|
584 | try: | |
585 | target_time = os.path.getmtime(target) |
|
585 | target_time = os.path.getmtime(target) | |
586 | except os.error: |
|
586 | except os.error: | |
587 | return 1 |
|
587 | return 1 | |
588 | for dep in deps: |
|
588 | for dep in deps: | |
589 | dep_time = os.path.getmtime(dep) |
|
589 | dep_time = os.path.getmtime(dep) | |
590 | if dep_time > target_time: |
|
590 | if dep_time > target_time: | |
591 | #print "For target",target,"Dep failed:",dep # dbg |
|
591 | #print "For target",target,"Dep failed:",dep # dbg | |
592 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
592 | #print "times (dep,tar):",dep_time,target_time # dbg | |
593 | return 1 |
|
593 | return 1 | |
594 | return 0 |
|
594 | return 0 | |
595 |
|
595 | |||
596 | #----------------------------------------------------------------------------- |
|
596 | #----------------------------------------------------------------------------- | |
597 | def target_update(target,deps,cmd): |
|
597 | def target_update(target,deps,cmd): | |
598 | """Update a target with a given command given a list of dependencies. |
|
598 | """Update a target with a given command given a list of dependencies. | |
599 |
|
599 | |||
600 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
600 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
601 |
|
601 | |||
602 | This is just a wrapper around target_outdated() which calls the given |
|
602 | This is just a wrapper around target_outdated() which calls the given | |
603 | command if target is outdated.""" |
|
603 | command if target is outdated.""" | |
604 |
|
604 | |||
605 | if target_outdated(target,deps): |
|
605 | if target_outdated(target,deps): | |
606 | xsys(cmd) |
|
606 | xsys(cmd) | |
607 |
|
607 | |||
608 | #---------------------------------------------------------------------------- |
|
608 | #---------------------------------------------------------------------------- | |
609 | def unquote_ends(istr): |
|
609 | def unquote_ends(istr): | |
610 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
610 | """Remove a single pair of quotes from the endpoints of a string.""" | |
611 |
|
611 | |||
612 | if not istr: |
|
612 | if not istr: | |
613 | return istr |
|
613 | return istr | |
614 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
614 | if (istr[0]=="'" and istr[-1]=="'") or \ | |
615 | (istr[0]=='"' and istr[-1]=='"'): |
|
615 | (istr[0]=='"' and istr[-1]=='"'): | |
616 | return istr[1:-1] |
|
616 | return istr[1:-1] | |
617 | else: |
|
617 | else: | |
618 | return istr |
|
618 | return istr | |
619 |
|
619 | |||
620 | #---------------------------------------------------------------------------- |
|
620 | #---------------------------------------------------------------------------- | |
621 | def process_cmdline(argv,names=[],defaults={},usage=''): |
|
621 | def process_cmdline(argv,names=[],defaults={},usage=''): | |
622 | """ Process command-line options and arguments. |
|
622 | """ Process command-line options and arguments. | |
623 |
|
623 | |||
624 | Arguments: |
|
624 | Arguments: | |
625 |
|
625 | |||
626 | - argv: list of arguments, typically sys.argv. |
|
626 | - argv: list of arguments, typically sys.argv. | |
627 |
|
627 | |||
628 | - names: list of option names. See DPyGetOpt docs for details on options |
|
628 | - names: list of option names. See DPyGetOpt docs for details on options | |
629 | syntax. |
|
629 | syntax. | |
630 |
|
630 | |||
631 | - defaults: dict of default values. |
|
631 | - defaults: dict of default values. | |
632 |
|
632 | |||
633 | - usage: optional usage notice to print if a wrong argument is passed. |
|
633 | - usage: optional usage notice to print if a wrong argument is passed. | |
634 |
|
634 | |||
635 | Return a dict of options and a list of free arguments.""" |
|
635 | Return a dict of options and a list of free arguments.""" | |
636 |
|
636 | |||
637 | getopt = DPyGetOpt.DPyGetOpt() |
|
637 | getopt = DPyGetOpt.DPyGetOpt() | |
638 | getopt.setIgnoreCase(0) |
|
638 | getopt.setIgnoreCase(0) | |
639 | getopt.parseConfiguration(names) |
|
639 | getopt.parseConfiguration(names) | |
640 |
|
640 | |||
641 | try: |
|
641 | try: | |
642 | getopt.processArguments(argv) |
|
642 | getopt.processArguments(argv) | |
643 | except DPyGetOpt.ArgumentError, exc: |
|
643 | except DPyGetOpt.ArgumentError, exc: | |
644 | print usage |
|
644 | print usage | |
645 | warn('"%s"' % exc,level=4) |
|
645 | warn('"%s"' % exc,level=4) | |
646 |
|
646 | |||
647 | defaults.update(getopt.optionValues) |
|
647 | defaults.update(getopt.optionValues) | |
648 | args = getopt.freeValues |
|
648 | args = getopt.freeValues | |
649 |
|
649 | |||
650 | return defaults,args |
|
650 | return defaults,args | |
651 |
|
651 | |||
652 | #---------------------------------------------------------------------------- |
|
652 | #---------------------------------------------------------------------------- | |
653 | def optstr2types(ostr): |
|
653 | def optstr2types(ostr): | |
654 | """Convert a string of option names to a dict of type mappings. |
|
654 | """Convert a string of option names to a dict of type mappings. | |
655 |
|
655 | |||
656 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} |
|
656 | optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'} | |
657 |
|
657 | |||
658 | This is used to get the types of all the options in a string formatted |
|
658 | This is used to get the types of all the options in a string formatted | |
659 | with the conventions of DPyGetOpt. The 'type' None is used for options |
|
659 | with the conventions of DPyGetOpt. The 'type' None is used for options | |
660 | which are strings (they need no further conversion). This function's main |
|
660 | which are strings (they need no further conversion). This function's main | |
661 | use is to get a typemap for use with read_dict(). |
|
661 | use is to get a typemap for use with read_dict(). | |
662 | """ |
|
662 | """ | |
663 |
|
663 | |||
664 | typeconv = {None:'',int:'',float:''} |
|
664 | typeconv = {None:'',int:'',float:''} | |
665 | typemap = {'s':None,'i':int,'f':float} |
|
665 | typemap = {'s':None,'i':int,'f':float} | |
666 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') |
|
666 | opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)') | |
667 |
|
667 | |||
668 | for w in ostr.split(): |
|
668 | for w in ostr.split(): | |
669 | oname,alias,otype = opt_re.match(w).groups() |
|
669 | oname,alias,otype = opt_re.match(w).groups() | |
670 | if otype == '' or alias == '!': # simple switches are integers too |
|
670 | if otype == '' or alias == '!': # simple switches are integers too | |
671 | otype = 'i' |
|
671 | otype = 'i' | |
672 | typeconv[typemap[otype]] += oname + ' ' |
|
672 | typeconv[typemap[otype]] += oname + ' ' | |
673 | return typeconv |
|
673 | return typeconv | |
674 |
|
674 | |||
675 | #---------------------------------------------------------------------------- |
|
675 | #---------------------------------------------------------------------------- | |
676 | def read_dict(filename,type_conv=None,**opt): |
|
676 | def read_dict(filename,type_conv=None,**opt): | |
677 | r"""Read a dictionary of key=value pairs from an input file, optionally |
|
677 | r"""Read a dictionary of key=value pairs from an input file, optionally | |
678 | performing conversions on the resulting values. |
|
678 | performing conversions on the resulting values. | |
679 |
|
679 | |||
680 | read_dict(filename,type_conv,**opt) -> dict |
|
680 | read_dict(filename,type_conv,**opt) -> dict | |
681 |
|
681 | |||
682 | Only one value per line is accepted, the format should be |
|
682 | Only one value per line is accepted, the format should be | |
683 | # optional comments are ignored |
|
683 | # optional comments are ignored | |
684 | key value\n |
|
684 | key value\n | |
685 |
|
685 | |||
686 | Args: |
|
686 | Args: | |
687 |
|
687 | |||
688 | - type_conv: A dictionary specifying which keys need to be converted to |
|
688 | - type_conv: A dictionary specifying which keys need to be converted to | |
689 | which types. By default all keys are read as strings. This dictionary |
|
689 | which types. By default all keys are read as strings. This dictionary | |
690 | should have as its keys valid conversion functions for strings |
|
690 | should have as its keys valid conversion functions for strings | |
691 | (int,long,float,complex, or your own). The value for each key |
|
691 | (int,long,float,complex, or your own). The value for each key | |
692 | (converter) should be a whitespace separated string containing the names |
|
692 | (converter) should be a whitespace separated string containing the names | |
693 | of all the entries in the file to be converted using that function. For |
|
693 | of all the entries in the file to be converted using that function. For | |
694 | keys to be left alone, use None as the conversion function (only needed |
|
694 | keys to be left alone, use None as the conversion function (only needed | |
695 | with purge=1, see below). |
|
695 | with purge=1, see below). | |
696 |
|
696 | |||
697 | - opt: dictionary with extra options as below (default in parens) |
|
697 | - opt: dictionary with extra options as below (default in parens) | |
698 |
|
698 | |||
699 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out |
|
699 | purge(0): if set to 1, all keys *not* listed in type_conv are purged out | |
700 | of the dictionary to be returned. If purge is going to be used, the |
|
700 | of the dictionary to be returned. If purge is going to be used, the | |
701 | set of keys to be left as strings also has to be explicitly specified |
|
701 | set of keys to be left as strings also has to be explicitly specified | |
702 | using the (non-existent) conversion function None. |
|
702 | using the (non-existent) conversion function None. | |
703 |
|
703 | |||
704 | fs(None): field separator. This is the key/value separator to be used |
|
704 | fs(None): field separator. This is the key/value separator to be used | |
705 | when parsing the file. The None default means any whitespace [behavior |
|
705 | when parsing the file. The None default means any whitespace [behavior | |
706 | of string.split()]. |
|
706 | of string.split()]. | |
707 |
|
707 | |||
708 | strip(0): if 1, strip string values of leading/trailinig whitespace. |
|
708 | strip(0): if 1, strip string values of leading/trailinig whitespace. | |
709 |
|
709 | |||
710 | warn(1): warning level if requested keys are not found in file. |
|
710 | warn(1): warning level if requested keys are not found in file. | |
711 | - 0: silently ignore. |
|
711 | - 0: silently ignore. | |
712 | - 1: inform but proceed. |
|
712 | - 1: inform but proceed. | |
713 | - 2: raise KeyError exception. |
|
713 | - 2: raise KeyError exception. | |
714 |
|
714 | |||
715 | no_empty(0): if 1, remove keys with whitespace strings as a value. |
|
715 | no_empty(0): if 1, remove keys with whitespace strings as a value. | |
716 |
|
716 | |||
717 | unique([]): list of keys (or space separated string) which can't be |
|
717 | unique([]): list of keys (or space separated string) which can't be | |
718 | repeated. If one such key is found in the file, each new instance |
|
718 | repeated. If one such key is found in the file, each new instance | |
719 | overwrites the previous one. For keys not listed here, the behavior is |
|
719 | overwrites the previous one. For keys not listed here, the behavior is | |
720 | to make a list of all appearances. |
|
720 | to make a list of all appearances. | |
721 |
|
721 | |||
722 | Example: |
|
722 | Example: | |
723 |
|
723 | |||
724 | If the input file test.ini contains (we put it in a string to keep the test |
|
724 | If the input file test.ini contains (we put it in a string to keep the test | |
725 | self-contained): |
|
725 | self-contained): | |
726 |
|
726 | |||
727 | >>> test_ini = '''\ |
|
727 | >>> test_ini = '''\ | |
728 | ... i 3 |
|
728 | ... i 3 | |
729 | ... x 4.5 |
|
729 | ... x 4.5 | |
730 | ... y 5.5 |
|
730 | ... y 5.5 | |
731 | ... s hi ho''' |
|
731 | ... s hi ho''' | |
732 |
|
732 | |||
733 | Then we can use it as follows: |
|
733 | Then we can use it as follows: | |
734 | >>> type_conv={int:'i',float:'x',None:'s'} |
|
734 | >>> type_conv={int:'i',float:'x',None:'s'} | |
735 |
|
735 | |||
736 | >>> d = read_dict(test_ini) |
|
736 | >>> d = read_dict(test_ini) | |
737 |
|
737 | |||
738 | >>> sorted(d.items()) |
|
738 | >>> sorted(d.items()) | |
739 | [('i', '3'), ('s', 'hi ho'), ('x', '4.5'), ('y', '5.5')] |
|
739 | [('i', '3'), ('s', 'hi ho'), ('x', '4.5'), ('y', '5.5')] | |
740 |
|
740 | |||
741 | >>> d = read_dict(test_ini,type_conv) |
|
741 | >>> d = read_dict(test_ini,type_conv) | |
742 |
|
742 | |||
743 | >>> sorted(d.items()) |
|
743 | >>> sorted(d.items()) | |
744 | [('i', 3), ('s', 'hi ho'), ('x', 4.5), ('y', '5.5')] |
|
744 | [('i', 3), ('s', 'hi ho'), ('x', 4.5), ('y', '5.5')] | |
745 |
|
745 | |||
746 | >>> d = read_dict(test_ini,type_conv,purge=True) |
|
746 | >>> d = read_dict(test_ini,type_conv,purge=True) | |
747 |
|
747 | |||
748 | >>> sorted(d.items()) |
|
748 | >>> sorted(d.items()) | |
749 | [('i', 3), ('s', 'hi ho'), ('x', 4.5)] |
|
749 | [('i', 3), ('s', 'hi ho'), ('x', 4.5)] | |
750 | """ |
|
750 | """ | |
751 |
|
751 | |||
752 | # starting config |
|
752 | # starting config | |
753 | opt.setdefault('purge',0) |
|
753 | opt.setdefault('purge',0) | |
754 | opt.setdefault('fs',None) # field sep defaults to any whitespace |
|
754 | opt.setdefault('fs',None) # field sep defaults to any whitespace | |
755 | opt.setdefault('strip',0) |
|
755 | opt.setdefault('strip',0) | |
756 | opt.setdefault('warn',1) |
|
756 | opt.setdefault('warn',1) | |
757 | opt.setdefault('no_empty',0) |
|
757 | opt.setdefault('no_empty',0) | |
758 | opt.setdefault('unique','') |
|
758 | opt.setdefault('unique','') | |
759 | if type(opt['unique']) in StringTypes: |
|
759 | if type(opt['unique']) in StringTypes: | |
760 | unique_keys = qw(opt['unique']) |
|
760 | unique_keys = qw(opt['unique']) | |
761 | elif type(opt['unique']) in (types.TupleType,types.ListType): |
|
761 | elif type(opt['unique']) in (types.TupleType,types.ListType): | |
762 | unique_keys = opt['unique'] |
|
762 | unique_keys = opt['unique'] | |
763 | else: |
|
763 | else: | |
764 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' |
|
764 | raise ValueError, 'Unique keys must be given as a string, List or Tuple' | |
765 |
|
765 | |||
766 | dict = {} |
|
766 | dict = {} | |
767 |
|
767 | |||
768 | # first read in table of values as strings |
|
768 | # first read in table of values as strings | |
769 | if '\n' in filename: |
|
769 | if '\n' in filename: | |
770 | lines = filename.splitlines() |
|
770 | lines = filename.splitlines() | |
771 | file = None |
|
771 | file = None | |
772 | else: |
|
772 | else: | |
773 | file = open(filename,'r') |
|
773 | file = open(filename,'r') | |
774 | lines = file.readlines() |
|
774 | lines = file.readlines() | |
775 | for line in lines: |
|
775 | for line in lines: | |
776 | line = line.strip() |
|
776 | line = line.strip() | |
777 | if len(line) and line[0]=='#': continue |
|
777 | if len(line) and line[0]=='#': continue | |
778 | if len(line)>0: |
|
778 | if len(line)>0: | |
779 | lsplit = line.split(opt['fs'],1) |
|
779 | lsplit = line.split(opt['fs'],1) | |
780 | try: |
|
780 | try: | |
781 | key,val = lsplit |
|
781 | key,val = lsplit | |
782 | except ValueError: |
|
782 | except ValueError: | |
783 | key,val = lsplit[0],'' |
|
783 | key,val = lsplit[0],'' | |
784 | key = key.strip() |
|
784 | key = key.strip() | |
785 | if opt['strip']: val = val.strip() |
|
785 | if opt['strip']: val = val.strip() | |
786 | if val == "''" or val == '""': val = '' |
|
786 | if val == "''" or val == '""': val = '' | |
787 | if opt['no_empty'] and (val=='' or val.isspace()): |
|
787 | if opt['no_empty'] and (val=='' or val.isspace()): | |
788 | continue |
|
788 | continue | |
789 | # if a key is found more than once in the file, build a list |
|
789 | # if a key is found more than once in the file, build a list | |
790 | # unless it's in the 'unique' list. In that case, last found in file |
|
790 | # unless it's in the 'unique' list. In that case, last found in file | |
791 | # takes precedence. User beware. |
|
791 | # takes precedence. User beware. | |
792 | try: |
|
792 | try: | |
793 | if dict[key] and key in unique_keys: |
|
793 | if dict[key] and key in unique_keys: | |
794 | dict[key] = val |
|
794 | dict[key] = val | |
795 | elif type(dict[key]) is types.ListType: |
|
795 | elif type(dict[key]) is types.ListType: | |
796 | dict[key].append(val) |
|
796 | dict[key].append(val) | |
797 | else: |
|
797 | else: | |
798 | dict[key] = [dict[key],val] |
|
798 | dict[key] = [dict[key],val] | |
799 | except KeyError: |
|
799 | except KeyError: | |
800 | dict[key] = val |
|
800 | dict[key] = val | |
801 | # purge if requested |
|
801 | # purge if requested | |
802 | if opt['purge']: |
|
802 | if opt['purge']: | |
803 | accepted_keys = qwflat(type_conv.values()) |
|
803 | accepted_keys = qwflat(type_conv.values()) | |
804 | for key in dict.keys(): |
|
804 | for key in dict.keys(): | |
805 | if key in accepted_keys: continue |
|
805 | if key in accepted_keys: continue | |
806 | del(dict[key]) |
|
806 | del(dict[key]) | |
807 | # now convert if requested |
|
807 | # now convert if requested | |
808 | if type_conv==None: return dict |
|
808 | if type_conv==None: return dict | |
809 | conversions = type_conv.keys() |
|
809 | conversions = type_conv.keys() | |
810 | try: conversions.remove(None) |
|
810 | try: conversions.remove(None) | |
811 | except: pass |
|
811 | except: pass | |
812 | for convert in conversions: |
|
812 | for convert in conversions: | |
813 | for val in qw(type_conv[convert]): |
|
813 | for val in qw(type_conv[convert]): | |
814 | try: |
|
814 | try: | |
815 | dict[val] = convert(dict[val]) |
|
815 | dict[val] = convert(dict[val]) | |
816 | except KeyError,e: |
|
816 | except KeyError,e: | |
817 | if opt['warn'] == 0: |
|
817 | if opt['warn'] == 0: | |
818 | pass |
|
818 | pass | |
819 | elif opt['warn'] == 1: |
|
819 | elif opt['warn'] == 1: | |
820 | print >>sys.stderr, 'Warning: key',val,\ |
|
820 | print >>sys.stderr, 'Warning: key',val,\ | |
821 | 'not found in file',filename |
|
821 | 'not found in file',filename | |
822 | elif opt['warn'] == 2: |
|
822 | elif opt['warn'] == 2: | |
823 | raise KeyError,e |
|
823 | raise KeyError,e | |
824 | else: |
|
824 | else: | |
825 | raise ValueError,'Warning level must be 0,1 or 2' |
|
825 | raise ValueError,'Warning level must be 0,1 or 2' | |
826 |
|
826 | |||
827 | return dict |
|
827 | return dict | |
828 |
|
828 | |||
829 | #---------------------------------------------------------------------------- |
|
829 | #---------------------------------------------------------------------------- | |
830 | def flag_calls(func): |
|
830 | def flag_calls(func): | |
831 | """Wrap a function to detect and flag when it gets called. |
|
831 | """Wrap a function to detect and flag when it gets called. | |
832 |
|
832 | |||
833 | This is a decorator which takes a function and wraps it in a function with |
|
833 | This is a decorator which takes a function and wraps it in a function with | |
834 | a 'called' attribute. wrapper.called is initialized to False. |
|
834 | a 'called' attribute. wrapper.called is initialized to False. | |
835 |
|
835 | |||
836 | The wrapper.called attribute is set to False right before each call to the |
|
836 | The wrapper.called attribute is set to False right before each call to the | |
837 | wrapped function, so if the call fails it remains False. After the call |
|
837 | wrapped function, so if the call fails it remains False. After the call | |
838 | completes, wrapper.called is set to True and the output is returned. |
|
838 | completes, wrapper.called is set to True and the output is returned. | |
839 |
|
839 | |||
840 | Testing for truth in wrapper.called allows you to determine if a call to |
|
840 | Testing for truth in wrapper.called allows you to determine if a call to | |
841 | func() was attempted and succeeded.""" |
|
841 | func() was attempted and succeeded.""" | |
842 |
|
842 | |||
843 | def wrapper(*args,**kw): |
|
843 | def wrapper(*args,**kw): | |
844 | wrapper.called = False |
|
844 | wrapper.called = False | |
845 | out = func(*args,**kw) |
|
845 | out = func(*args,**kw) | |
846 | wrapper.called = True |
|
846 | wrapper.called = True | |
847 | return out |
|
847 | return out | |
848 |
|
848 | |||
849 | wrapper.called = False |
|
849 | wrapper.called = False | |
850 | wrapper.__doc__ = func.__doc__ |
|
850 | wrapper.__doc__ = func.__doc__ | |
851 | return wrapper |
|
851 | return wrapper | |
852 |
|
852 | |||
853 | #---------------------------------------------------------------------------- |
|
853 | #---------------------------------------------------------------------------- | |
854 | def dhook_wrap(func,*a,**k): |
|
854 | def dhook_wrap(func,*a,**k): | |
855 | """Wrap a function call in a sys.displayhook controller. |
|
855 | """Wrap a function call in a sys.displayhook controller. | |
856 |
|
856 | |||
857 | Returns a wrapper around func which calls func, with all its arguments and |
|
857 | Returns a wrapper around func which calls func, with all its arguments and | |
858 | keywords unmodified, using the default sys.displayhook. Since IPython |
|
858 | keywords unmodified, using the default sys.displayhook. Since IPython | |
859 | modifies sys.displayhook, it breaks the behavior of certain systems that |
|
859 | modifies sys.displayhook, it breaks the behavior of certain systems that | |
860 | rely on the default behavior, notably doctest. |
|
860 | rely on the default behavior, notably doctest. | |
861 | """ |
|
861 | """ | |
862 |
|
862 | |||
863 | def f(*a,**k): |
|
863 | def f(*a,**k): | |
864 |
|
864 | |||
865 | dhook_s = sys.displayhook |
|
865 | dhook_s = sys.displayhook | |
866 | sys.displayhook = sys.__displayhook__ |
|
866 | sys.displayhook = sys.__displayhook__ | |
867 | try: |
|
867 | try: | |
868 | out = func(*a,**k) |
|
868 | out = func(*a,**k) | |
869 | finally: |
|
869 | finally: | |
870 | sys.displayhook = dhook_s |
|
870 | sys.displayhook = dhook_s | |
871 |
|
871 | |||
872 | return out |
|
872 | return out | |
873 |
|
873 | |||
874 | f.__doc__ = func.__doc__ |
|
874 | f.__doc__ = func.__doc__ | |
875 | return f |
|
875 | return f | |
876 |
|
876 | |||
877 | #---------------------------------------------------------------------------- |
|
877 | #---------------------------------------------------------------------------- | |
878 | def doctest_reload(): |
|
878 | def doctest_reload(): | |
879 | """Properly reload doctest to reuse it interactively. |
|
879 | """Properly reload doctest to reuse it interactively. | |
880 |
|
880 | |||
881 | This routine: |
|
881 | This routine: | |
882 |
|
882 | |||
883 | - reloads doctest |
|
883 | - reloads doctest | |
884 |
|
884 | |||
885 | - resets its global 'master' attribute to None, so that multiple uses of |
|
885 | - resets its global 'master' attribute to None, so that multiple uses of | |
886 | the module interactively don't produce cumulative reports. |
|
886 | the module interactively don't produce cumulative reports. | |
887 |
|
887 | |||
888 | - Monkeypatches its core test runner method to protect it from IPython's |
|
888 | - Monkeypatches its core test runner method to protect it from IPython's | |
889 | modified displayhook. Doctest expects the default displayhook behavior |
|
889 | modified displayhook. Doctest expects the default displayhook behavior | |
890 | deep down, so our modification breaks it completely. For this reason, a |
|
890 | deep down, so our modification breaks it completely. For this reason, a | |
891 | hard monkeypatch seems like a reasonable solution rather than asking |
|
891 | hard monkeypatch seems like a reasonable solution rather than asking | |
892 | users to manually use a different doctest runner when under IPython.""" |
|
892 | users to manually use a different doctest runner when under IPython.""" | |
893 |
|
893 | |||
894 | import doctest |
|
894 | import doctest | |
895 | reload(doctest) |
|
895 | reload(doctest) | |
896 | doctest.master=None |
|
896 | doctest.master=None | |
897 |
|
897 | |||
898 | try: |
|
898 | try: | |
899 | doctest.DocTestRunner |
|
899 | doctest.DocTestRunner | |
900 | except AttributeError: |
|
900 | except AttributeError: | |
901 | # This is only for python 2.3 compatibility, remove once we move to |
|
901 | # This is only for python 2.3 compatibility, remove once we move to | |
902 | # 2.4 only. |
|
902 | # 2.4 only. | |
903 | pass |
|
903 | pass | |
904 | else: |
|
904 | else: | |
905 | doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run) |
|
905 | doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run) | |
906 |
|
906 | |||
907 | #---------------------------------------------------------------------------- |
|
907 | #---------------------------------------------------------------------------- | |
908 | class HomeDirError(Error): |
|
908 | class HomeDirError(Error): | |
909 | pass |
|
909 | pass | |
910 |
|
910 | |||
911 | def get_home_dir(): |
|
911 | def get_home_dir(): | |
912 | """Return the closest possible equivalent to a 'home' directory. |
|
912 | """Return the closest possible equivalent to a 'home' directory. | |
913 |
|
913 | |||
914 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. |
|
914 | We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH. | |
915 |
|
915 | |||
916 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
916 | Currently only Posix and NT are implemented, a HomeDirError exception is | |
917 | raised for all other OSes. """ |
|
917 | raised for all other OSes. """ | |
918 |
|
918 | |||
919 | isdir = os.path.isdir |
|
919 | isdir = os.path.isdir | |
920 | env = os.environ |
|
920 | env = os.environ | |
921 |
|
921 | |||
922 | # first, check py2exe distribution root directory for _ipython. |
|
922 | # first, check py2exe distribution root directory for _ipython. | |
923 | # This overrides all. Normally does not exist. |
|
923 | # This overrides all. Normally does not exist. | |
924 |
|
924 | |||
925 | if '\\library.zip\\' in IPython.__file__.lower(): |
|
925 | if hasattr(sys, "frozen"): #Is frozen by py2exe | |
926 | root, rest = IPython.__file__.lower().split('library.zip') |
|
926 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file | |
927 | if isdir(root + '_ipython'): |
|
927 | root, rest = IPython.__file__.lower().split('library.zip') | |
928 | os.environ["IPYKITROOT"] = root.rstrip('\\') |
|
928 | else: | |
929 | return root |
|
929 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") | |
930 |
|
930 | root=os.path.abspath(root).rstrip('\\') | ||
|
931 | if isdir(os.path.join(root, '_ipython')): | |||
|
932 | os.environ["IPYKITROOT"] = root | |||
|
933 | return root | |||
931 | try: |
|
934 | try: | |
932 | homedir = env['HOME'] |
|
935 | homedir = env['HOME'] | |
933 | if not isdir(homedir): |
|
936 | if not isdir(homedir): | |
934 | # in case a user stuck some string which does NOT resolve to a |
|
937 | # in case a user stuck some string which does NOT resolve to a | |
935 | # valid path, it's as good as if we hadn't foud it |
|
938 | # valid path, it's as good as if we hadn't foud it | |
936 | raise KeyError |
|
939 | raise KeyError | |
937 | return homedir |
|
940 | return homedir | |
938 | except KeyError: |
|
941 | except KeyError: | |
939 | if os.name == 'posix': |
|
942 | if os.name == 'posix': | |
940 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' |
|
943 | raise HomeDirError,'undefined $HOME, IPython can not proceed.' | |
941 | elif os.name == 'nt': |
|
944 | elif os.name == 'nt': | |
942 | # For some strange reason, win9x returns 'nt' for os.name. |
|
945 | # For some strange reason, win9x returns 'nt' for os.name. | |
943 | try: |
|
946 | try: | |
944 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
947 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) | |
945 | if not isdir(homedir): |
|
948 | if not isdir(homedir): | |
946 | homedir = os.path.join(env['USERPROFILE']) |
|
949 | homedir = os.path.join(env['USERPROFILE']) | |
947 | if not isdir(homedir): |
|
950 | if not isdir(homedir): | |
948 | raise HomeDirError |
|
951 | raise HomeDirError | |
949 | return homedir |
|
952 | return homedir | |
950 | except: |
|
953 | except KeyError: | |
951 | try: |
|
954 | try: | |
952 | # Use the registry to get the 'My Documents' folder. |
|
955 | # Use the registry to get the 'My Documents' folder. | |
953 | import _winreg as wreg |
|
956 | import _winreg as wreg | |
954 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, |
|
957 | key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, | |
955 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") |
|
958 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") | |
956 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
959 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
957 | key.Close() |
|
960 | key.Close() | |
958 | if not isdir(homedir): |
|
961 | if not isdir(homedir): | |
959 | e = ('Invalid "Personal" folder registry key ' |
|
962 | e = ('Invalid "Personal" folder registry key ' | |
960 | 'typically "My Documents".\n' |
|
963 | 'typically "My Documents".\n' | |
961 | 'Value: %s\n' |
|
964 | 'Value: %s\n' | |
962 | 'This is not a valid directory on your system.' % |
|
965 | 'This is not a valid directory on your system.' % | |
963 | homedir) |
|
966 | homedir) | |
964 | raise HomeDirError(e) |
|
967 | raise HomeDirError(e) | |
965 | return homedir |
|
968 | return homedir | |
966 | except HomeDirError: |
|
969 | except HomeDirError: | |
967 | raise |
|
970 | raise | |
968 | except: |
|
971 | except: | |
969 | return 'C:\\' |
|
972 | return 'C:\\' | |
970 | elif os.name == 'dos': |
|
973 | elif os.name == 'dos': | |
971 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
974 | # Desperate, may do absurd things in classic MacOS. May work under DOS. | |
972 | return 'C:\\' |
|
975 | return 'C:\\' | |
973 | else: |
|
976 | else: | |
974 | raise HomeDirError,'support for your operating system not implemented.' |
|
977 | raise HomeDirError,'support for your operating system not implemented.' | |
975 |
|
978 | |||
976 |
|
979 | |||
977 | def get_ipython_dir(): |
|
980 | def get_ipython_dir(): | |
978 | """Get the IPython directory for this platform and user. |
|
981 | """Get the IPython directory for this platform and user. | |
979 |
|
982 | |||
980 | This uses the logic in `get_home_dir` to find the home directory |
|
983 | This uses the logic in `get_home_dir` to find the home directory | |
981 | and the adds either .ipython or _ipython to the end of the path. |
|
984 | and the adds either .ipython or _ipython to the end of the path. | |
982 | """ |
|
985 | """ | |
983 | if os.name == 'posix': |
|
986 | if os.name == 'posix': | |
984 | ipdir_def = '.ipython' |
|
987 | ipdir_def = '.ipython' | |
985 | else: |
|
988 | else: | |
986 | ipdir_def = '_ipython' |
|
989 | ipdir_def = '_ipython' | |
987 | home_dir = get_home_dir() |
|
990 | home_dir = get_home_dir() | |
988 | ipdir = os.path.abspath(os.environ.get('IPYTHONDIR', |
|
991 | ipdir = os.path.abspath(os.environ.get('IPYTHONDIR', | |
989 | os.path.join(home_dir,ipdir_def))) |
|
992 | os.path.join(home_dir, ipdir_def))) | |
990 | return ipdir |
|
993 | return ipdir.decode(sys.getfilesystemencoding()) | |
991 |
|
994 | |||
992 | def get_security_dir(): |
|
995 | def get_security_dir(): | |
993 | """Get the IPython security directory. |
|
996 | """Get the IPython security directory. | |
994 |
|
997 | |||
995 | This directory is the default location for all security related files, |
|
998 | This directory is the default location for all security related files, | |
996 | including SSL/TLS certificates and FURL files. |
|
999 | including SSL/TLS certificates and FURL files. | |
997 |
|
1000 | |||
998 | If the directory does not exist, it is created with 0700 permissions. |
|
1001 | If the directory does not exist, it is created with 0700 permissions. | |
999 | If it exists, permissions are set to 0700. |
|
1002 | If it exists, permissions are set to 0700. | |
1000 | """ |
|
1003 | """ | |
1001 | security_dir = os.path.join(get_ipython_dir(), 'security') |
|
1004 | security_dir = os.path.join(get_ipython_dir(), 'security') | |
1002 | if not os.path.isdir(security_dir): |
|
1005 | if not os.path.isdir(security_dir): | |
1003 | os.mkdir(security_dir, 0700) |
|
1006 | os.mkdir(security_dir, 0700) | |
1004 | else: |
|
1007 | else: | |
1005 | os.chmod(security_dir, 0700) |
|
1008 | os.chmod(security_dir, 0700) | |
1006 | return security_dir |
|
1009 | return security_dir | |
1007 |
|
1010 | |||
1008 | #**************************************************************************** |
|
1011 | #**************************************************************************** | |
1009 | # strings and text |
|
1012 | # strings and text | |
1010 |
|
1013 | |||
1011 | class LSString(str): |
|
1014 | class LSString(str): | |
1012 | """String derivative with a special access attributes. |
|
1015 | """String derivative with a special access attributes. | |
1013 |
|
1016 | |||
1014 | These are normal strings, but with the special attributes: |
|
1017 | These are normal strings, but with the special attributes: | |
1015 |
|
1018 | |||
1016 | .l (or .list) : value as list (split on newlines). |
|
1019 | .l (or .list) : value as list (split on newlines). | |
1017 | .n (or .nlstr): original value (the string itself). |
|
1020 | .n (or .nlstr): original value (the string itself). | |
1018 | .s (or .spstr): value as whitespace-separated string. |
|
1021 | .s (or .spstr): value as whitespace-separated string. | |
1019 | .p (or .paths): list of path objects |
|
1022 | .p (or .paths): list of path objects | |
1020 |
|
1023 | |||
1021 | Any values which require transformations are computed only once and |
|
1024 | Any values which require transformations are computed only once and | |
1022 | cached. |
|
1025 | cached. | |
1023 |
|
1026 | |||
1024 | Such strings are very useful to efficiently interact with the shell, which |
|
1027 | Such strings are very useful to efficiently interact with the shell, which | |
1025 | typically only understands whitespace-separated options for commands.""" |
|
1028 | typically only understands whitespace-separated options for commands.""" | |
1026 |
|
1029 | |||
1027 | def get_list(self): |
|
1030 | def get_list(self): | |
1028 | try: |
|
1031 | try: | |
1029 | return self.__list |
|
1032 | return self.__list | |
1030 | except AttributeError: |
|
1033 | except AttributeError: | |
1031 | self.__list = self.split('\n') |
|
1034 | self.__list = self.split('\n') | |
1032 | return self.__list |
|
1035 | return self.__list | |
1033 |
|
1036 | |||
1034 | l = list = property(get_list) |
|
1037 | l = list = property(get_list) | |
1035 |
|
1038 | |||
1036 | def get_spstr(self): |
|
1039 | def get_spstr(self): | |
1037 | try: |
|
1040 | try: | |
1038 | return self.__spstr |
|
1041 | return self.__spstr | |
1039 | except AttributeError: |
|
1042 | except AttributeError: | |
1040 | self.__spstr = self.replace('\n',' ') |
|
1043 | self.__spstr = self.replace('\n',' ') | |
1041 | return self.__spstr |
|
1044 | return self.__spstr | |
1042 |
|
1045 | |||
1043 | s = spstr = property(get_spstr) |
|
1046 | s = spstr = property(get_spstr) | |
1044 |
|
1047 | |||
1045 | def get_nlstr(self): |
|
1048 | def get_nlstr(self): | |
1046 | return self |
|
1049 | return self | |
1047 |
|
1050 | |||
1048 | n = nlstr = property(get_nlstr) |
|
1051 | n = nlstr = property(get_nlstr) | |
1049 |
|
1052 | |||
1050 | def get_paths(self): |
|
1053 | def get_paths(self): | |
1051 | try: |
|
1054 | try: | |
1052 | return self.__paths |
|
1055 | return self.__paths | |
1053 | except AttributeError: |
|
1056 | except AttributeError: | |
1054 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
1057 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] | |
1055 | return self.__paths |
|
1058 | return self.__paths | |
1056 |
|
1059 | |||
1057 | p = paths = property(get_paths) |
|
1060 | p = paths = property(get_paths) | |
1058 |
|
1061 | |||
1059 | def print_lsstring(arg): |
|
1062 | def print_lsstring(arg): | |
1060 | """ Prettier (non-repr-like) and more informative printer for LSString """ |
|
1063 | """ Prettier (non-repr-like) and more informative printer for LSString """ | |
1061 | print "LSString (.p, .n, .l, .s available). Value:" |
|
1064 | print "LSString (.p, .n, .l, .s available). Value:" | |
1062 | print arg |
|
1065 | print arg | |
1063 |
|
1066 | |||
1064 | print_lsstring = result_display.when_type(LSString)(print_lsstring) |
|
1067 | print_lsstring = result_display.when_type(LSString)(print_lsstring) | |
1065 |
|
1068 | |||
1066 | #---------------------------------------------------------------------------- |
|
1069 | #---------------------------------------------------------------------------- | |
1067 | class SList(list): |
|
1070 | class SList(list): | |
1068 | """List derivative with a special access attributes. |
|
1071 | """List derivative with a special access attributes. | |
1069 |
|
1072 | |||
1070 | These are normal lists, but with the special attributes: |
|
1073 | These are normal lists, but with the special attributes: | |
1071 |
|
1074 | |||
1072 | .l (or .list) : value as list (the list itself). |
|
1075 | .l (or .list) : value as list (the list itself). | |
1073 | .n (or .nlstr): value as a string, joined on newlines. |
|
1076 | .n (or .nlstr): value as a string, joined on newlines. | |
1074 | .s (or .spstr): value as a string, joined on spaces. |
|
1077 | .s (or .spstr): value as a string, joined on spaces. | |
1075 | .p (or .paths): list of path objects |
|
1078 | .p (or .paths): list of path objects | |
1076 |
|
1079 | |||
1077 | Any values which require transformations are computed only once and |
|
1080 | Any values which require transformations are computed only once and | |
1078 | cached.""" |
|
1081 | cached.""" | |
1079 |
|
1082 | |||
1080 | def get_list(self): |
|
1083 | def get_list(self): | |
1081 | return self |
|
1084 | return self | |
1082 |
|
1085 | |||
1083 | l = list = property(get_list) |
|
1086 | l = list = property(get_list) | |
1084 |
|
1087 | |||
1085 | def get_spstr(self): |
|
1088 | def get_spstr(self): | |
1086 | try: |
|
1089 | try: | |
1087 | return self.__spstr |
|
1090 | return self.__spstr | |
1088 | except AttributeError: |
|
1091 | except AttributeError: | |
1089 | self.__spstr = ' '.join(self) |
|
1092 | self.__spstr = ' '.join(self) | |
1090 | return self.__spstr |
|
1093 | return self.__spstr | |
1091 |
|
1094 | |||
1092 | s = spstr = property(get_spstr) |
|
1095 | s = spstr = property(get_spstr) | |
1093 |
|
1096 | |||
1094 | def get_nlstr(self): |
|
1097 | def get_nlstr(self): | |
1095 | try: |
|
1098 | try: | |
1096 | return self.__nlstr |
|
1099 | return self.__nlstr | |
1097 | except AttributeError: |
|
1100 | except AttributeError: | |
1098 | self.__nlstr = '\n'.join(self) |
|
1101 | self.__nlstr = '\n'.join(self) | |
1099 | return self.__nlstr |
|
1102 | return self.__nlstr | |
1100 |
|
1103 | |||
1101 | n = nlstr = property(get_nlstr) |
|
1104 | n = nlstr = property(get_nlstr) | |
1102 |
|
1105 | |||
1103 | def get_paths(self): |
|
1106 | def get_paths(self): | |
1104 | try: |
|
1107 | try: | |
1105 | return self.__paths |
|
1108 | return self.__paths | |
1106 | except AttributeError: |
|
1109 | except AttributeError: | |
1107 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
1110 | self.__paths = [path(p) for p in self if os.path.exists(p)] | |
1108 | return self.__paths |
|
1111 | return self.__paths | |
1109 |
|
1112 | |||
1110 | p = paths = property(get_paths) |
|
1113 | p = paths = property(get_paths) | |
1111 |
|
1114 | |||
1112 | def grep(self, pattern, prune = False, field = None): |
|
1115 | def grep(self, pattern, prune = False, field = None): | |
1113 | """ Return all strings matching 'pattern' (a regex or callable) |
|
1116 | """ Return all strings matching 'pattern' (a regex or callable) | |
1114 |
|
1117 | |||
1115 | This is case-insensitive. If prune is true, return all items |
|
1118 | This is case-insensitive. If prune is true, return all items | |
1116 | NOT matching the pattern. |
|
1119 | NOT matching the pattern. | |
1117 |
|
1120 | |||
1118 | If field is specified, the match must occur in the specified |
|
1121 | If field is specified, the match must occur in the specified | |
1119 | whitespace-separated field. |
|
1122 | whitespace-separated field. | |
1120 |
|
1123 | |||
1121 | Examples:: |
|
1124 | Examples:: | |
1122 |
|
1125 | |||
1123 | a.grep( lambda x: x.startswith('C') ) |
|
1126 | a.grep( lambda x: x.startswith('C') ) | |
1124 | a.grep('Cha.*log', prune=1) |
|
1127 | a.grep('Cha.*log', prune=1) | |
1125 | a.grep('chm', field=-1) |
|
1128 | a.grep('chm', field=-1) | |
1126 | """ |
|
1129 | """ | |
1127 |
|
1130 | |||
1128 | def match_target(s): |
|
1131 | def match_target(s): | |
1129 | if field is None: |
|
1132 | if field is None: | |
1130 | return s |
|
1133 | return s | |
1131 | parts = s.split() |
|
1134 | parts = s.split() | |
1132 | try: |
|
1135 | try: | |
1133 | tgt = parts[field] |
|
1136 | tgt = parts[field] | |
1134 | return tgt |
|
1137 | return tgt | |
1135 | except IndexError: |
|
1138 | except IndexError: | |
1136 | return "" |
|
1139 | return "" | |
1137 |
|
1140 | |||
1138 | if isinstance(pattern, basestring): |
|
1141 | if isinstance(pattern, basestring): | |
1139 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) |
|
1142 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) | |
1140 | else: |
|
1143 | else: | |
1141 | pred = pattern |
|
1144 | pred = pattern | |
1142 | if not prune: |
|
1145 | if not prune: | |
1143 | return SList([el for el in self if pred(match_target(el))]) |
|
1146 | return SList([el for el in self if pred(match_target(el))]) | |
1144 | else: |
|
1147 | else: | |
1145 | return SList([el for el in self if not pred(match_target(el))]) |
|
1148 | return SList([el for el in self if not pred(match_target(el))]) | |
1146 | def fields(self, *fields): |
|
1149 | def fields(self, *fields): | |
1147 | """ Collect whitespace-separated fields from string list |
|
1150 | """ Collect whitespace-separated fields from string list | |
1148 |
|
1151 | |||
1149 | Allows quick awk-like usage of string lists. |
|
1152 | Allows quick awk-like usage of string lists. | |
1150 |
|
1153 | |||
1151 | Example data (in var a, created by 'a = !ls -l'):: |
|
1154 | Example data (in var a, created by 'a = !ls -l'):: | |
1152 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog |
|
1155 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog | |
1153 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython |
|
1156 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython | |
1154 |
|
1157 | |||
1155 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] |
|
1158 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] | |
1156 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] |
|
1159 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] | |
1157 | (note the joining by space). |
|
1160 | (note the joining by space). | |
1158 | a.fields(-1) is ['ChangeLog', 'IPython'] |
|
1161 | a.fields(-1) is ['ChangeLog', 'IPython'] | |
1159 |
|
1162 | |||
1160 | IndexErrors are ignored. |
|
1163 | IndexErrors are ignored. | |
1161 |
|
1164 | |||
1162 | Without args, fields() just split()'s the strings. |
|
1165 | Without args, fields() just split()'s the strings. | |
1163 | """ |
|
1166 | """ | |
1164 | if len(fields) == 0: |
|
1167 | if len(fields) == 0: | |
1165 | return [el.split() for el in self] |
|
1168 | return [el.split() for el in self] | |
1166 |
|
1169 | |||
1167 | res = SList() |
|
1170 | res = SList() | |
1168 | for el in [f.split() for f in self]: |
|
1171 | for el in [f.split() for f in self]: | |
1169 | lineparts = [] |
|
1172 | lineparts = [] | |
1170 |
|
1173 | |||
1171 | for fd in fields: |
|
1174 | for fd in fields: | |
1172 | try: |
|
1175 | try: | |
1173 | lineparts.append(el[fd]) |
|
1176 | lineparts.append(el[fd]) | |
1174 | except IndexError: |
|
1177 | except IndexError: | |
1175 | pass |
|
1178 | pass | |
1176 | if lineparts: |
|
1179 | if lineparts: | |
1177 | res.append(" ".join(lineparts)) |
|
1180 | res.append(" ".join(lineparts)) | |
1178 |
|
1181 | |||
1179 | return res |
|
1182 | return res | |
1180 | def sort(self,field= None, nums = False): |
|
1183 | def sort(self,field= None, nums = False): | |
1181 | """ sort by specified fields (see fields()) |
|
1184 | """ sort by specified fields (see fields()) | |
1182 |
|
1185 | |||
1183 | Example:: |
|
1186 | Example:: | |
1184 | a.sort(1, nums = True) |
|
1187 | a.sort(1, nums = True) | |
1185 |
|
1188 | |||
1186 | Sorts a by second field, in numerical order (so that 21 > 3) |
|
1189 | Sorts a by second field, in numerical order (so that 21 > 3) | |
1187 |
|
1190 | |||
1188 | """ |
|
1191 | """ | |
1189 |
|
1192 | |||
1190 | #decorate, sort, undecorate |
|
1193 | #decorate, sort, undecorate | |
1191 | if field is not None: |
|
1194 | if field is not None: | |
1192 | dsu = [[SList([line]).fields(field), line] for line in self] |
|
1195 | dsu = [[SList([line]).fields(field), line] for line in self] | |
1193 | else: |
|
1196 | else: | |
1194 | dsu = [[line, line] for line in self] |
|
1197 | dsu = [[line, line] for line in self] | |
1195 | if nums: |
|
1198 | if nums: | |
1196 | for i in range(len(dsu)): |
|
1199 | for i in range(len(dsu)): | |
1197 | numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) |
|
1200 | numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) | |
1198 | try: |
|
1201 | try: | |
1199 | n = int(numstr) |
|
1202 | n = int(numstr) | |
1200 | except ValueError: |
|
1203 | except ValueError: | |
1201 | n = 0; |
|
1204 | n = 0; | |
1202 | dsu[i][0] = n |
|
1205 | dsu[i][0] = n | |
1203 |
|
1206 | |||
1204 |
|
1207 | |||
1205 | dsu.sort() |
|
1208 | dsu.sort() | |
1206 | return SList([t[1] for t in dsu]) |
|
1209 | return SList([t[1] for t in dsu]) | |
1207 |
|
1210 | |||
1208 | def print_slist(arg): |
|
1211 | def print_slist(arg): | |
1209 | """ Prettier (non-repr-like) and more informative printer for SList """ |
|
1212 | """ Prettier (non-repr-like) and more informative printer for SList """ | |
1210 | print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" |
|
1213 | print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" | |
1211 | if hasattr(arg, 'hideonce') and arg.hideonce: |
|
1214 | if hasattr(arg, 'hideonce') and arg.hideonce: | |
1212 | arg.hideonce = False |
|
1215 | arg.hideonce = False | |
1213 | return |
|
1216 | return | |
1214 |
|
1217 | |||
1215 | nlprint(arg) |
|
1218 | nlprint(arg) | |
1216 |
|
1219 | |||
1217 | print_slist = result_display.when_type(SList)(print_slist) |
|
1220 | print_slist = result_display.when_type(SList)(print_slist) | |
1218 |
|
1221 | |||
1219 |
|
1222 | |||
1220 |
|
1223 | |||
1221 | #---------------------------------------------------------------------------- |
|
1224 | #---------------------------------------------------------------------------- | |
1222 | def esc_quotes(strng): |
|
1225 | def esc_quotes(strng): | |
1223 | """Return the input string with single and double quotes escaped out""" |
|
1226 | """Return the input string with single and double quotes escaped out""" | |
1224 |
|
1227 | |||
1225 | return strng.replace('"','\\"').replace("'","\\'") |
|
1228 | return strng.replace('"','\\"').replace("'","\\'") | |
1226 |
|
1229 | |||
1227 | #---------------------------------------------------------------------------- |
|
1230 | #---------------------------------------------------------------------------- | |
1228 | def make_quoted_expr(s): |
|
1231 | def make_quoted_expr(s): | |
1229 | """Return string s in appropriate quotes, using raw string if possible. |
|
1232 | """Return string s in appropriate quotes, using raw string if possible. | |
1230 |
|
1233 | |||
1231 | XXX - example removed because it caused encoding errors in documentation |
|
1234 | XXX - example removed because it caused encoding errors in documentation | |
1232 | generation. We need a new example that doesn't contain invalid chars. |
|
1235 | generation. We need a new example that doesn't contain invalid chars. | |
1233 |
|
1236 | |||
1234 | Note the use of raw string and padding at the end to allow trailing |
|
1237 | Note the use of raw string and padding at the end to allow trailing | |
1235 | backslash. |
|
1238 | backslash. | |
1236 | """ |
|
1239 | """ | |
1237 |
|
1240 | |||
1238 | tail = '' |
|
1241 | tail = '' | |
1239 | tailpadding = '' |
|
1242 | tailpadding = '' | |
1240 | raw = '' |
|
1243 | raw = '' | |
1241 | if "\\" in s: |
|
1244 | if "\\" in s: | |
1242 | raw = 'r' |
|
1245 | raw = 'r' | |
1243 | if s.endswith('\\'): |
|
1246 | if s.endswith('\\'): | |
1244 | tail = '[:-1]' |
|
1247 | tail = '[:-1]' | |
1245 | tailpadding = '_' |
|
1248 | tailpadding = '_' | |
1246 | if '"' not in s: |
|
1249 | if '"' not in s: | |
1247 | quote = '"' |
|
1250 | quote = '"' | |
1248 | elif "'" not in s: |
|
1251 | elif "'" not in s: | |
1249 | quote = "'" |
|
1252 | quote = "'" | |
1250 | elif '"""' not in s and not s.endswith('"'): |
|
1253 | elif '"""' not in s and not s.endswith('"'): | |
1251 | quote = '"""' |
|
1254 | quote = '"""' | |
1252 | elif "'''" not in s and not s.endswith("'"): |
|
1255 | elif "'''" not in s and not s.endswith("'"): | |
1253 | quote = "'''" |
|
1256 | quote = "'''" | |
1254 | else: |
|
1257 | else: | |
1255 | # give up, backslash-escaped string will do |
|
1258 | # give up, backslash-escaped string will do | |
1256 | return '"%s"' % esc_quotes(s) |
|
1259 | return '"%s"' % esc_quotes(s) | |
1257 | res = raw + quote + s + tailpadding + quote + tail |
|
1260 | res = raw + quote + s + tailpadding + quote + tail | |
1258 | return res |
|
1261 | return res | |
1259 |
|
1262 | |||
1260 |
|
1263 | |||
1261 | #---------------------------------------------------------------------------- |
|
1264 | #---------------------------------------------------------------------------- | |
1262 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
1265 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): | |
1263 | """Take multiple lines of input. |
|
1266 | """Take multiple lines of input. | |
1264 |
|
1267 | |||
1265 | A list with each line of input as a separate element is returned when a |
|
1268 | A list with each line of input as a separate element is returned when a | |
1266 | termination string is entered (defaults to a single '.'). Input can also |
|
1269 | termination string is entered (defaults to a single '.'). Input can also | |
1267 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
1270 | terminate via EOF (^D in Unix, ^Z-RET in Windows). | |
1268 |
|
1271 | |||
1269 | Lines of input which end in \\ are joined into single entries (and a |
|
1272 | Lines of input which end in \\ are joined into single entries (and a | |
1270 | secondary continuation prompt is issued as long as the user terminates |
|
1273 | secondary continuation prompt is issued as long as the user terminates | |
1271 | lines with \\). This allows entering very long strings which are still |
|
1274 | lines with \\). This allows entering very long strings which are still | |
1272 | meant to be treated as single entities. |
|
1275 | meant to be treated as single entities. | |
1273 | """ |
|
1276 | """ | |
1274 |
|
1277 | |||
1275 | try: |
|
1278 | try: | |
1276 | if header: |
|
1279 | if header: | |
1277 | header += '\n' |
|
1280 | header += '\n' | |
1278 | lines = [raw_input(header + ps1)] |
|
1281 | lines = [raw_input(header + ps1)] | |
1279 | except EOFError: |
|
1282 | except EOFError: | |
1280 | return [] |
|
1283 | return [] | |
1281 | terminate = [terminate_str] |
|
1284 | terminate = [terminate_str] | |
1282 | try: |
|
1285 | try: | |
1283 | while lines[-1:] != terminate: |
|
1286 | while lines[-1:] != terminate: | |
1284 | new_line = raw_input(ps1) |
|
1287 | new_line = raw_input(ps1) | |
1285 | while new_line.endswith('\\'): |
|
1288 | while new_line.endswith('\\'): | |
1286 | new_line = new_line[:-1] + raw_input(ps2) |
|
1289 | new_line = new_line[:-1] + raw_input(ps2) | |
1287 | lines.append(new_line) |
|
1290 | lines.append(new_line) | |
1288 |
|
1291 | |||
1289 | return lines[:-1] # don't return the termination command |
|
1292 | return lines[:-1] # don't return the termination command | |
1290 | except EOFError: |
|
1293 | except EOFError: | |
1291 |
|
1294 | |||
1292 | return lines |
|
1295 | return lines | |
1293 |
|
1296 | |||
1294 | #---------------------------------------------------------------------------- |
|
1297 | #---------------------------------------------------------------------------- | |
1295 | def raw_input_ext(prompt='', ps2='... '): |
|
1298 | def raw_input_ext(prompt='', ps2='... '): | |
1296 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
1299 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" | |
1297 |
|
1300 | |||
1298 | line = raw_input(prompt) |
|
1301 | line = raw_input(prompt) | |
1299 | while line.endswith('\\'): |
|
1302 | while line.endswith('\\'): | |
1300 | line = line[:-1] + raw_input(ps2) |
|
1303 | line = line[:-1] + raw_input(ps2) | |
1301 | return line |
|
1304 | return line | |
1302 |
|
1305 | |||
1303 | #---------------------------------------------------------------------------- |
|
1306 | #---------------------------------------------------------------------------- | |
1304 | def ask_yes_no(prompt,default=None): |
|
1307 | def ask_yes_no(prompt,default=None): | |
1305 | """Asks a question and returns a boolean (y/n) answer. |
|
1308 | """Asks a question and returns a boolean (y/n) answer. | |
1306 |
|
1309 | |||
1307 | If default is given (one of 'y','n'), it is used if the user input is |
|
1310 | If default is given (one of 'y','n'), it is used if the user input is | |
1308 | empty. Otherwise the question is repeated until an answer is given. |
|
1311 | empty. Otherwise the question is repeated until an answer is given. | |
1309 |
|
1312 | |||
1310 | An EOF is treated as the default answer. If there is no default, an |
|
1313 | An EOF is treated as the default answer. If there is no default, an | |
1311 | exception is raised to prevent infinite loops. |
|
1314 | exception is raised to prevent infinite loops. | |
1312 |
|
1315 | |||
1313 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
1316 | Valid answers are: y/yes/n/no (match is not case sensitive).""" | |
1314 |
|
1317 | |||
1315 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
1318 | answers = {'y':True,'n':False,'yes':True,'no':False} | |
1316 | ans = None |
|
1319 | ans = None | |
1317 | while ans not in answers.keys(): |
|
1320 | while ans not in answers.keys(): | |
1318 | try: |
|
1321 | try: | |
1319 | ans = raw_input(prompt+' ').lower() |
|
1322 | ans = raw_input(prompt+' ').lower() | |
1320 | if not ans: # response was an empty string |
|
1323 | if not ans: # response was an empty string | |
1321 | ans = default |
|
1324 | ans = default | |
1322 | except KeyboardInterrupt: |
|
1325 | except KeyboardInterrupt: | |
1323 | pass |
|
1326 | pass | |
1324 | except EOFError: |
|
1327 | except EOFError: | |
1325 | if default in answers.keys(): |
|
1328 | if default in answers.keys(): | |
1326 | ans = default |
|
1329 | ans = default | |
1327 |
|
1330 | |||
1328 | else: |
|
1331 | else: | |
1329 | raise |
|
1332 | raise | |
1330 |
|
1333 | |||
1331 | return answers[ans] |
|
1334 | return answers[ans] | |
1332 |
|
1335 | |||
1333 | #---------------------------------------------------------------------------- |
|
1336 | #---------------------------------------------------------------------------- | |
1334 | def marquee(txt='',width=78,mark='*'): |
|
1337 | def marquee(txt='',width=78,mark='*'): | |
1335 | """Return the input string centered in a 'marquee'.""" |
|
1338 | """Return the input string centered in a 'marquee'.""" | |
1336 | if not txt: |
|
1339 | if not txt: | |
1337 | return (mark*width)[:width] |
|
1340 | return (mark*width)[:width] | |
1338 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
1341 | nmark = (width-len(txt)-2)/len(mark)/2 | |
1339 | if nmark < 0: nmark =0 |
|
1342 | if nmark < 0: nmark =0 | |
1340 | marks = mark*nmark |
|
1343 | marks = mark*nmark | |
1341 | return '%s %s %s' % (marks,txt,marks) |
|
1344 | return '%s %s %s' % (marks,txt,marks) | |
1342 |
|
1345 | |||
1343 | #---------------------------------------------------------------------------- |
|
1346 | #---------------------------------------------------------------------------- | |
1344 | class EvalDict: |
|
1347 | class EvalDict: | |
1345 | """ |
|
1348 | """ | |
1346 | Emulate a dict which evaluates its contents in the caller's frame. |
|
1349 | Emulate a dict which evaluates its contents in the caller's frame. | |
1347 |
|
1350 | |||
1348 | Usage: |
|
1351 | Usage: | |
1349 | >>> number = 19 |
|
1352 | >>> number = 19 | |
1350 |
|
1353 | |||
1351 | >>> text = "python" |
|
1354 | >>> text = "python" | |
1352 |
|
1355 | |||
1353 | >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
1356 | >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() | |
1354 | Python 2.1 rules! |
|
1357 | Python 2.1 rules! | |
1355 | """ |
|
1358 | """ | |
1356 |
|
1359 | |||
1357 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
1360 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a | |
1358 | # modified (shorter) version of: |
|
1361 | # modified (shorter) version of: | |
1359 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
1362 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by | |
1360 | # Skip Montanaro (skip@pobox.com). |
|
1363 | # Skip Montanaro (skip@pobox.com). | |
1361 |
|
1364 | |||
1362 | def __getitem__(self, name): |
|
1365 | def __getitem__(self, name): | |
1363 | frame = sys._getframe(1) |
|
1366 | frame = sys._getframe(1) | |
1364 | return eval(name, frame.f_globals, frame.f_locals) |
|
1367 | return eval(name, frame.f_globals, frame.f_locals) | |
1365 |
|
1368 | |||
1366 | EvalString = EvalDict # for backwards compatibility |
|
1369 | EvalString = EvalDict # for backwards compatibility | |
1367 | #---------------------------------------------------------------------------- |
|
1370 | #---------------------------------------------------------------------------- | |
1368 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
1371 | def qw(words,flat=0,sep=None,maxsplit=-1): | |
1369 | """Similar to Perl's qw() operator, but with some more options. |
|
1372 | """Similar to Perl's qw() operator, but with some more options. | |
1370 |
|
1373 | |||
1371 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
1374 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) | |
1372 |
|
1375 | |||
1373 | words can also be a list itself, and with flat=1, the output will be |
|
1376 | words can also be a list itself, and with flat=1, the output will be | |
1374 | recursively flattened. |
|
1377 | recursively flattened. | |
1375 |
|
1378 | |||
1376 | Examples: |
|
1379 | Examples: | |
1377 |
|
1380 | |||
1378 | >>> qw('1 2') |
|
1381 | >>> qw('1 2') | |
1379 | ['1', '2'] |
|
1382 | ['1', '2'] | |
1380 |
|
1383 | |||
1381 | >>> qw(['a b','1 2',['m n','p q']]) |
|
1384 | >>> qw(['a b','1 2',['m n','p q']]) | |
1382 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
1385 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] | |
1383 |
|
1386 | |||
1384 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
1387 | >>> qw(['a b','1 2',['m n','p q']],flat=1) | |
1385 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] |
|
1388 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] | |
1386 | """ |
|
1389 | """ | |
1387 |
|
1390 | |||
1388 | if type(words) in StringTypes: |
|
1391 | if type(words) in StringTypes: | |
1389 | return [word.strip() for word in words.split(sep,maxsplit) |
|
1392 | return [word.strip() for word in words.split(sep,maxsplit) | |
1390 | if word and not word.isspace() ] |
|
1393 | if word and not word.isspace() ] | |
1391 | if flat: |
|
1394 | if flat: | |
1392 | return flatten(map(qw,words,[1]*len(words))) |
|
1395 | return flatten(map(qw,words,[1]*len(words))) | |
1393 | return map(qw,words) |
|
1396 | return map(qw,words) | |
1394 |
|
1397 | |||
1395 | #---------------------------------------------------------------------------- |
|
1398 | #---------------------------------------------------------------------------- | |
1396 | def qwflat(words,sep=None,maxsplit=-1): |
|
1399 | def qwflat(words,sep=None,maxsplit=-1): | |
1397 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
1400 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" | |
1398 | return qw(words,1,sep,maxsplit) |
|
1401 | return qw(words,1,sep,maxsplit) | |
1399 |
|
1402 | |||
1400 | #---------------------------------------------------------------------------- |
|
1403 | #---------------------------------------------------------------------------- | |
1401 | def qw_lol(indata): |
|
1404 | def qw_lol(indata): | |
1402 | """qw_lol('a b') -> [['a','b']], |
|
1405 | """qw_lol('a b') -> [['a','b']], | |
1403 | otherwise it's just a call to qw(). |
|
1406 | otherwise it's just a call to qw(). | |
1404 |
|
1407 | |||
1405 | We need this to make sure the modules_some keys *always* end up as a |
|
1408 | We need this to make sure the modules_some keys *always* end up as a | |
1406 | list of lists.""" |
|
1409 | list of lists.""" | |
1407 |
|
1410 | |||
1408 | if type(indata) in StringTypes: |
|
1411 | if type(indata) in StringTypes: | |
1409 | return [qw(indata)] |
|
1412 | return [qw(indata)] | |
1410 | else: |
|
1413 | else: | |
1411 | return qw(indata) |
|
1414 | return qw(indata) | |
1412 |
|
1415 | |||
1413 | #----------------------------------------------------------------------------- |
|
1416 | #----------------------------------------------------------------------------- | |
1414 | def list_strings(arg): |
|
1417 | def list_strings(arg): | |
1415 | """Always return a list of strings, given a string or list of strings |
|
1418 | """Always return a list of strings, given a string or list of strings | |
1416 | as input.""" |
|
1419 | as input.""" | |
1417 |
|
1420 | |||
1418 | if type(arg) in StringTypes: return [arg] |
|
1421 | if type(arg) in StringTypes: return [arg] | |
1419 | else: return arg |
|
1422 | else: return arg | |
1420 |
|
1423 | |||
1421 | #---------------------------------------------------------------------------- |
|
1424 | #---------------------------------------------------------------------------- | |
1422 | def grep(pat,list,case=1): |
|
1425 | def grep(pat,list,case=1): | |
1423 | """Simple minded grep-like function. |
|
1426 | """Simple minded grep-like function. | |
1424 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
1427 | grep(pat,list) returns occurrences of pat in list, None on failure. | |
1425 |
|
1428 | |||
1426 | It only does simple string matching, with no support for regexps. Use the |
|
1429 | It only does simple string matching, with no support for regexps. Use the | |
1427 | option case=0 for case-insensitive matching.""" |
|
1430 | option case=0 for case-insensitive matching.""" | |
1428 |
|
1431 | |||
1429 | # This is pretty crude. At least it should implement copying only references |
|
1432 | # This is pretty crude. At least it should implement copying only references | |
1430 | # to the original data in case it's big. Now it copies the data for output. |
|
1433 | # to the original data in case it's big. Now it copies the data for output. | |
1431 | out=[] |
|
1434 | out=[] | |
1432 | if case: |
|
1435 | if case: | |
1433 | for term in list: |
|
1436 | for term in list: | |
1434 | if term.find(pat)>-1: out.append(term) |
|
1437 | if term.find(pat)>-1: out.append(term) | |
1435 | else: |
|
1438 | else: | |
1436 | lpat=pat.lower() |
|
1439 | lpat=pat.lower() | |
1437 | for term in list: |
|
1440 | for term in list: | |
1438 | if term.lower().find(lpat)>-1: out.append(term) |
|
1441 | if term.lower().find(lpat)>-1: out.append(term) | |
1439 |
|
1442 | |||
1440 | if len(out): return out |
|
1443 | if len(out): return out | |
1441 | else: return None |
|
1444 | else: return None | |
1442 |
|
1445 | |||
1443 | #---------------------------------------------------------------------------- |
|
1446 | #---------------------------------------------------------------------------- | |
1444 | def dgrep(pat,*opts): |
|
1447 | def dgrep(pat,*opts): | |
1445 | """Return grep() on dir()+dir(__builtins__). |
|
1448 | """Return grep() on dir()+dir(__builtins__). | |
1446 |
|
1449 | |||
1447 | A very common use of grep() when working interactively.""" |
|
1450 | A very common use of grep() when working interactively.""" | |
1448 |
|
1451 | |||
1449 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
1452 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) | |
1450 |
|
1453 | |||
1451 | #---------------------------------------------------------------------------- |
|
1454 | #---------------------------------------------------------------------------- | |
1452 | def idgrep(pat): |
|
1455 | def idgrep(pat): | |
1453 | """Case-insensitive dgrep()""" |
|
1456 | """Case-insensitive dgrep()""" | |
1454 |
|
1457 | |||
1455 | return dgrep(pat,0) |
|
1458 | return dgrep(pat,0) | |
1456 |
|
1459 | |||
1457 | #---------------------------------------------------------------------------- |
|
1460 | #---------------------------------------------------------------------------- | |
1458 | def igrep(pat,list): |
|
1461 | def igrep(pat,list): | |
1459 | """Synonym for case-insensitive grep.""" |
|
1462 | """Synonym for case-insensitive grep.""" | |
1460 |
|
1463 | |||
1461 | return grep(pat,list,case=0) |
|
1464 | return grep(pat,list,case=0) | |
1462 |
|
1465 | |||
1463 | #---------------------------------------------------------------------------- |
|
1466 | #---------------------------------------------------------------------------- | |
1464 | def indent(str,nspaces=4,ntabs=0): |
|
1467 | def indent(str,nspaces=4,ntabs=0): | |
1465 | """Indent a string a given number of spaces or tabstops. |
|
1468 | """Indent a string a given number of spaces or tabstops. | |
1466 |
|
1469 | |||
1467 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
1470 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. | |
1468 | """ |
|
1471 | """ | |
1469 | if str is None: |
|
1472 | if str is None: | |
1470 | return |
|
1473 | return | |
1471 | ind = '\t'*ntabs+' '*nspaces |
|
1474 | ind = '\t'*ntabs+' '*nspaces | |
1472 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
1475 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) | |
1473 | if outstr.endswith(os.linesep+ind): |
|
1476 | if outstr.endswith(os.linesep+ind): | |
1474 | return outstr[:-len(ind)] |
|
1477 | return outstr[:-len(ind)] | |
1475 | else: |
|
1478 | else: | |
1476 | return outstr |
|
1479 | return outstr | |
1477 |
|
1480 | |||
1478 | #----------------------------------------------------------------------------- |
|
1481 | #----------------------------------------------------------------------------- | |
1479 | def native_line_ends(filename,backup=1): |
|
1482 | def native_line_ends(filename,backup=1): | |
1480 | """Convert (in-place) a file to line-ends native to the current OS. |
|
1483 | """Convert (in-place) a file to line-ends native to the current OS. | |
1481 |
|
1484 | |||
1482 | If the optional backup argument is given as false, no backup of the |
|
1485 | If the optional backup argument is given as false, no backup of the | |
1483 | original file is left. """ |
|
1486 | original file is left. """ | |
1484 |
|
1487 | |||
1485 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
1488 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} | |
1486 |
|
1489 | |||
1487 | bak_filename = filename + backup_suffixes[os.name] |
|
1490 | bak_filename = filename + backup_suffixes[os.name] | |
1488 |
|
1491 | |||
1489 | original = open(filename).read() |
|
1492 | original = open(filename).read() | |
1490 | shutil.copy2(filename,bak_filename) |
|
1493 | shutil.copy2(filename,bak_filename) | |
1491 | try: |
|
1494 | try: | |
1492 | new = open(filename,'wb') |
|
1495 | new = open(filename,'wb') | |
1493 | new.write(os.linesep.join(original.splitlines())) |
|
1496 | new.write(os.linesep.join(original.splitlines())) | |
1494 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
1497 | new.write(os.linesep) # ALWAYS put an eol at the end of the file | |
1495 | new.close() |
|
1498 | new.close() | |
1496 | except: |
|
1499 | except: | |
1497 | os.rename(bak_filename,filename) |
|
1500 | os.rename(bak_filename,filename) | |
1498 | if not backup: |
|
1501 | if not backup: | |
1499 | try: |
|
1502 | try: | |
1500 | os.remove(bak_filename) |
|
1503 | os.remove(bak_filename) | |
1501 | except: |
|
1504 | except: | |
1502 | pass |
|
1505 | pass | |
1503 |
|
1506 | |||
1504 | #---------------------------------------------------------------------------- |
|
1507 | #---------------------------------------------------------------------------- | |
1505 | def get_pager_cmd(pager_cmd = None): |
|
1508 | def get_pager_cmd(pager_cmd = None): | |
1506 | """Return a pager command. |
|
1509 | """Return a pager command. | |
1507 |
|
1510 | |||
1508 | Makes some attempts at finding an OS-correct one.""" |
|
1511 | Makes some attempts at finding an OS-correct one.""" | |
1509 |
|
1512 | |||
1510 | if os.name == 'posix': |
|
1513 | if os.name == 'posix': | |
1511 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
1514 | default_pager_cmd = 'less -r' # -r for color control sequences | |
1512 | elif os.name in ['nt','dos']: |
|
1515 | elif os.name in ['nt','dos']: | |
1513 | default_pager_cmd = 'type' |
|
1516 | default_pager_cmd = 'type' | |
1514 |
|
1517 | |||
1515 | if pager_cmd is None: |
|
1518 | if pager_cmd is None: | |
1516 | try: |
|
1519 | try: | |
1517 | pager_cmd = os.environ['PAGER'] |
|
1520 | pager_cmd = os.environ['PAGER'] | |
1518 | except: |
|
1521 | except: | |
1519 | pager_cmd = default_pager_cmd |
|
1522 | pager_cmd = default_pager_cmd | |
1520 | return pager_cmd |
|
1523 | return pager_cmd | |
1521 |
|
1524 | |||
1522 | #----------------------------------------------------------------------------- |
|
1525 | #----------------------------------------------------------------------------- | |
1523 | def get_pager_start(pager,start): |
|
1526 | def get_pager_start(pager,start): | |
1524 | """Return the string for paging files with an offset. |
|
1527 | """Return the string for paging files with an offset. | |
1525 |
|
1528 | |||
1526 | This is the '+N' argument which less and more (under Unix) accept. |
|
1529 | This is the '+N' argument which less and more (under Unix) accept. | |
1527 | """ |
|
1530 | """ | |
1528 |
|
1531 | |||
1529 | if pager in ['less','more']: |
|
1532 | if pager in ['less','more']: | |
1530 | if start: |
|
1533 | if start: | |
1531 | start_string = '+' + str(start) |
|
1534 | start_string = '+' + str(start) | |
1532 | else: |
|
1535 | else: | |
1533 | start_string = '' |
|
1536 | start_string = '' | |
1534 | else: |
|
1537 | else: | |
1535 | start_string = '' |
|
1538 | start_string = '' | |
1536 | return start_string |
|
1539 | return start_string | |
1537 |
|
1540 | |||
1538 | #---------------------------------------------------------------------------- |
|
1541 | #---------------------------------------------------------------------------- | |
1539 | # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch() |
|
1542 | # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch() | |
1540 | if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': |
|
1543 | if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': | |
1541 | import msvcrt |
|
1544 | import msvcrt | |
1542 | def page_more(): |
|
1545 | def page_more(): | |
1543 | """ Smart pausing between pages |
|
1546 | """ Smart pausing between pages | |
1544 |
|
1547 | |||
1545 | @return: True if need print more lines, False if quit |
|
1548 | @return: True if need print more lines, False if quit | |
1546 | """ |
|
1549 | """ | |
1547 | Term.cout.write('---Return to continue, q to quit--- ') |
|
1550 | Term.cout.write('---Return to continue, q to quit--- ') | |
1548 | ans = msvcrt.getch() |
|
1551 | ans = msvcrt.getch() | |
1549 | if ans in ("q", "Q"): |
|
1552 | if ans in ("q", "Q"): | |
1550 | result = False |
|
1553 | result = False | |
1551 | else: |
|
1554 | else: | |
1552 | result = True |
|
1555 | result = True | |
1553 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) |
|
1556 | Term.cout.write("\b"*37 + " "*37 + "\b"*37) | |
1554 | return result |
|
1557 | return result | |
1555 | else: |
|
1558 | else: | |
1556 | def page_more(): |
|
1559 | def page_more(): | |
1557 | ans = raw_input('---Return to continue, q to quit--- ') |
|
1560 | ans = raw_input('---Return to continue, q to quit--- ') | |
1558 | if ans.lower().startswith('q'): |
|
1561 | if ans.lower().startswith('q'): | |
1559 | return False |
|
1562 | return False | |
1560 | else: |
|
1563 | else: | |
1561 | return True |
|
1564 | return True | |
1562 |
|
1565 | |||
1563 | esc_re = re.compile(r"(\x1b[^m]+m)") |
|
1566 | esc_re = re.compile(r"(\x1b[^m]+m)") | |
1564 |
|
1567 | |||
1565 | def page_dumb(strng,start=0,screen_lines=25): |
|
1568 | def page_dumb(strng,start=0,screen_lines=25): | |
1566 | """Very dumb 'pager' in Python, for when nothing else works. |
|
1569 | """Very dumb 'pager' in Python, for when nothing else works. | |
1567 |
|
1570 | |||
1568 | Only moves forward, same interface as page(), except for pager_cmd and |
|
1571 | Only moves forward, same interface as page(), except for pager_cmd and | |
1569 | mode.""" |
|
1572 | mode.""" | |
1570 |
|
1573 | |||
1571 | out_ln = strng.splitlines()[start:] |
|
1574 | out_ln = strng.splitlines()[start:] | |
1572 | screens = chop(out_ln,screen_lines-1) |
|
1575 | screens = chop(out_ln,screen_lines-1) | |
1573 | if len(screens) == 1: |
|
1576 | if len(screens) == 1: | |
1574 | print >>Term.cout, os.linesep.join(screens[0]) |
|
1577 | print >>Term.cout, os.linesep.join(screens[0]) | |
1575 | else: |
|
1578 | else: | |
1576 | last_escape = "" |
|
1579 | last_escape = "" | |
1577 | for scr in screens[0:-1]: |
|
1580 | for scr in screens[0:-1]: | |
1578 | hunk = os.linesep.join(scr) |
|
1581 | hunk = os.linesep.join(scr) | |
1579 | print >>Term.cout, last_escape + hunk |
|
1582 | print >>Term.cout, last_escape + hunk | |
1580 | if not page_more(): |
|
1583 | if not page_more(): | |
1581 | return |
|
1584 | return | |
1582 | esc_list = esc_re.findall(hunk) |
|
1585 | esc_list = esc_re.findall(hunk) | |
1583 | if len(esc_list) > 0: |
|
1586 | if len(esc_list) > 0: | |
1584 | last_escape = esc_list[-1] |
|
1587 | last_escape = esc_list[-1] | |
1585 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) |
|
1588 | print >>Term.cout, last_escape + os.linesep.join(screens[-1]) | |
1586 |
|
1589 | |||
1587 | #---------------------------------------------------------------------------- |
|
1590 | #---------------------------------------------------------------------------- | |
1588 | def page(strng,start=0,screen_lines=0,pager_cmd = None): |
|
1591 | def page(strng,start=0,screen_lines=0,pager_cmd = None): | |
1589 | """Print a string, piping through a pager after a certain length. |
|
1592 | """Print a string, piping through a pager after a certain length. | |
1590 |
|
1593 | |||
1591 | The screen_lines parameter specifies the number of *usable* lines of your |
|
1594 | The screen_lines parameter specifies the number of *usable* lines of your | |
1592 | terminal screen (total lines minus lines you need to reserve to show other |
|
1595 | terminal screen (total lines minus lines you need to reserve to show other | |
1593 | information). |
|
1596 | information). | |
1594 |
|
1597 | |||
1595 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
1598 | If you set screen_lines to a number <=0, page() will try to auto-determine | |
1596 | your screen size and will only use up to (screen_size+screen_lines) for |
|
1599 | your screen size and will only use up to (screen_size+screen_lines) for | |
1597 | printing, paging after that. That is, if you want auto-detection but need |
|
1600 | printing, paging after that. That is, if you want auto-detection but need | |
1598 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
1601 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for | |
1599 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
1602 | auto-detection without any lines reserved simply use screen_lines = 0. | |
1600 |
|
1603 | |||
1601 | If a string won't fit in the allowed lines, it is sent through the |
|
1604 | If a string won't fit in the allowed lines, it is sent through the | |
1602 | specified pager command. If none given, look for PAGER in the environment, |
|
1605 | specified pager command. If none given, look for PAGER in the environment, | |
1603 | and ultimately default to less. |
|
1606 | and ultimately default to less. | |
1604 |
|
1607 | |||
1605 | If no system pager works, the string is sent through a 'dumb pager' |
|
1608 | If no system pager works, the string is sent through a 'dumb pager' | |
1606 | written in python, very simplistic. |
|
1609 | written in python, very simplistic. | |
1607 | """ |
|
1610 | """ | |
1608 |
|
1611 | |||
1609 | # Some routines may auto-compute start offsets incorrectly and pass a |
|
1612 | # Some routines may auto-compute start offsets incorrectly and pass a | |
1610 | # negative value. Offset to 0 for robustness. |
|
1613 | # negative value. Offset to 0 for robustness. | |
1611 | start = max(0,start) |
|
1614 | start = max(0,start) | |
1612 |
|
1615 | |||
1613 | # first, try the hook |
|
1616 | # first, try the hook | |
1614 | ip = IPython.ipapi.get() |
|
1617 | ip = IPython.ipapi.get() | |
1615 | if ip: |
|
1618 | if ip: | |
1616 | try: |
|
1619 | try: | |
1617 | ip.IP.hooks.show_in_pager(strng) |
|
1620 | ip.IP.hooks.show_in_pager(strng) | |
1618 | return |
|
1621 | return | |
1619 | except IPython.ipapi.TryNext: |
|
1622 | except IPython.ipapi.TryNext: | |
1620 | pass |
|
1623 | pass | |
1621 |
|
1624 | |||
1622 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
1625 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs | |
1623 | TERM = os.environ.get('TERM','dumb') |
|
1626 | TERM = os.environ.get('TERM','dumb') | |
1624 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
1627 | if TERM in ['dumb','emacs'] and os.name != 'nt': | |
1625 | print strng |
|
1628 | print strng | |
1626 | return |
|
1629 | return | |
1627 | # chop off the topmost part of the string we don't want to see |
|
1630 | # chop off the topmost part of the string we don't want to see | |
1628 | str_lines = strng.split(os.linesep)[start:] |
|
1631 | str_lines = strng.split(os.linesep)[start:] | |
1629 | str_toprint = os.linesep.join(str_lines) |
|
1632 | str_toprint = os.linesep.join(str_lines) | |
1630 | num_newlines = len(str_lines) |
|
1633 | num_newlines = len(str_lines) | |
1631 | len_str = len(str_toprint) |
|
1634 | len_str = len(str_toprint) | |
1632 |
|
1635 | |||
1633 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
1636 | # Dumb heuristics to guesstimate number of on-screen lines the string | |
1634 | # takes. Very basic, but good enough for docstrings in reasonable |
|
1637 | # takes. Very basic, but good enough for docstrings in reasonable | |
1635 | # terminals. If someone later feels like refining it, it's not hard. |
|
1638 | # terminals. If someone later feels like refining it, it's not hard. | |
1636 | numlines = max(num_newlines,int(len_str/80)+1) |
|
1639 | numlines = max(num_newlines,int(len_str/80)+1) | |
1637 |
|
1640 | |||
1638 | if os.name == "nt": |
|
1641 | if os.name == "nt": | |
1639 | screen_lines_def = get_console_size(defaulty=25)[1] |
|
1642 | screen_lines_def = get_console_size(defaulty=25)[1] | |
1640 | else: |
|
1643 | else: | |
1641 | screen_lines_def = 25 # default value if we can't auto-determine |
|
1644 | screen_lines_def = 25 # default value if we can't auto-determine | |
1642 |
|
1645 | |||
1643 | # auto-determine screen size |
|
1646 | # auto-determine screen size | |
1644 | if screen_lines <= 0: |
|
1647 | if screen_lines <= 0: | |
1645 | if TERM=='xterm': |
|
1648 | if TERM=='xterm': | |
1646 | use_curses = USE_CURSES |
|
1649 | use_curses = USE_CURSES | |
1647 | else: |
|
1650 | else: | |
1648 | # curses causes problems on many terminals other than xterm. |
|
1651 | # curses causes problems on many terminals other than xterm. | |
1649 | use_curses = False |
|
1652 | use_curses = False | |
1650 | if use_curses: |
|
1653 | if use_curses: | |
1651 | # There is a bug in curses, where *sometimes* it fails to properly |
|
1654 | # There is a bug in curses, where *sometimes* it fails to properly | |
1652 | # initialize, and then after the endwin() call is made, the |
|
1655 | # initialize, and then after the endwin() call is made, the | |
1653 | # terminal is left in an unusable state. Rather than trying to |
|
1656 | # terminal is left in an unusable state. Rather than trying to | |
1654 | # check everytime for this (by requesting and comparing termios |
|
1657 | # check everytime for this (by requesting and comparing termios | |
1655 | # flags each time), we just save the initial terminal state and |
|
1658 | # flags each time), we just save the initial terminal state and | |
1656 | # unconditionally reset it every time. It's cheaper than making |
|
1659 | # unconditionally reset it every time. It's cheaper than making | |
1657 | # the checks. |
|
1660 | # the checks. | |
1658 | term_flags = termios.tcgetattr(sys.stdout) |
|
1661 | term_flags = termios.tcgetattr(sys.stdout) | |
1659 | scr = curses.initscr() |
|
1662 | scr = curses.initscr() | |
1660 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
1663 | screen_lines_real,screen_cols = scr.getmaxyx() | |
1661 | curses.endwin() |
|
1664 | curses.endwin() | |
1662 | # Restore terminal state in case endwin() didn't. |
|
1665 | # Restore terminal state in case endwin() didn't. | |
1663 | termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags) |
|
1666 | termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags) | |
1664 | # Now we have what we needed: the screen size in rows/columns |
|
1667 | # Now we have what we needed: the screen size in rows/columns | |
1665 | screen_lines += screen_lines_real |
|
1668 | screen_lines += screen_lines_real | |
1666 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
1669 | #print '***Screen size:',screen_lines_real,'lines x',\ | |
1667 | #screen_cols,'columns.' # dbg |
|
1670 | #screen_cols,'columns.' # dbg | |
1668 | else: |
|
1671 | else: | |
1669 | screen_lines += screen_lines_def |
|
1672 | screen_lines += screen_lines_def | |
1670 |
|
1673 | |||
1671 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
1674 | #print 'numlines',numlines,'screenlines',screen_lines # dbg | |
1672 | if numlines <= screen_lines : |
|
1675 | if numlines <= screen_lines : | |
1673 | #print '*** normal print' # dbg |
|
1676 | #print '*** normal print' # dbg | |
1674 | print >>Term.cout, str_toprint |
|
1677 | print >>Term.cout, str_toprint | |
1675 | else: |
|
1678 | else: | |
1676 | # Try to open pager and default to internal one if that fails. |
|
1679 | # Try to open pager and default to internal one if that fails. | |
1677 | # All failure modes are tagged as 'retval=1', to match the return |
|
1680 | # All failure modes are tagged as 'retval=1', to match the return | |
1678 | # value of a failed system command. If any intermediate attempt |
|
1681 | # value of a failed system command. If any intermediate attempt | |
1679 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
1682 | # sets retval to 1, at the end we resort to our own page_dumb() pager. | |
1680 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1683 | pager_cmd = get_pager_cmd(pager_cmd) | |
1681 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1684 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1682 | if os.name == 'nt': |
|
1685 | if os.name == 'nt': | |
1683 | if pager_cmd.startswith('type'): |
|
1686 | if pager_cmd.startswith('type'): | |
1684 | # The default WinXP 'type' command is failing on complex strings. |
|
1687 | # The default WinXP 'type' command is failing on complex strings. | |
1685 | retval = 1 |
|
1688 | retval = 1 | |
1686 | else: |
|
1689 | else: | |
1687 | tmpname = tempfile.mktemp('.txt') |
|
1690 | tmpname = tempfile.mktemp('.txt') | |
1688 | tmpfile = file(tmpname,'wt') |
|
1691 | tmpfile = file(tmpname,'wt') | |
1689 | tmpfile.write(strng) |
|
1692 | tmpfile.write(strng) | |
1690 | tmpfile.close() |
|
1693 | tmpfile.close() | |
1691 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
1694 | cmd = "%s < %s" % (pager_cmd,tmpname) | |
1692 | if os.system(cmd): |
|
1695 | if os.system(cmd): | |
1693 | retval = 1 |
|
1696 | retval = 1 | |
1694 | else: |
|
1697 | else: | |
1695 | retval = None |
|
1698 | retval = None | |
1696 | os.remove(tmpname) |
|
1699 | os.remove(tmpname) | |
1697 | else: |
|
1700 | else: | |
1698 | try: |
|
1701 | try: | |
1699 | retval = None |
|
1702 | retval = None | |
1700 | # if I use popen4, things hang. No idea why. |
|
1703 | # if I use popen4, things hang. No idea why. | |
1701 | #pager,shell_out = os.popen4(pager_cmd) |
|
1704 | #pager,shell_out = os.popen4(pager_cmd) | |
1702 | pager = os.popen(pager_cmd,'w') |
|
1705 | pager = os.popen(pager_cmd,'w') | |
1703 | pager.write(strng) |
|
1706 | pager.write(strng) | |
1704 | pager.close() |
|
1707 | pager.close() | |
1705 | retval = pager.close() # success returns None |
|
1708 | retval = pager.close() # success returns None | |
1706 | except IOError,msg: # broken pipe when user quits |
|
1709 | except IOError,msg: # broken pipe when user quits | |
1707 | if msg.args == (32,'Broken pipe'): |
|
1710 | if msg.args == (32,'Broken pipe'): | |
1708 | retval = None |
|
1711 | retval = None | |
1709 | else: |
|
1712 | else: | |
1710 | retval = 1 |
|
1713 | retval = 1 | |
1711 | except OSError: |
|
1714 | except OSError: | |
1712 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
1715 | # Other strange problems, sometimes seen in Win2k/cygwin | |
1713 | retval = 1 |
|
1716 | retval = 1 | |
1714 | if retval is not None: |
|
1717 | if retval is not None: | |
1715 | page_dumb(strng,screen_lines=screen_lines) |
|
1718 | page_dumb(strng,screen_lines=screen_lines) | |
1716 |
|
1719 | |||
1717 | #---------------------------------------------------------------------------- |
|
1720 | #---------------------------------------------------------------------------- | |
1718 | def page_file(fname,start = 0, pager_cmd = None): |
|
1721 | def page_file(fname,start = 0, pager_cmd = None): | |
1719 | """Page a file, using an optional pager command and starting line. |
|
1722 | """Page a file, using an optional pager command and starting line. | |
1720 | """ |
|
1723 | """ | |
1721 |
|
1724 | |||
1722 | pager_cmd = get_pager_cmd(pager_cmd) |
|
1725 | pager_cmd = get_pager_cmd(pager_cmd) | |
1723 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
1726 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) | |
1724 |
|
1727 | |||
1725 | try: |
|
1728 | try: | |
1726 | if os.environ['TERM'] in ['emacs','dumb']: |
|
1729 | if os.environ['TERM'] in ['emacs','dumb']: | |
1727 | raise EnvironmentError |
|
1730 | raise EnvironmentError | |
1728 | xsys(pager_cmd + ' ' + fname) |
|
1731 | xsys(pager_cmd + ' ' + fname) | |
1729 | except: |
|
1732 | except: | |
1730 | try: |
|
1733 | try: | |
1731 | if start > 0: |
|
1734 | if start > 0: | |
1732 | start -= 1 |
|
1735 | start -= 1 | |
1733 | page(open(fname).read(),start) |
|
1736 | page(open(fname).read(),start) | |
1734 | except: |
|
1737 | except: | |
1735 | print 'Unable to show file',`fname` |
|
1738 | print 'Unable to show file',`fname` | |
1736 |
|
1739 | |||
1737 |
|
1740 | |||
1738 | #---------------------------------------------------------------------------- |
|
1741 | #---------------------------------------------------------------------------- | |
1739 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
1742 | def snip_print(str,width = 75,print_full = 0,header = ''): | |
1740 | """Print a string snipping the midsection to fit in width. |
|
1743 | """Print a string snipping the midsection to fit in width. | |
1741 |
|
1744 | |||
1742 | print_full: mode control: |
|
1745 | print_full: mode control: | |
1743 | - 0: only snip long strings |
|
1746 | - 0: only snip long strings | |
1744 | - 1: send to page() directly. |
|
1747 | - 1: send to page() directly. | |
1745 | - 2: snip long strings and ask for full length viewing with page() |
|
1748 | - 2: snip long strings and ask for full length viewing with page() | |
1746 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
1749 | Return 1 if snipping was necessary, 0 otherwise.""" | |
1747 |
|
1750 | |||
1748 | if print_full == 1: |
|
1751 | if print_full == 1: | |
1749 | page(header+str) |
|
1752 | page(header+str) | |
1750 | return 0 |
|
1753 | return 0 | |
1751 |
|
1754 | |||
1752 | print header, |
|
1755 | print header, | |
1753 | if len(str) < width: |
|
1756 | if len(str) < width: | |
1754 | print str |
|
1757 | print str | |
1755 | snip = 0 |
|
1758 | snip = 0 | |
1756 | else: |
|
1759 | else: | |
1757 | whalf = int((width -5)/2) |
|
1760 | whalf = int((width -5)/2) | |
1758 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
1761 | print str[:whalf] + ' <...> ' + str[-whalf:] | |
1759 | snip = 1 |
|
1762 | snip = 1 | |
1760 | if snip and print_full == 2: |
|
1763 | if snip and print_full == 2: | |
1761 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
1764 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': | |
1762 | page(str) |
|
1765 | page(str) | |
1763 | return snip |
|
1766 | return snip | |
1764 |
|
1767 | |||
1765 | #**************************************************************************** |
|
1768 | #**************************************************************************** | |
1766 | # lists, dicts and structures |
|
1769 | # lists, dicts and structures | |
1767 |
|
1770 | |||
1768 | def belong(candidates,checklist): |
|
1771 | def belong(candidates,checklist): | |
1769 | """Check whether a list of items appear in a given list of options. |
|
1772 | """Check whether a list of items appear in a given list of options. | |
1770 |
|
1773 | |||
1771 | Returns a list of 1 and 0, one for each candidate given.""" |
|
1774 | Returns a list of 1 and 0, one for each candidate given.""" | |
1772 |
|
1775 | |||
1773 | return [x in checklist for x in candidates] |
|
1776 | return [x in checklist for x in candidates] | |
1774 |
|
1777 | |||
1775 | #---------------------------------------------------------------------------- |
|
1778 | #---------------------------------------------------------------------------- | |
1776 | def uniq_stable(elems): |
|
1779 | def uniq_stable(elems): | |
1777 | """uniq_stable(elems) -> list |
|
1780 | """uniq_stable(elems) -> list | |
1778 |
|
1781 | |||
1779 | Return from an iterable, a list of all the unique elements in the input, |
|
1782 | Return from an iterable, a list of all the unique elements in the input, | |
1780 | but maintaining the order in which they first appear. |
|
1783 | but maintaining the order in which they first appear. | |
1781 |
|
1784 | |||
1782 | A naive solution to this problem which just makes a dictionary with the |
|
1785 | A naive solution to this problem which just makes a dictionary with the | |
1783 | elements as keys fails to respect the stability condition, since |
|
1786 | elements as keys fails to respect the stability condition, since | |
1784 | dictionaries are unsorted by nature. |
|
1787 | dictionaries are unsorted by nature. | |
1785 |
|
1788 | |||
1786 | Note: All elements in the input must be valid dictionary keys for this |
|
1789 | Note: All elements in the input must be valid dictionary keys for this | |
1787 | routine to work, as it internally uses a dictionary for efficiency |
|
1790 | routine to work, as it internally uses a dictionary for efficiency | |
1788 | reasons.""" |
|
1791 | reasons.""" | |
1789 |
|
1792 | |||
1790 | unique = [] |
|
1793 | unique = [] | |
1791 | unique_dict = {} |
|
1794 | unique_dict = {} | |
1792 | for nn in elems: |
|
1795 | for nn in elems: | |
1793 | if nn not in unique_dict: |
|
1796 | if nn not in unique_dict: | |
1794 | unique.append(nn) |
|
1797 | unique.append(nn) | |
1795 | unique_dict[nn] = None |
|
1798 | unique_dict[nn] = None | |
1796 | return unique |
|
1799 | return unique | |
1797 |
|
1800 | |||
1798 | #---------------------------------------------------------------------------- |
|
1801 | #---------------------------------------------------------------------------- | |
1799 | class NLprinter: |
|
1802 | class NLprinter: | |
1800 | """Print an arbitrarily nested list, indicating index numbers. |
|
1803 | """Print an arbitrarily nested list, indicating index numbers. | |
1801 |
|
1804 | |||
1802 | An instance of this class called nlprint is available and callable as a |
|
1805 | An instance of this class called nlprint is available and callable as a | |
1803 | function. |
|
1806 | function. | |
1804 |
|
1807 | |||
1805 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
1808 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' | |
1806 | and using 'sep' to separate the index from the value. """ |
|
1809 | and using 'sep' to separate the index from the value. """ | |
1807 |
|
1810 | |||
1808 | def __init__(self): |
|
1811 | def __init__(self): | |
1809 | self.depth = 0 |
|
1812 | self.depth = 0 | |
1810 |
|
1813 | |||
1811 | def __call__(self,lst,pos='',**kw): |
|
1814 | def __call__(self,lst,pos='',**kw): | |
1812 | """Prints the nested list numbering levels.""" |
|
1815 | """Prints the nested list numbering levels.""" | |
1813 | kw.setdefault('indent',' ') |
|
1816 | kw.setdefault('indent',' ') | |
1814 | kw.setdefault('sep',': ') |
|
1817 | kw.setdefault('sep',': ') | |
1815 | kw.setdefault('start',0) |
|
1818 | kw.setdefault('start',0) | |
1816 | kw.setdefault('stop',len(lst)) |
|
1819 | kw.setdefault('stop',len(lst)) | |
1817 | # we need to remove start and stop from kw so they don't propagate |
|
1820 | # we need to remove start and stop from kw so they don't propagate | |
1818 | # into a recursive call for a nested list. |
|
1821 | # into a recursive call for a nested list. | |
1819 | start = kw['start']; del kw['start'] |
|
1822 | start = kw['start']; del kw['start'] | |
1820 | stop = kw['stop']; del kw['stop'] |
|
1823 | stop = kw['stop']; del kw['stop'] | |
1821 | if self.depth == 0 and 'header' in kw.keys(): |
|
1824 | if self.depth == 0 and 'header' in kw.keys(): | |
1822 | print kw['header'] |
|
1825 | print kw['header'] | |
1823 |
|
1826 | |||
1824 | for idx in range(start,stop): |
|
1827 | for idx in range(start,stop): | |
1825 | elem = lst[idx] |
|
1828 | elem = lst[idx] | |
1826 | if type(elem)==type([]): |
|
1829 | if type(elem)==type([]): | |
1827 | self.depth += 1 |
|
1830 | self.depth += 1 | |
1828 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
1831 | self.__call__(elem,itpl('$pos$idx,'),**kw) | |
1829 | self.depth -= 1 |
|
1832 | self.depth -= 1 | |
1830 | else: |
|
1833 | else: | |
1831 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
1834 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') | |
1832 |
|
1835 | |||
1833 | nlprint = NLprinter() |
|
1836 | nlprint = NLprinter() | |
1834 | #---------------------------------------------------------------------------- |
|
1837 | #---------------------------------------------------------------------------- | |
1835 | def all_belong(candidates,checklist): |
|
1838 | def all_belong(candidates,checklist): | |
1836 | """Check whether a list of items ALL appear in a given list of options. |
|
1839 | """Check whether a list of items ALL appear in a given list of options. | |
1837 |
|
1840 | |||
1838 | Returns a single 1 or 0 value.""" |
|
1841 | Returns a single 1 or 0 value.""" | |
1839 |
|
1842 | |||
1840 | return 1-(0 in [x in checklist for x in candidates]) |
|
1843 | return 1-(0 in [x in checklist for x in candidates]) | |
1841 |
|
1844 | |||
1842 | #---------------------------------------------------------------------------- |
|
1845 | #---------------------------------------------------------------------------- | |
1843 | def sort_compare(lst1,lst2,inplace = 1): |
|
1846 | def sort_compare(lst1,lst2,inplace = 1): | |
1844 | """Sort and compare two lists. |
|
1847 | """Sort and compare two lists. | |
1845 |
|
1848 | |||
1846 | By default it does it in place, thus modifying the lists. Use inplace = 0 |
|
1849 | By default it does it in place, thus modifying the lists. Use inplace = 0 | |
1847 | to avoid that (at the cost of temporary copy creation).""" |
|
1850 | to avoid that (at the cost of temporary copy creation).""" | |
1848 | if not inplace: |
|
1851 | if not inplace: | |
1849 | lst1 = lst1[:] |
|
1852 | lst1 = lst1[:] | |
1850 | lst2 = lst2[:] |
|
1853 | lst2 = lst2[:] | |
1851 | lst1.sort(); lst2.sort() |
|
1854 | lst1.sort(); lst2.sort() | |
1852 | return lst1 == lst2 |
|
1855 | return lst1 == lst2 | |
1853 |
|
1856 | |||
1854 | #---------------------------------------------------------------------------- |
|
1857 | #---------------------------------------------------------------------------- | |
1855 | def list2dict(lst): |
|
1858 | def list2dict(lst): | |
1856 | """Takes a list of (key,value) pairs and turns it into a dict.""" |
|
1859 | """Takes a list of (key,value) pairs and turns it into a dict.""" | |
1857 |
|
1860 | |||
1858 | dic = {} |
|
1861 | dic = {} | |
1859 | for k,v in lst: dic[k] = v |
|
1862 | for k,v in lst: dic[k] = v | |
1860 | return dic |
|
1863 | return dic | |
1861 |
|
1864 | |||
1862 | #---------------------------------------------------------------------------- |
|
1865 | #---------------------------------------------------------------------------- | |
1863 | def list2dict2(lst,default=''): |
|
1866 | def list2dict2(lst,default=''): | |
1864 | """Takes a list and turns it into a dict. |
|
1867 | """Takes a list and turns it into a dict. | |
1865 | Much slower than list2dict, but more versatile. This version can take |
|
1868 | Much slower than list2dict, but more versatile. This version can take | |
1866 | lists with sublists of arbitrary length (including sclars).""" |
|
1869 | lists with sublists of arbitrary length (including sclars).""" | |
1867 |
|
1870 | |||
1868 | dic = {} |
|
1871 | dic = {} | |
1869 | for elem in lst: |
|
1872 | for elem in lst: | |
1870 | if type(elem) in (types.ListType,types.TupleType): |
|
1873 | if type(elem) in (types.ListType,types.TupleType): | |
1871 | size = len(elem) |
|
1874 | size = len(elem) | |
1872 | if size == 0: |
|
1875 | if size == 0: | |
1873 | pass |
|
1876 | pass | |
1874 | elif size == 1: |
|
1877 | elif size == 1: | |
1875 | dic[elem] = default |
|
1878 | dic[elem] = default | |
1876 | else: |
|
1879 | else: | |
1877 | k,v = elem[0], elem[1:] |
|
1880 | k,v = elem[0], elem[1:] | |
1878 | if len(v) == 1: v = v[0] |
|
1881 | if len(v) == 1: v = v[0] | |
1879 | dic[k] = v |
|
1882 | dic[k] = v | |
1880 | else: |
|
1883 | else: | |
1881 | dic[elem] = default |
|
1884 | dic[elem] = default | |
1882 | return dic |
|
1885 | return dic | |
1883 |
|
1886 | |||
1884 | #---------------------------------------------------------------------------- |
|
1887 | #---------------------------------------------------------------------------- | |
1885 | def flatten(seq): |
|
1888 | def flatten(seq): | |
1886 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
1889 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" | |
1887 |
|
1890 | |||
1888 | return [x for subseq in seq for x in subseq] |
|
1891 | return [x for subseq in seq for x in subseq] | |
1889 |
|
1892 | |||
1890 | #---------------------------------------------------------------------------- |
|
1893 | #---------------------------------------------------------------------------- | |
1891 | def get_slice(seq,start=0,stop=None,step=1): |
|
1894 | def get_slice(seq,start=0,stop=None,step=1): | |
1892 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" |
|
1895 | """Get a slice of a sequence with variable step. Specify start,stop,step.""" | |
1893 | if stop == None: |
|
1896 | if stop == None: | |
1894 | stop = len(seq) |
|
1897 | stop = len(seq) | |
1895 | item = lambda i: seq[i] |
|
1898 | item = lambda i: seq[i] | |
1896 | return map(item,xrange(start,stop,step)) |
|
1899 | return map(item,xrange(start,stop,step)) | |
1897 |
|
1900 | |||
1898 | #---------------------------------------------------------------------------- |
|
1901 | #---------------------------------------------------------------------------- | |
1899 | def chop(seq,size): |
|
1902 | def chop(seq,size): | |
1900 | """Chop a sequence into chunks of the given size.""" |
|
1903 | """Chop a sequence into chunks of the given size.""" | |
1901 | chunk = lambda i: seq[i:i+size] |
|
1904 | chunk = lambda i: seq[i:i+size] | |
1902 | return map(chunk,xrange(0,len(seq),size)) |
|
1905 | return map(chunk,xrange(0,len(seq),size)) | |
1903 |
|
1906 | |||
1904 | #---------------------------------------------------------------------------- |
|
1907 | #---------------------------------------------------------------------------- | |
1905 | # with is a keyword as of python 2.5, so this function is renamed to withobj |
|
1908 | # with is a keyword as of python 2.5, so this function is renamed to withobj | |
1906 | # from its old 'with' name. |
|
1909 | # from its old 'with' name. | |
1907 | def with_obj(object, **args): |
|
1910 | def with_obj(object, **args): | |
1908 | """Set multiple attributes for an object, similar to Pascal's with. |
|
1911 | """Set multiple attributes for an object, similar to Pascal's with. | |
1909 |
|
1912 | |||
1910 | Example: |
|
1913 | Example: | |
1911 | with_obj(jim, |
|
1914 | with_obj(jim, | |
1912 | born = 1960, |
|
1915 | born = 1960, | |
1913 | haircolour = 'Brown', |
|
1916 | haircolour = 'Brown', | |
1914 | eyecolour = 'Green') |
|
1917 | eyecolour = 'Green') | |
1915 |
|
1918 | |||
1916 | Credit: Greg Ewing, in |
|
1919 | Credit: Greg Ewing, in | |
1917 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. |
|
1920 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. | |
1918 |
|
1921 | |||
1919 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' |
|
1922 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' | |
1920 | has become a keyword for Python 2.5, so we had to rename it.""" |
|
1923 | has become a keyword for Python 2.5, so we had to rename it.""" | |
1921 |
|
1924 | |||
1922 | object.__dict__.update(args) |
|
1925 | object.__dict__.update(args) | |
1923 |
|
1926 | |||
1924 | #---------------------------------------------------------------------------- |
|
1927 | #---------------------------------------------------------------------------- | |
1925 | def setattr_list(obj,alist,nspace = None): |
|
1928 | def setattr_list(obj,alist,nspace = None): | |
1926 | """Set a list of attributes for an object taken from a namespace. |
|
1929 | """Set a list of attributes for an object taken from a namespace. | |
1927 |
|
1930 | |||
1928 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in |
|
1931 | setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in | |
1929 | alist with their values taken from nspace, which must be a dict (something |
|
1932 | alist with their values taken from nspace, which must be a dict (something | |
1930 | like locals() will often do) If nspace isn't given, locals() of the |
|
1933 | like locals() will often do) If nspace isn't given, locals() of the | |
1931 | *caller* is used, so in most cases you can omit it. |
|
1934 | *caller* is used, so in most cases you can omit it. | |
1932 |
|
1935 | |||
1933 | Note that alist can be given as a string, which will be automatically |
|
1936 | Note that alist can be given as a string, which will be automatically | |
1934 | split into a list on whitespace. If given as a list, it must be a list of |
|
1937 | split into a list on whitespace. If given as a list, it must be a list of | |
1935 | *strings* (the variable names themselves), not of variables.""" |
|
1938 | *strings* (the variable names themselves), not of variables.""" | |
1936 |
|
1939 | |||
1937 | # this grabs the local variables from the *previous* call frame -- that is |
|
1940 | # this grabs the local variables from the *previous* call frame -- that is | |
1938 | # the locals from the function that called setattr_list(). |
|
1941 | # the locals from the function that called setattr_list(). | |
1939 | # - snipped from weave.inline() |
|
1942 | # - snipped from weave.inline() | |
1940 | if nspace is None: |
|
1943 | if nspace is None: | |
1941 | call_frame = sys._getframe().f_back |
|
1944 | call_frame = sys._getframe().f_back | |
1942 | nspace = call_frame.f_locals |
|
1945 | nspace = call_frame.f_locals | |
1943 |
|
1946 | |||
1944 | if type(alist) in StringTypes: |
|
1947 | if type(alist) in StringTypes: | |
1945 | alist = alist.split() |
|
1948 | alist = alist.split() | |
1946 | for attr in alist: |
|
1949 | for attr in alist: | |
1947 | val = eval(attr,nspace) |
|
1950 | val = eval(attr,nspace) | |
1948 | setattr(obj,attr,val) |
|
1951 | setattr(obj,attr,val) | |
1949 |
|
1952 | |||
1950 | #---------------------------------------------------------------------------- |
|
1953 | #---------------------------------------------------------------------------- | |
1951 | def getattr_list(obj,alist,*args): |
|
1954 | def getattr_list(obj,alist,*args): | |
1952 | """getattr_list(obj,alist[, default]) -> attribute list. |
|
1955 | """getattr_list(obj,alist[, default]) -> attribute list. | |
1953 |
|
1956 | |||
1954 | Get a list of named attributes for an object. When a default argument is |
|
1957 | Get a list of named attributes for an object. When a default argument is | |
1955 | given, it is returned when the attribute doesn't exist; without it, an |
|
1958 | given, it is returned when the attribute doesn't exist; without it, an | |
1956 | exception is raised in that case. |
|
1959 | exception is raised in that case. | |
1957 |
|
1960 | |||
1958 | Note that alist can be given as a string, which will be automatically |
|
1961 | Note that alist can be given as a string, which will be automatically | |
1959 | split into a list on whitespace. If given as a list, it must be a list of |
|
1962 | split into a list on whitespace. If given as a list, it must be a list of | |
1960 | *strings* (the variable names themselves), not of variables.""" |
|
1963 | *strings* (the variable names themselves), not of variables.""" | |
1961 |
|
1964 | |||
1962 | if type(alist) in StringTypes: |
|
1965 | if type(alist) in StringTypes: | |
1963 | alist = alist.split() |
|
1966 | alist = alist.split() | |
1964 | if args: |
|
1967 | if args: | |
1965 | if len(args)==1: |
|
1968 | if len(args)==1: | |
1966 | default = args[0] |
|
1969 | default = args[0] | |
1967 | return map(lambda attr: getattr(obj,attr,default),alist) |
|
1970 | return map(lambda attr: getattr(obj,attr,default),alist) | |
1968 | else: |
|
1971 | else: | |
1969 | raise ValueError,'getattr_list() takes only one optional argument' |
|
1972 | raise ValueError,'getattr_list() takes only one optional argument' | |
1970 | else: |
|
1973 | else: | |
1971 | return map(lambda attr: getattr(obj,attr),alist) |
|
1974 | return map(lambda attr: getattr(obj,attr),alist) | |
1972 |
|
1975 | |||
1973 | #---------------------------------------------------------------------------- |
|
1976 | #---------------------------------------------------------------------------- | |
1974 | def map_method(method,object_list,*argseq,**kw): |
|
1977 | def map_method(method,object_list,*argseq,**kw): | |
1975 | """map_method(method,object_list,*args,**kw) -> list |
|
1978 | """map_method(method,object_list,*args,**kw) -> list | |
1976 |
|
1979 | |||
1977 | Return a list of the results of applying the methods to the items of the |
|
1980 | Return a list of the results of applying the methods to the items of the | |
1978 | argument sequence(s). If more than one sequence is given, the method is |
|
1981 | argument sequence(s). If more than one sequence is given, the method is | |
1979 | called with an argument list consisting of the corresponding item of each |
|
1982 | called with an argument list consisting of the corresponding item of each | |
1980 | sequence. All sequences must be of the same length. |
|
1983 | sequence. All sequences must be of the same length. | |
1981 |
|
1984 | |||
1982 | Keyword arguments are passed verbatim to all objects called. |
|
1985 | Keyword arguments are passed verbatim to all objects called. | |
1983 |
|
1986 | |||
1984 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
1987 | This is Python code, so it's not nearly as fast as the builtin map().""" | |
1985 |
|
1988 | |||
1986 | out_list = [] |
|
1989 | out_list = [] | |
1987 | idx = 0 |
|
1990 | idx = 0 | |
1988 | for object in object_list: |
|
1991 | for object in object_list: | |
1989 | try: |
|
1992 | try: | |
1990 | handler = getattr(object, method) |
|
1993 | handler = getattr(object, method) | |
1991 | except AttributeError: |
|
1994 | except AttributeError: | |
1992 | out_list.append(None) |
|
1995 | out_list.append(None) | |
1993 | else: |
|
1996 | else: | |
1994 | if argseq: |
|
1997 | if argseq: | |
1995 | args = map(lambda lst:lst[idx],argseq) |
|
1998 | args = map(lambda lst:lst[idx],argseq) | |
1996 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
1999 | #print 'ob',object,'hand',handler,'ar',args # dbg | |
1997 | out_list.append(handler(args,**kw)) |
|
2000 | out_list.append(handler(args,**kw)) | |
1998 | else: |
|
2001 | else: | |
1999 | out_list.append(handler(**kw)) |
|
2002 | out_list.append(handler(**kw)) | |
2000 | idx += 1 |
|
2003 | idx += 1 | |
2001 | return out_list |
|
2004 | return out_list | |
2002 |
|
2005 | |||
2003 | #---------------------------------------------------------------------------- |
|
2006 | #---------------------------------------------------------------------------- | |
2004 | def get_class_members(cls): |
|
2007 | def get_class_members(cls): | |
2005 | ret = dir(cls) |
|
2008 | ret = dir(cls) | |
2006 | if hasattr(cls,'__bases__'): |
|
2009 | if hasattr(cls,'__bases__'): | |
2007 | for base in cls.__bases__: |
|
2010 | for base in cls.__bases__: | |
2008 | ret.extend(get_class_members(base)) |
|
2011 | ret.extend(get_class_members(base)) | |
2009 | return ret |
|
2012 | return ret | |
2010 |
|
2013 | |||
2011 | #---------------------------------------------------------------------------- |
|
2014 | #---------------------------------------------------------------------------- | |
2012 | def dir2(obj): |
|
2015 | def dir2(obj): | |
2013 | """dir2(obj) -> list of strings |
|
2016 | """dir2(obj) -> list of strings | |
2014 |
|
2017 | |||
2015 | Extended version of the Python builtin dir(), which does a few extra |
|
2018 | Extended version of the Python builtin dir(), which does a few extra | |
2016 | checks, and supports common objects with unusual internals that confuse |
|
2019 | checks, and supports common objects with unusual internals that confuse | |
2017 | dir(), such as Traits and PyCrust. |
|
2020 | dir(), such as Traits and PyCrust. | |
2018 |
|
2021 | |||
2019 | This version is guaranteed to return only a list of true strings, whereas |
|
2022 | This version is guaranteed to return only a list of true strings, whereas | |
2020 | dir() returns anything that objects inject into themselves, even if they |
|
2023 | dir() returns anything that objects inject into themselves, even if they | |
2021 | are later not really valid for attribute access (many extension libraries |
|
2024 | are later not really valid for attribute access (many extension libraries | |
2022 | have such bugs). |
|
2025 | have such bugs). | |
2023 | """ |
|
2026 | """ | |
2024 |
|
2027 | |||
2025 | # Start building the attribute list via dir(), and then complete it |
|
2028 | # Start building the attribute list via dir(), and then complete it | |
2026 | # with a few extra special-purpose calls. |
|
2029 | # with a few extra special-purpose calls. | |
2027 | words = dir(obj) |
|
2030 | words = dir(obj) | |
2028 |
|
2031 | |||
2029 | if hasattr(obj,'__class__'): |
|
2032 | if hasattr(obj,'__class__'): | |
2030 | words.append('__class__') |
|
2033 | words.append('__class__') | |
2031 | words.extend(get_class_members(obj.__class__)) |
|
2034 | words.extend(get_class_members(obj.__class__)) | |
2032 | #if '__base__' in words: 1/0 |
|
2035 | #if '__base__' in words: 1/0 | |
2033 |
|
2036 | |||
2034 | # Some libraries (such as traits) may introduce duplicates, we want to |
|
2037 | # Some libraries (such as traits) may introduce duplicates, we want to | |
2035 | # track and clean this up if it happens |
|
2038 | # track and clean this up if it happens | |
2036 | may_have_dupes = False |
|
2039 | may_have_dupes = False | |
2037 |
|
2040 | |||
2038 | # this is the 'dir' function for objects with Enthought's traits |
|
2041 | # this is the 'dir' function for objects with Enthought's traits | |
2039 | if hasattr(obj, 'trait_names'): |
|
2042 | if hasattr(obj, 'trait_names'): | |
2040 | try: |
|
2043 | try: | |
2041 | words.extend(obj.trait_names()) |
|
2044 | words.extend(obj.trait_names()) | |
2042 | may_have_dupes = True |
|
2045 | may_have_dupes = True | |
2043 | except TypeError: |
|
2046 | except TypeError: | |
2044 | # This will happen if `obj` is a class and not an instance. |
|
2047 | # This will happen if `obj` is a class and not an instance. | |
2045 | pass |
|
2048 | pass | |
2046 |
|
2049 | |||
2047 | # Support for PyCrust-style _getAttributeNames magic method. |
|
2050 | # Support for PyCrust-style _getAttributeNames magic method. | |
2048 | if hasattr(obj, '_getAttributeNames'): |
|
2051 | if hasattr(obj, '_getAttributeNames'): | |
2049 | try: |
|
2052 | try: | |
2050 | words.extend(obj._getAttributeNames()) |
|
2053 | words.extend(obj._getAttributeNames()) | |
2051 | may_have_dupes = True |
|
2054 | may_have_dupes = True | |
2052 | except TypeError: |
|
2055 | except TypeError: | |
2053 | # `obj` is a class and not an instance. Ignore |
|
2056 | # `obj` is a class and not an instance. Ignore | |
2054 | # this error. |
|
2057 | # this error. | |
2055 | pass |
|
2058 | pass | |
2056 |
|
2059 | |||
2057 | if may_have_dupes: |
|
2060 | if may_have_dupes: | |
2058 | # eliminate possible duplicates, as some traits may also |
|
2061 | # eliminate possible duplicates, as some traits may also | |
2059 | # appear as normal attributes in the dir() call. |
|
2062 | # appear as normal attributes in the dir() call. | |
2060 | words = list(set(words)) |
|
2063 | words = list(set(words)) | |
2061 | words.sort() |
|
2064 | words.sort() | |
2062 |
|
2065 | |||
2063 | # filter out non-string attributes which may be stuffed by dir() calls |
|
2066 | # filter out non-string attributes which may be stuffed by dir() calls | |
2064 | # and poor coding in third-party modules |
|
2067 | # and poor coding in third-party modules | |
2065 | return [w for w in words if isinstance(w, basestring)] |
|
2068 | return [w for w in words if isinstance(w, basestring)] | |
2066 |
|
2069 | |||
2067 | #---------------------------------------------------------------------------- |
|
2070 | #---------------------------------------------------------------------------- | |
2068 | def import_fail_info(mod_name,fns=None): |
|
2071 | def import_fail_info(mod_name,fns=None): | |
2069 | """Inform load failure for a module.""" |
|
2072 | """Inform load failure for a module.""" | |
2070 |
|
2073 | |||
2071 | if fns == None: |
|
2074 | if fns == None: | |
2072 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
2075 | warn("Loading of %s failed.\n" % (mod_name,)) | |
2073 | else: |
|
2076 | else: | |
2074 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
2077 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) | |
2075 |
|
2078 | |||
2076 | #---------------------------------------------------------------------------- |
|
2079 | #---------------------------------------------------------------------------- | |
2077 | # Proposed popitem() extension, written as a method |
|
2080 | # Proposed popitem() extension, written as a method | |
2078 |
|
2081 | |||
2079 |
|
2082 | |||
2080 | class NotGiven: pass |
|
2083 | class NotGiven: pass | |
2081 |
|
2084 | |||
2082 | def popkey(dct,key,default=NotGiven): |
|
2085 | def popkey(dct,key,default=NotGiven): | |
2083 | """Return dct[key] and delete dct[key]. |
|
2086 | """Return dct[key] and delete dct[key]. | |
2084 |
|
2087 | |||
2085 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
2088 | If default is given, return it if dct[key] doesn't exist, otherwise raise | |
2086 | KeyError. """ |
|
2089 | KeyError. """ | |
2087 |
|
2090 | |||
2088 | try: |
|
2091 | try: | |
2089 | val = dct[key] |
|
2092 | val = dct[key] | |
2090 | except KeyError: |
|
2093 | except KeyError: | |
2091 | if default is NotGiven: |
|
2094 | if default is NotGiven: | |
2092 | raise |
|
2095 | raise | |
2093 | else: |
|
2096 | else: | |
2094 | return default |
|
2097 | return default | |
2095 | else: |
|
2098 | else: | |
2096 | del dct[key] |
|
2099 | del dct[key] | |
2097 | return val |
|
2100 | return val | |
2098 |
|
2101 | |||
2099 | def wrap_deprecated(func, suggest = '<nothing>'): |
|
2102 | def wrap_deprecated(func, suggest = '<nothing>'): | |
2100 | def newFunc(*args, **kwargs): |
|
2103 | def newFunc(*args, **kwargs): | |
2101 | warnings.warn("Call to deprecated function %s, use %s instead" % |
|
2104 | warnings.warn("Call to deprecated function %s, use %s instead" % | |
2102 | ( func.__name__, suggest), |
|
2105 | ( func.__name__, suggest), | |
2103 | category=DeprecationWarning, |
|
2106 | category=DeprecationWarning, | |
2104 | stacklevel = 2) |
|
2107 | stacklevel = 2) | |
2105 | return func(*args, **kwargs) |
|
2108 | return func(*args, **kwargs) | |
2106 | return newFunc |
|
2109 | return newFunc | |
2107 |
|
2110 | |||
2108 |
|
2111 | |||
2109 | def _num_cpus_unix(): |
|
2112 | def _num_cpus_unix(): | |
2110 | """Return the number of active CPUs on a Unix system.""" |
|
2113 | """Return the number of active CPUs on a Unix system.""" | |
2111 | return os.sysconf("SC_NPROCESSORS_ONLN") |
|
2114 | return os.sysconf("SC_NPROCESSORS_ONLN") | |
2112 |
|
2115 | |||
2113 |
|
2116 | |||
2114 | def _num_cpus_darwin(): |
|
2117 | def _num_cpus_darwin(): | |
2115 | """Return the number of active CPUs on a Darwin system.""" |
|
2118 | """Return the number of active CPUs on a Darwin system.""" | |
2116 | p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) |
|
2119 | p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) | |
2117 | return p.stdout.read() |
|
2120 | return p.stdout.read() | |
2118 |
|
2121 | |||
2119 |
|
2122 | |||
2120 | def _num_cpus_windows(): |
|
2123 | def _num_cpus_windows(): | |
2121 | """Return the number of active CPUs on a Windows system.""" |
|
2124 | """Return the number of active CPUs on a Windows system.""" | |
2122 | return os.environ.get("NUMBER_OF_PROCESSORS") |
|
2125 | return os.environ.get("NUMBER_OF_PROCESSORS") | |
2123 |
|
2126 | |||
2124 |
|
2127 | |||
2125 | def num_cpus(): |
|
2128 | def num_cpus(): | |
2126 | """Return the effective number of CPUs in the system as an integer. |
|
2129 | """Return the effective number of CPUs in the system as an integer. | |
2127 |
|
2130 | |||
2128 | This cross-platform function makes an attempt at finding the total number of |
|
2131 | This cross-platform function makes an attempt at finding the total number of | |
2129 | available CPUs in the system, as returned by various underlying system and |
|
2132 | available CPUs in the system, as returned by various underlying system and | |
2130 | python calls. |
|
2133 | python calls. | |
2131 |
|
2134 | |||
2132 | If it can't find a sensible answer, it returns 1 (though an error *may* make |
|
2135 | If it can't find a sensible answer, it returns 1 (though an error *may* make | |
2133 | it return a large positive number that's actually incorrect). |
|
2136 | it return a large positive number that's actually incorrect). | |
2134 | """ |
|
2137 | """ | |
2135 |
|
2138 | |||
2136 | # Many thanks to the Parallel Python project (http://www.parallelpython.com) |
|
2139 | # Many thanks to the Parallel Python project (http://www.parallelpython.com) | |
2137 | # for the names of the keys we needed to look up for this function. This |
|
2140 | # for the names of the keys we needed to look up for this function. This | |
2138 | # code was inspired by their equivalent function. |
|
2141 | # code was inspired by their equivalent function. | |
2139 |
|
2142 | |||
2140 | ncpufuncs = {'Linux':_num_cpus_unix, |
|
2143 | ncpufuncs = {'Linux':_num_cpus_unix, | |
2141 | 'Darwin':_num_cpus_darwin, |
|
2144 | 'Darwin':_num_cpus_darwin, | |
2142 | 'Windows':_num_cpus_windows, |
|
2145 | 'Windows':_num_cpus_windows, | |
2143 | # On Vista, python < 2.5.2 has a bug and returns 'Microsoft' |
|
2146 | # On Vista, python < 2.5.2 has a bug and returns 'Microsoft' | |
2144 | # See http://bugs.python.org/issue1082 for details. |
|
2147 | # See http://bugs.python.org/issue1082 for details. | |
2145 | 'Microsoft':_num_cpus_windows, |
|
2148 | 'Microsoft':_num_cpus_windows, | |
2146 | } |
|
2149 | } | |
2147 |
|
2150 | |||
2148 | ncpufunc = ncpufuncs.get(platform.system(), |
|
2151 | ncpufunc = ncpufuncs.get(platform.system(), | |
2149 | # default to unix version (Solaris, AIX, etc) |
|
2152 | # default to unix version (Solaris, AIX, etc) | |
2150 | _num_cpus_unix) |
|
2153 | _num_cpus_unix) | |
2151 |
|
2154 | |||
2152 | try: |
|
2155 | try: | |
2153 | ncpus = max(1,int(ncpufunc())) |
|
2156 | ncpus = max(1,int(ncpufunc())) | |
2154 | except: |
|
2157 | except: | |
2155 | ncpus = 1 |
|
2158 | ncpus = 1 | |
2156 | return ncpus |
|
2159 | return ncpus | |
2157 |
|
2160 | |||
2158 | #*************************** end of file <genutils.py> ********************** |
|
2161 | #*************************** end of file <genutils.py> ********************** |
@@ -1,2789 +1,2790 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.4 or newer. |
|
5 | Requires Python 2.4 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 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
11 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | # |
|
16 | # | |
17 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
17 | # Note: this code originally subclassed code.InteractiveConsole from the | |
18 | # Python standard library. Over time, all of that class has been copied |
|
18 | # Python standard library. Over time, all of that class has been copied | |
19 | # verbatim here for modifications which could not be accomplished by |
|
19 | # verbatim here for modifications which could not be accomplished by | |
20 | # subclassing. At this point, there are no dependencies at all on the code |
|
20 | # subclassing. At this point, there are no dependencies at all on the code | |
21 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
21 | # module anymore (it is not even imported). The Python License (sec. 2) | |
22 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
22 | # allows for this, but it's always nice to acknowledge credit where credit is | |
23 | # due. |
|
23 | # due. | |
24 | #***************************************************************************** |
|
24 | #***************************************************************************** | |
25 |
|
25 | |||
26 | #**************************************************************************** |
|
26 | #**************************************************************************** | |
27 | # Modules and globals |
|
27 | # Modules and globals | |
28 |
|
28 | |||
29 | # Python standard modules |
|
29 | # Python standard modules | |
30 | import __main__ |
|
30 | import __main__ | |
31 | import __builtin__ |
|
31 | import __builtin__ | |
32 | import StringIO |
|
32 | import StringIO | |
33 | import bdb |
|
33 | import bdb | |
34 | import cPickle as pickle |
|
34 | import cPickle as pickle | |
35 | import codeop |
|
35 | import codeop | |
36 | import exceptions |
|
36 | import exceptions | |
37 | import glob |
|
37 | import glob | |
38 | import inspect |
|
38 | import inspect | |
39 | import keyword |
|
39 | import keyword | |
40 | import new |
|
40 | import new | |
41 | import os |
|
41 | import os | |
42 | import pydoc |
|
42 | import pydoc | |
43 | import re |
|
43 | import re | |
44 | import shutil |
|
44 | import shutil | |
45 | import string |
|
45 | import string | |
46 | import sys |
|
46 | import sys | |
47 | import tempfile |
|
47 | import tempfile | |
48 | import traceback |
|
48 | import traceback | |
49 | import types |
|
49 | import types | |
50 | from pprint import pprint, pformat |
|
50 | from pprint import pprint, pformat | |
51 |
|
51 | |||
52 | # IPython's own modules |
|
52 | # IPython's own modules | |
53 | #import IPython |
|
53 | #import IPython | |
54 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
54 | from IPython import Debugger,OInspect,PyColorize,ultraTB | |
55 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
55 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names | |
56 | from IPython.Extensions import pickleshare |
|
56 | from IPython.Extensions import pickleshare | |
57 | from IPython.FakeModule import FakeModule |
|
57 | from IPython.FakeModule import FakeModule | |
58 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
58 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
59 | from IPython.Logger import Logger |
|
59 | from IPython.Logger import Logger | |
60 | from IPython.Magic import Magic |
|
60 | from IPython.Magic import Magic | |
61 | from IPython.Prompts import CachedOutput |
|
61 | from IPython.Prompts import CachedOutput | |
62 | from IPython.ipstruct import Struct |
|
62 | from IPython.ipstruct import Struct | |
63 | from IPython.background_jobs import BackgroundJobManager |
|
63 | from IPython.background_jobs import BackgroundJobManager | |
64 | from IPython.usage import cmd_line_usage,interactive_usage |
|
64 | from IPython.usage import cmd_line_usage,interactive_usage | |
65 | from IPython.genutils import * |
|
65 | from IPython.genutils import * | |
66 | from IPython.strdispatch import StrDispatch |
|
66 | from IPython.strdispatch import StrDispatch | |
67 | import IPython.ipapi |
|
67 | import IPython.ipapi | |
68 | import IPython.history |
|
68 | import IPython.history | |
69 | import IPython.prefilter as prefilter |
|
69 | import IPython.prefilter as prefilter | |
70 | import IPython.shadowns |
|
70 | import IPython.shadowns | |
71 | # Globals |
|
71 | # Globals | |
72 |
|
72 | |||
73 | # store the builtin raw_input globally, and use this always, in case user code |
|
73 | # store the builtin raw_input globally, and use this always, in case user code | |
74 | # overwrites it (like wx.py.PyShell does) |
|
74 | # overwrites it (like wx.py.PyShell does) | |
75 | raw_input_original = raw_input |
|
75 | raw_input_original = raw_input | |
76 |
|
76 | |||
77 | # compiled regexps for autoindent management |
|
77 | # compiled regexps for autoindent management | |
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
79 |
|
79 | |||
80 |
|
80 | |||
81 | #**************************************************************************** |
|
81 | #**************************************************************************** | |
82 | # Some utility function definitions |
|
82 | # Some utility function definitions | |
83 |
|
83 | |||
84 | ini_spaces_re = re.compile(r'^(\s+)') |
|
84 | ini_spaces_re = re.compile(r'^(\s+)') | |
85 |
|
85 | |||
86 | def num_ini_spaces(strng): |
|
86 | def num_ini_spaces(strng): | |
87 | """Return the number of initial spaces in a string""" |
|
87 | """Return the number of initial spaces in a string""" | |
88 |
|
88 | |||
89 | ini_spaces = ini_spaces_re.match(strng) |
|
89 | ini_spaces = ini_spaces_re.match(strng) | |
90 | if ini_spaces: |
|
90 | if ini_spaces: | |
91 | return ini_spaces.end() |
|
91 | return ini_spaces.end() | |
92 | else: |
|
92 | else: | |
93 | return 0 |
|
93 | return 0 | |
94 |
|
94 | |||
95 | def softspace(file, newvalue): |
|
95 | def softspace(file, newvalue): | |
96 | """Copied from code.py, to remove the dependency""" |
|
96 | """Copied from code.py, to remove the dependency""" | |
97 |
|
97 | |||
98 | oldvalue = 0 |
|
98 | oldvalue = 0 | |
99 | try: |
|
99 | try: | |
100 | oldvalue = file.softspace |
|
100 | oldvalue = file.softspace | |
101 | except AttributeError: |
|
101 | except AttributeError: | |
102 | pass |
|
102 | pass | |
103 | try: |
|
103 | try: | |
104 | file.softspace = newvalue |
|
104 | file.softspace = newvalue | |
105 | except (AttributeError, TypeError): |
|
105 | except (AttributeError, TypeError): | |
106 | # "attribute-less object" or "read-only attributes" |
|
106 | # "attribute-less object" or "read-only attributes" | |
107 | pass |
|
107 | pass | |
108 | return oldvalue |
|
108 | return oldvalue | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | #**************************************************************************** |
|
111 | #**************************************************************************** | |
112 | # Local use exceptions |
|
112 | # Local use exceptions | |
113 | class SpaceInInput(exceptions.Exception): pass |
|
113 | class SpaceInInput(exceptions.Exception): pass | |
114 |
|
114 | |||
115 |
|
115 | |||
116 | #**************************************************************************** |
|
116 | #**************************************************************************** | |
117 | # Local use classes |
|
117 | # Local use classes | |
118 | class Bunch: pass |
|
118 | class Bunch: pass | |
119 |
|
119 | |||
120 | class Undefined: pass |
|
120 | class Undefined: pass | |
121 |
|
121 | |||
122 | class Quitter(object): |
|
122 | class Quitter(object): | |
123 | """Simple class to handle exit, similar to Python 2.5's. |
|
123 | """Simple class to handle exit, similar to Python 2.5's. | |
124 |
|
124 | |||
125 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
125 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 | |
126 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
126 | doesn't do (obviously, since it doesn't know about ipython).""" | |
127 |
|
127 | |||
128 | def __init__(self,shell,name): |
|
128 | def __init__(self,shell,name): | |
129 | self.shell = shell |
|
129 | self.shell = shell | |
130 | self.name = name |
|
130 | self.name = name | |
131 |
|
131 | |||
132 | def __repr__(self): |
|
132 | def __repr__(self): | |
133 | return 'Type %s() to exit.' % self.name |
|
133 | return 'Type %s() to exit.' % self.name | |
134 | __str__ = __repr__ |
|
134 | __str__ = __repr__ | |
135 |
|
135 | |||
136 | def __call__(self): |
|
136 | def __call__(self): | |
137 | self.shell.exit() |
|
137 | self.shell.exit() | |
138 |
|
138 | |||
139 | class InputList(list): |
|
139 | class InputList(list): | |
140 | """Class to store user input. |
|
140 | """Class to store user input. | |
141 |
|
141 | |||
142 | It's basically a list, but slices return a string instead of a list, thus |
|
142 | It's basically a list, but slices return a string instead of a list, thus | |
143 | allowing things like (assuming 'In' is an instance): |
|
143 | allowing things like (assuming 'In' is an instance): | |
144 |
|
144 | |||
145 | exec In[4:7] |
|
145 | exec In[4:7] | |
146 |
|
146 | |||
147 | or |
|
147 | or | |
148 |
|
148 | |||
149 | exec In[5:9] + In[14] + In[21:25]""" |
|
149 | exec In[5:9] + In[14] + In[21:25]""" | |
150 |
|
150 | |||
151 | def __getslice__(self,i,j): |
|
151 | def __getslice__(self,i,j): | |
152 | return ''.join(list.__getslice__(self,i,j)) |
|
152 | return ''.join(list.__getslice__(self,i,j)) | |
153 |
|
153 | |||
154 | class SyntaxTB(ultraTB.ListTB): |
|
154 | class SyntaxTB(ultraTB.ListTB): | |
155 | """Extension which holds some state: the last exception value""" |
|
155 | """Extension which holds some state: the last exception value""" | |
156 |
|
156 | |||
157 | def __init__(self,color_scheme = 'NoColor'): |
|
157 | def __init__(self,color_scheme = 'NoColor'): | |
158 | ultraTB.ListTB.__init__(self,color_scheme) |
|
158 | ultraTB.ListTB.__init__(self,color_scheme) | |
159 | self.last_syntax_error = None |
|
159 | self.last_syntax_error = None | |
160 |
|
160 | |||
161 | def __call__(self, etype, value, elist): |
|
161 | def __call__(self, etype, value, elist): | |
162 | self.last_syntax_error = value |
|
162 | self.last_syntax_error = value | |
163 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
163 | ultraTB.ListTB.__call__(self,etype,value,elist) | |
164 |
|
164 | |||
165 | def clear_err_state(self): |
|
165 | def clear_err_state(self): | |
166 | """Return the current error state and clear it""" |
|
166 | """Return the current error state and clear it""" | |
167 | e = self.last_syntax_error |
|
167 | e = self.last_syntax_error | |
168 | self.last_syntax_error = None |
|
168 | self.last_syntax_error = None | |
169 | return e |
|
169 | return e | |
170 |
|
170 | |||
171 | #**************************************************************************** |
|
171 | #**************************************************************************** | |
172 | # Main IPython class |
|
172 | # Main IPython class | |
173 |
|
173 | |||
174 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
174 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |
175 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
175 | # until a full rewrite is made. I've cleaned all cross-class uses of | |
176 | # attributes and methods, but too much user code out there relies on the |
|
176 | # attributes and methods, but too much user code out there relies on the | |
177 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
177 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |
178 | # |
|
178 | # | |
179 | # But at least now, all the pieces have been separated and we could, in |
|
179 | # But at least now, all the pieces have been separated and we could, in | |
180 | # principle, stop using the mixin. This will ease the transition to the |
|
180 | # principle, stop using the mixin. This will ease the transition to the | |
181 | # chainsaw branch. |
|
181 | # chainsaw branch. | |
182 |
|
182 | |||
183 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
183 | # For reference, the following is the list of 'self.foo' uses in the Magic | |
184 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
184 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |
185 | # class, to prevent clashes. |
|
185 | # class, to prevent clashes. | |
186 |
|
186 | |||
187 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
187 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |
188 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
188 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |
189 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
189 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |
190 | # 'self.value'] |
|
190 | # 'self.value'] | |
191 |
|
191 | |||
192 | class InteractiveShell(object,Magic): |
|
192 | class InteractiveShell(object,Magic): | |
193 | """An enhanced console for Python.""" |
|
193 | """An enhanced console for Python.""" | |
194 |
|
194 | |||
195 | # class attribute to indicate whether the class supports threads or not. |
|
195 | # class attribute to indicate whether the class supports threads or not. | |
196 | # Subclasses with thread support should override this as needed. |
|
196 | # Subclasses with thread support should override this as needed. | |
197 | isthreaded = False |
|
197 | isthreaded = False | |
198 |
|
198 | |||
199 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
199 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
200 | user_ns=None,user_global_ns=None,banner2='', |
|
200 | user_ns=None,user_global_ns=None,banner2='', | |
201 | custom_exceptions=((),None),embedded=False): |
|
201 | custom_exceptions=((),None),embedded=False): | |
202 |
|
202 | |||
203 | # log system |
|
203 | # log system | |
204 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
204 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
205 |
|
205 | |||
206 | # Job manager (for jobs run as background threads) |
|
206 | # Job manager (for jobs run as background threads) | |
207 | self.jobs = BackgroundJobManager() |
|
207 | self.jobs = BackgroundJobManager() | |
208 |
|
208 | |||
209 | # Store the actual shell's name |
|
209 | # Store the actual shell's name | |
210 | self.name = name |
|
210 | self.name = name | |
211 | self.more = False |
|
211 | self.more = False | |
212 |
|
212 | |||
213 | # We need to know whether the instance is meant for embedding, since |
|
213 | # We need to know whether the instance is meant for embedding, since | |
214 | # global/local namespaces need to be handled differently in that case |
|
214 | # global/local namespaces need to be handled differently in that case | |
215 | self.embedded = embedded |
|
215 | self.embedded = embedded | |
216 | if embedded: |
|
216 | if embedded: | |
217 | # Control variable so users can, from within the embedded instance, |
|
217 | # Control variable so users can, from within the embedded instance, | |
218 | # permanently deactivate it. |
|
218 | # permanently deactivate it. | |
219 | self.embedded_active = True |
|
219 | self.embedded_active = True | |
220 |
|
220 | |||
221 | # command compiler |
|
221 | # command compiler | |
222 | self.compile = codeop.CommandCompiler() |
|
222 | self.compile = codeop.CommandCompiler() | |
223 |
|
223 | |||
224 | # User input buffer |
|
224 | # User input buffer | |
225 | self.buffer = [] |
|
225 | self.buffer = [] | |
226 |
|
226 | |||
227 | # Default name given in compilation of code |
|
227 | # Default name given in compilation of code | |
228 | self.filename = '<ipython console>' |
|
228 | self.filename = '<ipython console>' | |
229 |
|
229 | |||
230 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
230 | # Install our own quitter instead of the builtins. For python2.3-2.4, | |
231 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
231 | # this brings in behavior like 2.5, and for 2.5 it's identical. | |
232 | __builtin__.exit = Quitter(self,'exit') |
|
232 | __builtin__.exit = Quitter(self,'exit') | |
233 | __builtin__.quit = Quitter(self,'quit') |
|
233 | __builtin__.quit = Quitter(self,'quit') | |
234 |
|
234 | |||
235 | # Make an empty namespace, which extension writers can rely on both |
|
235 | # Make an empty namespace, which extension writers can rely on both | |
236 | # existing and NEVER being used by ipython itself. This gives them a |
|
236 | # existing and NEVER being used by ipython itself. This gives them a | |
237 | # convenient location for storing additional information and state |
|
237 | # convenient location for storing additional information and state | |
238 | # their extensions may require, without fear of collisions with other |
|
238 | # their extensions may require, without fear of collisions with other | |
239 | # ipython names that may develop later. |
|
239 | # ipython names that may develop later. | |
240 | self.meta = Struct() |
|
240 | self.meta = Struct() | |
241 |
|
241 | |||
242 | # Create the namespace where the user will operate. user_ns is |
|
242 | # Create the namespace where the user will operate. user_ns is | |
243 | # normally the only one used, and it is passed to the exec calls as |
|
243 | # normally the only one used, and it is passed to the exec calls as | |
244 | # the locals argument. But we do carry a user_global_ns namespace |
|
244 | # the locals argument. But we do carry a user_global_ns namespace | |
245 | # given as the exec 'globals' argument, This is useful in embedding |
|
245 | # given as the exec 'globals' argument, This is useful in embedding | |
246 | # situations where the ipython shell opens in a context where the |
|
246 | # situations where the ipython shell opens in a context where the | |
247 | # distinction between locals and globals is meaningful. For |
|
247 | # distinction between locals and globals is meaningful. For | |
248 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
248 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
249 |
|
249 | |||
250 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
250 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
251 | # level as a dict instead of a module. This is a manual fix, but I |
|
251 | # level as a dict instead of a module. This is a manual fix, but I | |
252 | # should really track down where the problem is coming from. Alex |
|
252 | # should really track down where the problem is coming from. Alex | |
253 | # Schmolck reported this problem first. |
|
253 | # Schmolck reported this problem first. | |
254 |
|
254 | |||
255 | # A useful post by Alex Martelli on this topic: |
|
255 | # A useful post by Alex Martelli on this topic: | |
256 | # Re: inconsistent value from __builtins__ |
|
256 | # Re: inconsistent value from __builtins__ | |
257 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
257 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
258 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
258 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
259 | # Gruppen: comp.lang.python |
|
259 | # Gruppen: comp.lang.python | |
260 |
|
260 | |||
261 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
261 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
262 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
262 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
263 | # > <type 'dict'> |
|
263 | # > <type 'dict'> | |
264 | # > >>> print type(__builtins__) |
|
264 | # > >>> print type(__builtins__) | |
265 | # > <type 'module'> |
|
265 | # > <type 'module'> | |
266 | # > Is this difference in return value intentional? |
|
266 | # > Is this difference in return value intentional? | |
267 |
|
267 | |||
268 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
268 | # Well, it's documented that '__builtins__' can be either a dictionary | |
269 | # or a module, and it's been that way for a long time. Whether it's |
|
269 | # or a module, and it's been that way for a long time. Whether it's | |
270 | # intentional (or sensible), I don't know. In any case, the idea is |
|
270 | # intentional (or sensible), I don't know. In any case, the idea is | |
271 | # that if you need to access the built-in namespace directly, you |
|
271 | # that if you need to access the built-in namespace directly, you | |
272 | # should start with "import __builtin__" (note, no 's') which will |
|
272 | # should start with "import __builtin__" (note, no 's') which will | |
273 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
273 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
274 |
|
274 | |||
275 | # These routines return properly built dicts as needed by the rest of |
|
275 | # These routines return properly built dicts as needed by the rest of | |
276 | # the code, and can also be used by extension writers to generate |
|
276 | # the code, and can also be used by extension writers to generate | |
277 | # properly initialized namespaces. |
|
277 | # properly initialized namespaces. | |
278 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, |
|
278 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, | |
279 | user_global_ns) |
|
279 | user_global_ns) | |
280 |
|
280 | |||
281 | # Assign namespaces |
|
281 | # Assign namespaces | |
282 | # This is the namespace where all normal user variables live |
|
282 | # This is the namespace where all normal user variables live | |
283 | self.user_ns = user_ns |
|
283 | self.user_ns = user_ns | |
284 | self.user_global_ns = user_global_ns |
|
284 | self.user_global_ns = user_global_ns | |
285 |
|
285 | |||
286 | # An auxiliary namespace that checks what parts of the user_ns were |
|
286 | # An auxiliary namespace that checks what parts of the user_ns were | |
287 | # loaded at startup, so we can list later only variables defined in |
|
287 | # loaded at startup, so we can list later only variables defined in | |
288 | # actual interactive use. Since it is always a subset of user_ns, it |
|
288 | # actual interactive use. Since it is always a subset of user_ns, it | |
289 | # doesn't need to be seaparately tracked in the ns_table |
|
289 | # doesn't need to be seaparately tracked in the ns_table | |
290 | self.user_config_ns = {} |
|
290 | self.user_config_ns = {} | |
291 |
|
291 | |||
292 | # A namespace to keep track of internal data structures to prevent |
|
292 | # A namespace to keep track of internal data structures to prevent | |
293 | # them from cluttering user-visible stuff. Will be updated later |
|
293 | # them from cluttering user-visible stuff. Will be updated later | |
294 | self.internal_ns = {} |
|
294 | self.internal_ns = {} | |
295 |
|
295 | |||
296 | # Namespace of system aliases. Each entry in the alias |
|
296 | # Namespace of system aliases. Each entry in the alias | |
297 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
297 | # table must be a 2-tuple of the form (N,name), where N is the number | |
298 | # of positional arguments of the alias. |
|
298 | # of positional arguments of the alias. | |
299 | self.alias_table = {} |
|
299 | self.alias_table = {} | |
300 |
|
300 | |||
301 | # Now that FakeModule produces a real module, we've run into a nasty |
|
301 | # Now that FakeModule produces a real module, we've run into a nasty | |
302 | # problem: after script execution (via %run), the module where the user |
|
302 | # problem: after script execution (via %run), the module where the user | |
303 | # code ran is deleted. Now that this object is a true module (needed |
|
303 | # code ran is deleted. Now that this object is a true module (needed | |
304 | # so docetst and other tools work correctly), the Python module |
|
304 | # so docetst and other tools work correctly), the Python module | |
305 | # teardown mechanism runs over it, and sets to None every variable |
|
305 | # teardown mechanism runs over it, and sets to None every variable | |
306 | # present in that module. Top-level references to objects from the |
|
306 | # present in that module. Top-level references to objects from the | |
307 | # script survive, because the user_ns is updated with them. However, |
|
307 | # script survive, because the user_ns is updated with them. However, | |
308 | # calling functions defined in the script that use other things from |
|
308 | # calling functions defined in the script that use other things from | |
309 | # the script will fail, because the function's closure had references |
|
309 | # the script will fail, because the function's closure had references | |
310 | # to the original objects, which are now all None. So we must protect |
|
310 | # to the original objects, which are now all None. So we must protect | |
311 | # these modules from deletion by keeping a cache. To avoid keeping |
|
311 | # these modules from deletion by keeping a cache. To avoid keeping | |
312 | # stale modules around (we only need the one from the last run), we use |
|
312 | # stale modules around (we only need the one from the last run), we use | |
313 | # a dict keyed with the full path to the script, so only the last |
|
313 | # a dict keyed with the full path to the script, so only the last | |
314 | # version of the module is held in the cache. The %reset command will |
|
314 | # version of the module is held in the cache. The %reset command will | |
315 | # flush this cache. See the cache_main_mod() and clear_main_mod_cache() |
|
315 | # flush this cache. See the cache_main_mod() and clear_main_mod_cache() | |
316 | # methods for details on use. |
|
316 | # methods for details on use. | |
317 | self._user_main_modules = {} |
|
317 | self._user_main_modules = {} | |
318 |
|
318 | |||
319 | # A table holding all the namespaces IPython deals with, so that |
|
319 | # A table holding all the namespaces IPython deals with, so that | |
320 | # introspection facilities can search easily. |
|
320 | # introspection facilities can search easily. | |
321 | self.ns_table = {'user':user_ns, |
|
321 | self.ns_table = {'user':user_ns, | |
322 | 'user_global':user_global_ns, |
|
322 | 'user_global':user_global_ns, | |
323 | 'alias':self.alias_table, |
|
323 | 'alias':self.alias_table, | |
324 | 'internal':self.internal_ns, |
|
324 | 'internal':self.internal_ns, | |
325 | 'builtin':__builtin__.__dict__ |
|
325 | 'builtin':__builtin__.__dict__ | |
326 | } |
|
326 | } | |
327 |
|
327 | |||
328 | # Similarly, track all namespaces where references can be held and that |
|
328 | # Similarly, track all namespaces where references can be held and that | |
329 | # we can safely clear (so it can NOT include builtin). This one can be |
|
329 | # we can safely clear (so it can NOT include builtin). This one can be | |
330 | # a simple list. |
|
330 | # a simple list. | |
331 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
331 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |
332 | self.alias_table, self.internal_ns, |
|
332 | self.alias_table, self.internal_ns, | |
333 | self._user_main_modules ] |
|
333 | self._user_main_modules ] | |
334 |
|
334 | |||
335 | # We need to insert into sys.modules something that looks like a |
|
335 | # We need to insert into sys.modules something that looks like a | |
336 | # module but which accesses the IPython namespace, for shelve and |
|
336 | # module but which accesses the IPython namespace, for shelve and | |
337 | # pickle to work interactively. Normally they rely on getting |
|
337 | # pickle to work interactively. Normally they rely on getting | |
338 | # everything out of __main__, but for embedding purposes each IPython |
|
338 | # everything out of __main__, but for embedding purposes each IPython | |
339 | # instance has its own private namespace, so we can't go shoving |
|
339 | # instance has its own private namespace, so we can't go shoving | |
340 | # everything into __main__. |
|
340 | # everything into __main__. | |
341 |
|
341 | |||
342 | # note, however, that we should only do this for non-embedded |
|
342 | # note, however, that we should only do this for non-embedded | |
343 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
343 | # ipythons, which really mimic the __main__.__dict__ with their own | |
344 | # namespace. Embedded instances, on the other hand, should not do |
|
344 | # namespace. Embedded instances, on the other hand, should not do | |
345 | # this because they need to manage the user local/global namespaces |
|
345 | # this because they need to manage the user local/global namespaces | |
346 | # only, but they live within a 'normal' __main__ (meaning, they |
|
346 | # only, but they live within a 'normal' __main__ (meaning, they | |
347 | # shouldn't overtake the execution environment of the script they're |
|
347 | # shouldn't overtake the execution environment of the script they're | |
348 | # embedded in). |
|
348 | # embedded in). | |
349 |
|
349 | |||
350 | if not embedded: |
|
350 | if not embedded: | |
351 | try: |
|
351 | try: | |
352 | main_name = self.user_ns['__name__'] |
|
352 | main_name = self.user_ns['__name__'] | |
353 | except KeyError: |
|
353 | except KeyError: | |
354 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
354 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
355 | else: |
|
355 | else: | |
356 | #print "pickle hack in place" # dbg |
|
356 | #print "pickle hack in place" # dbg | |
357 | #print 'main_name:',main_name # dbg |
|
357 | #print 'main_name:',main_name # dbg | |
358 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
358 | sys.modules[main_name] = FakeModule(self.user_ns) | |
359 |
|
359 | |||
360 | # List of input with multi-line handling. |
|
360 | # List of input with multi-line handling. | |
361 | self.input_hist = InputList() |
|
361 | self.input_hist = InputList() | |
362 | # This one will hold the 'raw' input history, without any |
|
362 | # This one will hold the 'raw' input history, without any | |
363 | # pre-processing. This will allow users to retrieve the input just as |
|
363 | # pre-processing. This will allow users to retrieve the input just as | |
364 | # it was exactly typed in by the user, with %hist -r. |
|
364 | # it was exactly typed in by the user, with %hist -r. | |
365 | self.input_hist_raw = InputList() |
|
365 | self.input_hist_raw = InputList() | |
366 |
|
366 | |||
367 | # list of visited directories |
|
367 | # list of visited directories | |
368 | try: |
|
368 | try: | |
369 | self.dir_hist = [os.getcwd()] |
|
369 | self.dir_hist = [os.getcwd()] | |
370 | except OSError: |
|
370 | except OSError: | |
371 | self.dir_hist = [] |
|
371 | self.dir_hist = [] | |
372 |
|
372 | |||
373 | # dict of output history |
|
373 | # dict of output history | |
374 | self.output_hist = {} |
|
374 | self.output_hist = {} | |
375 |
|
375 | |||
376 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
376 | # Get system encoding at startup time. Certain terminals (like Emacs | |
377 | # under Win32 have it set to None, and we need to have a known valid |
|
377 | # under Win32 have it set to None, and we need to have a known valid | |
378 | # encoding to use in the raw_input() method |
|
378 | # encoding to use in the raw_input() method | |
379 | try: |
|
379 | try: | |
380 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
380 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
381 | except AttributeError: |
|
381 | except AttributeError: | |
382 | self.stdin_encoding = 'ascii' |
|
382 | self.stdin_encoding = 'ascii' | |
383 |
|
383 | |||
384 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
384 | # dict of things NOT to alias (keywords, builtins and some magics) | |
385 | no_alias = {} |
|
385 | no_alias = {} | |
386 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
386 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
387 | for key in keyword.kwlist + no_alias_magics: |
|
387 | for key in keyword.kwlist + no_alias_magics: | |
388 | no_alias[key] = 1 |
|
388 | no_alias[key] = 1 | |
389 | no_alias.update(__builtin__.__dict__) |
|
389 | no_alias.update(__builtin__.__dict__) | |
390 | self.no_alias = no_alias |
|
390 | self.no_alias = no_alias | |
391 |
|
391 | |||
392 | # Object variable to store code object waiting execution. This is |
|
392 | # Object variable to store code object waiting execution. This is | |
393 | # used mainly by the multithreaded shells, but it can come in handy in |
|
393 | # used mainly by the multithreaded shells, but it can come in handy in | |
394 | # other situations. No need to use a Queue here, since it's a single |
|
394 | # other situations. No need to use a Queue here, since it's a single | |
395 | # item which gets cleared once run. |
|
395 | # item which gets cleared once run. | |
396 | self.code_to_run = None |
|
396 | self.code_to_run = None | |
397 |
|
397 | |||
398 | # escapes for automatic behavior on the command line |
|
398 | # escapes for automatic behavior on the command line | |
399 | self.ESC_SHELL = '!' |
|
399 | self.ESC_SHELL = '!' | |
400 | self.ESC_SH_CAP = '!!' |
|
400 | self.ESC_SH_CAP = '!!' | |
401 | self.ESC_HELP = '?' |
|
401 | self.ESC_HELP = '?' | |
402 | self.ESC_MAGIC = '%' |
|
402 | self.ESC_MAGIC = '%' | |
403 | self.ESC_QUOTE = ',' |
|
403 | self.ESC_QUOTE = ',' | |
404 | self.ESC_QUOTE2 = ';' |
|
404 | self.ESC_QUOTE2 = ';' | |
405 | self.ESC_PAREN = '/' |
|
405 | self.ESC_PAREN = '/' | |
406 |
|
406 | |||
407 | # And their associated handlers |
|
407 | # And their associated handlers | |
408 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
408 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
409 | self.ESC_QUOTE : self.handle_auto, |
|
409 | self.ESC_QUOTE : self.handle_auto, | |
410 | self.ESC_QUOTE2 : self.handle_auto, |
|
410 | self.ESC_QUOTE2 : self.handle_auto, | |
411 | self.ESC_MAGIC : self.handle_magic, |
|
411 | self.ESC_MAGIC : self.handle_magic, | |
412 | self.ESC_HELP : self.handle_help, |
|
412 | self.ESC_HELP : self.handle_help, | |
413 | self.ESC_SHELL : self.handle_shell_escape, |
|
413 | self.ESC_SHELL : self.handle_shell_escape, | |
414 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
414 | self.ESC_SH_CAP : self.handle_shell_escape, | |
415 | } |
|
415 | } | |
416 |
|
416 | |||
417 | # class initializations |
|
417 | # class initializations | |
418 | Magic.__init__(self,self) |
|
418 | Magic.__init__(self,self) | |
419 |
|
419 | |||
420 | # Python source parser/formatter for syntax highlighting |
|
420 | # Python source parser/formatter for syntax highlighting | |
421 | pyformat = PyColorize.Parser().format |
|
421 | pyformat = PyColorize.Parser().format | |
422 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
422 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |
423 |
|
423 | |||
424 | # hooks holds pointers used for user-side customizations |
|
424 | # hooks holds pointers used for user-side customizations | |
425 | self.hooks = Struct() |
|
425 | self.hooks = Struct() | |
426 |
|
426 | |||
427 | self.strdispatchers = {} |
|
427 | self.strdispatchers = {} | |
428 |
|
428 | |||
429 | # Set all default hooks, defined in the IPython.hooks module. |
|
429 | # Set all default hooks, defined in the IPython.hooks module. | |
430 | hooks = IPython.hooks |
|
430 | hooks = IPython.hooks | |
431 | for hook_name in hooks.__all__: |
|
431 | for hook_name in hooks.__all__: | |
432 | # default hooks have priority 100, i.e. low; user hooks should have |
|
432 | # default hooks have priority 100, i.e. low; user hooks should have | |
433 | # 0-100 priority |
|
433 | # 0-100 priority | |
434 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
434 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
435 | #print "bound hook",hook_name |
|
435 | #print "bound hook",hook_name | |
436 |
|
436 | |||
437 | # Flag to mark unconditional exit |
|
437 | # Flag to mark unconditional exit | |
438 | self.exit_now = False |
|
438 | self.exit_now = False | |
439 |
|
439 | |||
440 | self.usage_min = """\ |
|
440 | self.usage_min = """\ | |
441 | An enhanced console for Python. |
|
441 | An enhanced console for Python. | |
442 | Some of its features are: |
|
442 | Some of its features are: | |
443 | - Readline support if the readline library is present. |
|
443 | - Readline support if the readline library is present. | |
444 | - Tab completion in the local namespace. |
|
444 | - Tab completion in the local namespace. | |
445 | - Logging of input, see command-line options. |
|
445 | - Logging of input, see command-line options. | |
446 | - System shell escape via ! , eg !ls. |
|
446 | - System shell escape via ! , eg !ls. | |
447 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
447 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
448 | - Keeps track of locally defined variables via %who, %whos. |
|
448 | - Keeps track of locally defined variables via %who, %whos. | |
449 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
449 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
450 | """ |
|
450 | """ | |
451 | if usage: self.usage = usage |
|
451 | if usage: self.usage = usage | |
452 | else: self.usage = self.usage_min |
|
452 | else: self.usage = self.usage_min | |
453 |
|
453 | |||
454 | # Storage |
|
454 | # Storage | |
455 | self.rc = rc # This will hold all configuration information |
|
455 | self.rc = rc # This will hold all configuration information | |
456 | self.pager = 'less' |
|
456 | self.pager = 'less' | |
457 | # temporary files used for various purposes. Deleted at exit. |
|
457 | # temporary files used for various purposes. Deleted at exit. | |
458 | self.tempfiles = [] |
|
458 | self.tempfiles = [] | |
459 |
|
459 | |||
460 | # Keep track of readline usage (later set by init_readline) |
|
460 | # Keep track of readline usage (later set by init_readline) | |
461 | self.has_readline = False |
|
461 | self.has_readline = False | |
462 |
|
462 | |||
463 | # template for logfile headers. It gets resolved at runtime by the |
|
463 | # template for logfile headers. It gets resolved at runtime by the | |
464 | # logstart method. |
|
464 | # logstart method. | |
465 | self.loghead_tpl = \ |
|
465 | self.loghead_tpl = \ | |
466 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
466 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
467 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
467 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
468 | #log# opts = %s |
|
468 | #log# opts = %s | |
469 | #log# args = %s |
|
469 | #log# args = %s | |
470 | #log# It is safe to make manual edits below here. |
|
470 | #log# It is safe to make manual edits below here. | |
471 | #log#----------------------------------------------------------------------- |
|
471 | #log#----------------------------------------------------------------------- | |
472 | """ |
|
472 | """ | |
473 | # for pushd/popd management |
|
473 | # for pushd/popd management | |
474 | try: |
|
474 | try: | |
475 | self.home_dir = get_home_dir() |
|
475 | self.home_dir = get_home_dir() | |
476 | except HomeDirError,msg: |
|
476 | except HomeDirError,msg: | |
477 | fatal(msg) |
|
477 | fatal(msg) | |
478 |
|
478 | |||
479 | self.dir_stack = [] |
|
479 | self.dir_stack = [] | |
480 |
|
480 | |||
481 | # Functions to call the underlying shell. |
|
481 | # Functions to call the underlying shell. | |
482 |
|
482 | |||
483 | # The first is similar to os.system, but it doesn't return a value, |
|
483 | # The first is similar to os.system, but it doesn't return a value, | |
484 | # and it allows interpolation of variables in the user's namespace. |
|
484 | # and it allows interpolation of variables in the user's namespace. | |
485 | self.system = lambda cmd: \ |
|
485 | self.system = lambda cmd: \ | |
486 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
486 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) | |
487 |
|
487 | |||
488 | # These are for getoutput and getoutputerror: |
|
488 | # These are for getoutput and getoutputerror: | |
489 | self.getoutput = lambda cmd: \ |
|
489 | self.getoutput = lambda cmd: \ | |
490 | getoutput(self.var_expand(cmd,depth=2), |
|
490 | getoutput(self.var_expand(cmd,depth=2), | |
491 | header=self.rc.system_header, |
|
491 | header=self.rc.system_header, | |
492 | verbose=self.rc.system_verbose) |
|
492 | verbose=self.rc.system_verbose) | |
493 |
|
493 | |||
494 | self.getoutputerror = lambda cmd: \ |
|
494 | self.getoutputerror = lambda cmd: \ | |
495 | getoutputerror(self.var_expand(cmd,depth=2), |
|
495 | getoutputerror(self.var_expand(cmd,depth=2), | |
496 | header=self.rc.system_header, |
|
496 | header=self.rc.system_header, | |
497 | verbose=self.rc.system_verbose) |
|
497 | verbose=self.rc.system_verbose) | |
498 |
|
498 | |||
499 |
|
499 | |||
500 | # keep track of where we started running (mainly for crash post-mortem) |
|
500 | # keep track of where we started running (mainly for crash post-mortem) | |
501 | self.starting_dir = os.getcwd() |
|
501 | self.starting_dir = os.getcwd() | |
502 |
|
502 | |||
503 | # Various switches which can be set |
|
503 | # Various switches which can be set | |
504 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
504 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
505 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
505 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
506 | self.banner2 = banner2 |
|
506 | self.banner2 = banner2 | |
507 |
|
507 | |||
508 | # TraceBack handlers: |
|
508 | # TraceBack handlers: | |
509 |
|
509 | |||
510 | # Syntax error handler. |
|
510 | # Syntax error handler. | |
511 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
511 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
512 |
|
512 | |||
513 | # The interactive one is initialized with an offset, meaning we always |
|
513 | # The interactive one is initialized with an offset, meaning we always | |
514 | # want to remove the topmost item in the traceback, which is our own |
|
514 | # want to remove the topmost item in the traceback, which is our own | |
515 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
515 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
516 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
516 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
517 | color_scheme='NoColor', |
|
517 | color_scheme='NoColor', | |
518 | tb_offset = 1) |
|
518 | tb_offset = 1) | |
519 |
|
519 | |||
520 | # IPython itself shouldn't crash. This will produce a detailed |
|
520 | # IPython itself shouldn't crash. This will produce a detailed | |
521 | # post-mortem if it does. But we only install the crash handler for |
|
521 | # post-mortem if it does. But we only install the crash handler for | |
522 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
522 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
523 | # and lose the crash handler. This is because exceptions in the main |
|
523 | # and lose the crash handler. This is because exceptions in the main | |
524 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
524 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
525 | # and there's no point in printing crash dumps for every user exception. |
|
525 | # and there's no point in printing crash dumps for every user exception. | |
526 | if self.isthreaded: |
|
526 | if self.isthreaded: | |
527 | ipCrashHandler = ultraTB.FormattedTB() |
|
527 | ipCrashHandler = ultraTB.FormattedTB() | |
528 | else: |
|
528 | else: | |
529 | from IPython import CrashHandler |
|
529 | from IPython import CrashHandler | |
530 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
530 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) | |
531 | self.set_crash_handler(ipCrashHandler) |
|
531 | self.set_crash_handler(ipCrashHandler) | |
532 |
|
532 | |||
533 | # and add any custom exception handlers the user may have specified |
|
533 | # and add any custom exception handlers the user may have specified | |
534 | self.set_custom_exc(*custom_exceptions) |
|
534 | self.set_custom_exc(*custom_exceptions) | |
535 |
|
535 | |||
536 | # indentation management |
|
536 | # indentation management | |
537 | self.autoindent = False |
|
537 | self.autoindent = False | |
538 | self.indent_current_nsp = 0 |
|
538 | self.indent_current_nsp = 0 | |
539 |
|
539 | |||
540 | # Make some aliases automatically |
|
540 | # Make some aliases automatically | |
541 | # Prepare list of shell aliases to auto-define |
|
541 | # Prepare list of shell aliases to auto-define | |
542 | if os.name == 'posix': |
|
542 | if os.name == 'posix': | |
543 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
543 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
544 | 'mv mv -i','rm rm -i','cp cp -i', |
|
544 | 'mv mv -i','rm rm -i','cp cp -i', | |
545 | 'cat cat','less less','clear clear', |
|
545 | 'cat cat','less less','clear clear', | |
546 | # a better ls |
|
546 | # a better ls | |
547 | 'ls ls -F', |
|
547 | 'ls ls -F', | |
548 | # long ls |
|
548 | # long ls | |
549 | 'll ls -lF') |
|
549 | 'll ls -lF') | |
550 | # Extra ls aliases with color, which need special treatment on BSD |
|
550 | # Extra ls aliases with color, which need special treatment on BSD | |
551 | # variants |
|
551 | # variants | |
552 | ls_extra = ( # color ls |
|
552 | ls_extra = ( # color ls | |
553 | 'lc ls -F -o --color', |
|
553 | 'lc ls -F -o --color', | |
554 | # ls normal files only |
|
554 | # ls normal files only | |
555 | 'lf ls -F -o --color %l | grep ^-', |
|
555 | 'lf ls -F -o --color %l | grep ^-', | |
556 | # ls symbolic links |
|
556 | # ls symbolic links | |
557 | 'lk ls -F -o --color %l | grep ^l', |
|
557 | 'lk ls -F -o --color %l | grep ^l', | |
558 | # directories or links to directories, |
|
558 | # directories or links to directories, | |
559 | 'ldir ls -F -o --color %l | grep /$', |
|
559 | 'ldir ls -F -o --color %l | grep /$', | |
560 | # things which are executable |
|
560 | # things which are executable | |
561 | 'lx ls -F -o --color %l | grep ^-..x', |
|
561 | 'lx ls -F -o --color %l | grep ^-..x', | |
562 | ) |
|
562 | ) | |
563 | # The BSDs don't ship GNU ls, so they don't understand the |
|
563 | # The BSDs don't ship GNU ls, so they don't understand the | |
564 | # --color switch out of the box |
|
564 | # --color switch out of the box | |
565 | if 'bsd' in sys.platform: |
|
565 | if 'bsd' in sys.platform: | |
566 | ls_extra = ( # ls normal files only |
|
566 | ls_extra = ( # ls normal files only | |
567 | 'lf ls -lF | grep ^-', |
|
567 | 'lf ls -lF | grep ^-', | |
568 | # ls symbolic links |
|
568 | # ls symbolic links | |
569 | 'lk ls -lF | grep ^l', |
|
569 | 'lk ls -lF | grep ^l', | |
570 | # directories or links to directories, |
|
570 | # directories or links to directories, | |
571 | 'ldir ls -lF | grep /$', |
|
571 | 'ldir ls -lF | grep /$', | |
572 | # things which are executable |
|
572 | # things which are executable | |
573 | 'lx ls -lF | grep ^-..x', |
|
573 | 'lx ls -lF | grep ^-..x', | |
574 | ) |
|
574 | ) | |
575 | auto_alias = auto_alias + ls_extra |
|
575 | auto_alias = auto_alias + ls_extra | |
576 | elif os.name in ['nt','dos']: |
|
576 | elif os.name in ['nt','dos']: | |
577 | auto_alias = ('ls dir /on', |
|
577 | auto_alias = ('ls dir /on', | |
578 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
578 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
579 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
579 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
580 | 'ren ren','cls cls','copy copy') |
|
580 | 'ren ren','cls cls','copy copy') | |
581 | else: |
|
581 | else: | |
582 | auto_alias = () |
|
582 | auto_alias = () | |
583 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
583 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |
584 |
|
584 | |||
585 | # Produce a public API instance |
|
585 | # Produce a public API instance | |
586 | self.api = IPython.ipapi.IPApi(self) |
|
586 | self.api = IPython.ipapi.IPApi(self) | |
587 |
|
587 | |||
588 | # Initialize all user-visible namespaces |
|
588 | # Initialize all user-visible namespaces | |
589 | self.init_namespaces() |
|
589 | self.init_namespaces() | |
590 |
|
590 | |||
591 | # Call the actual (public) initializer |
|
591 | # Call the actual (public) initializer | |
592 | self.init_auto_alias() |
|
592 | self.init_auto_alias() | |
593 |
|
593 | |||
594 | # track which builtins we add, so we can clean up later |
|
594 | # track which builtins we add, so we can clean up later | |
595 | self.builtins_added = {} |
|
595 | self.builtins_added = {} | |
596 | # This method will add the necessary builtins for operation, but |
|
596 | # This method will add the necessary builtins for operation, but | |
597 | # tracking what it did via the builtins_added dict. |
|
597 | # tracking what it did via the builtins_added dict. | |
598 |
|
598 | |||
599 | #TODO: remove this, redundant |
|
599 | #TODO: remove this, redundant | |
600 | self.add_builtins() |
|
600 | self.add_builtins() | |
601 | # end __init__ |
|
601 | # end __init__ | |
602 |
|
602 | |||
603 | def var_expand(self,cmd,depth=0): |
|
603 | def var_expand(self,cmd,depth=0): | |
604 | """Expand python variables in a string. |
|
604 | """Expand python variables in a string. | |
605 |
|
605 | |||
606 | The depth argument indicates how many frames above the caller should |
|
606 | The depth argument indicates how many frames above the caller should | |
607 | be walked to look for the local namespace where to expand variables. |
|
607 | be walked to look for the local namespace where to expand variables. | |
608 |
|
608 | |||
609 | The global namespace for expansion is always the user's interactive |
|
609 | The global namespace for expansion is always the user's interactive | |
610 | namespace. |
|
610 | namespace. | |
611 | """ |
|
611 | """ | |
612 |
|
612 | |||
613 | return str(ItplNS(cmd, |
|
613 | return str(ItplNS(cmd, | |
614 | self.user_ns, # globals |
|
614 | self.user_ns, # globals | |
615 | # Skip our own frame in searching for locals: |
|
615 | # Skip our own frame in searching for locals: | |
616 | sys._getframe(depth+1).f_locals # locals |
|
616 | sys._getframe(depth+1).f_locals # locals | |
617 | )) |
|
617 | )) | |
618 |
|
618 | |||
619 | def pre_config_initialization(self): |
|
619 | def pre_config_initialization(self): | |
620 | """Pre-configuration init method |
|
620 | """Pre-configuration init method | |
621 |
|
621 | |||
622 | This is called before the configuration files are processed to |
|
622 | This is called before the configuration files are processed to | |
623 | prepare the services the config files might need. |
|
623 | prepare the services the config files might need. | |
624 |
|
624 | |||
625 | self.rc already has reasonable default values at this point. |
|
625 | self.rc already has reasonable default values at this point. | |
626 | """ |
|
626 | """ | |
627 | rc = self.rc |
|
627 | rc = self.rc | |
628 | try: |
|
628 | try: | |
629 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
629 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") | |
630 | except exceptions.UnicodeDecodeError: |
|
630 | except exceptions.UnicodeDecodeError: | |
631 | print "Your ipythondir can't be decoded to unicode!" |
|
631 | print "Your ipythondir can't be decoded to unicode!" | |
632 | print "Please set HOME environment variable to something that" |
|
632 | print "Please set HOME environment variable to something that" | |
633 | print r"only has ASCII characters, e.g. c:\home" |
|
633 | print r"only has ASCII characters, e.g. c:\home" | |
634 | print "Now it is",rc.ipythondir |
|
634 | print "Now it is",rc.ipythondir | |
635 | sys.exit() |
|
635 | sys.exit() | |
636 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
636 | self.shadowhist = IPython.history.ShadowHist(self.db) | |
637 |
|
637 | |||
638 | def post_config_initialization(self): |
|
638 | def post_config_initialization(self): | |
639 | """Post configuration init method |
|
639 | """Post configuration init method | |
640 |
|
640 | |||
641 | This is called after the configuration files have been processed to |
|
641 | This is called after the configuration files have been processed to | |
642 | 'finalize' the initialization.""" |
|
642 | 'finalize' the initialization.""" | |
643 |
|
643 | |||
644 | rc = self.rc |
|
644 | rc = self.rc | |
645 |
|
645 | |||
646 | # Object inspector |
|
646 | # Object inspector | |
647 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
647 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
648 | PyColorize.ANSICodeColors, |
|
648 | PyColorize.ANSICodeColors, | |
649 | 'NoColor', |
|
649 | 'NoColor', | |
650 | rc.object_info_string_level) |
|
650 | rc.object_info_string_level) | |
651 |
|
651 | |||
652 | self.rl_next_input = None |
|
652 | self.rl_next_input = None | |
653 | self.rl_do_indent = False |
|
653 | self.rl_do_indent = False | |
654 | # Load readline proper |
|
654 | # Load readline proper | |
655 | if rc.readline: |
|
655 | if rc.readline: | |
656 | self.init_readline() |
|
656 | self.init_readline() | |
657 |
|
657 | |||
658 | # local shortcut, this is used a LOT |
|
658 | # local shortcut, this is used a LOT | |
659 | self.log = self.logger.log |
|
659 | self.log = self.logger.log | |
660 |
|
660 | |||
661 | # Initialize cache, set in/out prompts and printing system |
|
661 | # Initialize cache, set in/out prompts and printing system | |
662 | self.outputcache = CachedOutput(self, |
|
662 | self.outputcache = CachedOutput(self, | |
663 | rc.cache_size, |
|
663 | rc.cache_size, | |
664 | rc.pprint, |
|
664 | rc.pprint, | |
665 | input_sep = rc.separate_in, |
|
665 | input_sep = rc.separate_in, | |
666 | output_sep = rc.separate_out, |
|
666 | output_sep = rc.separate_out, | |
667 | output_sep2 = rc.separate_out2, |
|
667 | output_sep2 = rc.separate_out2, | |
668 | ps1 = rc.prompt_in1, |
|
668 | ps1 = rc.prompt_in1, | |
669 | ps2 = rc.prompt_in2, |
|
669 | ps2 = rc.prompt_in2, | |
670 | ps_out = rc.prompt_out, |
|
670 | ps_out = rc.prompt_out, | |
671 | pad_left = rc.prompts_pad_left) |
|
671 | pad_left = rc.prompts_pad_left) | |
672 |
|
672 | |||
673 | # user may have over-ridden the default print hook: |
|
673 | # user may have over-ridden the default print hook: | |
674 | try: |
|
674 | try: | |
675 | self.outputcache.__class__.display = self.hooks.display |
|
675 | self.outputcache.__class__.display = self.hooks.display | |
676 | except AttributeError: |
|
676 | except AttributeError: | |
677 | pass |
|
677 | pass | |
678 |
|
678 | |||
679 | # I don't like assigning globally to sys, because it means when |
|
679 | # I don't like assigning globally to sys, because it means when | |
680 | # embedding instances, each embedded instance overrides the previous |
|
680 | # embedding instances, each embedded instance overrides the previous | |
681 | # choice. But sys.displayhook seems to be called internally by exec, |
|
681 | # choice. But sys.displayhook seems to be called internally by exec, | |
682 | # so I don't see a way around it. We first save the original and then |
|
682 | # so I don't see a way around it. We first save the original and then | |
683 | # overwrite it. |
|
683 | # overwrite it. | |
684 | self.sys_displayhook = sys.displayhook |
|
684 | self.sys_displayhook = sys.displayhook | |
685 | sys.displayhook = self.outputcache |
|
685 | sys.displayhook = self.outputcache | |
686 |
|
686 | |||
687 | # Do a proper resetting of doctest, including the necessary displayhook |
|
687 | # Do a proper resetting of doctest, including the necessary displayhook | |
688 | # monkeypatching |
|
688 | # monkeypatching | |
689 | try: |
|
689 | try: | |
690 | doctest_reload() |
|
690 | doctest_reload() | |
691 | except ImportError: |
|
691 | except ImportError: | |
692 | warn("doctest module does not exist.") |
|
692 | warn("doctest module does not exist.") | |
693 |
|
693 | |||
694 | # Set user colors (don't do it in the constructor above so that it |
|
694 | # Set user colors (don't do it in the constructor above so that it | |
695 | # doesn't crash if colors option is invalid) |
|
695 | # doesn't crash if colors option is invalid) | |
696 | self.magic_colors(rc.colors) |
|
696 | self.magic_colors(rc.colors) | |
697 |
|
697 | |||
698 | # Set calling of pdb on exceptions |
|
698 | # Set calling of pdb on exceptions | |
699 | self.call_pdb = rc.pdb |
|
699 | self.call_pdb = rc.pdb | |
700 |
|
700 | |||
701 | # Load user aliases |
|
701 | # Load user aliases | |
702 | for alias in rc.alias: |
|
702 | for alias in rc.alias: | |
703 | self.magic_alias(alias) |
|
703 | self.magic_alias(alias) | |
704 |
|
704 | |||
705 | self.hooks.late_startup_hook() |
|
705 | self.hooks.late_startup_hook() | |
706 |
|
706 | |||
707 | for cmd in self.rc.autoexec: |
|
707 | for cmd in self.rc.autoexec: | |
708 | #print "autoexec>",cmd #dbg |
|
708 | #print "autoexec>",cmd #dbg | |
709 | self.api.runlines(cmd) |
|
709 | self.api.runlines(cmd) | |
710 |
|
710 | |||
711 | batchrun = False |
|
711 | batchrun = False | |
712 | for batchfile in [path(arg) for arg in self.rc.args |
|
712 | for batchfile in [path(arg) for arg in self.rc.args | |
713 | if arg.lower().endswith('.ipy')]: |
|
713 | if arg.lower().endswith('.ipy')]: | |
714 | if not batchfile.isfile(): |
|
714 | if not batchfile.isfile(): | |
715 | print "No such batch file:", batchfile |
|
715 | print "No such batch file:", batchfile | |
716 | continue |
|
716 | continue | |
717 | self.api.runlines(batchfile.text()) |
|
717 | self.api.runlines(batchfile.text()) | |
718 | batchrun = True |
|
718 | batchrun = True | |
719 | # without -i option, exit after running the batch file |
|
719 | # without -i option, exit after running the batch file | |
720 | if batchrun and not self.rc.interact: |
|
720 | if batchrun and not self.rc.interact: | |
721 | self.ask_exit() |
|
721 | self.ask_exit() | |
722 |
|
722 | |||
723 | def init_namespaces(self): |
|
723 | def init_namespaces(self): | |
724 | """Initialize all user-visible namespaces to their minimum defaults. |
|
724 | """Initialize all user-visible namespaces to their minimum defaults. | |
725 |
|
725 | |||
726 | Certain history lists are also initialized here, as they effectively |
|
726 | Certain history lists are also initialized here, as they effectively | |
727 | act as user namespaces. |
|
727 | act as user namespaces. | |
728 |
|
728 | |||
729 | Note |
|
729 | Note | |
730 | ---- |
|
730 | ---- | |
731 | All data structures here are only filled in, they are NOT reset by this |
|
731 | All data structures here are only filled in, they are NOT reset by this | |
732 | method. If they were not empty before, data will simply be added to |
|
732 | method. If they were not empty before, data will simply be added to | |
733 | therm. |
|
733 | therm. | |
734 | """ |
|
734 | """ | |
735 | # The user namespace MUST have a pointer to the shell itself. |
|
735 | # The user namespace MUST have a pointer to the shell itself. | |
736 | self.user_ns[self.name] = self |
|
736 | self.user_ns[self.name] = self | |
737 |
|
737 | |||
738 | # Store the public api instance |
|
738 | # Store the public api instance | |
739 | self.user_ns['_ip'] = self.api |
|
739 | self.user_ns['_ip'] = self.api | |
740 |
|
740 | |||
741 | # make global variables for user access to the histories |
|
741 | # make global variables for user access to the histories | |
742 | self.user_ns['_ih'] = self.input_hist |
|
742 | self.user_ns['_ih'] = self.input_hist | |
743 | self.user_ns['_oh'] = self.output_hist |
|
743 | self.user_ns['_oh'] = self.output_hist | |
744 | self.user_ns['_dh'] = self.dir_hist |
|
744 | self.user_ns['_dh'] = self.dir_hist | |
745 |
|
745 | |||
746 | # user aliases to input and output histories |
|
746 | # user aliases to input and output histories | |
747 | self.user_ns['In'] = self.input_hist |
|
747 | self.user_ns['In'] = self.input_hist | |
748 | self.user_ns['Out'] = self.output_hist |
|
748 | self.user_ns['Out'] = self.output_hist | |
749 |
|
749 | |||
750 | self.user_ns['_sh'] = IPython.shadowns |
|
750 | self.user_ns['_sh'] = IPython.shadowns | |
751 |
|
751 | |||
752 | # Fill the history zero entry, user counter starts at 1 |
|
752 | # Fill the history zero entry, user counter starts at 1 | |
753 | self.input_hist.append('\n') |
|
753 | self.input_hist.append('\n') | |
754 | self.input_hist_raw.append('\n') |
|
754 | self.input_hist_raw.append('\n') | |
755 |
|
755 | |||
756 | def add_builtins(self): |
|
756 | def add_builtins(self): | |
757 | """Store ipython references into the builtin namespace. |
|
757 | """Store ipython references into the builtin namespace. | |
758 |
|
758 | |||
759 | Some parts of ipython operate via builtins injected here, which hold a |
|
759 | Some parts of ipython operate via builtins injected here, which hold a | |
760 | reference to IPython itself.""" |
|
760 | reference to IPython itself.""" | |
761 |
|
761 | |||
762 | # TODO: deprecate all of these, they are unsafe |
|
762 | # TODO: deprecate all of these, they are unsafe | |
763 | builtins_new = dict(__IPYTHON__ = self, |
|
763 | builtins_new = dict(__IPYTHON__ = self, | |
764 | ip_set_hook = self.set_hook, |
|
764 | ip_set_hook = self.set_hook, | |
765 | jobs = self.jobs, |
|
765 | jobs = self.jobs, | |
766 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
766 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), | |
767 | ipalias = wrap_deprecated(self.ipalias), |
|
767 | ipalias = wrap_deprecated(self.ipalias), | |
768 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
768 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), | |
769 | #_ip = self.api |
|
769 | #_ip = self.api | |
770 | ) |
|
770 | ) | |
771 | for biname,bival in builtins_new.items(): |
|
771 | for biname,bival in builtins_new.items(): | |
772 | try: |
|
772 | try: | |
773 | # store the orignal value so we can restore it |
|
773 | # store the orignal value so we can restore it | |
774 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
774 | self.builtins_added[biname] = __builtin__.__dict__[biname] | |
775 | except KeyError: |
|
775 | except KeyError: | |
776 | # or mark that it wasn't defined, and we'll just delete it at |
|
776 | # or mark that it wasn't defined, and we'll just delete it at | |
777 | # cleanup |
|
777 | # cleanup | |
778 | self.builtins_added[biname] = Undefined |
|
778 | self.builtins_added[biname] = Undefined | |
779 | __builtin__.__dict__[biname] = bival |
|
779 | __builtin__.__dict__[biname] = bival | |
780 |
|
780 | |||
781 | # Keep in the builtins a flag for when IPython is active. We set it |
|
781 | # Keep in the builtins a flag for when IPython is active. We set it | |
782 | # with setdefault so that multiple nested IPythons don't clobber one |
|
782 | # with setdefault so that multiple nested IPythons don't clobber one | |
783 | # another. Each will increase its value by one upon being activated, |
|
783 | # another. Each will increase its value by one upon being activated, | |
784 | # which also gives us a way to determine the nesting level. |
|
784 | # which also gives us a way to determine the nesting level. | |
785 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
785 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
786 |
|
786 | |||
787 | def clean_builtins(self): |
|
787 | def clean_builtins(self): | |
788 | """Remove any builtins which might have been added by add_builtins, or |
|
788 | """Remove any builtins which might have been added by add_builtins, or | |
789 | restore overwritten ones to their previous values.""" |
|
789 | restore overwritten ones to their previous values.""" | |
790 | for biname,bival in self.builtins_added.items(): |
|
790 | for biname,bival in self.builtins_added.items(): | |
791 | if bival is Undefined: |
|
791 | if bival is Undefined: | |
792 | del __builtin__.__dict__[biname] |
|
792 | del __builtin__.__dict__[biname] | |
793 | else: |
|
793 | else: | |
794 | __builtin__.__dict__[biname] = bival |
|
794 | __builtin__.__dict__[biname] = bival | |
795 | self.builtins_added.clear() |
|
795 | self.builtins_added.clear() | |
796 |
|
796 | |||
797 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
797 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
798 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
798 | """set_hook(name,hook) -> sets an internal IPython hook. | |
799 |
|
799 | |||
800 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
800 | IPython exposes some of its internal API as user-modifiable hooks. By | |
801 | adding your function to one of these hooks, you can modify IPython's |
|
801 | adding your function to one of these hooks, you can modify IPython's | |
802 | behavior to call at runtime your own routines.""" |
|
802 | behavior to call at runtime your own routines.""" | |
803 |
|
803 | |||
804 | # At some point in the future, this should validate the hook before it |
|
804 | # At some point in the future, this should validate the hook before it | |
805 | # accepts it. Probably at least check that the hook takes the number |
|
805 | # accepts it. Probably at least check that the hook takes the number | |
806 | # of args it's supposed to. |
|
806 | # of args it's supposed to. | |
807 |
|
807 | |||
808 | f = new.instancemethod(hook,self,self.__class__) |
|
808 | f = new.instancemethod(hook,self,self.__class__) | |
809 |
|
809 | |||
810 | # check if the hook is for strdispatcher first |
|
810 | # check if the hook is for strdispatcher first | |
811 | if str_key is not None: |
|
811 | if str_key is not None: | |
812 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
812 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
813 | sdp.add_s(str_key, f, priority ) |
|
813 | sdp.add_s(str_key, f, priority ) | |
814 | self.strdispatchers[name] = sdp |
|
814 | self.strdispatchers[name] = sdp | |
815 | return |
|
815 | return | |
816 | if re_key is not None: |
|
816 | if re_key is not None: | |
817 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
817 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
818 | sdp.add_re(re.compile(re_key), f, priority ) |
|
818 | sdp.add_re(re.compile(re_key), f, priority ) | |
819 | self.strdispatchers[name] = sdp |
|
819 | self.strdispatchers[name] = sdp | |
820 | return |
|
820 | return | |
821 |
|
821 | |||
822 | dp = getattr(self.hooks, name, None) |
|
822 | dp = getattr(self.hooks, name, None) | |
823 | if name not in IPython.hooks.__all__: |
|
823 | if name not in IPython.hooks.__all__: | |
824 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
824 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) | |
825 | if not dp: |
|
825 | if not dp: | |
826 | dp = IPython.hooks.CommandChainDispatcher() |
|
826 | dp = IPython.hooks.CommandChainDispatcher() | |
827 |
|
827 | |||
828 | try: |
|
828 | try: | |
829 | dp.add(f,priority) |
|
829 | dp.add(f,priority) | |
830 | except AttributeError: |
|
830 | except AttributeError: | |
831 | # it was not commandchain, plain old func - replace |
|
831 | # it was not commandchain, plain old func - replace | |
832 | dp = f |
|
832 | dp = f | |
833 |
|
833 | |||
834 | setattr(self.hooks,name, dp) |
|
834 | setattr(self.hooks,name, dp) | |
835 |
|
835 | |||
836 |
|
836 | |||
837 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
837 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
838 |
|
838 | |||
839 | def set_crash_handler(self,crashHandler): |
|
839 | def set_crash_handler(self,crashHandler): | |
840 | """Set the IPython crash handler. |
|
840 | """Set the IPython crash handler. | |
841 |
|
841 | |||
842 | This must be a callable with a signature suitable for use as |
|
842 | This must be a callable with a signature suitable for use as | |
843 | sys.excepthook.""" |
|
843 | sys.excepthook.""" | |
844 |
|
844 | |||
845 | # Install the given crash handler as the Python exception hook |
|
845 | # Install the given crash handler as the Python exception hook | |
846 | sys.excepthook = crashHandler |
|
846 | sys.excepthook = crashHandler | |
847 |
|
847 | |||
848 | # The instance will store a pointer to this, so that runtime code |
|
848 | # The instance will store a pointer to this, so that runtime code | |
849 | # (such as magics) can access it. This is because during the |
|
849 | # (such as magics) can access it. This is because during the | |
850 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
850 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
851 | # frameworks). |
|
851 | # frameworks). | |
852 | self.sys_excepthook = sys.excepthook |
|
852 | self.sys_excepthook = sys.excepthook | |
853 |
|
853 | |||
854 |
|
854 | |||
855 | def set_custom_exc(self,exc_tuple,handler): |
|
855 | def set_custom_exc(self,exc_tuple,handler): | |
856 | """set_custom_exc(exc_tuple,handler) |
|
856 | """set_custom_exc(exc_tuple,handler) | |
857 |
|
857 | |||
858 | Set a custom exception handler, which will be called if any of the |
|
858 | Set a custom exception handler, which will be called if any of the | |
859 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
859 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
860 | runcode() method. |
|
860 | runcode() method. | |
861 |
|
861 | |||
862 | Inputs: |
|
862 | Inputs: | |
863 |
|
863 | |||
864 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
864 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
865 | handler for. It is very important that you use a tuple, and NOT A |
|
865 | handler for. It is very important that you use a tuple, and NOT A | |
866 | LIST here, because of the way Python's except statement works. If |
|
866 | LIST here, because of the way Python's except statement works. If | |
867 | you only want to trap a single exception, use a singleton tuple: |
|
867 | you only want to trap a single exception, use a singleton tuple: | |
868 |
|
868 | |||
869 | exc_tuple == (MyCustomException,) |
|
869 | exc_tuple == (MyCustomException,) | |
870 |
|
870 | |||
871 | - handler: this must be defined as a function with the following |
|
871 | - handler: this must be defined as a function with the following | |
872 | basic interface: def my_handler(self,etype,value,tb). |
|
872 | basic interface: def my_handler(self,etype,value,tb). | |
873 |
|
873 | |||
874 | This will be made into an instance method (via new.instancemethod) |
|
874 | This will be made into an instance method (via new.instancemethod) | |
875 | of IPython itself, and it will be called if any of the exceptions |
|
875 | of IPython itself, and it will be called if any of the exceptions | |
876 | listed in the exc_tuple are caught. If the handler is None, an |
|
876 | listed in the exc_tuple are caught. If the handler is None, an | |
877 | internal basic one is used, which just prints basic info. |
|
877 | internal basic one is used, which just prints basic info. | |
878 |
|
878 | |||
879 | WARNING: by putting in your own exception handler into IPython's main |
|
879 | WARNING: by putting in your own exception handler into IPython's main | |
880 | execution loop, you run a very good chance of nasty crashes. This |
|
880 | execution loop, you run a very good chance of nasty crashes. This | |
881 | facility should only be used if you really know what you are doing.""" |
|
881 | facility should only be used if you really know what you are doing.""" | |
882 |
|
882 | |||
883 | assert type(exc_tuple)==type(()) , \ |
|
883 | assert type(exc_tuple)==type(()) , \ | |
884 | "The custom exceptions must be given AS A TUPLE." |
|
884 | "The custom exceptions must be given AS A TUPLE." | |
885 |
|
885 | |||
886 | def dummy_handler(self,etype,value,tb): |
|
886 | def dummy_handler(self,etype,value,tb): | |
887 | print '*** Simple custom exception handler ***' |
|
887 | print '*** Simple custom exception handler ***' | |
888 | print 'Exception type :',etype |
|
888 | print 'Exception type :',etype | |
889 | print 'Exception value:',value |
|
889 | print 'Exception value:',value | |
890 | print 'Traceback :',tb |
|
890 | print 'Traceback :',tb | |
891 | print 'Source code :','\n'.join(self.buffer) |
|
891 | print 'Source code :','\n'.join(self.buffer) | |
892 |
|
892 | |||
893 | if handler is None: handler = dummy_handler |
|
893 | if handler is None: handler = dummy_handler | |
894 |
|
894 | |||
895 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
895 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
896 | self.custom_exceptions = exc_tuple |
|
896 | self.custom_exceptions = exc_tuple | |
897 |
|
897 | |||
898 | def set_custom_completer(self,completer,pos=0): |
|
898 | def set_custom_completer(self,completer,pos=0): | |
899 | """set_custom_completer(completer,pos=0) |
|
899 | """set_custom_completer(completer,pos=0) | |
900 |
|
900 | |||
901 | Adds a new custom completer function. |
|
901 | Adds a new custom completer function. | |
902 |
|
902 | |||
903 | The position argument (defaults to 0) is the index in the completers |
|
903 | The position argument (defaults to 0) is the index in the completers | |
904 | list where you want the completer to be inserted.""" |
|
904 | list where you want the completer to be inserted.""" | |
905 |
|
905 | |||
906 | newcomp = new.instancemethod(completer,self.Completer, |
|
906 | newcomp = new.instancemethod(completer,self.Completer, | |
907 | self.Completer.__class__) |
|
907 | self.Completer.__class__) | |
908 | self.Completer.matchers.insert(pos,newcomp) |
|
908 | self.Completer.matchers.insert(pos,newcomp) | |
909 |
|
909 | |||
910 | def set_completer(self): |
|
910 | def set_completer(self): | |
911 | """reset readline's completer to be our own.""" |
|
911 | """reset readline's completer to be our own.""" | |
912 | self.readline.set_completer(self.Completer.complete) |
|
912 | self.readline.set_completer(self.Completer.complete) | |
913 |
|
913 | |||
914 | def _get_call_pdb(self): |
|
914 | def _get_call_pdb(self): | |
915 | return self._call_pdb |
|
915 | return self._call_pdb | |
916 |
|
916 | |||
917 | def _set_call_pdb(self,val): |
|
917 | def _set_call_pdb(self,val): | |
918 |
|
918 | |||
919 | if val not in (0,1,False,True): |
|
919 | if val not in (0,1,False,True): | |
920 | raise ValueError,'new call_pdb value must be boolean' |
|
920 | raise ValueError,'new call_pdb value must be boolean' | |
921 |
|
921 | |||
922 | # store value in instance |
|
922 | # store value in instance | |
923 | self._call_pdb = val |
|
923 | self._call_pdb = val | |
924 |
|
924 | |||
925 | # notify the actual exception handlers |
|
925 | # notify the actual exception handlers | |
926 | self.InteractiveTB.call_pdb = val |
|
926 | self.InteractiveTB.call_pdb = val | |
927 | if self.isthreaded: |
|
927 | if self.isthreaded: | |
928 | try: |
|
928 | try: | |
929 | self.sys_excepthook.call_pdb = val |
|
929 | self.sys_excepthook.call_pdb = val | |
930 | except: |
|
930 | except: | |
931 | warn('Failed to activate pdb for threaded exception handler') |
|
931 | warn('Failed to activate pdb for threaded exception handler') | |
932 |
|
932 | |||
933 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
933 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
934 | 'Control auto-activation of pdb at exceptions') |
|
934 | 'Control auto-activation of pdb at exceptions') | |
935 |
|
935 | |||
936 | # These special functions get installed in the builtin namespace, to |
|
936 | # These special functions get installed in the builtin namespace, to | |
937 | # provide programmatic (pure python) access to magics, aliases and system |
|
937 | # provide programmatic (pure python) access to magics, aliases and system | |
938 | # calls. This is important for logging, user scripting, and more. |
|
938 | # calls. This is important for logging, user scripting, and more. | |
939 |
|
939 | |||
940 | # We are basically exposing, via normal python functions, the three |
|
940 | # We are basically exposing, via normal python functions, the three | |
941 | # mechanisms in which ipython offers special call modes (magics for |
|
941 | # mechanisms in which ipython offers special call modes (magics for | |
942 | # internal control, aliases for direct system access via pre-selected |
|
942 | # internal control, aliases for direct system access via pre-selected | |
943 | # names, and !cmd for calling arbitrary system commands). |
|
943 | # names, and !cmd for calling arbitrary system commands). | |
944 |
|
944 | |||
945 | def ipmagic(self,arg_s): |
|
945 | def ipmagic(self,arg_s): | |
946 | """Call a magic function by name. |
|
946 | """Call a magic function by name. | |
947 |
|
947 | |||
948 | Input: a string containing the name of the magic function to call and any |
|
948 | Input: a string containing the name of the magic function to call and any | |
949 | additional arguments to be passed to the magic. |
|
949 | additional arguments to be passed to the magic. | |
950 |
|
950 | |||
951 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
951 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
952 | prompt: |
|
952 | prompt: | |
953 |
|
953 | |||
954 | In[1]: %name -opt foo bar |
|
954 | In[1]: %name -opt foo bar | |
955 |
|
955 | |||
956 | To call a magic without arguments, simply use ipmagic('name'). |
|
956 | To call a magic without arguments, simply use ipmagic('name'). | |
957 |
|
957 | |||
958 | This provides a proper Python function to call IPython's magics in any |
|
958 | This provides a proper Python function to call IPython's magics in any | |
959 | valid Python code you can type at the interpreter, including loops and |
|
959 | valid Python code you can type at the interpreter, including loops and | |
960 | compound statements. It is added by IPython to the Python builtin |
|
960 | compound statements. It is added by IPython to the Python builtin | |
961 | namespace upon initialization.""" |
|
961 | namespace upon initialization.""" | |
962 |
|
962 | |||
963 | args = arg_s.split(' ',1) |
|
963 | args = arg_s.split(' ',1) | |
964 | magic_name = args[0] |
|
964 | magic_name = args[0] | |
965 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
965 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
966 |
|
966 | |||
967 | try: |
|
967 | try: | |
968 | magic_args = args[1] |
|
968 | magic_args = args[1] | |
969 | except IndexError: |
|
969 | except IndexError: | |
970 | magic_args = '' |
|
970 | magic_args = '' | |
971 | fn = getattr(self,'magic_'+magic_name,None) |
|
971 | fn = getattr(self,'magic_'+magic_name,None) | |
972 | if fn is None: |
|
972 | if fn is None: | |
973 | error("Magic function `%s` not found." % magic_name) |
|
973 | error("Magic function `%s` not found." % magic_name) | |
974 | else: |
|
974 | else: | |
975 | magic_args = self.var_expand(magic_args,1) |
|
975 | magic_args = self.var_expand(magic_args,1) | |
976 | return fn(magic_args) |
|
976 | return fn(magic_args) | |
977 |
|
977 | |||
978 | def ipalias(self,arg_s): |
|
978 | def ipalias(self,arg_s): | |
979 | """Call an alias by name. |
|
979 | """Call an alias by name. | |
980 |
|
980 | |||
981 | Input: a string containing the name of the alias to call and any |
|
981 | Input: a string containing the name of the alias to call and any | |
982 | additional arguments to be passed to the magic. |
|
982 | additional arguments to be passed to the magic. | |
983 |
|
983 | |||
984 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
984 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
985 | prompt: |
|
985 | prompt: | |
986 |
|
986 | |||
987 | In[1]: name -opt foo bar |
|
987 | In[1]: name -opt foo bar | |
988 |
|
988 | |||
989 | To call an alias without arguments, simply use ipalias('name'). |
|
989 | To call an alias without arguments, simply use ipalias('name'). | |
990 |
|
990 | |||
991 | This provides a proper Python function to call IPython's aliases in any |
|
991 | This provides a proper Python function to call IPython's aliases in any | |
992 | valid Python code you can type at the interpreter, including loops and |
|
992 | valid Python code you can type at the interpreter, including loops and | |
993 | compound statements. It is added by IPython to the Python builtin |
|
993 | compound statements. It is added by IPython to the Python builtin | |
994 | namespace upon initialization.""" |
|
994 | namespace upon initialization.""" | |
995 |
|
995 | |||
996 | args = arg_s.split(' ',1) |
|
996 | args = arg_s.split(' ',1) | |
997 | alias_name = args[0] |
|
997 | alias_name = args[0] | |
998 | try: |
|
998 | try: | |
999 | alias_args = args[1] |
|
999 | alias_args = args[1] | |
1000 | except IndexError: |
|
1000 | except IndexError: | |
1001 | alias_args = '' |
|
1001 | alias_args = '' | |
1002 | if alias_name in self.alias_table: |
|
1002 | if alias_name in self.alias_table: | |
1003 | self.call_alias(alias_name,alias_args) |
|
1003 | self.call_alias(alias_name,alias_args) | |
1004 | else: |
|
1004 | else: | |
1005 | error("Alias `%s` not found." % alias_name) |
|
1005 | error("Alias `%s` not found." % alias_name) | |
1006 |
|
1006 | |||
1007 | def ipsystem(self,arg_s): |
|
1007 | def ipsystem(self,arg_s): | |
1008 | """Make a system call, using IPython.""" |
|
1008 | """Make a system call, using IPython.""" | |
1009 |
|
1009 | |||
1010 | self.system(arg_s) |
|
1010 | self.system(arg_s) | |
1011 |
|
1011 | |||
1012 | def complete(self,text): |
|
1012 | def complete(self,text): | |
1013 | """Return a sorted list of all possible completions on text. |
|
1013 | """Return a sorted list of all possible completions on text. | |
1014 |
|
1014 | |||
1015 | Inputs: |
|
1015 | Inputs: | |
1016 |
|
1016 | |||
1017 | - text: a string of text to be completed on. |
|
1017 | - text: a string of text to be completed on. | |
1018 |
|
1018 | |||
1019 | This is a wrapper around the completion mechanism, similar to what |
|
1019 | This is a wrapper around the completion mechanism, similar to what | |
1020 | readline does at the command line when the TAB key is hit. By |
|
1020 | readline does at the command line when the TAB key is hit. By | |
1021 | exposing it as a method, it can be used by other non-readline |
|
1021 | exposing it as a method, it can be used by other non-readline | |
1022 | environments (such as GUIs) for text completion. |
|
1022 | environments (such as GUIs) for text completion. | |
1023 |
|
1023 | |||
1024 | Simple usage example: |
|
1024 | Simple usage example: | |
1025 |
|
1025 | |||
1026 | In [7]: x = 'hello' |
|
1026 | In [7]: x = 'hello' | |
1027 |
|
1027 | |||
1028 | In [8]: x |
|
1028 | In [8]: x | |
1029 | Out[8]: 'hello' |
|
1029 | Out[8]: 'hello' | |
1030 |
|
1030 | |||
1031 | In [9]: print x |
|
1031 | In [9]: print x | |
1032 | hello |
|
1032 | hello | |
1033 |
|
1033 | |||
1034 | In [10]: _ip.IP.complete('x.l') |
|
1034 | In [10]: _ip.IP.complete('x.l') | |
1035 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1035 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1036 | """ |
|
1036 | """ | |
1037 |
|
1037 | |||
1038 | complete = self.Completer.complete |
|
1038 | complete = self.Completer.complete | |
1039 | state = 0 |
|
1039 | state = 0 | |
1040 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1040 | # use a dict so we get unique keys, since ipyhton's multiple | |
1041 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1041 | # completers can return duplicates. When we make 2.4 a requirement, | |
1042 | # start using sets instead, which are faster. |
|
1042 | # start using sets instead, which are faster. | |
1043 | comps = {} |
|
1043 | comps = {} | |
1044 | while True: |
|
1044 | while True: | |
1045 | newcomp = complete(text,state,line_buffer=text) |
|
1045 | newcomp = complete(text,state,line_buffer=text) | |
1046 | if newcomp is None: |
|
1046 | if newcomp is None: | |
1047 | break |
|
1047 | break | |
1048 | comps[newcomp] = 1 |
|
1048 | comps[newcomp] = 1 | |
1049 | state += 1 |
|
1049 | state += 1 | |
1050 | outcomps = comps.keys() |
|
1050 | outcomps = comps.keys() | |
1051 | outcomps.sort() |
|
1051 | outcomps.sort() | |
1052 | #print "T:",text,"OC:",outcomps # dbg |
|
1052 | #print "T:",text,"OC:",outcomps # dbg | |
1053 | #print "vars:",self.user_ns.keys() |
|
1053 | #print "vars:",self.user_ns.keys() | |
1054 | return outcomps |
|
1054 | return outcomps | |
1055 |
|
1055 | |||
1056 | def set_completer_frame(self, frame=None): |
|
1056 | def set_completer_frame(self, frame=None): | |
1057 | if frame: |
|
1057 | if frame: | |
1058 | self.Completer.namespace = frame.f_locals |
|
1058 | self.Completer.namespace = frame.f_locals | |
1059 | self.Completer.global_namespace = frame.f_globals |
|
1059 | self.Completer.global_namespace = frame.f_globals | |
1060 | else: |
|
1060 | else: | |
1061 | self.Completer.namespace = self.user_ns |
|
1061 | self.Completer.namespace = self.user_ns | |
1062 | self.Completer.global_namespace = self.user_global_ns |
|
1062 | self.Completer.global_namespace = self.user_global_ns | |
1063 |
|
1063 | |||
1064 | def init_auto_alias(self): |
|
1064 | def init_auto_alias(self): | |
1065 | """Define some aliases automatically. |
|
1065 | """Define some aliases automatically. | |
1066 |
|
1066 | |||
1067 | These are ALL parameter-less aliases""" |
|
1067 | These are ALL parameter-less aliases""" | |
1068 |
|
1068 | |||
1069 | for alias,cmd in self.auto_alias: |
|
1069 | for alias,cmd in self.auto_alias: | |
1070 | self.getapi().defalias(alias,cmd) |
|
1070 | self.getapi().defalias(alias,cmd) | |
1071 |
|
1071 | |||
1072 |
|
1072 | |||
1073 | def alias_table_validate(self,verbose=0): |
|
1073 | def alias_table_validate(self,verbose=0): | |
1074 | """Update information about the alias table. |
|
1074 | """Update information about the alias table. | |
1075 |
|
1075 | |||
1076 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1076 | In particular, make sure no Python keywords/builtins are in it.""" | |
1077 |
|
1077 | |||
1078 | no_alias = self.no_alias |
|
1078 | no_alias = self.no_alias | |
1079 | for k in self.alias_table.keys(): |
|
1079 | for k in self.alias_table.keys(): | |
1080 | if k in no_alias: |
|
1080 | if k in no_alias: | |
1081 | del self.alias_table[k] |
|
1081 | del self.alias_table[k] | |
1082 | if verbose: |
|
1082 | if verbose: | |
1083 | print ("Deleting alias <%s>, it's a Python " |
|
1083 | print ("Deleting alias <%s>, it's a Python " | |
1084 | "keyword or builtin." % k) |
|
1084 | "keyword or builtin." % k) | |
1085 |
|
1085 | |||
1086 | def set_autoindent(self,value=None): |
|
1086 | def set_autoindent(self,value=None): | |
1087 | """Set the autoindent flag, checking for readline support. |
|
1087 | """Set the autoindent flag, checking for readline support. | |
1088 |
|
1088 | |||
1089 | If called with no arguments, it acts as a toggle.""" |
|
1089 | If called with no arguments, it acts as a toggle.""" | |
1090 |
|
1090 | |||
1091 | if not self.has_readline: |
|
1091 | if not self.has_readline: | |
1092 | if os.name == 'posix': |
|
1092 | if os.name == 'posix': | |
1093 | warn("The auto-indent feature requires the readline library") |
|
1093 | warn("The auto-indent feature requires the readline library") | |
1094 | self.autoindent = 0 |
|
1094 | self.autoindent = 0 | |
1095 | return |
|
1095 | return | |
1096 | if value is None: |
|
1096 | if value is None: | |
1097 | self.autoindent = not self.autoindent |
|
1097 | self.autoindent = not self.autoindent | |
1098 | else: |
|
1098 | else: | |
1099 | self.autoindent = value |
|
1099 | self.autoindent = value | |
1100 |
|
1100 | |||
1101 | def rc_set_toggle(self,rc_field,value=None): |
|
1101 | def rc_set_toggle(self,rc_field,value=None): | |
1102 | """Set or toggle a field in IPython's rc config. structure. |
|
1102 | """Set or toggle a field in IPython's rc config. structure. | |
1103 |
|
1103 | |||
1104 | If called with no arguments, it acts as a toggle. |
|
1104 | If called with no arguments, it acts as a toggle. | |
1105 |
|
1105 | |||
1106 | If called with a non-existent field, the resulting AttributeError |
|
1106 | If called with a non-existent field, the resulting AttributeError | |
1107 | exception will propagate out.""" |
|
1107 | exception will propagate out.""" | |
1108 |
|
1108 | |||
1109 | rc_val = getattr(self.rc,rc_field) |
|
1109 | rc_val = getattr(self.rc,rc_field) | |
1110 | if value is None: |
|
1110 | if value is None: | |
1111 | value = not rc_val |
|
1111 | value = not rc_val | |
1112 | setattr(self.rc,rc_field,value) |
|
1112 | setattr(self.rc,rc_field,value) | |
1113 |
|
1113 | |||
1114 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1114 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
1115 | """Install the user configuration directory. |
|
1115 | """Install the user configuration directory. | |
1116 |
|
1116 | |||
1117 | Can be called when running for the first time or to upgrade the user's |
|
1117 | Can be called when running for the first time or to upgrade the user's | |
1118 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
1118 | .ipython/ directory with the mode parameter. Valid modes are 'install' | |
1119 | and 'upgrade'.""" |
|
1119 | and 'upgrade'.""" | |
1120 |
|
1120 | |||
1121 | def wait(): |
|
1121 | def wait(): | |
1122 | try: |
|
1122 | try: | |
1123 | raw_input("Please press <RETURN> to start IPython.") |
|
1123 | raw_input("Please press <RETURN> to start IPython.") | |
1124 | except EOFError: |
|
1124 | except EOFError: | |
1125 | print >> Term.cout |
|
1125 | print >> Term.cout | |
1126 | print '*'*70 |
|
1126 | print '*'*70 | |
1127 |
|
1127 | |||
1128 | cwd = os.getcwd() # remember where we started |
|
1128 | cwd = os.getcwd() # remember where we started | |
1129 | glb = glob.glob |
|
1129 | glb = glob.glob | |
1130 | print '*'*70 |
|
1130 | print '*'*70 | |
1131 | if mode == 'install': |
|
1131 | if mode == 'install': | |
1132 | print \ |
|
1132 | print \ | |
1133 | """Welcome to IPython. I will try to create a personal configuration directory |
|
1133 | """Welcome to IPython. I will try to create a personal configuration directory | |
1134 | where you can customize many aspects of IPython's functionality in:\n""" |
|
1134 | where you can customize many aspects of IPython's functionality in:\n""" | |
1135 | else: |
|
1135 | else: | |
1136 | print 'I am going to upgrade your configuration in:' |
|
1136 | print 'I am going to upgrade your configuration in:' | |
1137 |
|
1137 | |||
1138 | print ipythondir |
|
1138 | print ipythondir | |
1139 |
|
1139 | |||
1140 | rcdirend = os.path.join('IPython','UserConfig') |
|
1140 | rcdirend = os.path.join('IPython','UserConfig') | |
1141 | cfg = lambda d: os.path.join(d,rcdirend) |
|
1141 | cfg = lambda d: os.path.join(d,rcdirend) | |
1142 | try: |
|
1142 | try: | |
1143 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
1143 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
1144 | print "Initializing from configuration",rcdir |
|
1144 | print "Initializing from configuration",rcdir | |
1145 | except IndexError: |
|
1145 | except IndexError: | |
1146 | warning = """ |
|
1146 | warning = """ | |
1147 | Installation error. IPython's directory was not found. |
|
1147 | Installation error. IPython's directory was not found. | |
1148 |
|
1148 | |||
1149 | Check the following: |
|
1149 | Check the following: | |
1150 |
|
1150 | |||
1151 | The ipython/IPython directory should be in a directory belonging to your |
|
1151 | The ipython/IPython directory should be in a directory belonging to your | |
1152 | PYTHONPATH environment variable (that is, it should be in a directory |
|
1152 | PYTHONPATH environment variable (that is, it should be in a directory | |
1153 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
1153 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
1154 |
|
1154 | |||
1155 | IPython will create a minimal default configuration for you. |
|
1155 | IPython will create a minimal default configuration for you. | |
1156 |
|
1156 | |||
1157 | """ |
|
1157 | """ | |
1158 | warn(warning) |
|
1158 | warn(warning) | |
1159 | wait() |
|
1159 | wait() | |
1160 |
|
1160 | |||
1161 | if sys.platform =='win32': |
|
1161 | if sys.platform =='win32': | |
1162 | inif = 'ipythonrc.ini' |
|
1162 | inif = 'ipythonrc.ini' | |
1163 | else: |
|
1163 | else: | |
1164 | inif = 'ipythonrc' |
|
1164 | inif = 'ipythonrc' | |
1165 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', |
|
1165 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', | |
1166 | inif : '# intentionally left blank' } |
|
1166 | inif : '# intentionally left blank' } | |
1167 | os.makedirs(ipythondir, mode = 0777) |
|
1167 | os.makedirs(ipythondir, mode = 0777) | |
1168 | for f, cont in minimal_setup.items(): |
|
1168 | for f, cont in minimal_setup.items(): | |
1169 | open(ipythondir + '/' + f,'w').write(cont) |
|
1169 | open(ipythondir + '/' + f,'w').write(cont) | |
1170 |
|
1170 | |||
1171 | return |
|
1171 | return | |
1172 |
|
1172 | |||
1173 | if mode == 'install': |
|
1173 | if mode == 'install': | |
1174 | try: |
|
1174 | try: | |
1175 | shutil.copytree(rcdir,ipythondir) |
|
1175 | shutil.copytree(rcdir,ipythondir) | |
1176 | os.chdir(ipythondir) |
|
1176 | os.chdir(ipythondir) | |
1177 | rc_files = glb("ipythonrc*") |
|
1177 | rc_files = glb("ipythonrc*") | |
1178 | for rc_file in rc_files: |
|
1178 | for rc_file in rc_files: | |
1179 | os.rename(rc_file,rc_file+rc_suffix) |
|
1179 | os.rename(rc_file,rc_file+rc_suffix) | |
1180 | except: |
|
1180 | except: | |
1181 | warning = """ |
|
1181 | warning = """ | |
1182 |
|
1182 | |||
1183 | There was a problem with the installation: |
|
1183 | There was a problem with the installation: | |
1184 | %s |
|
1184 | %s | |
1185 | Try to correct it or contact the developers if you think it's a bug. |
|
1185 | Try to correct it or contact the developers if you think it's a bug. | |
1186 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
1186 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
1187 | warn(warning) |
|
1187 | warn(warning) | |
1188 | wait() |
|
1188 | wait() | |
1189 | return |
|
1189 | return | |
1190 |
|
1190 | |||
1191 | elif mode == 'upgrade': |
|
1191 | elif mode == 'upgrade': | |
1192 | try: |
|
1192 | try: | |
1193 | os.chdir(ipythondir) |
|
1193 | os.chdir(ipythondir) | |
1194 | except: |
|
1194 | except: | |
1195 | print """ |
|
1195 | print """ | |
1196 | Can not upgrade: changing to directory %s failed. Details: |
|
1196 | Can not upgrade: changing to directory %s failed. Details: | |
1197 | %s |
|
1197 | %s | |
1198 | """ % (ipythondir,sys.exc_info()[1]) |
|
1198 | """ % (ipythondir,sys.exc_info()[1]) | |
1199 | wait() |
|
1199 | wait() | |
1200 | return |
|
1200 | return | |
1201 | else: |
|
1201 | else: | |
1202 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
1202 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
1203 | for new_full_path in sources: |
|
1203 | for new_full_path in sources: | |
1204 | new_filename = os.path.basename(new_full_path) |
|
1204 | new_filename = os.path.basename(new_full_path) | |
1205 | if new_filename.startswith('ipythonrc'): |
|
1205 | if new_filename.startswith('ipythonrc'): | |
1206 | new_filename = new_filename + rc_suffix |
|
1206 | new_filename = new_filename + rc_suffix | |
1207 | # The config directory should only contain files, skip any |
|
1207 | # The config directory should only contain files, skip any | |
1208 | # directories which may be there (like CVS) |
|
1208 | # directories which may be there (like CVS) | |
1209 | if os.path.isdir(new_full_path): |
|
1209 | if os.path.isdir(new_full_path): | |
1210 | continue |
|
1210 | continue | |
1211 | if os.path.exists(new_filename): |
|
1211 | if os.path.exists(new_filename): | |
1212 | old_file = new_filename+'.old' |
|
1212 | old_file = new_filename+'.old' | |
1213 | if os.path.exists(old_file): |
|
1213 | if os.path.exists(old_file): | |
1214 | os.remove(old_file) |
|
1214 | os.remove(old_file) | |
1215 | os.rename(new_filename,old_file) |
|
1215 | os.rename(new_filename,old_file) | |
1216 | shutil.copy(new_full_path,new_filename) |
|
1216 | shutil.copy(new_full_path,new_filename) | |
1217 | else: |
|
1217 | else: | |
1218 | raise ValueError,'unrecognized mode for install:',`mode` |
|
1218 | raise ValueError,'unrecognized mode for install:',`mode` | |
1219 |
|
1219 | |||
1220 | # Fix line-endings to those native to each platform in the config |
|
1220 | # Fix line-endings to those native to each platform in the config | |
1221 | # directory. |
|
1221 | # directory. | |
1222 | try: |
|
1222 | try: | |
1223 | os.chdir(ipythondir) |
|
1223 | os.chdir(ipythondir) | |
1224 | except: |
|
1224 | except: | |
1225 | print """ |
|
1225 | print """ | |
1226 | Problem: changing to directory %s failed. |
|
1226 | Problem: changing to directory %s failed. | |
1227 | Details: |
|
1227 | Details: | |
1228 | %s |
|
1228 | %s | |
1229 |
|
1229 | |||
1230 | Some configuration files may have incorrect line endings. This should not |
|
1230 | Some configuration files may have incorrect line endings. This should not | |
1231 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1231 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) | |
1232 | wait() |
|
1232 | wait() | |
1233 | else: |
|
1233 | else: | |
1234 | for fname in glb('ipythonrc*'): |
|
1234 | for fname in glb('ipythonrc*'): | |
1235 | try: |
|
1235 | try: | |
1236 | native_line_ends(fname,backup=0) |
|
1236 | native_line_ends(fname,backup=0) | |
1237 | except IOError: |
|
1237 | except IOError: | |
1238 | pass |
|
1238 | pass | |
1239 |
|
1239 | |||
1240 | if mode == 'install': |
|
1240 | if mode == 'install': | |
1241 | print """ |
|
1241 | print """ | |
1242 | Successful installation! |
|
1242 | Successful installation! | |
1243 |
|
1243 | |||
1244 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1244 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
1245 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1245 | IPython manual (there are both HTML and PDF versions supplied with the | |
1246 | distribution) to make sure that your system environment is properly configured |
|
1246 | distribution) to make sure that your system environment is properly configured | |
1247 | to take advantage of IPython's features. |
|
1247 | to take advantage of IPython's features. | |
1248 |
|
1248 | |||
1249 | Important note: the configuration system has changed! The old system is |
|
1249 | Important note: the configuration system has changed! The old system is | |
1250 | still in place, but its setting may be partly overridden by the settings in |
|
1250 | still in place, but its setting may be partly overridden by the settings in | |
1251 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
1251 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
1252 | if some of the new settings bother you. |
|
1252 | if some of the new settings bother you. | |
1253 |
|
1253 | |||
1254 | """ |
|
1254 | """ | |
1255 | else: |
|
1255 | else: | |
1256 | print """ |
|
1256 | print """ | |
1257 | Successful upgrade! |
|
1257 | Successful upgrade! | |
1258 |
|
1258 | |||
1259 | All files in your directory: |
|
1259 | All files in your directory: | |
1260 | %(ipythondir)s |
|
1260 | %(ipythondir)s | |
1261 | which would have been overwritten by the upgrade were backed up with a .old |
|
1261 | which would have been overwritten by the upgrade were backed up with a .old | |
1262 | extension. If you had made particular customizations in those files you may |
|
1262 | extension. If you had made particular customizations in those files you may | |
1263 | want to merge them back into the new files.""" % locals() |
|
1263 | want to merge them back into the new files.""" % locals() | |
1264 | wait() |
|
1264 | wait() | |
1265 | os.chdir(cwd) |
|
1265 | os.chdir(cwd) | |
1266 | # end user_setup() |
|
1266 | # end user_setup() | |
1267 |
|
1267 | |||
1268 | def atexit_operations(self): |
|
1268 | def atexit_operations(self): | |
1269 | """This will be executed at the time of exit. |
|
1269 | """This will be executed at the time of exit. | |
1270 |
|
1270 | |||
1271 | Saving of persistent data should be performed here. """ |
|
1271 | Saving of persistent data should be performed here. """ | |
1272 |
|
1272 | |||
1273 | #print '*** IPython exit cleanup ***' # dbg |
|
1273 | #print '*** IPython exit cleanup ***' # dbg | |
1274 | # input history |
|
1274 | # input history | |
1275 | self.savehist() |
|
1275 | self.savehist() | |
1276 |
|
1276 | |||
1277 | # Cleanup all tempfiles left around |
|
1277 | # Cleanup all tempfiles left around | |
1278 | for tfile in self.tempfiles: |
|
1278 | for tfile in self.tempfiles: | |
1279 | try: |
|
1279 | try: | |
1280 | os.unlink(tfile) |
|
1280 | os.unlink(tfile) | |
1281 | except OSError: |
|
1281 | except OSError: | |
1282 | pass |
|
1282 | pass | |
1283 |
|
1283 | |||
1284 | # Clear all user namespaces to release all references cleanly. |
|
1284 | # Clear all user namespaces to release all references cleanly. | |
1285 | self.reset() |
|
1285 | self.reset() | |
1286 |
|
1286 | |||
1287 | # Run user hooks |
|
1287 | # Run user hooks | |
1288 | self.hooks.shutdown_hook() |
|
1288 | self.hooks.shutdown_hook() | |
1289 |
|
1289 | |||
1290 | def reset(self): |
|
1290 | def reset(self): | |
1291 | """Clear all internal namespaces. |
|
1291 | """Clear all internal namespaces. | |
1292 |
|
1292 | |||
1293 | Note that this is much more aggressive than %reset, since it clears |
|
1293 | Note that this is much more aggressive than %reset, since it clears | |
1294 | fully all namespaces, as well as all input/output lists. |
|
1294 | fully all namespaces, as well as all input/output lists. | |
1295 | """ |
|
1295 | """ | |
1296 | for ns in self.ns_refs_table: |
|
1296 | for ns in self.ns_refs_table: | |
1297 | ns.clear() |
|
1297 | ns.clear() | |
1298 |
|
1298 | |||
1299 | # Clear input and output histories |
|
1299 | # Clear input and output histories | |
1300 | self.input_hist[:] = [] |
|
1300 | self.input_hist[:] = [] | |
1301 | self.input_hist_raw[:] = [] |
|
1301 | self.input_hist_raw[:] = [] | |
1302 | self.output_hist.clear() |
|
1302 | self.output_hist.clear() | |
1303 | # Restore the user namespaces to minimal usability |
|
1303 | # Restore the user namespaces to minimal usability | |
1304 | self.init_namespaces() |
|
1304 | self.init_namespaces() | |
1305 |
|
1305 | |||
1306 | def savehist(self): |
|
1306 | def savehist(self): | |
1307 | """Save input history to a file (via readline library).""" |
|
1307 | """Save input history to a file (via readline library).""" | |
1308 |
|
1308 | |||
1309 | if not self.has_readline: |
|
1309 | if not self.has_readline: | |
1310 | return |
|
1310 | return | |
1311 |
|
1311 | |||
1312 | try: |
|
1312 | try: | |
1313 | self.readline.write_history_file(self.histfile) |
|
1313 | self.readline.write_history_file(self.histfile) | |
1314 | except: |
|
1314 | except: | |
1315 | print 'Unable to save IPython command history to file: ' + \ |
|
1315 | print 'Unable to save IPython command history to file: ' + \ | |
1316 | `self.histfile` |
|
1316 | `self.histfile` | |
1317 |
|
1317 | |||
1318 | def reloadhist(self): |
|
1318 | def reloadhist(self): | |
1319 | """Reload the input history from disk file.""" |
|
1319 | """Reload the input history from disk file.""" | |
1320 |
|
1320 | |||
1321 | if self.has_readline: |
|
1321 | if self.has_readline: | |
1322 | try: |
|
1322 | try: | |
1323 | self.readline.clear_history() |
|
1323 | self.readline.clear_history() | |
1324 | self.readline.read_history_file(self.shell.histfile) |
|
1324 | self.readline.read_history_file(self.shell.histfile) | |
1325 | except AttributeError: |
|
1325 | except AttributeError: | |
1326 | pass |
|
1326 | pass | |
1327 |
|
1327 | |||
1328 |
|
1328 | |||
1329 | def history_saving_wrapper(self, func): |
|
1329 | def history_saving_wrapper(self, func): | |
1330 | """ Wrap func for readline history saving |
|
1330 | """ Wrap func for readline history saving | |
1331 |
|
1331 | |||
1332 | Convert func into callable that saves & restores |
|
1332 | Convert func into callable that saves & restores | |
1333 | history around the call """ |
|
1333 | history around the call """ | |
1334 |
|
1334 | |||
1335 | if not self.has_readline: |
|
1335 | if not self.has_readline: | |
1336 | return func |
|
1336 | return func | |
1337 |
|
1337 | |||
1338 | def wrapper(): |
|
1338 | def wrapper(): | |
1339 | self.savehist() |
|
1339 | self.savehist() | |
1340 | try: |
|
1340 | try: | |
1341 | func() |
|
1341 | func() | |
1342 | finally: |
|
1342 | finally: | |
1343 | readline.read_history_file(self.histfile) |
|
1343 | readline.read_history_file(self.histfile) | |
1344 | return wrapper |
|
1344 | return wrapper | |
1345 |
|
1345 | |||
1346 | def pre_readline(self): |
|
1346 | def pre_readline(self): | |
1347 | """readline hook to be used at the start of each line. |
|
1347 | """readline hook to be used at the start of each line. | |
1348 |
|
1348 | |||
1349 | Currently it handles auto-indent only.""" |
|
1349 | Currently it handles auto-indent only.""" | |
1350 |
|
1350 | |||
1351 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1351 | #debugx('self.indent_current_nsp','pre_readline:') | |
1352 |
|
1352 | |||
1353 | if self.rl_do_indent: |
|
1353 | if self.rl_do_indent: | |
1354 | self.readline.insert_text(self.indent_current_str()) |
|
1354 | self.readline.insert_text(self.indent_current_str()) | |
1355 | if self.rl_next_input is not None: |
|
1355 | if self.rl_next_input is not None: | |
1356 | self.readline.insert_text(self.rl_next_input) |
|
1356 | self.readline.insert_text(self.rl_next_input) | |
1357 | self.rl_next_input = None |
|
1357 | self.rl_next_input = None | |
1358 |
|
1358 | |||
1359 | def init_readline(self): |
|
1359 | def init_readline(self): | |
1360 | """Command history completion/saving/reloading.""" |
|
1360 | """Command history completion/saving/reloading.""" | |
1361 |
|
1361 | |||
1362 |
|
1362 | |||
1363 | import IPython.rlineimpl as readline |
|
1363 | import IPython.rlineimpl as readline | |
1364 |
|
1364 | |||
1365 | if not readline.have_readline: |
|
1365 | if not readline.have_readline: | |
1366 | self.has_readline = 0 |
|
1366 | self.has_readline = 0 | |
1367 | self.readline = None |
|
1367 | self.readline = None | |
1368 | # no point in bugging windows users with this every time: |
|
1368 | # no point in bugging windows users with this every time: | |
1369 | warn('Readline services not available on this platform.') |
|
1369 | warn('Readline services not available on this platform.') | |
1370 | else: |
|
1370 | else: | |
1371 | sys.modules['readline'] = readline |
|
1371 | sys.modules['readline'] = readline | |
1372 | import atexit |
|
1372 | import atexit | |
1373 | from IPython.completer import IPCompleter |
|
1373 | from IPython.completer import IPCompleter | |
1374 | self.Completer = IPCompleter(self, |
|
1374 | self.Completer = IPCompleter(self, | |
1375 | self.user_ns, |
|
1375 | self.user_ns, | |
1376 | self.user_global_ns, |
|
1376 | self.user_global_ns, | |
1377 | self.rc.readline_omit__names, |
|
1377 | self.rc.readline_omit__names, | |
1378 | self.alias_table) |
|
1378 | self.alias_table) | |
1379 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1379 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1380 | self.strdispatchers['complete_command'] = sdisp |
|
1380 | self.strdispatchers['complete_command'] = sdisp | |
1381 | self.Completer.custom_completers = sdisp |
|
1381 | self.Completer.custom_completers = sdisp | |
1382 | # Platform-specific configuration |
|
1382 | # Platform-specific configuration | |
1383 | if os.name == 'nt': |
|
1383 | if os.name == 'nt': | |
1384 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1384 | self.readline_startup_hook = readline.set_pre_input_hook | |
1385 | else: |
|
1385 | else: | |
1386 | self.readline_startup_hook = readline.set_startup_hook |
|
1386 | self.readline_startup_hook = readline.set_startup_hook | |
1387 |
|
1387 | |||
1388 | # Load user's initrc file (readline config) |
|
1388 | # Load user's initrc file (readline config) | |
1389 | # Or if libedit is used, load editrc. |
|
1389 | # Or if libedit is used, load editrc. | |
1390 | inputrc_name = os.environ.get('INPUTRC') |
|
1390 | inputrc_name = os.environ.get('INPUTRC') | |
1391 | if inputrc_name is None: |
|
1391 | if inputrc_name is None: | |
1392 | home_dir = get_home_dir() |
|
1392 | home_dir = get_home_dir() | |
1393 | if home_dir is not None: |
|
1393 | if home_dir is not None: | |
1394 | inputrc_name = '.inputrc' |
|
1394 | inputrc_name = '.inputrc' | |
1395 | if readline.uses_libedit: |
|
1395 | if readline.uses_libedit: | |
1396 | inputrc_name = '.editrc' |
|
1396 | inputrc_name = '.editrc' | |
1397 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1397 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1398 | if os.path.isfile(inputrc_name): |
|
1398 | if os.path.isfile(inputrc_name): | |
1399 | try: |
|
1399 | try: | |
1400 | readline.read_init_file(inputrc_name) |
|
1400 | readline.read_init_file(inputrc_name) | |
1401 | except: |
|
1401 | except: | |
1402 | warn('Problems reading readline initialization file <%s>' |
|
1402 | warn('Problems reading readline initialization file <%s>' | |
1403 | % inputrc_name) |
|
1403 | % inputrc_name) | |
1404 |
|
1404 | |||
1405 | self.has_readline = 1 |
|
1405 | self.has_readline = 1 | |
1406 | self.readline = readline |
|
1406 | self.readline = readline | |
1407 | # save this in sys so embedded copies can restore it properly |
|
1407 | # save this in sys so embedded copies can restore it properly | |
1408 | sys.ipcompleter = self.Completer.complete |
|
1408 | sys.ipcompleter = self.Completer.complete | |
1409 | self.set_completer() |
|
1409 | self.set_completer() | |
1410 |
|
1410 | |||
1411 | # Configure readline according to user's prefs |
|
1411 | # Configure readline according to user's prefs | |
1412 | # This is only done if GNU readline is being used. If libedit |
|
1412 | # This is only done if GNU readline is being used. If libedit | |
1413 | # is being used (as on Leopard) the readline config is |
|
1413 | # is being used (as on Leopard) the readline config is | |
1414 | # not run as the syntax for libedit is different. |
|
1414 | # not run as the syntax for libedit is different. | |
1415 | if not readline.uses_libedit: |
|
1415 | if not readline.uses_libedit: | |
1416 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1416 | for rlcommand in self.rc.readline_parse_and_bind: | |
|
1417 | #print "loading rl:",rlcommand # dbg | |||
1417 | readline.parse_and_bind(rlcommand) |
|
1418 | readline.parse_and_bind(rlcommand) | |
1418 |
|
1419 | |||
1419 | # remove some chars from the delimiters list |
|
1420 | # remove some chars from the delimiters list | |
1420 | delims = readline.get_completer_delims() |
|
1421 | delims = readline.get_completer_delims() | |
1421 | delims = delims.translate(string._idmap, |
|
1422 | delims = delims.translate(string._idmap, | |
1422 | self.rc.readline_remove_delims) |
|
1423 | self.rc.readline_remove_delims) | |
1423 | readline.set_completer_delims(delims) |
|
1424 | readline.set_completer_delims(delims) | |
1424 | # otherwise we end up with a monster history after a while: |
|
1425 | # otherwise we end up with a monster history after a while: | |
1425 | readline.set_history_length(1000) |
|
1426 | readline.set_history_length(1000) | |
1426 | try: |
|
1427 | try: | |
1427 | #print '*** Reading readline history' # dbg |
|
1428 | #print '*** Reading readline history' # dbg | |
1428 | readline.read_history_file(self.histfile) |
|
1429 | readline.read_history_file(self.histfile) | |
1429 | except IOError: |
|
1430 | except IOError: | |
1430 | pass # It doesn't exist yet. |
|
1431 | pass # It doesn't exist yet. | |
1431 |
|
1432 | |||
1432 | atexit.register(self.atexit_operations) |
|
1433 | atexit.register(self.atexit_operations) | |
1433 | del atexit |
|
1434 | del atexit | |
1434 |
|
1435 | |||
1435 | # Configure auto-indent for all platforms |
|
1436 | # Configure auto-indent for all platforms | |
1436 | self.set_autoindent(self.rc.autoindent) |
|
1437 | self.set_autoindent(self.rc.autoindent) | |
1437 |
|
1438 | |||
1438 | def ask_yes_no(self,prompt,default=True): |
|
1439 | def ask_yes_no(self,prompt,default=True): | |
1439 | if self.rc.quiet: |
|
1440 | if self.rc.quiet: | |
1440 | return True |
|
1441 | return True | |
1441 | return ask_yes_no(prompt,default) |
|
1442 | return ask_yes_no(prompt,default) | |
1442 |
|
1443 | |||
1443 | def cache_main_mod(self,mod): |
|
1444 | def cache_main_mod(self,mod): | |
1444 | """Cache a main module. |
|
1445 | """Cache a main module. | |
1445 |
|
1446 | |||
1446 | When scripts are executed via %run, we must keep a reference to their |
|
1447 | When scripts are executed via %run, we must keep a reference to their | |
1447 | __main__ module (a FakeModule instance) around so that Python doesn't |
|
1448 | __main__ module (a FakeModule instance) around so that Python doesn't | |
1448 | clear it, rendering objects defined therein useless. |
|
1449 | clear it, rendering objects defined therein useless. | |
1449 |
|
1450 | |||
1450 | This method keeps said reference in a private dict, keyed by the |
|
1451 | This method keeps said reference in a private dict, keyed by the | |
1451 | absolute path of the module object (which corresponds to the script |
|
1452 | absolute path of the module object (which corresponds to the script | |
1452 | path). This way, for multiple executions of the same script we only |
|
1453 | path). This way, for multiple executions of the same script we only | |
1453 | keep one copy of __main__ (the last one), thus preventing memory leaks |
|
1454 | keep one copy of __main__ (the last one), thus preventing memory leaks | |
1454 | from old references while allowing the objects from the last execution |
|
1455 | from old references while allowing the objects from the last execution | |
1455 | to be accessible. |
|
1456 | to be accessible. | |
1456 |
|
1457 | |||
1457 | Parameters |
|
1458 | Parameters | |
1458 | ---------- |
|
1459 | ---------- | |
1459 | mod : a module object |
|
1460 | mod : a module object | |
1460 |
|
1461 | |||
1461 | Examples |
|
1462 | Examples | |
1462 | -------- |
|
1463 | -------- | |
1463 |
|
1464 | |||
1464 | In [10]: import IPython |
|
1465 | In [10]: import IPython | |
1465 |
|
1466 | |||
1466 | In [11]: _ip.IP.cache_main_mod(IPython) |
|
1467 | In [11]: _ip.IP.cache_main_mod(IPython) | |
1467 |
|
1468 | |||
1468 | In [12]: IPython.__file__ in _ip.IP._user_main_modules |
|
1469 | In [12]: IPython.__file__ in _ip.IP._user_main_modules | |
1469 | Out[12]: True |
|
1470 | Out[12]: True | |
1470 | """ |
|
1471 | """ | |
1471 | self._user_main_modules[os.path.abspath(mod.__file__) ] = mod |
|
1472 | self._user_main_modules[os.path.abspath(mod.__file__) ] = mod | |
1472 |
|
1473 | |||
1473 | def clear_main_mod_cache(self): |
|
1474 | def clear_main_mod_cache(self): | |
1474 | """Clear the cache of main modules. |
|
1475 | """Clear the cache of main modules. | |
1475 |
|
1476 | |||
1476 | Mainly for use by utilities like %reset. |
|
1477 | Mainly for use by utilities like %reset. | |
1477 |
|
1478 | |||
1478 | Examples |
|
1479 | Examples | |
1479 | -------- |
|
1480 | -------- | |
1480 |
|
1481 | |||
1481 | In [15]: import IPython |
|
1482 | In [15]: import IPython | |
1482 |
|
1483 | |||
1483 | In [16]: _ip.IP.cache_main_mod(IPython) |
|
1484 | In [16]: _ip.IP.cache_main_mod(IPython) | |
1484 |
|
1485 | |||
1485 | In [17]: len(_ip.IP._user_main_modules) > 0 |
|
1486 | In [17]: len(_ip.IP._user_main_modules) > 0 | |
1486 | Out[17]: True |
|
1487 | Out[17]: True | |
1487 |
|
1488 | |||
1488 | In [18]: _ip.IP.clear_main_mod_cache() |
|
1489 | In [18]: _ip.IP.clear_main_mod_cache() | |
1489 |
|
1490 | |||
1490 | In [19]: len(_ip.IP._user_main_modules) == 0 |
|
1491 | In [19]: len(_ip.IP._user_main_modules) == 0 | |
1491 | Out[19]: True |
|
1492 | Out[19]: True | |
1492 | """ |
|
1493 | """ | |
1493 | self._user_main_modules.clear() |
|
1494 | self._user_main_modules.clear() | |
1494 |
|
1495 | |||
1495 | def _should_recompile(self,e): |
|
1496 | def _should_recompile(self,e): | |
1496 | """Utility routine for edit_syntax_error""" |
|
1497 | """Utility routine for edit_syntax_error""" | |
1497 |
|
1498 | |||
1498 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1499 | if e.filename in ('<ipython console>','<input>','<string>', | |
1499 | '<console>','<BackgroundJob compilation>', |
|
1500 | '<console>','<BackgroundJob compilation>', | |
1500 | None): |
|
1501 | None): | |
1501 |
|
1502 | |||
1502 | return False |
|
1503 | return False | |
1503 | try: |
|
1504 | try: | |
1504 | if (self.rc.autoedit_syntax and |
|
1505 | if (self.rc.autoedit_syntax and | |
1505 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1506 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1506 | '[Y/n] ','y')): |
|
1507 | '[Y/n] ','y')): | |
1507 | return False |
|
1508 | return False | |
1508 | except EOFError: |
|
1509 | except EOFError: | |
1509 | return False |
|
1510 | return False | |
1510 |
|
1511 | |||
1511 | def int0(x): |
|
1512 | def int0(x): | |
1512 | try: |
|
1513 | try: | |
1513 | return int(x) |
|
1514 | return int(x) | |
1514 | except TypeError: |
|
1515 | except TypeError: | |
1515 | return 0 |
|
1516 | return 0 | |
1516 | # always pass integer line and offset values to editor hook |
|
1517 | # always pass integer line and offset values to editor hook | |
1517 | try: |
|
1518 | try: | |
1518 | self.hooks.fix_error_editor(e.filename, |
|
1519 | self.hooks.fix_error_editor(e.filename, | |
1519 | int0(e.lineno),int0(e.offset),e.msg) |
|
1520 | int0(e.lineno),int0(e.offset),e.msg) | |
1520 | except IPython.ipapi.TryNext: |
|
1521 | except IPython.ipapi.TryNext: | |
1521 | warn('Could not open editor') |
|
1522 | warn('Could not open editor') | |
1522 | return False |
|
1523 | return False | |
1523 | return True |
|
1524 | return True | |
1524 |
|
1525 | |||
1525 | def edit_syntax_error(self): |
|
1526 | def edit_syntax_error(self): | |
1526 | """The bottom half of the syntax error handler called in the main loop. |
|
1527 | """The bottom half of the syntax error handler called in the main loop. | |
1527 |
|
1528 | |||
1528 | Loop until syntax error is fixed or user cancels. |
|
1529 | Loop until syntax error is fixed or user cancels. | |
1529 | """ |
|
1530 | """ | |
1530 |
|
1531 | |||
1531 | while self.SyntaxTB.last_syntax_error: |
|
1532 | while self.SyntaxTB.last_syntax_error: | |
1532 | # copy and clear last_syntax_error |
|
1533 | # copy and clear last_syntax_error | |
1533 | err = self.SyntaxTB.clear_err_state() |
|
1534 | err = self.SyntaxTB.clear_err_state() | |
1534 | if not self._should_recompile(err): |
|
1535 | if not self._should_recompile(err): | |
1535 | return |
|
1536 | return | |
1536 | try: |
|
1537 | try: | |
1537 | # may set last_syntax_error again if a SyntaxError is raised |
|
1538 | # may set last_syntax_error again if a SyntaxError is raised | |
1538 | self.safe_execfile(err.filename,self.user_ns) |
|
1539 | self.safe_execfile(err.filename,self.user_ns) | |
1539 | except: |
|
1540 | except: | |
1540 | self.showtraceback() |
|
1541 | self.showtraceback() | |
1541 | else: |
|
1542 | else: | |
1542 | try: |
|
1543 | try: | |
1543 | f = file(err.filename) |
|
1544 | f = file(err.filename) | |
1544 | try: |
|
1545 | try: | |
1545 | sys.displayhook(f.read()) |
|
1546 | sys.displayhook(f.read()) | |
1546 | finally: |
|
1547 | finally: | |
1547 | f.close() |
|
1548 | f.close() | |
1548 | except: |
|
1549 | except: | |
1549 | self.showtraceback() |
|
1550 | self.showtraceback() | |
1550 |
|
1551 | |||
1551 | def showsyntaxerror(self, filename=None): |
|
1552 | def showsyntaxerror(self, filename=None): | |
1552 | """Display the syntax error that just occurred. |
|
1553 | """Display the syntax error that just occurred. | |
1553 |
|
1554 | |||
1554 | This doesn't display a stack trace because there isn't one. |
|
1555 | This doesn't display a stack trace because there isn't one. | |
1555 |
|
1556 | |||
1556 | If a filename is given, it is stuffed in the exception instead |
|
1557 | If a filename is given, it is stuffed in the exception instead | |
1557 | of what was there before (because Python's parser always uses |
|
1558 | of what was there before (because Python's parser always uses | |
1558 | "<string>" when reading from a string). |
|
1559 | "<string>" when reading from a string). | |
1559 | """ |
|
1560 | """ | |
1560 | etype, value, last_traceback = sys.exc_info() |
|
1561 | etype, value, last_traceback = sys.exc_info() | |
1561 |
|
1562 | |||
1562 | # See note about these variables in showtraceback() below |
|
1563 | # See note about these variables in showtraceback() below | |
1563 | sys.last_type = etype |
|
1564 | sys.last_type = etype | |
1564 | sys.last_value = value |
|
1565 | sys.last_value = value | |
1565 | sys.last_traceback = last_traceback |
|
1566 | sys.last_traceback = last_traceback | |
1566 |
|
1567 | |||
1567 | if filename and etype is SyntaxError: |
|
1568 | if filename and etype is SyntaxError: | |
1568 | # Work hard to stuff the correct filename in the exception |
|
1569 | # Work hard to stuff the correct filename in the exception | |
1569 | try: |
|
1570 | try: | |
1570 | msg, (dummy_filename, lineno, offset, line) = value |
|
1571 | msg, (dummy_filename, lineno, offset, line) = value | |
1571 | except: |
|
1572 | except: | |
1572 | # Not the format we expect; leave it alone |
|
1573 | # Not the format we expect; leave it alone | |
1573 | pass |
|
1574 | pass | |
1574 | else: |
|
1575 | else: | |
1575 | # Stuff in the right filename |
|
1576 | # Stuff in the right filename | |
1576 | try: |
|
1577 | try: | |
1577 | # Assume SyntaxError is a class exception |
|
1578 | # Assume SyntaxError is a class exception | |
1578 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1579 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1579 | except: |
|
1580 | except: | |
1580 | # If that failed, assume SyntaxError is a string |
|
1581 | # If that failed, assume SyntaxError is a string | |
1581 | value = msg, (filename, lineno, offset, line) |
|
1582 | value = msg, (filename, lineno, offset, line) | |
1582 | self.SyntaxTB(etype,value,[]) |
|
1583 | self.SyntaxTB(etype,value,[]) | |
1583 |
|
1584 | |||
1584 | def debugger(self,force=False): |
|
1585 | def debugger(self,force=False): | |
1585 | """Call the pydb/pdb debugger. |
|
1586 | """Call the pydb/pdb debugger. | |
1586 |
|
1587 | |||
1587 | Keywords: |
|
1588 | Keywords: | |
1588 |
|
1589 | |||
1589 | - force(False): by default, this routine checks the instance call_pdb |
|
1590 | - force(False): by default, this routine checks the instance call_pdb | |
1590 | flag and does not actually invoke the debugger if the flag is false. |
|
1591 | flag and does not actually invoke the debugger if the flag is false. | |
1591 | The 'force' option forces the debugger to activate even if the flag |
|
1592 | The 'force' option forces the debugger to activate even if the flag | |
1592 | is false. |
|
1593 | is false. | |
1593 | """ |
|
1594 | """ | |
1594 |
|
1595 | |||
1595 | if not (force or self.call_pdb): |
|
1596 | if not (force or self.call_pdb): | |
1596 | return |
|
1597 | return | |
1597 |
|
1598 | |||
1598 | if not hasattr(sys,'last_traceback'): |
|
1599 | if not hasattr(sys,'last_traceback'): | |
1599 | error('No traceback has been produced, nothing to debug.') |
|
1600 | error('No traceback has been produced, nothing to debug.') | |
1600 | return |
|
1601 | return | |
1601 |
|
1602 | |||
1602 | # use pydb if available |
|
1603 | # use pydb if available | |
1603 | if Debugger.has_pydb: |
|
1604 | if Debugger.has_pydb: | |
1604 | from pydb import pm |
|
1605 | from pydb import pm | |
1605 | else: |
|
1606 | else: | |
1606 | # fallback to our internal debugger |
|
1607 | # fallback to our internal debugger | |
1607 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1608 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
1608 | self.history_saving_wrapper(pm)() |
|
1609 | self.history_saving_wrapper(pm)() | |
1609 |
|
1610 | |||
1610 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1611 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1611 | """Display the exception that just occurred. |
|
1612 | """Display the exception that just occurred. | |
1612 |
|
1613 | |||
1613 | If nothing is known about the exception, this is the method which |
|
1614 | If nothing is known about the exception, this is the method which | |
1614 | should be used throughout the code for presenting user tracebacks, |
|
1615 | should be used throughout the code for presenting user tracebacks, | |
1615 | rather than directly invoking the InteractiveTB object. |
|
1616 | rather than directly invoking the InteractiveTB object. | |
1616 |
|
1617 | |||
1617 | A specific showsyntaxerror() also exists, but this method can take |
|
1618 | A specific showsyntaxerror() also exists, but this method can take | |
1618 | care of calling it if needed, so unless you are explicitly catching a |
|
1619 | care of calling it if needed, so unless you are explicitly catching a | |
1619 | SyntaxError exception, don't try to analyze the stack manually and |
|
1620 | SyntaxError exception, don't try to analyze the stack manually and | |
1620 | simply call this method.""" |
|
1621 | simply call this method.""" | |
1621 |
|
1622 | |||
1622 |
|
1623 | |||
1623 | # Though this won't be called by syntax errors in the input line, |
|
1624 | # Though this won't be called by syntax errors in the input line, | |
1624 | # there may be SyntaxError cases whith imported code. |
|
1625 | # there may be SyntaxError cases whith imported code. | |
1625 |
|
1626 | |||
1626 | try: |
|
1627 | try: | |
1627 | if exc_tuple is None: |
|
1628 | if exc_tuple is None: | |
1628 | etype, value, tb = sys.exc_info() |
|
1629 | etype, value, tb = sys.exc_info() | |
1629 | else: |
|
1630 | else: | |
1630 | etype, value, tb = exc_tuple |
|
1631 | etype, value, tb = exc_tuple | |
1631 |
|
1632 | |||
1632 | if etype is SyntaxError: |
|
1633 | if etype is SyntaxError: | |
1633 | self.showsyntaxerror(filename) |
|
1634 | self.showsyntaxerror(filename) | |
1634 | elif etype is IPython.ipapi.UsageError: |
|
1635 | elif etype is IPython.ipapi.UsageError: | |
1635 | print "UsageError:", value |
|
1636 | print "UsageError:", value | |
1636 | else: |
|
1637 | else: | |
1637 | # WARNING: these variables are somewhat deprecated and not |
|
1638 | # WARNING: these variables are somewhat deprecated and not | |
1638 | # necessarily safe to use in a threaded environment, but tools |
|
1639 | # necessarily safe to use in a threaded environment, but tools | |
1639 | # like pdb depend on their existence, so let's set them. If we |
|
1640 | # like pdb depend on their existence, so let's set them. If we | |
1640 | # find problems in the field, we'll need to revisit their use. |
|
1641 | # find problems in the field, we'll need to revisit their use. | |
1641 | sys.last_type = etype |
|
1642 | sys.last_type = etype | |
1642 | sys.last_value = value |
|
1643 | sys.last_value = value | |
1643 | sys.last_traceback = tb |
|
1644 | sys.last_traceback = tb | |
1644 |
|
1645 | |||
1645 | if etype in self.custom_exceptions: |
|
1646 | if etype in self.custom_exceptions: | |
1646 | self.CustomTB(etype,value,tb) |
|
1647 | self.CustomTB(etype,value,tb) | |
1647 | else: |
|
1648 | else: | |
1648 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1649 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1649 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1650 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1650 | # pdb mucks up readline, fix it back |
|
1651 | # pdb mucks up readline, fix it back | |
1651 | self.set_completer() |
|
1652 | self.set_completer() | |
1652 | except KeyboardInterrupt: |
|
1653 | except KeyboardInterrupt: | |
1653 | self.write("\nKeyboardInterrupt\n") |
|
1654 | self.write("\nKeyboardInterrupt\n") | |
1654 |
|
1655 | |||
1655 | def mainloop(self,banner=None): |
|
1656 | def mainloop(self,banner=None): | |
1656 | """Creates the local namespace and starts the mainloop. |
|
1657 | """Creates the local namespace and starts the mainloop. | |
1657 |
|
1658 | |||
1658 | If an optional banner argument is given, it will override the |
|
1659 | If an optional banner argument is given, it will override the | |
1659 | internally created default banner.""" |
|
1660 | internally created default banner.""" | |
1660 |
|
1661 | |||
1661 | if self.rc.c: # Emulate Python's -c option |
|
1662 | if self.rc.c: # Emulate Python's -c option | |
1662 | self.exec_init_cmd() |
|
1663 | self.exec_init_cmd() | |
1663 | if banner is None: |
|
1664 | if banner is None: | |
1664 | if not self.rc.banner: |
|
1665 | if not self.rc.banner: | |
1665 | banner = '' |
|
1666 | banner = '' | |
1666 | # banner is string? Use it directly! |
|
1667 | # banner is string? Use it directly! | |
1667 | elif isinstance(self.rc.banner,basestring): |
|
1668 | elif isinstance(self.rc.banner,basestring): | |
1668 | banner = self.rc.banner |
|
1669 | banner = self.rc.banner | |
1669 | else: |
|
1670 | else: | |
1670 | banner = self.BANNER+self.banner2 |
|
1671 | banner = self.BANNER+self.banner2 | |
1671 |
|
1672 | |||
1672 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1673 | # if you run stuff with -c <cmd>, raw hist is not updated | |
1673 | # ensure that it's in sync |
|
1674 | # ensure that it's in sync | |
1674 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1675 | if len(self.input_hist) != len (self.input_hist_raw): | |
1675 | self.input_hist_raw = InputList(self.input_hist) |
|
1676 | self.input_hist_raw = InputList(self.input_hist) | |
1676 |
|
1677 | |||
1677 | while 1: |
|
1678 | while 1: | |
1678 | try: |
|
1679 | try: | |
1679 | self.interact(banner) |
|
1680 | self.interact(banner) | |
1680 | #self.interact_with_readline() |
|
1681 | #self.interact_with_readline() | |
1681 |
|
1682 | |||
1682 | # XXX for testing of a readline-decoupled repl loop, call |
|
1683 | # XXX for testing of a readline-decoupled repl loop, call | |
1683 | # interact_with_readline above |
|
1684 | # interact_with_readline above | |
1684 |
|
1685 | |||
1685 | break |
|
1686 | break | |
1686 | except KeyboardInterrupt: |
|
1687 | except KeyboardInterrupt: | |
1687 | # this should not be necessary, but KeyboardInterrupt |
|
1688 | # this should not be necessary, but KeyboardInterrupt | |
1688 | # handling seems rather unpredictable... |
|
1689 | # handling seems rather unpredictable... | |
1689 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1690 | self.write("\nKeyboardInterrupt in interact()\n") | |
1690 |
|
1691 | |||
1691 | def exec_init_cmd(self): |
|
1692 | def exec_init_cmd(self): | |
1692 | """Execute a command given at the command line. |
|
1693 | """Execute a command given at the command line. | |
1693 |
|
1694 | |||
1694 | This emulates Python's -c option.""" |
|
1695 | This emulates Python's -c option.""" | |
1695 |
|
1696 | |||
1696 | #sys.argv = ['-c'] |
|
1697 | #sys.argv = ['-c'] | |
1697 | self.push(self.prefilter(self.rc.c, False)) |
|
1698 | self.push(self.prefilter(self.rc.c, False)) | |
1698 | if not self.rc.interact: |
|
1699 | if not self.rc.interact: | |
1699 | self.ask_exit() |
|
1700 | self.ask_exit() | |
1700 |
|
1701 | |||
1701 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1702 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1702 | """Embeds IPython into a running python program. |
|
1703 | """Embeds IPython into a running python program. | |
1703 |
|
1704 | |||
1704 | Input: |
|
1705 | Input: | |
1705 |
|
1706 | |||
1706 | - header: An optional header message can be specified. |
|
1707 | - header: An optional header message can be specified. | |
1707 |
|
1708 | |||
1708 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1709 | - local_ns, global_ns: working namespaces. If given as None, the | |
1709 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1710 | IPython-initialized one is updated with __main__.__dict__, so that | |
1710 | program variables become visible but user-specific configuration |
|
1711 | program variables become visible but user-specific configuration | |
1711 | remains possible. |
|
1712 | remains possible. | |
1712 |
|
1713 | |||
1713 | - stack_depth: specifies how many levels in the stack to go to |
|
1714 | - stack_depth: specifies how many levels in the stack to go to | |
1714 | looking for namespaces (when local_ns and global_ns are None). This |
|
1715 | looking for namespaces (when local_ns and global_ns are None). This | |
1715 | allows an intermediate caller to make sure that this function gets |
|
1716 | allows an intermediate caller to make sure that this function gets | |
1716 | the namespace from the intended level in the stack. By default (0) |
|
1717 | the namespace from the intended level in the stack. By default (0) | |
1717 | it will get its locals and globals from the immediate caller. |
|
1718 | it will get its locals and globals from the immediate caller. | |
1718 |
|
1719 | |||
1719 | Warning: it's possible to use this in a program which is being run by |
|
1720 | Warning: it's possible to use this in a program which is being run by | |
1720 | IPython itself (via %run), but some funny things will happen (a few |
|
1721 | IPython itself (via %run), but some funny things will happen (a few | |
1721 | globals get overwritten). In the future this will be cleaned up, as |
|
1722 | globals get overwritten). In the future this will be cleaned up, as | |
1722 | there is no fundamental reason why it can't work perfectly.""" |
|
1723 | there is no fundamental reason why it can't work perfectly.""" | |
1723 |
|
1724 | |||
1724 | # Get locals and globals from caller |
|
1725 | # Get locals and globals from caller | |
1725 | if local_ns is None or global_ns is None: |
|
1726 | if local_ns is None or global_ns is None: | |
1726 | call_frame = sys._getframe(stack_depth).f_back |
|
1727 | call_frame = sys._getframe(stack_depth).f_back | |
1727 |
|
1728 | |||
1728 | if local_ns is None: |
|
1729 | if local_ns is None: | |
1729 | local_ns = call_frame.f_locals |
|
1730 | local_ns = call_frame.f_locals | |
1730 | if global_ns is None: |
|
1731 | if global_ns is None: | |
1731 | global_ns = call_frame.f_globals |
|
1732 | global_ns = call_frame.f_globals | |
1732 |
|
1733 | |||
1733 | # Update namespaces and fire up interpreter |
|
1734 | # Update namespaces and fire up interpreter | |
1734 |
|
1735 | |||
1735 | # The global one is easy, we can just throw it in |
|
1736 | # The global one is easy, we can just throw it in | |
1736 | self.user_global_ns = global_ns |
|
1737 | self.user_global_ns = global_ns | |
1737 |
|
1738 | |||
1738 | # but the user/local one is tricky: ipython needs it to store internal |
|
1739 | # but the user/local one is tricky: ipython needs it to store internal | |
1739 | # data, but we also need the locals. We'll copy locals in the user |
|
1740 | # data, but we also need the locals. We'll copy locals in the user | |
1740 | # one, but will track what got copied so we can delete them at exit. |
|
1741 | # one, but will track what got copied so we can delete them at exit. | |
1741 | # This is so that a later embedded call doesn't see locals from a |
|
1742 | # This is so that a later embedded call doesn't see locals from a | |
1742 | # previous call (which most likely existed in a separate scope). |
|
1743 | # previous call (which most likely existed in a separate scope). | |
1743 | local_varnames = local_ns.keys() |
|
1744 | local_varnames = local_ns.keys() | |
1744 | self.user_ns.update(local_ns) |
|
1745 | self.user_ns.update(local_ns) | |
1745 | #self.user_ns['local_ns'] = local_ns # dbg |
|
1746 | #self.user_ns['local_ns'] = local_ns # dbg | |
1746 |
|
1747 | |||
1747 | # Patch for global embedding to make sure that things don't overwrite |
|
1748 | # Patch for global embedding to make sure that things don't overwrite | |
1748 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1749 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1749 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1750 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1750 | if local_ns is None and global_ns is None: |
|
1751 | if local_ns is None and global_ns is None: | |
1751 | self.user_global_ns.update(__main__.__dict__) |
|
1752 | self.user_global_ns.update(__main__.__dict__) | |
1752 |
|
1753 | |||
1753 | # make sure the tab-completer has the correct frame information, so it |
|
1754 | # make sure the tab-completer has the correct frame information, so it | |
1754 | # actually completes using the frame's locals/globals |
|
1755 | # actually completes using the frame's locals/globals | |
1755 | self.set_completer_frame() |
|
1756 | self.set_completer_frame() | |
1756 |
|
1757 | |||
1757 | # before activating the interactive mode, we need to make sure that |
|
1758 | # before activating the interactive mode, we need to make sure that | |
1758 | # all names in the builtin namespace needed by ipython point to |
|
1759 | # all names in the builtin namespace needed by ipython point to | |
1759 | # ourselves, and not to other instances. |
|
1760 | # ourselves, and not to other instances. | |
1760 | self.add_builtins() |
|
1761 | self.add_builtins() | |
1761 |
|
1762 | |||
1762 | self.interact(header) |
|
1763 | self.interact(header) | |
1763 |
|
1764 | |||
1764 | # now, purge out the user namespace from anything we might have added |
|
1765 | # now, purge out the user namespace from anything we might have added | |
1765 | # from the caller's local namespace |
|
1766 | # from the caller's local namespace | |
1766 | delvar = self.user_ns.pop |
|
1767 | delvar = self.user_ns.pop | |
1767 | for var in local_varnames: |
|
1768 | for var in local_varnames: | |
1768 | delvar(var,None) |
|
1769 | delvar(var,None) | |
1769 | # and clean builtins we may have overridden |
|
1770 | # and clean builtins we may have overridden | |
1770 | self.clean_builtins() |
|
1771 | self.clean_builtins() | |
1771 |
|
1772 | |||
1772 | def interact_prompt(self): |
|
1773 | def interact_prompt(self): | |
1773 | """ Print the prompt (in read-eval-print loop) |
|
1774 | """ Print the prompt (in read-eval-print loop) | |
1774 |
|
1775 | |||
1775 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1776 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1776 | used in standard IPython flow. |
|
1777 | used in standard IPython flow. | |
1777 | """ |
|
1778 | """ | |
1778 | if self.more: |
|
1779 | if self.more: | |
1779 | try: |
|
1780 | try: | |
1780 | prompt = self.hooks.generate_prompt(True) |
|
1781 | prompt = self.hooks.generate_prompt(True) | |
1781 | except: |
|
1782 | except: | |
1782 | self.showtraceback() |
|
1783 | self.showtraceback() | |
1783 | if self.autoindent: |
|
1784 | if self.autoindent: | |
1784 | self.rl_do_indent = True |
|
1785 | self.rl_do_indent = True | |
1785 |
|
1786 | |||
1786 | else: |
|
1787 | else: | |
1787 | try: |
|
1788 | try: | |
1788 | prompt = self.hooks.generate_prompt(False) |
|
1789 | prompt = self.hooks.generate_prompt(False) | |
1789 | except: |
|
1790 | except: | |
1790 | self.showtraceback() |
|
1791 | self.showtraceback() | |
1791 | self.write(prompt) |
|
1792 | self.write(prompt) | |
1792 |
|
1793 | |||
1793 | def interact_handle_input(self,line): |
|
1794 | def interact_handle_input(self,line): | |
1794 | """ Handle the input line (in read-eval-print loop) |
|
1795 | """ Handle the input line (in read-eval-print loop) | |
1795 |
|
1796 | |||
1796 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1797 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1797 | used in standard IPython flow. |
|
1798 | used in standard IPython flow. | |
1798 | """ |
|
1799 | """ | |
1799 | if line.lstrip() == line: |
|
1800 | if line.lstrip() == line: | |
1800 | self.shadowhist.add(line.strip()) |
|
1801 | self.shadowhist.add(line.strip()) | |
1801 | lineout = self.prefilter(line,self.more) |
|
1802 | lineout = self.prefilter(line,self.more) | |
1802 |
|
1803 | |||
1803 | if line.strip(): |
|
1804 | if line.strip(): | |
1804 | if self.more: |
|
1805 | if self.more: | |
1805 | self.input_hist_raw[-1] += '%s\n' % line |
|
1806 | self.input_hist_raw[-1] += '%s\n' % line | |
1806 | else: |
|
1807 | else: | |
1807 | self.input_hist_raw.append('%s\n' % line) |
|
1808 | self.input_hist_raw.append('%s\n' % line) | |
1808 |
|
1809 | |||
1809 |
|
1810 | |||
1810 | self.more = self.push(lineout) |
|
1811 | self.more = self.push(lineout) | |
1811 | if (self.SyntaxTB.last_syntax_error and |
|
1812 | if (self.SyntaxTB.last_syntax_error and | |
1812 | self.rc.autoedit_syntax): |
|
1813 | self.rc.autoedit_syntax): | |
1813 | self.edit_syntax_error() |
|
1814 | self.edit_syntax_error() | |
1814 |
|
1815 | |||
1815 | def interact_with_readline(self): |
|
1816 | def interact_with_readline(self): | |
1816 | """ Demo of using interact_handle_input, interact_prompt |
|
1817 | """ Demo of using interact_handle_input, interact_prompt | |
1817 |
|
1818 | |||
1818 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1819 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1819 | it should work like this. |
|
1820 | it should work like this. | |
1820 | """ |
|
1821 | """ | |
1821 | self.readline_startup_hook(self.pre_readline) |
|
1822 | self.readline_startup_hook(self.pre_readline) | |
1822 | while not self.exit_now: |
|
1823 | while not self.exit_now: | |
1823 | self.interact_prompt() |
|
1824 | self.interact_prompt() | |
1824 | if self.more: |
|
1825 | if self.more: | |
1825 | self.rl_do_indent = True |
|
1826 | self.rl_do_indent = True | |
1826 | else: |
|
1827 | else: | |
1827 | self.rl_do_indent = False |
|
1828 | self.rl_do_indent = False | |
1828 | line = raw_input_original().decode(self.stdin_encoding) |
|
1829 | line = raw_input_original().decode(self.stdin_encoding) | |
1829 | self.interact_handle_input(line) |
|
1830 | self.interact_handle_input(line) | |
1830 |
|
1831 | |||
1831 |
|
1832 | |||
1832 | def interact(self, banner=None): |
|
1833 | def interact(self, banner=None): | |
1833 | """Closely emulate the interactive Python console. |
|
1834 | """Closely emulate the interactive Python console. | |
1834 |
|
1835 | |||
1835 | The optional banner argument specify the banner to print |
|
1836 | The optional banner argument specify the banner to print | |
1836 | before the first interaction; by default it prints a banner |
|
1837 | before the first interaction; by default it prints a banner | |
1837 | similar to the one printed by the real Python interpreter, |
|
1838 | similar to the one printed by the real Python interpreter, | |
1838 | followed by the current class name in parentheses (so as not |
|
1839 | followed by the current class name in parentheses (so as not | |
1839 | to confuse this with the real interpreter -- since it's so |
|
1840 | to confuse this with the real interpreter -- since it's so | |
1840 | close!). |
|
1841 | close!). | |
1841 |
|
1842 | |||
1842 | """ |
|
1843 | """ | |
1843 |
|
1844 | |||
1844 | if self.exit_now: |
|
1845 | if self.exit_now: | |
1845 | # batch run -> do not interact |
|
1846 | # batch run -> do not interact | |
1846 | return |
|
1847 | return | |
1847 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1848 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1848 | if banner is None: |
|
1849 | if banner is None: | |
1849 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1850 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1850 | (sys.version, sys.platform, cprt, |
|
1851 | (sys.version, sys.platform, cprt, | |
1851 | self.__class__.__name__)) |
|
1852 | self.__class__.__name__)) | |
1852 | else: |
|
1853 | else: | |
1853 | self.write(banner) |
|
1854 | self.write(banner) | |
1854 |
|
1855 | |||
1855 | more = 0 |
|
1856 | more = 0 | |
1856 |
|
1857 | |||
1857 | # Mark activity in the builtins |
|
1858 | # Mark activity in the builtins | |
1858 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1859 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1859 |
|
1860 | |||
1860 | if self.has_readline: |
|
1861 | if self.has_readline: | |
1861 | self.readline_startup_hook(self.pre_readline) |
|
1862 | self.readline_startup_hook(self.pre_readline) | |
1862 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1863 | # exit_now is set by a call to %Exit or %Quit, through the | |
1863 | # ask_exit callback. |
|
1864 | # ask_exit callback. | |
1864 |
|
1865 | |||
1865 | while not self.exit_now: |
|
1866 | while not self.exit_now: | |
1866 | self.hooks.pre_prompt_hook() |
|
1867 | self.hooks.pre_prompt_hook() | |
1867 | if more: |
|
1868 | if more: | |
1868 | try: |
|
1869 | try: | |
1869 | prompt = self.hooks.generate_prompt(True) |
|
1870 | prompt = self.hooks.generate_prompt(True) | |
1870 | except: |
|
1871 | except: | |
1871 | self.showtraceback() |
|
1872 | self.showtraceback() | |
1872 | if self.autoindent: |
|
1873 | if self.autoindent: | |
1873 | self.rl_do_indent = True |
|
1874 | self.rl_do_indent = True | |
1874 |
|
1875 | |||
1875 | else: |
|
1876 | else: | |
1876 | try: |
|
1877 | try: | |
1877 | prompt = self.hooks.generate_prompt(False) |
|
1878 | prompt = self.hooks.generate_prompt(False) | |
1878 | except: |
|
1879 | except: | |
1879 | self.showtraceback() |
|
1880 | self.showtraceback() | |
1880 | try: |
|
1881 | try: | |
1881 | line = self.raw_input(prompt,more) |
|
1882 | line = self.raw_input(prompt,more) | |
1882 | if self.exit_now: |
|
1883 | if self.exit_now: | |
1883 | # quick exit on sys.std[in|out] close |
|
1884 | # quick exit on sys.std[in|out] close | |
1884 | break |
|
1885 | break | |
1885 | if self.autoindent: |
|
1886 | if self.autoindent: | |
1886 | self.rl_do_indent = False |
|
1887 | self.rl_do_indent = False | |
1887 |
|
1888 | |||
1888 | except KeyboardInterrupt: |
|
1889 | except KeyboardInterrupt: | |
1889 | #double-guard against keyboardinterrupts during kbdint handling |
|
1890 | #double-guard against keyboardinterrupts during kbdint handling | |
1890 | try: |
|
1891 | try: | |
1891 | self.write('\nKeyboardInterrupt\n') |
|
1892 | self.write('\nKeyboardInterrupt\n') | |
1892 | self.resetbuffer() |
|
1893 | self.resetbuffer() | |
1893 | # keep cache in sync with the prompt counter: |
|
1894 | # keep cache in sync with the prompt counter: | |
1894 | self.outputcache.prompt_count -= 1 |
|
1895 | self.outputcache.prompt_count -= 1 | |
1895 |
|
1896 | |||
1896 | if self.autoindent: |
|
1897 | if self.autoindent: | |
1897 | self.indent_current_nsp = 0 |
|
1898 | self.indent_current_nsp = 0 | |
1898 | more = 0 |
|
1899 | more = 0 | |
1899 | except KeyboardInterrupt: |
|
1900 | except KeyboardInterrupt: | |
1900 | pass |
|
1901 | pass | |
1901 | except EOFError: |
|
1902 | except EOFError: | |
1902 | if self.autoindent: |
|
1903 | if self.autoindent: | |
1903 | self.rl_do_indent = False |
|
1904 | self.rl_do_indent = False | |
1904 | self.readline_startup_hook(None) |
|
1905 | self.readline_startup_hook(None) | |
1905 | self.write('\n') |
|
1906 | self.write('\n') | |
1906 | self.exit() |
|
1907 | self.exit() | |
1907 | except bdb.BdbQuit: |
|
1908 | except bdb.BdbQuit: | |
1908 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1909 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1909 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1910 | 'Because of how pdb handles the stack, it is impossible\n' | |
1910 | 'for IPython to properly format this particular exception.\n' |
|
1911 | 'for IPython to properly format this particular exception.\n' | |
1911 | 'IPython will resume normal operation.') |
|
1912 | 'IPython will resume normal operation.') | |
1912 | except: |
|
1913 | except: | |
1913 | # exceptions here are VERY RARE, but they can be triggered |
|
1914 | # exceptions here are VERY RARE, but they can be triggered | |
1914 | # asynchronously by signal handlers, for example. |
|
1915 | # asynchronously by signal handlers, for example. | |
1915 | self.showtraceback() |
|
1916 | self.showtraceback() | |
1916 | else: |
|
1917 | else: | |
1917 | more = self.push(line) |
|
1918 | more = self.push(line) | |
1918 | if (self.SyntaxTB.last_syntax_error and |
|
1919 | if (self.SyntaxTB.last_syntax_error and | |
1919 | self.rc.autoedit_syntax): |
|
1920 | self.rc.autoedit_syntax): | |
1920 | self.edit_syntax_error() |
|
1921 | self.edit_syntax_error() | |
1921 |
|
1922 | |||
1922 | # We are off again... |
|
1923 | # We are off again... | |
1923 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1924 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1924 |
|
1925 | |||
1925 | def excepthook(self, etype, value, tb): |
|
1926 | def excepthook(self, etype, value, tb): | |
1926 | """One more defense for GUI apps that call sys.excepthook. |
|
1927 | """One more defense for GUI apps that call sys.excepthook. | |
1927 |
|
1928 | |||
1928 | GUI frameworks like wxPython trap exceptions and call |
|
1929 | GUI frameworks like wxPython trap exceptions and call | |
1929 | sys.excepthook themselves. I guess this is a feature that |
|
1930 | sys.excepthook themselves. I guess this is a feature that | |
1930 | enables them to keep running after exceptions that would |
|
1931 | enables them to keep running after exceptions that would | |
1931 | otherwise kill their mainloop. This is a bother for IPython |
|
1932 | otherwise kill their mainloop. This is a bother for IPython | |
1932 | which excepts to catch all of the program exceptions with a try: |
|
1933 | which excepts to catch all of the program exceptions with a try: | |
1933 | except: statement. |
|
1934 | except: statement. | |
1934 |
|
1935 | |||
1935 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1936 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1936 | any app directly invokes sys.excepthook, it will look to the user like |
|
1937 | any app directly invokes sys.excepthook, it will look to the user like | |
1937 | IPython crashed. In order to work around this, we can disable the |
|
1938 | IPython crashed. In order to work around this, we can disable the | |
1938 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1939 | CrashHandler and replace it with this excepthook instead, which prints a | |
1939 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1940 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1940 | call sys.excepthook will generate a regular-looking exception from |
|
1941 | call sys.excepthook will generate a regular-looking exception from | |
1941 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1942 | IPython, and the CrashHandler will only be triggered by real IPython | |
1942 | crashes. |
|
1943 | crashes. | |
1943 |
|
1944 | |||
1944 | This hook should be used sparingly, only in places which are not likely |
|
1945 | This hook should be used sparingly, only in places which are not likely | |
1945 | to be true IPython errors. |
|
1946 | to be true IPython errors. | |
1946 | """ |
|
1947 | """ | |
1947 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1948 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1948 |
|
1949 | |||
1949 | def expand_aliases(self,fn,rest): |
|
1950 | def expand_aliases(self,fn,rest): | |
1950 | """ Expand multiple levels of aliases: |
|
1951 | """ Expand multiple levels of aliases: | |
1951 |
|
1952 | |||
1952 | if: |
|
1953 | if: | |
1953 |
|
1954 | |||
1954 | alias foo bar /tmp |
|
1955 | alias foo bar /tmp | |
1955 | alias baz foo |
|
1956 | alias baz foo | |
1956 |
|
1957 | |||
1957 | then: |
|
1958 | then: | |
1958 |
|
1959 | |||
1959 | baz huhhahhei -> bar /tmp huhhahhei |
|
1960 | baz huhhahhei -> bar /tmp huhhahhei | |
1960 |
|
1961 | |||
1961 | """ |
|
1962 | """ | |
1962 | line = fn + " " + rest |
|
1963 | line = fn + " " + rest | |
1963 |
|
1964 | |||
1964 | done = set() |
|
1965 | done = set() | |
1965 | while 1: |
|
1966 | while 1: | |
1966 | pre,fn,rest = prefilter.splitUserInput(line, |
|
1967 | pre,fn,rest = prefilter.splitUserInput(line, | |
1967 | prefilter.shell_line_split) |
|
1968 | prefilter.shell_line_split) | |
1968 | if fn in self.alias_table: |
|
1969 | if fn in self.alias_table: | |
1969 | if fn in done: |
|
1970 | if fn in done: | |
1970 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1971 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
1971 | return "" |
|
1972 | return "" | |
1972 | done.add(fn) |
|
1973 | done.add(fn) | |
1973 |
|
1974 | |||
1974 | l2 = self.transform_alias(fn,rest) |
|
1975 | l2 = self.transform_alias(fn,rest) | |
1975 | # dir -> dir |
|
1976 | # dir -> dir | |
1976 | # print "alias",line, "->",l2 #dbg |
|
1977 | # print "alias",line, "->",l2 #dbg | |
1977 | if l2 == line: |
|
1978 | if l2 == line: | |
1978 | break |
|
1979 | break | |
1979 | # ls -> ls -F should not recurse forever |
|
1980 | # ls -> ls -F should not recurse forever | |
1980 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1981 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
1981 | line = l2 |
|
1982 | line = l2 | |
1982 | break |
|
1983 | break | |
1983 |
|
1984 | |||
1984 | line=l2 |
|
1985 | line=l2 | |
1985 |
|
1986 | |||
1986 |
|
1987 | |||
1987 | # print "al expand to",line #dbg |
|
1988 | # print "al expand to",line #dbg | |
1988 | else: |
|
1989 | else: | |
1989 | break |
|
1990 | break | |
1990 |
|
1991 | |||
1991 | return line |
|
1992 | return line | |
1992 |
|
1993 | |||
1993 | def transform_alias(self, alias,rest=''): |
|
1994 | def transform_alias(self, alias,rest=''): | |
1994 | """ Transform alias to system command string. |
|
1995 | """ Transform alias to system command string. | |
1995 | """ |
|
1996 | """ | |
1996 | trg = self.alias_table[alias] |
|
1997 | trg = self.alias_table[alias] | |
1997 |
|
1998 | |||
1998 | nargs,cmd = trg |
|
1999 | nargs,cmd = trg | |
1999 | # print trg #dbg |
|
2000 | # print trg #dbg | |
2000 | if ' ' in cmd and os.path.isfile(cmd): |
|
2001 | if ' ' in cmd and os.path.isfile(cmd): | |
2001 | cmd = '"%s"' % cmd |
|
2002 | cmd = '"%s"' % cmd | |
2002 |
|
2003 | |||
2003 | # Expand the %l special to be the user's input line |
|
2004 | # Expand the %l special to be the user's input line | |
2004 | if cmd.find('%l') >= 0: |
|
2005 | if cmd.find('%l') >= 0: | |
2005 | cmd = cmd.replace('%l',rest) |
|
2006 | cmd = cmd.replace('%l',rest) | |
2006 | rest = '' |
|
2007 | rest = '' | |
2007 | if nargs==0: |
|
2008 | if nargs==0: | |
2008 | # Simple, argument-less aliases |
|
2009 | # Simple, argument-less aliases | |
2009 | cmd = '%s %s' % (cmd,rest) |
|
2010 | cmd = '%s %s' % (cmd,rest) | |
2010 | else: |
|
2011 | else: | |
2011 | # Handle aliases with positional arguments |
|
2012 | # Handle aliases with positional arguments | |
2012 | args = rest.split(None,nargs) |
|
2013 | args = rest.split(None,nargs) | |
2013 | if len(args)< nargs: |
|
2014 | if len(args)< nargs: | |
2014 | error('Alias <%s> requires %s arguments, %s given.' % |
|
2015 | error('Alias <%s> requires %s arguments, %s given.' % | |
2015 | (alias,nargs,len(args))) |
|
2016 | (alias,nargs,len(args))) | |
2016 | return None |
|
2017 | return None | |
2017 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
2018 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
2018 | # Now call the macro, evaluating in the user's namespace |
|
2019 | # Now call the macro, evaluating in the user's namespace | |
2019 | #print 'new command: <%r>' % cmd # dbg |
|
2020 | #print 'new command: <%r>' % cmd # dbg | |
2020 | return cmd |
|
2021 | return cmd | |
2021 |
|
2022 | |||
2022 | def call_alias(self,alias,rest=''): |
|
2023 | def call_alias(self,alias,rest=''): | |
2023 | """Call an alias given its name and the rest of the line. |
|
2024 | """Call an alias given its name and the rest of the line. | |
2024 |
|
2025 | |||
2025 | This is only used to provide backwards compatibility for users of |
|
2026 | This is only used to provide backwards compatibility for users of | |
2026 | ipalias(), use of which is not recommended for anymore.""" |
|
2027 | ipalias(), use of which is not recommended for anymore.""" | |
2027 |
|
2028 | |||
2028 | # Now call the macro, evaluating in the user's namespace |
|
2029 | # Now call the macro, evaluating in the user's namespace | |
2029 | cmd = self.transform_alias(alias, rest) |
|
2030 | cmd = self.transform_alias(alias, rest) | |
2030 | try: |
|
2031 | try: | |
2031 | self.system(cmd) |
|
2032 | self.system(cmd) | |
2032 | except: |
|
2033 | except: | |
2033 | self.showtraceback() |
|
2034 | self.showtraceback() | |
2034 |
|
2035 | |||
2035 | def indent_current_str(self): |
|
2036 | def indent_current_str(self): | |
2036 | """return the current level of indentation as a string""" |
|
2037 | """return the current level of indentation as a string""" | |
2037 | return self.indent_current_nsp * ' ' |
|
2038 | return self.indent_current_nsp * ' ' | |
2038 |
|
2039 | |||
2039 | def autoindent_update(self,line): |
|
2040 | def autoindent_update(self,line): | |
2040 | """Keep track of the indent level.""" |
|
2041 | """Keep track of the indent level.""" | |
2041 |
|
2042 | |||
2042 | #debugx('line') |
|
2043 | #debugx('line') | |
2043 | #debugx('self.indent_current_nsp') |
|
2044 | #debugx('self.indent_current_nsp') | |
2044 | if self.autoindent: |
|
2045 | if self.autoindent: | |
2045 | if line: |
|
2046 | if line: | |
2046 | inisp = num_ini_spaces(line) |
|
2047 | inisp = num_ini_spaces(line) | |
2047 | if inisp < self.indent_current_nsp: |
|
2048 | if inisp < self.indent_current_nsp: | |
2048 | self.indent_current_nsp = inisp |
|
2049 | self.indent_current_nsp = inisp | |
2049 |
|
2050 | |||
2050 | if line[-1] == ':': |
|
2051 | if line[-1] == ':': | |
2051 | self.indent_current_nsp += 4 |
|
2052 | self.indent_current_nsp += 4 | |
2052 | elif dedent_re.match(line): |
|
2053 | elif dedent_re.match(line): | |
2053 | self.indent_current_nsp -= 4 |
|
2054 | self.indent_current_nsp -= 4 | |
2054 | else: |
|
2055 | else: | |
2055 | self.indent_current_nsp = 0 |
|
2056 | self.indent_current_nsp = 0 | |
2056 |
|
2057 | |||
2057 | def runlines(self,lines): |
|
2058 | def runlines(self,lines): | |
2058 | """Run a string of one or more lines of source. |
|
2059 | """Run a string of one or more lines of source. | |
2059 |
|
2060 | |||
2060 | This method is capable of running a string containing multiple source |
|
2061 | This method is capable of running a string containing multiple source | |
2061 | lines, as if they had been entered at the IPython prompt. Since it |
|
2062 | lines, as if they had been entered at the IPython prompt. Since it | |
2062 | exposes IPython's processing machinery, the given strings can contain |
|
2063 | exposes IPython's processing machinery, the given strings can contain | |
2063 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
2064 | magic calls (%magic), special shell access (!cmd), etc.""" | |
2064 |
|
2065 | |||
2065 | # We must start with a clean buffer, in case this is run from an |
|
2066 | # We must start with a clean buffer, in case this is run from an | |
2066 | # interactive IPython session (via a magic, for example). |
|
2067 | # interactive IPython session (via a magic, for example). | |
2067 | self.resetbuffer() |
|
2068 | self.resetbuffer() | |
2068 | lines = lines.split('\n') |
|
2069 | lines = lines.split('\n') | |
2069 | more = 0 |
|
2070 | more = 0 | |
2070 |
|
2071 | |||
2071 | for line in lines: |
|
2072 | for line in lines: | |
2072 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2073 | # skip blank lines so we don't mess up the prompt counter, but do | |
2073 | # NOT skip even a blank line if we are in a code block (more is |
|
2074 | # NOT skip even a blank line if we are in a code block (more is | |
2074 | # true) |
|
2075 | # true) | |
2075 |
|
2076 | |||
2076 | if line or more: |
|
2077 | if line or more: | |
2077 | # push to raw history, so hist line numbers stay in sync |
|
2078 | # push to raw history, so hist line numbers stay in sync | |
2078 | self.input_hist_raw.append("# " + line + "\n") |
|
2079 | self.input_hist_raw.append("# " + line + "\n") | |
2079 | more = self.push(self.prefilter(line,more)) |
|
2080 | more = self.push(self.prefilter(line,more)) | |
2080 | # IPython's runsource returns None if there was an error |
|
2081 | # IPython's runsource returns None if there was an error | |
2081 | # compiling the code. This allows us to stop processing right |
|
2082 | # compiling the code. This allows us to stop processing right | |
2082 | # away, so the user gets the error message at the right place. |
|
2083 | # away, so the user gets the error message at the right place. | |
2083 | if more is None: |
|
2084 | if more is None: | |
2084 | break |
|
2085 | break | |
2085 | else: |
|
2086 | else: | |
2086 | self.input_hist_raw.append("\n") |
|
2087 | self.input_hist_raw.append("\n") | |
2087 | # final newline in case the input didn't have it, so that the code |
|
2088 | # final newline in case the input didn't have it, so that the code | |
2088 | # actually does get executed |
|
2089 | # actually does get executed | |
2089 | if more: |
|
2090 | if more: | |
2090 | self.push('\n') |
|
2091 | self.push('\n') | |
2091 |
|
2092 | |||
2092 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2093 | def runsource(self, source, filename='<input>', symbol='single'): | |
2093 | """Compile and run some source in the interpreter. |
|
2094 | """Compile and run some source in the interpreter. | |
2094 |
|
2095 | |||
2095 | Arguments are as for compile_command(). |
|
2096 | Arguments are as for compile_command(). | |
2096 |
|
2097 | |||
2097 | One several things can happen: |
|
2098 | One several things can happen: | |
2098 |
|
2099 | |||
2099 | 1) The input is incorrect; compile_command() raised an |
|
2100 | 1) The input is incorrect; compile_command() raised an | |
2100 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2101 | exception (SyntaxError or OverflowError). A syntax traceback | |
2101 | will be printed by calling the showsyntaxerror() method. |
|
2102 | will be printed by calling the showsyntaxerror() method. | |
2102 |
|
2103 | |||
2103 | 2) The input is incomplete, and more input is required; |
|
2104 | 2) The input is incomplete, and more input is required; | |
2104 | compile_command() returned None. Nothing happens. |
|
2105 | compile_command() returned None. Nothing happens. | |
2105 |
|
2106 | |||
2106 | 3) The input is complete; compile_command() returned a code |
|
2107 | 3) The input is complete; compile_command() returned a code | |
2107 | object. The code is executed by calling self.runcode() (which |
|
2108 | object. The code is executed by calling self.runcode() (which | |
2108 | also handles run-time exceptions, except for SystemExit). |
|
2109 | also handles run-time exceptions, except for SystemExit). | |
2109 |
|
2110 | |||
2110 | The return value is: |
|
2111 | The return value is: | |
2111 |
|
2112 | |||
2112 | - True in case 2 |
|
2113 | - True in case 2 | |
2113 |
|
2114 | |||
2114 | - False in the other cases, unless an exception is raised, where |
|
2115 | - False in the other cases, unless an exception is raised, where | |
2115 | None is returned instead. This can be used by external callers to |
|
2116 | None is returned instead. This can be used by external callers to | |
2116 | know whether to continue feeding input or not. |
|
2117 | know whether to continue feeding input or not. | |
2117 |
|
2118 | |||
2118 | The return value can be used to decide whether to use sys.ps1 or |
|
2119 | The return value can be used to decide whether to use sys.ps1 or | |
2119 | sys.ps2 to prompt the next line.""" |
|
2120 | sys.ps2 to prompt the next line.""" | |
2120 |
|
2121 | |||
2121 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2122 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2122 | # this allows execution of indented pasted code. It is tempting |
|
2123 | # this allows execution of indented pasted code. It is tempting | |
2123 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2124 | # to add '\n' at the end of source to run commands like ' a=1' | |
2124 | # directly, but this fails for more complicated scenarios |
|
2125 | # directly, but this fails for more complicated scenarios | |
2125 | source=source.encode(self.stdin_encoding) |
|
2126 | source=source.encode(self.stdin_encoding) | |
2126 | if source[:1] in [' ', '\t']: |
|
2127 | if source[:1] in [' ', '\t']: | |
2127 | source = 'if 1:\n%s' % source |
|
2128 | source = 'if 1:\n%s' % source | |
2128 |
|
2129 | |||
2129 | try: |
|
2130 | try: | |
2130 | code = self.compile(source,filename,symbol) |
|
2131 | code = self.compile(source,filename,symbol) | |
2131 | except (OverflowError, SyntaxError, ValueError, TypeError): |
|
2132 | except (OverflowError, SyntaxError, ValueError, TypeError): | |
2132 | # Case 1 |
|
2133 | # Case 1 | |
2133 | self.showsyntaxerror(filename) |
|
2134 | self.showsyntaxerror(filename) | |
2134 | return None |
|
2135 | return None | |
2135 |
|
2136 | |||
2136 | if code is None: |
|
2137 | if code is None: | |
2137 | # Case 2 |
|
2138 | # Case 2 | |
2138 | return True |
|
2139 | return True | |
2139 |
|
2140 | |||
2140 | # Case 3 |
|
2141 | # Case 3 | |
2141 | # We store the code object so that threaded shells and |
|
2142 | # We store the code object so that threaded shells and | |
2142 | # custom exception handlers can access all this info if needed. |
|
2143 | # custom exception handlers can access all this info if needed. | |
2143 | # The source corresponding to this can be obtained from the |
|
2144 | # The source corresponding to this can be obtained from the | |
2144 | # buffer attribute as '\n'.join(self.buffer). |
|
2145 | # buffer attribute as '\n'.join(self.buffer). | |
2145 | self.code_to_run = code |
|
2146 | self.code_to_run = code | |
2146 | # now actually execute the code object |
|
2147 | # now actually execute the code object | |
2147 | if self.runcode(code) == 0: |
|
2148 | if self.runcode(code) == 0: | |
2148 | return False |
|
2149 | return False | |
2149 | else: |
|
2150 | else: | |
2150 | return None |
|
2151 | return None | |
2151 |
|
2152 | |||
2152 | def runcode(self,code_obj): |
|
2153 | def runcode(self,code_obj): | |
2153 | """Execute a code object. |
|
2154 | """Execute a code object. | |
2154 |
|
2155 | |||
2155 | When an exception occurs, self.showtraceback() is called to display a |
|
2156 | When an exception occurs, self.showtraceback() is called to display a | |
2156 | traceback. |
|
2157 | traceback. | |
2157 |
|
2158 | |||
2158 | Return value: a flag indicating whether the code to be run completed |
|
2159 | Return value: a flag indicating whether the code to be run completed | |
2159 | successfully: |
|
2160 | successfully: | |
2160 |
|
2161 | |||
2161 | - 0: successful execution. |
|
2162 | - 0: successful execution. | |
2162 | - 1: an error occurred. |
|
2163 | - 1: an error occurred. | |
2163 | """ |
|
2164 | """ | |
2164 |
|
2165 | |||
2165 | # Set our own excepthook in case the user code tries to call it |
|
2166 | # Set our own excepthook in case the user code tries to call it | |
2166 | # directly, so that the IPython crash handler doesn't get triggered |
|
2167 | # directly, so that the IPython crash handler doesn't get triggered | |
2167 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2168 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2168 |
|
2169 | |||
2169 | # we save the original sys.excepthook in the instance, in case config |
|
2170 | # we save the original sys.excepthook in the instance, in case config | |
2170 | # code (such as magics) needs access to it. |
|
2171 | # code (such as magics) needs access to it. | |
2171 | self.sys_excepthook = old_excepthook |
|
2172 | self.sys_excepthook = old_excepthook | |
2172 | outflag = 1 # happens in more places, so it's easier as default |
|
2173 | outflag = 1 # happens in more places, so it's easier as default | |
2173 | try: |
|
2174 | try: | |
2174 | try: |
|
2175 | try: | |
2175 | self.hooks.pre_runcode_hook() |
|
2176 | self.hooks.pre_runcode_hook() | |
2176 | exec code_obj in self.user_global_ns, self.user_ns |
|
2177 | exec code_obj in self.user_global_ns, self.user_ns | |
2177 | finally: |
|
2178 | finally: | |
2178 | # Reset our crash handler in place |
|
2179 | # Reset our crash handler in place | |
2179 | sys.excepthook = old_excepthook |
|
2180 | sys.excepthook = old_excepthook | |
2180 | except SystemExit: |
|
2181 | except SystemExit: | |
2181 | self.resetbuffer() |
|
2182 | self.resetbuffer() | |
2182 | self.showtraceback() |
|
2183 | self.showtraceback() | |
2183 | warn("Type %exit or %quit to exit IPython " |
|
2184 | warn("Type %exit or %quit to exit IPython " | |
2184 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2185 | "(%Exit or %Quit do so unconditionally).",level=1) | |
2185 | except self.custom_exceptions: |
|
2186 | except self.custom_exceptions: | |
2186 | etype,value,tb = sys.exc_info() |
|
2187 | etype,value,tb = sys.exc_info() | |
2187 | self.CustomTB(etype,value,tb) |
|
2188 | self.CustomTB(etype,value,tb) | |
2188 | except: |
|
2189 | except: | |
2189 | self.showtraceback() |
|
2190 | self.showtraceback() | |
2190 | else: |
|
2191 | else: | |
2191 | outflag = 0 |
|
2192 | outflag = 0 | |
2192 | if softspace(sys.stdout, 0): |
|
2193 | if softspace(sys.stdout, 0): | |
2193 |
|
2194 | |||
2194 | # Flush out code object which has been run (and source) |
|
2195 | # Flush out code object which has been run (and source) | |
2195 | self.code_to_run = None |
|
2196 | self.code_to_run = None | |
2196 | return outflag |
|
2197 | return outflag | |
2197 |
|
2198 | |||
2198 | def push(self, line): |
|
2199 | def push(self, line): | |
2199 | """Push a line to the interpreter. |
|
2200 | """Push a line to the interpreter. | |
2200 |
|
2201 | |||
2201 | The line should not have a trailing newline; it may have |
|
2202 | The line should not have a trailing newline; it may have | |
2202 | internal newlines. The line is appended to a buffer and the |
|
2203 | internal newlines. The line is appended to a buffer and the | |
2203 | interpreter's runsource() method is called with the |
|
2204 | interpreter's runsource() method is called with the | |
2204 | concatenated contents of the buffer as source. If this |
|
2205 | concatenated contents of the buffer as source. If this | |
2205 | indicates that the command was executed or invalid, the buffer |
|
2206 | indicates that the command was executed or invalid, the buffer | |
2206 | is reset; otherwise, the command is incomplete, and the buffer |
|
2207 | is reset; otherwise, the command is incomplete, and the buffer | |
2207 | is left as it was after the line was appended. The return |
|
2208 | is left as it was after the line was appended. The return | |
2208 | value is 1 if more input is required, 0 if the line was dealt |
|
2209 | value is 1 if more input is required, 0 if the line was dealt | |
2209 | with in some way (this is the same as runsource()). |
|
2210 | with in some way (this is the same as runsource()). | |
2210 | """ |
|
2211 | """ | |
2211 |
|
2212 | |||
2212 | # autoindent management should be done here, and not in the |
|
2213 | # autoindent management should be done here, and not in the | |
2213 | # interactive loop, since that one is only seen by keyboard input. We |
|
2214 | # interactive loop, since that one is only seen by keyboard input. We | |
2214 | # need this done correctly even for code run via runlines (which uses |
|
2215 | # need this done correctly even for code run via runlines (which uses | |
2215 | # push). |
|
2216 | # push). | |
2216 |
|
2217 | |||
2217 | #print 'push line: <%s>' % line # dbg |
|
2218 | #print 'push line: <%s>' % line # dbg | |
2218 | for subline in line.splitlines(): |
|
2219 | for subline in line.splitlines(): | |
2219 | self.autoindent_update(subline) |
|
2220 | self.autoindent_update(subline) | |
2220 | self.buffer.append(line) |
|
2221 | self.buffer.append(line) | |
2221 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2222 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2222 | if not more: |
|
2223 | if not more: | |
2223 | self.resetbuffer() |
|
2224 | self.resetbuffer() | |
2224 | return more |
|
2225 | return more | |
2225 |
|
2226 | |||
2226 | def split_user_input(self, line): |
|
2227 | def split_user_input(self, line): | |
2227 | # This is really a hold-over to support ipapi and some extensions |
|
2228 | # This is really a hold-over to support ipapi and some extensions | |
2228 | return prefilter.splitUserInput(line) |
|
2229 | return prefilter.splitUserInput(line) | |
2229 |
|
2230 | |||
2230 | def resetbuffer(self): |
|
2231 | def resetbuffer(self): | |
2231 | """Reset the input buffer.""" |
|
2232 | """Reset the input buffer.""" | |
2232 | self.buffer[:] = [] |
|
2233 | self.buffer[:] = [] | |
2233 |
|
2234 | |||
2234 | def raw_input(self,prompt='',continue_prompt=False): |
|
2235 | def raw_input(self,prompt='',continue_prompt=False): | |
2235 | """Write a prompt and read a line. |
|
2236 | """Write a prompt and read a line. | |
2236 |
|
2237 | |||
2237 | The returned line does not include the trailing newline. |
|
2238 | The returned line does not include the trailing newline. | |
2238 | When the user enters the EOF key sequence, EOFError is raised. |
|
2239 | When the user enters the EOF key sequence, EOFError is raised. | |
2239 |
|
2240 | |||
2240 | Optional inputs: |
|
2241 | Optional inputs: | |
2241 |
|
2242 | |||
2242 | - prompt(''): a string to be printed to prompt the user. |
|
2243 | - prompt(''): a string to be printed to prompt the user. | |
2243 |
|
2244 | |||
2244 | - continue_prompt(False): whether this line is the first one or a |
|
2245 | - continue_prompt(False): whether this line is the first one or a | |
2245 | continuation in a sequence of inputs. |
|
2246 | continuation in a sequence of inputs. | |
2246 | """ |
|
2247 | """ | |
2247 |
|
2248 | |||
2248 | # Code run by the user may have modified the readline completer state. |
|
2249 | # Code run by the user may have modified the readline completer state. | |
2249 | # We must ensure that our completer is back in place. |
|
2250 | # We must ensure that our completer is back in place. | |
2250 | if self.has_readline: |
|
2251 | if self.has_readline: | |
2251 | self.set_completer() |
|
2252 | self.set_completer() | |
2252 |
|
2253 | |||
2253 | try: |
|
2254 | try: | |
2254 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2255 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2255 | except ValueError: |
|
2256 | except ValueError: | |
2256 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2257 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2257 | " or sys.stdout.close()!\nExiting IPython!") |
|
2258 | " or sys.stdout.close()!\nExiting IPython!") | |
2258 | self.ask_exit() |
|
2259 | self.ask_exit() | |
2259 | return "" |
|
2260 | return "" | |
2260 |
|
2261 | |||
2261 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2262 | # Try to be reasonably smart about not re-indenting pasted input more | |
2262 | # than necessary. We do this by trimming out the auto-indent initial |
|
2263 | # than necessary. We do this by trimming out the auto-indent initial | |
2263 | # spaces, if the user's actual input started itself with whitespace. |
|
2264 | # spaces, if the user's actual input started itself with whitespace. | |
2264 | #debugx('self.buffer[-1]') |
|
2265 | #debugx('self.buffer[-1]') | |
2265 |
|
2266 | |||
2266 | if self.autoindent: |
|
2267 | if self.autoindent: | |
2267 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2268 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2268 | line = line[self.indent_current_nsp:] |
|
2269 | line = line[self.indent_current_nsp:] | |
2269 | self.indent_current_nsp = 0 |
|
2270 | self.indent_current_nsp = 0 | |
2270 |
|
2271 | |||
2271 | # store the unfiltered input before the user has any chance to modify |
|
2272 | # store the unfiltered input before the user has any chance to modify | |
2272 | # it. |
|
2273 | # it. | |
2273 | if line.strip(): |
|
2274 | if line.strip(): | |
2274 | if continue_prompt: |
|
2275 | if continue_prompt: | |
2275 | self.input_hist_raw[-1] += '%s\n' % line |
|
2276 | self.input_hist_raw[-1] += '%s\n' % line | |
2276 | if self.has_readline: # and some config option is set? |
|
2277 | if self.has_readline: # and some config option is set? | |
2277 | try: |
|
2278 | try: | |
2278 | histlen = self.readline.get_current_history_length() |
|
2279 | histlen = self.readline.get_current_history_length() | |
2279 | if histlen > 1: |
|
2280 | if histlen > 1: | |
2280 | newhist = self.input_hist_raw[-1].rstrip() |
|
2281 | newhist = self.input_hist_raw[-1].rstrip() | |
2281 | self.readline.remove_history_item(histlen-1) |
|
2282 | self.readline.remove_history_item(histlen-1) | |
2282 | self.readline.replace_history_item(histlen-2, |
|
2283 | self.readline.replace_history_item(histlen-2, | |
2283 | newhist.encode(self.stdin_encoding)) |
|
2284 | newhist.encode(self.stdin_encoding)) | |
2284 | except AttributeError: |
|
2285 | except AttributeError: | |
2285 | pass # re{move,place}_history_item are new in 2.4. |
|
2286 | pass # re{move,place}_history_item are new in 2.4. | |
2286 | else: |
|
2287 | else: | |
2287 | self.input_hist_raw.append('%s\n' % line) |
|
2288 | self.input_hist_raw.append('%s\n' % line) | |
2288 | # only entries starting at first column go to shadow history |
|
2289 | # only entries starting at first column go to shadow history | |
2289 | if line.lstrip() == line: |
|
2290 | if line.lstrip() == line: | |
2290 | self.shadowhist.add(line.strip()) |
|
2291 | self.shadowhist.add(line.strip()) | |
2291 | elif not continue_prompt: |
|
2292 | elif not continue_prompt: | |
2292 | self.input_hist_raw.append('\n') |
|
2293 | self.input_hist_raw.append('\n') | |
2293 | try: |
|
2294 | try: | |
2294 | lineout = self.prefilter(line,continue_prompt) |
|
2295 | lineout = self.prefilter(line,continue_prompt) | |
2295 | except: |
|
2296 | except: | |
2296 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2297 | # blanket except, in case a user-defined prefilter crashes, so it | |
2297 | # can't take all of ipython with it. |
|
2298 | # can't take all of ipython with it. | |
2298 | self.showtraceback() |
|
2299 | self.showtraceback() | |
2299 | return '' |
|
2300 | return '' | |
2300 | else: |
|
2301 | else: | |
2301 | return lineout |
|
2302 | return lineout | |
2302 |
|
2303 | |||
2303 | def _prefilter(self, line, continue_prompt): |
|
2304 | def _prefilter(self, line, continue_prompt): | |
2304 | """Calls different preprocessors, depending on the form of line.""" |
|
2305 | """Calls different preprocessors, depending on the form of line.""" | |
2305 |
|
2306 | |||
2306 | # All handlers *must* return a value, even if it's blank (''). |
|
2307 | # All handlers *must* return a value, even if it's blank (''). | |
2307 |
|
2308 | |||
2308 | # Lines are NOT logged here. Handlers should process the line as |
|
2309 | # Lines are NOT logged here. Handlers should process the line as | |
2309 | # needed, update the cache AND log it (so that the input cache array |
|
2310 | # needed, update the cache AND log it (so that the input cache array | |
2310 | # stays synced). |
|
2311 | # stays synced). | |
2311 |
|
2312 | |||
2312 | #..................................................................... |
|
2313 | #..................................................................... | |
2313 | # Code begins |
|
2314 | # Code begins | |
2314 |
|
2315 | |||
2315 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2316 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
2316 |
|
2317 | |||
2317 | # save the line away in case we crash, so the post-mortem handler can |
|
2318 | # save the line away in case we crash, so the post-mortem handler can | |
2318 | # record it |
|
2319 | # record it | |
2319 | self._last_input_line = line |
|
2320 | self._last_input_line = line | |
2320 |
|
2321 | |||
2321 | #print '***line: <%s>' % line # dbg |
|
2322 | #print '***line: <%s>' % line # dbg | |
2322 |
|
2323 | |||
2323 | if not line: |
|
2324 | if not line: | |
2324 | # Return immediately on purely empty lines, so that if the user |
|
2325 | # Return immediately on purely empty lines, so that if the user | |
2325 | # previously typed some whitespace that started a continuation |
|
2326 | # previously typed some whitespace that started a continuation | |
2326 | # prompt, he can break out of that loop with just an empty line. |
|
2327 | # prompt, he can break out of that loop with just an empty line. | |
2327 | # This is how the default python prompt works. |
|
2328 | # This is how the default python prompt works. | |
2328 |
|
2329 | |||
2329 | # Only return if the accumulated input buffer was just whitespace! |
|
2330 | # Only return if the accumulated input buffer was just whitespace! | |
2330 | if ''.join(self.buffer).isspace(): |
|
2331 | if ''.join(self.buffer).isspace(): | |
2331 | self.buffer[:] = [] |
|
2332 | self.buffer[:] = [] | |
2332 | return '' |
|
2333 | return '' | |
2333 |
|
2334 | |||
2334 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2335 | line_info = prefilter.LineInfo(line, continue_prompt) | |
2335 |
|
2336 | |||
2336 | # the input history needs to track even empty lines |
|
2337 | # the input history needs to track even empty lines | |
2337 | stripped = line.strip() |
|
2338 | stripped = line.strip() | |
2338 |
|
2339 | |||
2339 | if not stripped: |
|
2340 | if not stripped: | |
2340 | if not continue_prompt: |
|
2341 | if not continue_prompt: | |
2341 | self.outputcache.prompt_count -= 1 |
|
2342 | self.outputcache.prompt_count -= 1 | |
2342 | return self.handle_normal(line_info) |
|
2343 | return self.handle_normal(line_info) | |
2343 |
|
2344 | |||
2344 | # print '***cont',continue_prompt # dbg |
|
2345 | # print '***cont',continue_prompt # dbg | |
2345 | # special handlers are only allowed for single line statements |
|
2346 | # special handlers are only allowed for single line statements | |
2346 | if continue_prompt and not self.rc.multi_line_specials: |
|
2347 | if continue_prompt and not self.rc.multi_line_specials: | |
2347 | return self.handle_normal(line_info) |
|
2348 | return self.handle_normal(line_info) | |
2348 |
|
2349 | |||
2349 |
|
2350 | |||
2350 | # See whether any pre-existing handler can take care of it |
|
2351 | # See whether any pre-existing handler can take care of it | |
2351 | rewritten = self.hooks.input_prefilter(stripped) |
|
2352 | rewritten = self.hooks.input_prefilter(stripped) | |
2352 | if rewritten != stripped: # ok, some prefilter did something |
|
2353 | if rewritten != stripped: # ok, some prefilter did something | |
2353 | rewritten = line_info.pre + rewritten # add indentation |
|
2354 | rewritten = line_info.pre + rewritten # add indentation | |
2354 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2355 | return self.handle_normal(prefilter.LineInfo(rewritten, | |
2355 | continue_prompt)) |
|
2356 | continue_prompt)) | |
2356 |
|
2357 | |||
2357 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2358 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2358 |
|
2359 | |||
2359 | return prefilter.prefilter(line_info, self) |
|
2360 | return prefilter.prefilter(line_info, self) | |
2360 |
|
2361 | |||
2361 |
|
2362 | |||
2362 | def _prefilter_dumb(self, line, continue_prompt): |
|
2363 | def _prefilter_dumb(self, line, continue_prompt): | |
2363 | """simple prefilter function, for debugging""" |
|
2364 | """simple prefilter function, for debugging""" | |
2364 | return self.handle_normal(line,continue_prompt) |
|
2365 | return self.handle_normal(line,continue_prompt) | |
2365 |
|
2366 | |||
2366 |
|
2367 | |||
2367 | def multiline_prefilter(self, line, continue_prompt): |
|
2368 | def multiline_prefilter(self, line, continue_prompt): | |
2368 | """ Run _prefilter for each line of input |
|
2369 | """ Run _prefilter for each line of input | |
2369 |
|
2370 | |||
2370 | Covers cases where there are multiple lines in the user entry, |
|
2371 | Covers cases where there are multiple lines in the user entry, | |
2371 | which is the case when the user goes back to a multiline history |
|
2372 | which is the case when the user goes back to a multiline history | |
2372 | entry and presses enter. |
|
2373 | entry and presses enter. | |
2373 |
|
2374 | |||
2374 | """ |
|
2375 | """ | |
2375 | out = [] |
|
2376 | out = [] | |
2376 | for l in line.rstrip('\n').split('\n'): |
|
2377 | for l in line.rstrip('\n').split('\n'): | |
2377 | out.append(self._prefilter(l, continue_prompt)) |
|
2378 | out.append(self._prefilter(l, continue_prompt)) | |
2378 | return '\n'.join(out) |
|
2379 | return '\n'.join(out) | |
2379 |
|
2380 | |||
2380 | # Set the default prefilter() function (this can be user-overridden) |
|
2381 | # Set the default prefilter() function (this can be user-overridden) | |
2381 | prefilter = multiline_prefilter |
|
2382 | prefilter = multiline_prefilter | |
2382 |
|
2383 | |||
2383 | def handle_normal(self,line_info): |
|
2384 | def handle_normal(self,line_info): | |
2384 | """Handle normal input lines. Use as a template for handlers.""" |
|
2385 | """Handle normal input lines. Use as a template for handlers.""" | |
2385 |
|
2386 | |||
2386 | # With autoindent on, we need some way to exit the input loop, and I |
|
2387 | # With autoindent on, we need some way to exit the input loop, and I | |
2387 | # don't want to force the user to have to backspace all the way to |
|
2388 | # don't want to force the user to have to backspace all the way to | |
2388 | # clear the line. The rule will be in this case, that either two |
|
2389 | # clear the line. The rule will be in this case, that either two | |
2389 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2390 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2390 | # of a size different to the indent level, will exit the input loop. |
|
2391 | # of a size different to the indent level, will exit the input loop. | |
2391 | line = line_info.line |
|
2392 | line = line_info.line | |
2392 | continue_prompt = line_info.continue_prompt |
|
2393 | continue_prompt = line_info.continue_prompt | |
2393 |
|
2394 | |||
2394 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2395 | if (continue_prompt and self.autoindent and line.isspace() and | |
2395 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2396 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2396 | (self.buffer[-1]).isspace() )): |
|
2397 | (self.buffer[-1]).isspace() )): | |
2397 | line = '' |
|
2398 | line = '' | |
2398 |
|
2399 | |||
2399 | self.log(line,line,continue_prompt) |
|
2400 | self.log(line,line,continue_prompt) | |
2400 | return line |
|
2401 | return line | |
2401 |
|
2402 | |||
2402 | def handle_alias(self,line_info): |
|
2403 | def handle_alias(self,line_info): | |
2403 | """Handle alias input lines. """ |
|
2404 | """Handle alias input lines. """ | |
2404 | tgt = self.alias_table[line_info.iFun] |
|
2405 | tgt = self.alias_table[line_info.iFun] | |
2405 | # print "=>",tgt #dbg |
|
2406 | # print "=>",tgt #dbg | |
2406 | if callable(tgt): |
|
2407 | if callable(tgt): | |
2407 | if '$' in line_info.line: |
|
2408 | if '$' in line_info.line: | |
2408 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2409 | call_meth = '(_ip, _ip.itpl(%s))' | |
2409 | else: |
|
2410 | else: | |
2410 | call_meth = '(_ip,%s)' |
|
2411 | call_meth = '(_ip,%s)' | |
2411 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2412 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, | |
2412 | line_info.iFun, |
|
2413 | line_info.iFun, | |
2413 | make_quoted_expr(line_info.line)) |
|
2414 | make_quoted_expr(line_info.line)) | |
2414 | else: |
|
2415 | else: | |
2415 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2416 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) | |
2416 |
|
2417 | |||
2417 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2418 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2418 | # aliases won't work in indented sections. |
|
2419 | # aliases won't work in indented sections. | |
2419 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2420 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2420 | make_quoted_expr( transformed )) |
|
2421 | make_quoted_expr( transformed )) | |
2421 |
|
2422 | |||
2422 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2423 | self.log(line_info.line,line_out,line_info.continue_prompt) | |
2423 | #print 'line out:',line_out # dbg |
|
2424 | #print 'line out:',line_out # dbg | |
2424 | return line_out |
|
2425 | return line_out | |
2425 |
|
2426 | |||
2426 | def handle_shell_escape(self, line_info): |
|
2427 | def handle_shell_escape(self, line_info): | |
2427 | """Execute the line in a shell, empty return value""" |
|
2428 | """Execute the line in a shell, empty return value""" | |
2428 | #print 'line in :', `line` # dbg |
|
2429 | #print 'line in :', `line` # dbg | |
2429 | line = line_info.line |
|
2430 | line = line_info.line | |
2430 | if line.lstrip().startswith('!!'): |
|
2431 | if line.lstrip().startswith('!!'): | |
2431 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2432 | # rewrite LineInfo's line, iFun and theRest to properly hold the | |
2432 | # call to %sx and the actual command to be executed, so |
|
2433 | # call to %sx and the actual command to be executed, so | |
2433 | # handle_magic can work correctly. Note that this works even if |
|
2434 | # handle_magic can work correctly. Note that this works even if | |
2434 | # the line is indented, so it handles multi_line_specials |
|
2435 | # the line is indented, so it handles multi_line_specials | |
2435 | # properly. |
|
2436 | # properly. | |
2436 | new_rest = line.lstrip()[2:] |
|
2437 | new_rest = line.lstrip()[2:] | |
2437 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2438 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) | |
2438 | line_info.iFun = 'sx' |
|
2439 | line_info.iFun = 'sx' | |
2439 | line_info.theRest = new_rest |
|
2440 | line_info.theRest = new_rest | |
2440 | return self.handle_magic(line_info) |
|
2441 | return self.handle_magic(line_info) | |
2441 | else: |
|
2442 | else: | |
2442 | cmd = line.lstrip().lstrip('!') |
|
2443 | cmd = line.lstrip().lstrip('!') | |
2443 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2444 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2444 | make_quoted_expr(cmd)) |
|
2445 | make_quoted_expr(cmd)) | |
2445 | # update cache/log and return |
|
2446 | # update cache/log and return | |
2446 | self.log(line,line_out,line_info.continue_prompt) |
|
2447 | self.log(line,line_out,line_info.continue_prompt) | |
2447 | return line_out |
|
2448 | return line_out | |
2448 |
|
2449 | |||
2449 | def handle_magic(self, line_info): |
|
2450 | def handle_magic(self, line_info): | |
2450 | """Execute magic functions.""" |
|
2451 | """Execute magic functions.""" | |
2451 | iFun = line_info.iFun |
|
2452 | iFun = line_info.iFun | |
2452 | theRest = line_info.theRest |
|
2453 | theRest = line_info.theRest | |
2453 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2454 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, | |
2454 | make_quoted_expr(iFun + " " + theRest)) |
|
2455 | make_quoted_expr(iFun + " " + theRest)) | |
2455 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2456 | self.log(line_info.line,cmd,line_info.continue_prompt) | |
2456 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2457 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2457 | return cmd |
|
2458 | return cmd | |
2458 |
|
2459 | |||
2459 | def handle_auto(self, line_info): |
|
2460 | def handle_auto(self, line_info): | |
2460 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2461 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2461 |
|
2462 | |||
2462 | line = line_info.line |
|
2463 | line = line_info.line | |
2463 | iFun = line_info.iFun |
|
2464 | iFun = line_info.iFun | |
2464 | theRest = line_info.theRest |
|
2465 | theRest = line_info.theRest | |
2465 | pre = line_info.pre |
|
2466 | pre = line_info.pre | |
2466 | continue_prompt = line_info.continue_prompt |
|
2467 | continue_prompt = line_info.continue_prompt | |
2467 | obj = line_info.ofind(self)['obj'] |
|
2468 | obj = line_info.ofind(self)['obj'] | |
2468 |
|
2469 | |||
2469 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2470 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2470 |
|
2471 | |||
2471 | # This should only be active for single-line input! |
|
2472 | # This should only be active for single-line input! | |
2472 | if continue_prompt: |
|
2473 | if continue_prompt: | |
2473 | self.log(line,line,continue_prompt) |
|
2474 | self.log(line,line,continue_prompt) | |
2474 | return line |
|
2475 | return line | |
2475 |
|
2476 | |||
2476 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
2477 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) | |
2477 | auto_rewrite = True |
|
2478 | auto_rewrite = True | |
2478 |
|
2479 | |||
2479 | if pre == self.ESC_QUOTE: |
|
2480 | if pre == self.ESC_QUOTE: | |
2480 | # Auto-quote splitting on whitespace |
|
2481 | # Auto-quote splitting on whitespace | |
2481 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2482 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2482 | elif pre == self.ESC_QUOTE2: |
|
2483 | elif pre == self.ESC_QUOTE2: | |
2483 | # Auto-quote whole string |
|
2484 | # Auto-quote whole string | |
2484 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2485 | newcmd = '%s("%s")' % (iFun,theRest) | |
2485 | elif pre == self.ESC_PAREN: |
|
2486 | elif pre == self.ESC_PAREN: | |
2486 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2487 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2487 | else: |
|
2488 | else: | |
2488 | # Auto-paren. |
|
2489 | # Auto-paren. | |
2489 | # We only apply it to argument-less calls if the autocall |
|
2490 | # We only apply it to argument-less calls if the autocall | |
2490 | # parameter is set to 2. We only need to check that autocall is < |
|
2491 | # parameter is set to 2. We only need to check that autocall is < | |
2491 | # 2, since this function isn't called unless it's at least 1. |
|
2492 | # 2, since this function isn't called unless it's at least 1. | |
2492 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
2493 | if not theRest and (self.rc.autocall < 2) and not force_auto: | |
2493 | newcmd = '%s %s' % (iFun,theRest) |
|
2494 | newcmd = '%s %s' % (iFun,theRest) | |
2494 | auto_rewrite = False |
|
2495 | auto_rewrite = False | |
2495 | else: |
|
2496 | else: | |
2496 | if not force_auto and theRest.startswith('['): |
|
2497 | if not force_auto and theRest.startswith('['): | |
2497 | if hasattr(obj,'__getitem__'): |
|
2498 | if hasattr(obj,'__getitem__'): | |
2498 | # Don't autocall in this case: item access for an object |
|
2499 | # Don't autocall in this case: item access for an object | |
2499 | # which is BOTH callable and implements __getitem__. |
|
2500 | # which is BOTH callable and implements __getitem__. | |
2500 | newcmd = '%s %s' % (iFun,theRest) |
|
2501 | newcmd = '%s %s' % (iFun,theRest) | |
2501 | auto_rewrite = False |
|
2502 | auto_rewrite = False | |
2502 | else: |
|
2503 | else: | |
2503 | # if the object doesn't support [] access, go ahead and |
|
2504 | # if the object doesn't support [] access, go ahead and | |
2504 | # autocall |
|
2505 | # autocall | |
2505 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2506 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2506 | elif theRest.endswith(';'): |
|
2507 | elif theRest.endswith(';'): | |
2507 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2508 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2508 | else: |
|
2509 | else: | |
2509 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2510 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2510 |
|
2511 | |||
2511 | if auto_rewrite: |
|
2512 | if auto_rewrite: | |
2512 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2513 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd | |
2513 |
|
2514 | |||
2514 | try: |
|
2515 | try: | |
2515 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2516 | # plain ascii works better w/ pyreadline, on some machines, so | |
2516 | # we use it and only print uncolored rewrite if we have unicode |
|
2517 | # we use it and only print uncolored rewrite if we have unicode | |
2517 | rw = str(rw) |
|
2518 | rw = str(rw) | |
2518 | print >>Term.cout, rw |
|
2519 | print >>Term.cout, rw | |
2519 | except UnicodeEncodeError: |
|
2520 | except UnicodeEncodeError: | |
2520 | print "-------------->" + newcmd |
|
2521 | print "-------------->" + newcmd | |
2521 |
|
2522 | |||
2522 | # log what is now valid Python, not the actual user input (without the |
|
2523 | # log what is now valid Python, not the actual user input (without the | |
2523 | # final newline) |
|
2524 | # final newline) | |
2524 | self.log(line,newcmd,continue_prompt) |
|
2525 | self.log(line,newcmd,continue_prompt) | |
2525 | return newcmd |
|
2526 | return newcmd | |
2526 |
|
2527 | |||
2527 | def handle_help(self, line_info): |
|
2528 | def handle_help(self, line_info): | |
2528 | """Try to get some help for the object. |
|
2529 | """Try to get some help for the object. | |
2529 |
|
2530 | |||
2530 | obj? or ?obj -> basic information. |
|
2531 | obj? or ?obj -> basic information. | |
2531 | obj?? or ??obj -> more details. |
|
2532 | obj?? or ??obj -> more details. | |
2532 | """ |
|
2533 | """ | |
2533 |
|
2534 | |||
2534 | line = line_info.line |
|
2535 | line = line_info.line | |
2535 | # We need to make sure that we don't process lines which would be |
|
2536 | # We need to make sure that we don't process lines which would be | |
2536 | # otherwise valid python, such as "x=1 # what?" |
|
2537 | # otherwise valid python, such as "x=1 # what?" | |
2537 | try: |
|
2538 | try: | |
2538 | codeop.compile_command(line) |
|
2539 | codeop.compile_command(line) | |
2539 | except SyntaxError: |
|
2540 | except SyntaxError: | |
2540 | # We should only handle as help stuff which is NOT valid syntax |
|
2541 | # We should only handle as help stuff which is NOT valid syntax | |
2541 | if line[0]==self.ESC_HELP: |
|
2542 | if line[0]==self.ESC_HELP: | |
2542 | line = line[1:] |
|
2543 | line = line[1:] | |
2543 | elif line[-1]==self.ESC_HELP: |
|
2544 | elif line[-1]==self.ESC_HELP: | |
2544 | line = line[:-1] |
|
2545 | line = line[:-1] | |
2545 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2546 | self.log(line,'#?'+line,line_info.continue_prompt) | |
2546 | if line: |
|
2547 | if line: | |
2547 | #print 'line:<%r>' % line # dbg |
|
2548 | #print 'line:<%r>' % line # dbg | |
2548 | self.magic_pinfo(line) |
|
2549 | self.magic_pinfo(line) | |
2549 | else: |
|
2550 | else: | |
2550 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2551 | page(self.usage,screen_lines=self.rc.screen_length) | |
2551 | return '' # Empty string is needed here! |
|
2552 | return '' # Empty string is needed here! | |
2552 | except: |
|
2553 | except: | |
2553 | # Pass any other exceptions through to the normal handler |
|
2554 | # Pass any other exceptions through to the normal handler | |
2554 | return self.handle_normal(line_info) |
|
2555 | return self.handle_normal(line_info) | |
2555 | else: |
|
2556 | else: | |
2556 | # If the code compiles ok, we should handle it normally |
|
2557 | # If the code compiles ok, we should handle it normally | |
2557 | return self.handle_normal(line_info) |
|
2558 | return self.handle_normal(line_info) | |
2558 |
|
2559 | |||
2559 | def getapi(self): |
|
2560 | def getapi(self): | |
2560 | """ Get an IPApi object for this shell instance |
|
2561 | """ Get an IPApi object for this shell instance | |
2561 |
|
2562 | |||
2562 | Getting an IPApi object is always preferable to accessing the shell |
|
2563 | Getting an IPApi object is always preferable to accessing the shell | |
2563 | directly, but this holds true especially for extensions. |
|
2564 | directly, but this holds true especially for extensions. | |
2564 |
|
2565 | |||
2565 | It should always be possible to implement an extension with IPApi |
|
2566 | It should always be possible to implement an extension with IPApi | |
2566 | alone. If not, contact maintainer to request an addition. |
|
2567 | alone. If not, contact maintainer to request an addition. | |
2567 |
|
2568 | |||
2568 | """ |
|
2569 | """ | |
2569 | return self.api |
|
2570 | return self.api | |
2570 |
|
2571 | |||
2571 | def handle_emacs(self, line_info): |
|
2572 | def handle_emacs(self, line_info): | |
2572 | """Handle input lines marked by python-mode.""" |
|
2573 | """Handle input lines marked by python-mode.""" | |
2573 |
|
2574 | |||
2574 | # Currently, nothing is done. Later more functionality can be added |
|
2575 | # Currently, nothing is done. Later more functionality can be added | |
2575 | # here if needed. |
|
2576 | # here if needed. | |
2576 |
|
2577 | |||
2577 | # The input cache shouldn't be updated |
|
2578 | # The input cache shouldn't be updated | |
2578 | return line_info.line |
|
2579 | return line_info.line | |
2579 |
|
2580 | |||
2580 |
|
2581 | |||
2581 | def mktempfile(self,data=None): |
|
2582 | def mktempfile(self,data=None): | |
2582 | """Make a new tempfile and return its filename. |
|
2583 | """Make a new tempfile and return its filename. | |
2583 |
|
2584 | |||
2584 | This makes a call to tempfile.mktemp, but it registers the created |
|
2585 | This makes a call to tempfile.mktemp, but it registers the created | |
2585 | filename internally so ipython cleans it up at exit time. |
|
2586 | filename internally so ipython cleans it up at exit time. | |
2586 |
|
2587 | |||
2587 | Optional inputs: |
|
2588 | Optional inputs: | |
2588 |
|
2589 | |||
2589 | - data(None): if data is given, it gets written out to the temp file |
|
2590 | - data(None): if data is given, it gets written out to the temp file | |
2590 | immediately, and the file is closed again.""" |
|
2591 | immediately, and the file is closed again.""" | |
2591 |
|
2592 | |||
2592 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2593 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2593 | self.tempfiles.append(filename) |
|
2594 | self.tempfiles.append(filename) | |
2594 |
|
2595 | |||
2595 | if data: |
|
2596 | if data: | |
2596 | tmp_file = open(filename,'w') |
|
2597 | tmp_file = open(filename,'w') | |
2597 | tmp_file.write(data) |
|
2598 | tmp_file.write(data) | |
2598 | tmp_file.close() |
|
2599 | tmp_file.close() | |
2599 | return filename |
|
2600 | return filename | |
2600 |
|
2601 | |||
2601 | def write(self,data): |
|
2602 | def write(self,data): | |
2602 | """Write a string to the default output""" |
|
2603 | """Write a string to the default output""" | |
2603 | Term.cout.write(data) |
|
2604 | Term.cout.write(data) | |
2604 |
|
2605 | |||
2605 | def write_err(self,data): |
|
2606 | def write_err(self,data): | |
2606 | """Write a string to the default error output""" |
|
2607 | """Write a string to the default error output""" | |
2607 | Term.cerr.write(data) |
|
2608 | Term.cerr.write(data) | |
2608 |
|
2609 | |||
2609 | def ask_exit(self): |
|
2610 | def ask_exit(self): | |
2610 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2611 | """ Call for exiting. Can be overiden and used as a callback. """ | |
2611 | self.exit_now = True |
|
2612 | self.exit_now = True | |
2612 |
|
2613 | |||
2613 | def exit(self): |
|
2614 | def exit(self): | |
2614 | """Handle interactive exit. |
|
2615 | """Handle interactive exit. | |
2615 |
|
2616 | |||
2616 | This method calls the ask_exit callback.""" |
|
2617 | This method calls the ask_exit callback.""" | |
2617 |
|
2618 | |||
2618 | if self.rc.confirm_exit: |
|
2619 | if self.rc.confirm_exit: | |
2619 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2620 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2620 | self.ask_exit() |
|
2621 | self.ask_exit() | |
2621 | else: |
|
2622 | else: | |
2622 | self.ask_exit() |
|
2623 | self.ask_exit() | |
2623 |
|
2624 | |||
2624 | def safe_execfile(self,fname,*where,**kw): |
|
2625 | def safe_execfile(self,fname,*where,**kw): | |
2625 | """A safe version of the builtin execfile(). |
|
2626 | """A safe version of the builtin execfile(). | |
2626 |
|
2627 | |||
2627 | This version will never throw an exception, and knows how to handle |
|
2628 | This version will never throw an exception, and knows how to handle | |
2628 | ipython logs as well. |
|
2629 | ipython logs as well. | |
2629 |
|
2630 | |||
2630 | :Parameters: |
|
2631 | :Parameters: | |
2631 | fname : string |
|
2632 | fname : string | |
2632 | Name of the file to be executed. |
|
2633 | Name of the file to be executed. | |
2633 |
|
2634 | |||
2634 | where : tuple |
|
2635 | where : tuple | |
2635 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2636 | One or two namespaces, passed to execfile() as (globals,locals). | |
2636 | If only one is given, it is passed as both. |
|
2637 | If only one is given, it is passed as both. | |
2637 |
|
2638 | |||
2638 | :Keywords: |
|
2639 | :Keywords: | |
2639 | islog : boolean (False) |
|
2640 | islog : boolean (False) | |
2640 |
|
2641 | |||
2641 | quiet : boolean (True) |
|
2642 | quiet : boolean (True) | |
2642 |
|
2643 | |||
2643 | exit_ignore : boolean (False) |
|
2644 | exit_ignore : boolean (False) | |
2644 | """ |
|
2645 | """ | |
2645 |
|
2646 | |||
2646 | def syspath_cleanup(): |
|
2647 | def syspath_cleanup(): | |
2647 | """Internal cleanup routine for sys.path.""" |
|
2648 | """Internal cleanup routine for sys.path.""" | |
2648 | if add_dname: |
|
2649 | if add_dname: | |
2649 | try: |
|
2650 | try: | |
2650 | sys.path.remove(dname) |
|
2651 | sys.path.remove(dname) | |
2651 | except ValueError: |
|
2652 | except ValueError: | |
2652 | # For some reason the user has already removed it, ignore. |
|
2653 | # For some reason the user has already removed it, ignore. | |
2653 | pass |
|
2654 | pass | |
2654 |
|
2655 | |||
2655 | fname = os.path.expanduser(fname) |
|
2656 | fname = os.path.expanduser(fname) | |
2656 |
|
2657 | |||
2657 | # Find things also in current directory. This is needed to mimic the |
|
2658 | # Find things also in current directory. This is needed to mimic the | |
2658 | # behavior of running a script from the system command line, where |
|
2659 | # behavior of running a script from the system command line, where | |
2659 | # Python inserts the script's directory into sys.path |
|
2660 | # Python inserts the script's directory into sys.path | |
2660 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2661 | dname = os.path.dirname(os.path.abspath(fname)) | |
2661 | add_dname = False |
|
2662 | add_dname = False | |
2662 | if dname not in sys.path: |
|
2663 | if dname not in sys.path: | |
2663 | sys.path.insert(0,dname) |
|
2664 | sys.path.insert(0,dname) | |
2664 | add_dname = True |
|
2665 | add_dname = True | |
2665 |
|
2666 | |||
2666 | try: |
|
2667 | try: | |
2667 | xfile = open(fname) |
|
2668 | xfile = open(fname) | |
2668 | except: |
|
2669 | except: | |
2669 | print >> Term.cerr, \ |
|
2670 | print >> Term.cerr, \ | |
2670 | 'Could not open file <%s> for safe execution.' % fname |
|
2671 | 'Could not open file <%s> for safe execution.' % fname | |
2671 | syspath_cleanup() |
|
2672 | syspath_cleanup() | |
2672 | return None |
|
2673 | return None | |
2673 |
|
2674 | |||
2674 | kw.setdefault('islog',0) |
|
2675 | kw.setdefault('islog',0) | |
2675 | kw.setdefault('quiet',1) |
|
2676 | kw.setdefault('quiet',1) | |
2676 | kw.setdefault('exit_ignore',0) |
|
2677 | kw.setdefault('exit_ignore',0) | |
2677 |
|
2678 | |||
2678 | first = xfile.readline() |
|
2679 | first = xfile.readline() | |
2679 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2680 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2680 | xfile.close() |
|
2681 | xfile.close() | |
2681 | # line by line execution |
|
2682 | # line by line execution | |
2682 | if first.startswith(loghead) or kw['islog']: |
|
2683 | if first.startswith(loghead) or kw['islog']: | |
2683 | print 'Loading log file <%s> one line at a time...' % fname |
|
2684 | print 'Loading log file <%s> one line at a time...' % fname | |
2684 | if kw['quiet']: |
|
2685 | if kw['quiet']: | |
2685 | stdout_save = sys.stdout |
|
2686 | stdout_save = sys.stdout | |
2686 | sys.stdout = StringIO.StringIO() |
|
2687 | sys.stdout = StringIO.StringIO() | |
2687 | try: |
|
2688 | try: | |
2688 | globs,locs = where[0:2] |
|
2689 | globs,locs = where[0:2] | |
2689 | except: |
|
2690 | except: | |
2690 | try: |
|
2691 | try: | |
2691 | globs = locs = where[0] |
|
2692 | globs = locs = where[0] | |
2692 | except: |
|
2693 | except: | |
2693 | globs = locs = globals() |
|
2694 | globs = locs = globals() | |
2694 | badblocks = [] |
|
2695 | badblocks = [] | |
2695 |
|
2696 | |||
2696 | # we also need to identify indented blocks of code when replaying |
|
2697 | # we also need to identify indented blocks of code when replaying | |
2697 | # logs and put them together before passing them to an exec |
|
2698 | # logs and put them together before passing them to an exec | |
2698 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2699 | # statement. This takes a bit of regexp and look-ahead work in the | |
2699 | # file. It's easiest if we swallow the whole thing in memory |
|
2700 | # file. It's easiest if we swallow the whole thing in memory | |
2700 | # first, and manually walk through the lines list moving the |
|
2701 | # first, and manually walk through the lines list moving the | |
2701 | # counter ourselves. |
|
2702 | # counter ourselves. | |
2702 | indent_re = re.compile('\s+\S') |
|
2703 | indent_re = re.compile('\s+\S') | |
2703 | xfile = open(fname) |
|
2704 | xfile = open(fname) | |
2704 | filelines = xfile.readlines() |
|
2705 | filelines = xfile.readlines() | |
2705 | xfile.close() |
|
2706 | xfile.close() | |
2706 | nlines = len(filelines) |
|
2707 | nlines = len(filelines) | |
2707 | lnum = 0 |
|
2708 | lnum = 0 | |
2708 | while lnum < nlines: |
|
2709 | while lnum < nlines: | |
2709 | line = filelines[lnum] |
|
2710 | line = filelines[lnum] | |
2710 | lnum += 1 |
|
2711 | lnum += 1 | |
2711 | # don't re-insert logger status info into cache |
|
2712 | # don't re-insert logger status info into cache | |
2712 | if line.startswith('#log#'): |
|
2713 | if line.startswith('#log#'): | |
2713 | continue |
|
2714 | continue | |
2714 | else: |
|
2715 | else: | |
2715 | # build a block of code (maybe a single line) for execution |
|
2716 | # build a block of code (maybe a single line) for execution | |
2716 | block = line |
|
2717 | block = line | |
2717 | try: |
|
2718 | try: | |
2718 | next = filelines[lnum] # lnum has already incremented |
|
2719 | next = filelines[lnum] # lnum has already incremented | |
2719 | except: |
|
2720 | except: | |
2720 | next = None |
|
2721 | next = None | |
2721 | while next and indent_re.match(next): |
|
2722 | while next and indent_re.match(next): | |
2722 | block += next |
|
2723 | block += next | |
2723 | lnum += 1 |
|
2724 | lnum += 1 | |
2724 | try: |
|
2725 | try: | |
2725 | next = filelines[lnum] |
|
2726 | next = filelines[lnum] | |
2726 | except: |
|
2727 | except: | |
2727 | next = None |
|
2728 | next = None | |
2728 | # now execute the block of one or more lines |
|
2729 | # now execute the block of one or more lines | |
2729 | try: |
|
2730 | try: | |
2730 | exec block in globs,locs |
|
2731 | exec block in globs,locs | |
2731 | except SystemExit: |
|
2732 | except SystemExit: | |
2732 | pass |
|
2733 | pass | |
2733 | except: |
|
2734 | except: | |
2734 | badblocks.append(block.rstrip()) |
|
2735 | badblocks.append(block.rstrip()) | |
2735 | if kw['quiet']: # restore stdout |
|
2736 | if kw['quiet']: # restore stdout | |
2736 | sys.stdout.close() |
|
2737 | sys.stdout.close() | |
2737 | sys.stdout = stdout_save |
|
2738 | sys.stdout = stdout_save | |
2738 | print 'Finished replaying log file <%s>' % fname |
|
2739 | print 'Finished replaying log file <%s>' % fname | |
2739 | if badblocks: |
|
2740 | if badblocks: | |
2740 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2741 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2741 | '<%s> reported errors:' % fname) |
|
2742 | '<%s> reported errors:' % fname) | |
2742 |
|
2743 | |||
2743 | for badline in badblocks: |
|
2744 | for badline in badblocks: | |
2744 | print >> sys.stderr, badline |
|
2745 | print >> sys.stderr, badline | |
2745 | else: # regular file execution |
|
2746 | else: # regular file execution | |
2746 | try: |
|
2747 | try: | |
2747 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2748 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
2748 | # Work around a bug in Python for Windows. The bug was |
|
2749 | # Work around a bug in Python for Windows. The bug was | |
2749 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2750 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |
2750 | # SVN Python as of March/07. For details, see: |
|
2751 | # SVN Python as of March/07. For details, see: | |
2751 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2752 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |
2752 | try: |
|
2753 | try: | |
2753 | globs,locs = where[0:2] |
|
2754 | globs,locs = where[0:2] | |
2754 | except: |
|
2755 | except: | |
2755 | try: |
|
2756 | try: | |
2756 | globs = locs = where[0] |
|
2757 | globs = locs = where[0] | |
2757 | except: |
|
2758 | except: | |
2758 | globs = locs = globals() |
|
2759 | globs = locs = globals() | |
2759 | exec file(fname) in globs,locs |
|
2760 | exec file(fname) in globs,locs | |
2760 | else: |
|
2761 | else: | |
2761 | execfile(fname,*where) |
|
2762 | execfile(fname,*where) | |
2762 | except SyntaxError: |
|
2763 | except SyntaxError: | |
2763 | self.showsyntaxerror() |
|
2764 | self.showsyntaxerror() | |
2764 | warn('Failure executing file: <%s>' % fname) |
|
2765 | warn('Failure executing file: <%s>' % fname) | |
2765 | except SystemExit,status: |
|
2766 | except SystemExit,status: | |
2766 | # Code that correctly sets the exit status flag to success (0) |
|
2767 | # Code that correctly sets the exit status flag to success (0) | |
2767 | # shouldn't be bothered with a traceback. Note that a plain |
|
2768 | # shouldn't be bothered with a traceback. Note that a plain | |
2768 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2769 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |
2769 | # will still get a traceback. Note that the structure of the |
|
2770 | # will still get a traceback. Note that the structure of the | |
2770 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2771 | # SystemExit exception changed between Python 2.4 and 2.5, so | |
2771 | # the checks must be done in a version-dependent way. |
|
2772 | # the checks must be done in a version-dependent way. | |
2772 | show = False |
|
2773 | show = False | |
2773 |
|
2774 | |||
2774 | if sys.version_info[:2] > (2,5): |
|
2775 | if sys.version_info[:2] > (2,5): | |
2775 | if status.message!=0 and not kw['exit_ignore']: |
|
2776 | if status.message!=0 and not kw['exit_ignore']: | |
2776 | show = True |
|
2777 | show = True | |
2777 | else: |
|
2778 | else: | |
2778 | if status.code and not kw['exit_ignore']: |
|
2779 | if status.code and not kw['exit_ignore']: | |
2779 | show = True |
|
2780 | show = True | |
2780 | if show: |
|
2781 | if show: | |
2781 | self.showtraceback() |
|
2782 | self.showtraceback() | |
2782 | warn('Failure executing file: <%s>' % fname) |
|
2783 | warn('Failure executing file: <%s>' % fname) | |
2783 | except: |
|
2784 | except: | |
2784 | self.showtraceback() |
|
2785 | self.showtraceback() | |
2785 | warn('Failure executing file: <%s>' % fname) |
|
2786 | warn('Failure executing file: <%s>' % fname) | |
2786 |
|
2787 | |||
2787 | syspath_cleanup() |
|
2788 | syspath_cleanup() | |
2788 |
|
2789 | |||
2789 | #************************* end of file <iplib.py> ***************************** |
|
2790 | #************************* end of file <iplib.py> ***************************** |
@@ -1,780 +1,775 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | Requires Python 2.1 or better. |
|
5 | Requires Python 2.1 or better. | |
6 |
|
6 | |||
7 | This file contains the main make_IPython() starter function. |
|
7 | This file contains the main make_IPython() starter function. | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
11 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
18 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
19 | __license__ = Release.license |
|
19 | __license__ = Release.license | |
20 | __version__ = Release.version |
|
20 | __version__ = Release.version | |
21 |
|
21 | |||
22 | try: |
|
22 | try: | |
23 | credits._Printer__data = """ |
|
23 | credits._Printer__data = """ | |
24 | Python: %s |
|
24 | Python: %s | |
25 |
|
25 | |||
26 | IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users. |
|
26 | IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users. | |
27 | See http://ipython.scipy.org for more information.""" \ |
|
27 | See http://ipython.scipy.org for more information.""" \ | |
28 | % credits._Printer__data |
|
28 | % credits._Printer__data | |
29 |
|
29 | |||
30 | copyright._Printer__data += """ |
|
30 | copyright._Printer__data += """ | |
31 |
|
31 | |||
32 | Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray. |
|
32 | Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray. | |
33 | All Rights Reserved.""" |
|
33 | All Rights Reserved.""" | |
34 | except NameError: |
|
34 | except NameError: | |
35 | # Can happen if ipython was started with 'python -S', so that site.py is |
|
35 | # Can happen if ipython was started with 'python -S', so that site.py is | |
36 | # not loaded |
|
36 | # not loaded | |
37 | pass |
|
37 | pass | |
38 |
|
38 | |||
39 | #**************************************************************************** |
|
39 | #**************************************************************************** | |
40 | # Required modules |
|
40 | # Required modules | |
41 |
|
41 | |||
42 | # From the standard library |
|
42 | # From the standard library | |
43 | import __main__ |
|
43 | import __main__ | |
44 | import __builtin__ |
|
44 | import __builtin__ | |
45 | import os |
|
45 | import os | |
46 | import re |
|
46 | import re | |
47 | import sys |
|
47 | import sys | |
48 | import types |
|
48 | import types | |
49 | from pprint import pprint,pformat |
|
49 | from pprint import pprint,pformat | |
50 |
|
50 | |||
51 | # Our own |
|
51 | # Our own | |
52 | from IPython import DPyGetOpt |
|
52 | from IPython import DPyGetOpt | |
53 | from IPython.ipstruct import Struct |
|
53 | from IPython.ipstruct import Struct | |
54 | from IPython.OutputTrap import OutputTrap |
|
54 | from IPython.OutputTrap import OutputTrap | |
55 | from IPython.ConfigLoader import ConfigLoader |
|
55 | from IPython.ConfigLoader import ConfigLoader | |
56 | from IPython.iplib import InteractiveShell |
|
56 | from IPython.iplib import InteractiveShell | |
57 | from IPython.usage import cmd_line_usage,interactive_usage |
|
57 | from IPython.usage import cmd_line_usage,interactive_usage | |
58 | from IPython.genutils import * |
|
58 | from IPython.genutils import * | |
59 |
|
59 | |||
60 | def force_import(modname): |
|
60 | def force_import(modname): | |
61 | if modname in sys.modules: |
|
61 | if modname in sys.modules: | |
62 | print "reload",modname |
|
62 | print "reload",modname | |
63 | reload(sys.modules[modname]) |
|
63 | reload(sys.modules[modname]) | |
64 | else: |
|
64 | else: | |
65 | __import__(modname) |
|
65 | __import__(modname) | |
66 |
|
66 | |||
67 |
|
67 | |||
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 | def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1, |
|
69 | def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1, | |
70 | rc_override=None,shell_class=InteractiveShell, |
|
70 | rc_override=None,shell_class=InteractiveShell, | |
71 | embedded=False,**kw): |
|
71 | embedded=False,**kw): | |
72 | """This is a dump of IPython into a single function. |
|
72 | """This is a dump of IPython into a single function. | |
73 |
|
73 | |||
74 | Later it will have to be broken up in a sensible manner. |
|
74 | Later it will have to be broken up in a sensible manner. | |
75 |
|
75 | |||
76 | Arguments: |
|
76 | Arguments: | |
77 |
|
77 | |||
78 | - argv: a list similar to sys.argv[1:]. It should NOT contain the desired |
|
78 | - argv: a list similar to sys.argv[1:]. It should NOT contain the desired | |
79 | script name, b/c DPyGetOpt strips the first argument only for the real |
|
79 | script name, b/c DPyGetOpt strips the first argument only for the real | |
80 | sys.argv. |
|
80 | sys.argv. | |
81 |
|
81 | |||
82 | - user_ns: a dict to be used as the user's namespace.""" |
|
82 | - user_ns: a dict to be used as the user's namespace.""" | |
83 |
|
83 | |||
84 | #---------------------------------------------------------------------- |
|
84 | #---------------------------------------------------------------------- | |
85 | # Defaults and initialization |
|
85 | # Defaults and initialization | |
86 |
|
86 | |||
87 | # For developer debugging, deactivates crash handler and uses pdb. |
|
87 | # For developer debugging, deactivates crash handler and uses pdb. | |
88 | DEVDEBUG = False |
|
88 | DEVDEBUG = False | |
89 |
|
89 | |||
90 | if argv is None: |
|
90 | if argv is None: | |
91 | argv = sys.argv |
|
91 | argv = sys.argv | |
92 |
|
92 | |||
93 | # __IP is the main global that lives throughout and represents the whole |
|
93 | # __IP is the main global that lives throughout and represents the whole | |
94 | # application. If the user redefines it, all bets are off as to what |
|
94 | # application. If the user redefines it, all bets are off as to what | |
95 | # happens. |
|
95 | # happens. | |
96 |
|
96 | |||
97 | # __IP is the name of he global which the caller will have accessible as |
|
97 | # __IP is the name of he global which the caller will have accessible as | |
98 | # __IP.name. We set its name via the first parameter passed to |
|
98 | # __IP.name. We set its name via the first parameter passed to | |
99 | # InteractiveShell: |
|
99 | # InteractiveShell: | |
100 |
|
100 | |||
101 | IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns, |
|
101 | IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns, | |
102 | embedded=embedded,**kw) |
|
102 | embedded=embedded,**kw) | |
103 |
|
103 | |||
104 | # Put 'help' in the user namespace |
|
104 | # Put 'help' in the user namespace | |
105 | try: |
|
105 | try: | |
106 | from site import _Helper |
|
106 | from site import _Helper | |
107 | IP.user_ns['help'] = _Helper() |
|
107 | IP.user_ns['help'] = _Helper() | |
108 | except ImportError: |
|
108 | except ImportError: | |
109 | warn('help() not available - check site.py') |
|
109 | warn('help() not available - check site.py') | |
110 |
|
110 | |||
111 | if DEVDEBUG: |
|
111 | if DEVDEBUG: | |
112 | # For developer debugging only (global flag) |
|
112 | # For developer debugging only (global flag) | |
113 | from IPython import ultraTB |
|
113 | from IPython import ultraTB | |
114 | sys.excepthook = ultraTB.VerboseTB(call_pdb=1) |
|
114 | sys.excepthook = ultraTB.VerboseTB(call_pdb=1) | |
115 |
|
115 | |||
116 | IP.BANNER_PARTS = ['Python %s\n' |
|
116 | IP.BANNER_PARTS = ['Python %s\n' | |
117 | 'Type "copyright", "credits" or "license" ' |
|
117 | 'Type "copyright", "credits" or "license" ' | |
118 | 'for more information.\n' |
|
118 | 'for more information.\n' | |
119 | % (sys.version.split('\n')[0],), |
|
119 | % (sys.version.split('\n')[0],), | |
120 | "IPython %s -- An enhanced Interactive Python." |
|
120 | "IPython %s -- An enhanced Interactive Python." | |
121 | % (__version__,), |
|
121 | % (__version__,), | |
122 | """\ |
|
122 | """\ | |
123 | ? -> Introduction and overview of IPython's features. |
|
123 | ? -> Introduction and overview of IPython's features. | |
124 | %quickref -> Quick reference. |
|
124 | %quickref -> Quick reference. | |
125 | help -> Python's own help system. |
|
125 | help -> Python's own help system. | |
126 | object? -> Details about 'object'. ?object also works, ?? prints more. |
|
126 | object? -> Details about 'object'. ?object also works, ?? prints more. | |
127 | """ ] |
|
127 | """ ] | |
128 |
|
128 | |||
129 | IP.usage = interactive_usage |
|
129 | IP.usage = interactive_usage | |
130 |
|
130 | |||
131 | # Platform-dependent suffix and directory names. We use _ipython instead |
|
131 | # Platform-dependent suffix. | |
132 | # of .ipython under win32 b/c there's software that breaks with .named |
|
|||
133 | # directories on that platform. |
|
|||
134 | if os.name == 'posix': |
|
132 | if os.name == 'posix': | |
135 | rc_suffix = '' |
|
133 | rc_suffix = '' | |
136 | ipdir_def = '.ipython' |
|
|||
137 | else: |
|
134 | else: | |
138 | rc_suffix = '.ini' |
|
135 | rc_suffix = '.ini' | |
139 | ipdir_def = '_ipython' |
|
|||
140 |
|
136 | |||
141 | # default directory for configuration |
|
137 | # default directory for configuration | |
142 | ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR', |
|
138 | ipythondir_def = get_ipython_dir() | |
143 | os.path.join(IP.home_dir,ipdir_def))) |
|
139 | ||
144 |
|
||||
145 | sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran |
|
140 | sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran | |
146 |
|
141 | |||
147 | # we need the directory where IPython itself is installed |
|
142 | # we need the directory where IPython itself is installed | |
148 | import IPython |
|
143 | import IPython | |
149 | IPython_dir = os.path.dirname(IPython.__file__) |
|
144 | IPython_dir = os.path.dirname(IPython.__file__) | |
150 | del IPython |
|
145 | del IPython | |
151 |
|
146 | |||
152 | #------------------------------------------------------------------------- |
|
147 | #------------------------------------------------------------------------- | |
153 | # Command line handling |
|
148 | # Command line handling | |
154 |
|
149 | |||
155 | # Valid command line options (uses DPyGetOpt syntax, like Perl's |
|
150 | # Valid command line options (uses DPyGetOpt syntax, like Perl's | |
156 | # GetOpt::Long) |
|
151 | # GetOpt::Long) | |
157 |
|
152 | |||
158 | # Any key not listed here gets deleted even if in the file (like session |
|
153 | # Any key not listed here gets deleted even if in the file (like session | |
159 | # or profile). That's deliberate, to maintain the rc namespace clean. |
|
154 | # or profile). That's deliberate, to maintain the rc namespace clean. | |
160 |
|
155 | |||
161 | # Each set of options appears twice: under _conv only the names are |
|
156 | # Each set of options appears twice: under _conv only the names are | |
162 | # listed, indicating which type they must be converted to when reading the |
|
157 | # listed, indicating which type they must be converted to when reading the | |
163 | # ipythonrc file. And under DPyGetOpt they are listed with the regular |
|
158 | # ipythonrc file. And under DPyGetOpt they are listed with the regular | |
164 | # DPyGetOpt syntax (=s,=i,:f,etc). |
|
159 | # DPyGetOpt syntax (=s,=i,:f,etc). | |
165 |
|
160 | |||
166 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
161 | # Make sure there's a space before each end of line (they get auto-joined!) | |
167 | cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i ' |
|
162 | cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i ' | |
168 | 'c=s classic|cl color_info! colors=s confirm_exit! ' |
|
163 | 'c=s classic|cl color_info! colors=s confirm_exit! ' | |
169 | 'debug! deep_reload! editor=s log|l messages! nosep ' |
|
164 | 'debug! deep_reload! editor=s log|l messages! nosep ' | |
170 | 'object_info_string_level=i pdb! ' |
|
165 | 'object_info_string_level=i pdb! ' | |
171 | 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' |
|
166 | 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' | |
172 | 'pydb! ' |
|
167 | 'pydb! ' | |
173 | 'pylab_import_all! ' |
|
168 | 'pylab_import_all! ' | |
174 | 'quick screen_length|sl=i prompts_pad_left=i ' |
|
169 | 'quick screen_length|sl=i prompts_pad_left=i ' | |
175 | 'logfile|lf=s logplay|lp=s profile|p=s ' |
|
170 | 'logfile|lf=s logplay|lp=s profile|p=s ' | |
176 | 'readline! readline_merge_completions! ' |
|
171 | 'readline! readline_merge_completions! ' | |
177 | 'readline_omit__names! ' |
|
172 | 'readline_omit__names! ' | |
178 | 'rcfile=s separate_in|si=s separate_out|so=s ' |
|
173 | 'rcfile=s separate_in|si=s separate_out|so=s ' | |
179 | 'separate_out2|so2=s xmode=s wildcards_case_sensitive! ' |
|
174 | 'separate_out2|so2=s xmode=s wildcards_case_sensitive! ' | |
180 | 'magic_docstrings system_verbose! ' |
|
175 | 'magic_docstrings system_verbose! ' | |
181 | 'multi_line_specials! ' |
|
176 | 'multi_line_specials! ' | |
182 | 'term_title! wxversion=s ' |
|
177 | 'term_title! wxversion=s ' | |
183 | 'autoedit_syntax!') |
|
178 | 'autoedit_syntax!') | |
184 |
|
179 | |||
185 | # Options that can *only* appear at the cmd line (not in rcfiles). |
|
180 | # Options that can *only* appear at the cmd line (not in rcfiles). | |
186 |
|
181 | |||
187 | cmdline_only = ('help interact|i ipythondir=s Version upgrade ' |
|
182 | cmdline_only = ('help interact|i ipythondir=s Version upgrade ' | |
188 | 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! ' |
|
183 | 'gthread! qthread! q4thread! wthread! tkthread! pylab! tk! ' | |
189 | # 'twisted!' # disabled for now. |
|
184 | # 'twisted!' # disabled for now. | |
190 | ) |
|
185 | ) | |
191 |
|
186 | |||
192 | # Build the actual name list to be used by DPyGetOpt |
|
187 | # Build the actual name list to be used by DPyGetOpt | |
193 | opts_names = qw(cmdline_opts) + qw(cmdline_only) |
|
188 | opts_names = qw(cmdline_opts) + qw(cmdline_only) | |
194 |
|
189 | |||
195 | # Set sensible command line defaults. |
|
190 | # Set sensible command line defaults. | |
196 | # This should have everything from cmdline_opts and cmdline_only |
|
191 | # This should have everything from cmdline_opts and cmdline_only | |
197 | opts_def = Struct(autocall = 1, |
|
192 | opts_def = Struct(autocall = 1, | |
198 | autoedit_syntax = 0, |
|
193 | autoedit_syntax = 0, | |
199 | autoindent = 0, |
|
194 | autoindent = 0, | |
200 | automagic = 1, |
|
195 | automagic = 1, | |
201 | autoexec = [], |
|
196 | autoexec = [], | |
202 | banner = 1, |
|
197 | banner = 1, | |
203 | c = '', |
|
198 | c = '', | |
204 | cache_size = 1000, |
|
199 | cache_size = 1000, | |
205 | classic = 0, |
|
200 | classic = 0, | |
206 | color_info = 0, |
|
201 | color_info = 0, | |
207 | colors = 'NoColor', |
|
202 | colors = 'NoColor', | |
208 | confirm_exit = 1, |
|
203 | confirm_exit = 1, | |
209 | debug = 0, |
|
204 | debug = 0, | |
210 | deep_reload = 0, |
|
205 | deep_reload = 0, | |
211 | editor = '0', |
|
206 | editor = '0', | |
212 | gthread = 0, |
|
207 | gthread = 0, | |
213 | help = 0, |
|
208 | help = 0, | |
214 | interact = 0, |
|
209 | interact = 0, | |
215 | ipythondir = ipythondir_def, |
|
210 | ipythondir = ipythondir_def, | |
216 | log = 0, |
|
211 | log = 0, | |
217 | logfile = '', |
|
212 | logfile = '', | |
218 | logplay = '', |
|
213 | logplay = '', | |
219 | messages = 1, |
|
214 | messages = 1, | |
220 | multi_line_specials = 1, |
|
215 | multi_line_specials = 1, | |
221 | nosep = 0, |
|
216 | nosep = 0, | |
222 | object_info_string_level = 0, |
|
217 | object_info_string_level = 0, | |
223 | pdb = 0, |
|
218 | pdb = 0, | |
224 | pprint = 0, |
|
219 | pprint = 0, | |
225 | profile = '', |
|
220 | profile = '', | |
226 | prompt_in1 = 'In [\\#]: ', |
|
221 | prompt_in1 = 'In [\\#]: ', | |
227 | prompt_in2 = ' .\\D.: ', |
|
222 | prompt_in2 = ' .\\D.: ', | |
228 | prompt_out = 'Out[\\#]: ', |
|
223 | prompt_out = 'Out[\\#]: ', | |
229 | prompts_pad_left = 1, |
|
224 | prompts_pad_left = 1, | |
230 | pydb = 0, |
|
225 | pydb = 0, | |
231 | pylab = 0, |
|
226 | pylab = 0, | |
232 | pylab_import_all = 1, |
|
227 | pylab_import_all = 1, | |
233 | q4thread = 0, |
|
228 | q4thread = 0, | |
234 | qthread = 0, |
|
229 | qthread = 0, | |
235 | quick = 0, |
|
230 | quick = 0, | |
236 | quiet = 0, |
|
231 | quiet = 0, | |
237 | rcfile = 'ipythonrc' + rc_suffix, |
|
232 | rcfile = 'ipythonrc' + rc_suffix, | |
238 | readline = 1, |
|
233 | readline = 1, | |
239 | readline_merge_completions = 1, |
|
234 | readline_merge_completions = 1, | |
240 | readline_omit__names = 0, |
|
235 | readline_omit__names = 0, | |
241 | screen_length = 0, |
|
236 | screen_length = 0, | |
242 | separate_in = '\n', |
|
237 | separate_in = '\n', | |
243 | separate_out = '\n', |
|
238 | separate_out = '\n', | |
244 | separate_out2 = '', |
|
239 | separate_out2 = '', | |
245 | system_header = 'IPython system call: ', |
|
240 | system_header = 'IPython system call: ', | |
246 | system_verbose = 0, |
|
241 | system_verbose = 0, | |
247 | term_title = 1, |
|
242 | term_title = 1, | |
248 | tk = 0, |
|
243 | tk = 0, | |
249 | #twisted= 0, # disabled for now |
|
244 | #twisted= 0, # disabled for now | |
250 | upgrade = 0, |
|
245 | upgrade = 0, | |
251 | Version = 0, |
|
246 | Version = 0, | |
252 | wildcards_case_sensitive = 1, |
|
247 | wildcards_case_sensitive = 1, | |
253 | wthread = 0, |
|
248 | wthread = 0, | |
254 | wxversion = '0', |
|
249 | wxversion = '0', | |
255 | xmode = 'Context', |
|
250 | xmode = 'Context', | |
256 | magic_docstrings = 0, # undocumented, for doc generation |
|
251 | magic_docstrings = 0, # undocumented, for doc generation | |
257 | ) |
|
252 | ) | |
258 |
|
253 | |||
259 | # Things that will *only* appear in rcfiles (not at the command line). |
|
254 | # Things that will *only* appear in rcfiles (not at the command line). | |
260 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
255 | # Make sure there's a space before each end of line (they get auto-joined!) | |
261 | rcfile_opts = { qwflat: 'include import_mod import_all execfile ', |
|
256 | rcfile_opts = { qwflat: 'include import_mod import_all execfile ', | |
262 | qw_lol: 'import_some ', |
|
257 | qw_lol: 'import_some ', | |
263 | # for things with embedded whitespace: |
|
258 | # for things with embedded whitespace: | |
264 | list_strings:'execute alias readline_parse_and_bind ', |
|
259 | list_strings:'execute alias readline_parse_and_bind ', | |
265 | # Regular strings need no conversion: |
|
260 | # Regular strings need no conversion: | |
266 | None:'readline_remove_delims ', |
|
261 | None:'readline_remove_delims ', | |
267 | } |
|
262 | } | |
268 | # Default values for these |
|
263 | # Default values for these | |
269 | rc_def = Struct(include = [], |
|
264 | rc_def = Struct(include = [], | |
270 | import_mod = [], |
|
265 | import_mod = [], | |
271 | import_all = [], |
|
266 | import_all = [], | |
272 | import_some = [[]], |
|
267 | import_some = [[]], | |
273 | execute = [], |
|
268 | execute = [], | |
274 | execfile = [], |
|
269 | execfile = [], | |
275 | alias = [], |
|
270 | alias = [], | |
276 | readline_parse_and_bind = [], |
|
271 | readline_parse_and_bind = [], | |
277 | readline_remove_delims = '', |
|
272 | readline_remove_delims = '', | |
278 | ) |
|
273 | ) | |
279 |
|
274 | |||
280 | # Build the type conversion dictionary from the above tables: |
|
275 | # Build the type conversion dictionary from the above tables: | |
281 | typeconv = rcfile_opts.copy() |
|
276 | typeconv = rcfile_opts.copy() | |
282 | typeconv.update(optstr2types(cmdline_opts)) |
|
277 | typeconv.update(optstr2types(cmdline_opts)) | |
283 |
|
278 | |||
284 | # FIXME: the None key appears in both, put that back together by hand. Ugly! |
|
279 | # FIXME: the None key appears in both, put that back together by hand. Ugly! | |
285 | typeconv[None] += ' ' + rcfile_opts[None] |
|
280 | typeconv[None] += ' ' + rcfile_opts[None] | |
286 |
|
281 | |||
287 | # Remove quotes at ends of all strings (used to protect spaces) |
|
282 | # Remove quotes at ends of all strings (used to protect spaces) | |
288 | typeconv[unquote_ends] = typeconv[None] |
|
283 | typeconv[unquote_ends] = typeconv[None] | |
289 | del typeconv[None] |
|
284 | del typeconv[None] | |
290 |
|
285 | |||
291 | # Build the list we'll use to make all config decisions with defaults: |
|
286 | # Build the list we'll use to make all config decisions with defaults: | |
292 | opts_all = opts_def.copy() |
|
287 | opts_all = opts_def.copy() | |
293 | opts_all.update(rc_def) |
|
288 | opts_all.update(rc_def) | |
294 |
|
289 | |||
295 | # Build conflict resolver for recursive loading of config files: |
|
290 | # Build conflict resolver for recursive loading of config files: | |
296 | # - preserve means the outermost file maintains the value, it is not |
|
291 | # - preserve means the outermost file maintains the value, it is not | |
297 | # overwritten if an included file has the same key. |
|
292 | # overwritten if an included file has the same key. | |
298 | # - add_flip applies + to the two values, so it better make sense to add |
|
293 | # - add_flip applies + to the two values, so it better make sense to add | |
299 | # those types of keys. But it flips them first so that things loaded |
|
294 | # those types of keys. But it flips them first so that things loaded | |
300 | # deeper in the inclusion chain have lower precedence. |
|
295 | # deeper in the inclusion chain have lower precedence. | |
301 | conflict = {'preserve': ' '.join([ typeconv[int], |
|
296 | conflict = {'preserve': ' '.join([ typeconv[int], | |
302 | typeconv[unquote_ends] ]), |
|
297 | typeconv[unquote_ends] ]), | |
303 | 'add_flip': ' '.join([ typeconv[qwflat], |
|
298 | 'add_flip': ' '.join([ typeconv[qwflat], | |
304 | typeconv[qw_lol], |
|
299 | typeconv[qw_lol], | |
305 | typeconv[list_strings] ]) |
|
300 | typeconv[list_strings] ]) | |
306 | } |
|
301 | } | |
307 |
|
302 | |||
308 | # Now actually process the command line |
|
303 | # Now actually process the command line | |
309 | getopt = DPyGetOpt.DPyGetOpt() |
|
304 | getopt = DPyGetOpt.DPyGetOpt() | |
310 | getopt.setIgnoreCase(0) |
|
305 | getopt.setIgnoreCase(0) | |
311 |
|
306 | |||
312 | getopt.parseConfiguration(opts_names) |
|
307 | getopt.parseConfiguration(opts_names) | |
313 |
|
308 | |||
314 | try: |
|
309 | try: | |
315 | getopt.processArguments(argv) |
|
310 | getopt.processArguments(argv) | |
316 | except DPyGetOpt.ArgumentError, exc: |
|
311 | except DPyGetOpt.ArgumentError, exc: | |
317 | print cmd_line_usage |
|
312 | print cmd_line_usage | |
318 | warn('\nError in Arguments: "%s"' % exc) |
|
313 | warn('\nError in Arguments: "%s"' % exc) | |
319 | sys.exit(1) |
|
314 | sys.exit(1) | |
320 |
|
315 | |||
321 | # convert the options dict to a struct for much lighter syntax later |
|
316 | # convert the options dict to a struct for much lighter syntax later | |
322 | opts = Struct(getopt.optionValues) |
|
317 | opts = Struct(getopt.optionValues) | |
323 | args = getopt.freeValues |
|
318 | args = getopt.freeValues | |
324 |
|
319 | |||
325 | # this is the struct (which has default values at this point) with which |
|
320 | # this is the struct (which has default values at this point) with which | |
326 | # we make all decisions: |
|
321 | # we make all decisions: | |
327 | opts_all.update(opts) |
|
322 | opts_all.update(opts) | |
328 |
|
323 | |||
329 | # Options that force an immediate exit |
|
324 | # Options that force an immediate exit | |
330 | if opts_all.help: |
|
325 | if opts_all.help: | |
331 | page(cmd_line_usage) |
|
326 | page(cmd_line_usage) | |
332 | sys.exit() |
|
327 | sys.exit() | |
333 |
|
328 | |||
334 | if opts_all.Version: |
|
329 | if opts_all.Version: | |
335 | print __version__ |
|
330 | print __version__ | |
336 | sys.exit() |
|
331 | sys.exit() | |
337 |
|
332 | |||
338 | if opts_all.magic_docstrings: |
|
333 | if opts_all.magic_docstrings: | |
339 | IP.magic_magic('-latex') |
|
334 | IP.magic_magic('-latex') | |
340 | sys.exit() |
|
335 | sys.exit() | |
341 |
|
336 | |||
342 | # add personal ipythondir to sys.path so that users can put things in |
|
337 | # add personal ipythondir to sys.path so that users can put things in | |
343 | # there for customization |
|
338 | # there for customization | |
344 | sys.path.append(os.path.abspath(opts_all.ipythondir)) |
|
339 | sys.path.append(os.path.abspath(opts_all.ipythondir)) | |
345 |
|
340 | |||
346 | # Create user config directory if it doesn't exist. This must be done |
|
341 | # Create user config directory if it doesn't exist. This must be done | |
347 | # *after* getting the cmd line options. |
|
342 | # *after* getting the cmd line options. | |
348 | if not os.path.isdir(opts_all.ipythondir): |
|
343 | if not os.path.isdir(opts_all.ipythondir): | |
349 | IP.user_setup(opts_all.ipythondir,rc_suffix,'install') |
|
344 | IP.user_setup(opts_all.ipythondir,rc_suffix,'install') | |
350 |
|
345 | |||
351 | # upgrade user config files while preserving a copy of the originals |
|
346 | # upgrade user config files while preserving a copy of the originals | |
352 | if opts_all.upgrade: |
|
347 | if opts_all.upgrade: | |
353 | IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade') |
|
348 | IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade') | |
354 |
|
349 | |||
355 | # check mutually exclusive options in the *original* command line |
|
350 | # check mutually exclusive options in the *original* command line | |
356 | mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), |
|
351 | mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), | |
357 | qw('classic profile'),qw('classic rcfile')]) |
|
352 | qw('classic profile'),qw('classic rcfile')]) | |
358 |
|
353 | |||
359 | #--------------------------------------------------------------------------- |
|
354 | #--------------------------------------------------------------------------- | |
360 | # Log replay |
|
355 | # Log replay | |
361 |
|
356 | |||
362 | # if -logplay, we need to 'become' the other session. That basically means |
|
357 | # if -logplay, we need to 'become' the other session. That basically means | |
363 | # replacing the current command line environment with that of the old |
|
358 | # replacing the current command line environment with that of the old | |
364 | # session and moving on. |
|
359 | # session and moving on. | |
365 |
|
360 | |||
366 | # this is needed so that later we know we're in session reload mode, as |
|
361 | # this is needed so that later we know we're in session reload mode, as | |
367 | # opts_all will get overwritten: |
|
362 | # opts_all will get overwritten: | |
368 | load_logplay = 0 |
|
363 | load_logplay = 0 | |
369 |
|
364 | |||
370 | if opts_all.logplay: |
|
365 | if opts_all.logplay: | |
371 | load_logplay = opts_all.logplay |
|
366 | load_logplay = opts_all.logplay | |
372 | opts_debug_save = opts_all.debug |
|
367 | opts_debug_save = opts_all.debug | |
373 | try: |
|
368 | try: | |
374 | logplay = open(opts_all.logplay) |
|
369 | logplay = open(opts_all.logplay) | |
375 | except IOError: |
|
370 | except IOError: | |
376 | if opts_all.debug: IP.InteractiveTB() |
|
371 | if opts_all.debug: IP.InteractiveTB() | |
377 | warn('Could not open logplay file '+`opts_all.logplay`) |
|
372 | warn('Could not open logplay file '+`opts_all.logplay`) | |
378 | # restore state as if nothing had happened and move on, but make |
|
373 | # restore state as if nothing had happened and move on, but make | |
379 | # sure that later we don't try to actually load the session file |
|
374 | # sure that later we don't try to actually load the session file | |
380 | logplay = None |
|
375 | logplay = None | |
381 | load_logplay = 0 |
|
376 | load_logplay = 0 | |
382 | del opts_all.logplay |
|
377 | del opts_all.logplay | |
383 | else: |
|
378 | else: | |
384 | try: |
|
379 | try: | |
385 | logplay.readline() |
|
380 | logplay.readline() | |
386 | logplay.readline(); |
|
381 | logplay.readline(); | |
387 | # this reloads that session's command line |
|
382 | # this reloads that session's command line | |
388 | cmd = logplay.readline()[6:] |
|
383 | cmd = logplay.readline()[6:] | |
389 | exec cmd |
|
384 | exec cmd | |
390 | # restore the true debug flag given so that the process of |
|
385 | # restore the true debug flag given so that the process of | |
391 | # session loading itself can be monitored. |
|
386 | # session loading itself can be monitored. | |
392 | opts.debug = opts_debug_save |
|
387 | opts.debug = opts_debug_save | |
393 | # save the logplay flag so later we don't overwrite the log |
|
388 | # save the logplay flag so later we don't overwrite the log | |
394 | opts.logplay = load_logplay |
|
389 | opts.logplay = load_logplay | |
395 | # now we must update our own structure with defaults |
|
390 | # now we must update our own structure with defaults | |
396 | opts_all.update(opts) |
|
391 | opts_all.update(opts) | |
397 | # now load args |
|
392 | # now load args | |
398 | cmd = logplay.readline()[6:] |
|
393 | cmd = logplay.readline()[6:] | |
399 | exec cmd |
|
394 | exec cmd | |
400 | logplay.close() |
|
395 | logplay.close() | |
401 | except: |
|
396 | except: | |
402 | logplay.close() |
|
397 | logplay.close() | |
403 | if opts_all.debug: IP.InteractiveTB() |
|
398 | if opts_all.debug: IP.InteractiveTB() | |
404 | warn("Logplay file lacking full configuration information.\n" |
|
399 | warn("Logplay file lacking full configuration information.\n" | |
405 | "I'll try to read it, but some things may not work.") |
|
400 | "I'll try to read it, but some things may not work.") | |
406 |
|
401 | |||
407 | #------------------------------------------------------------------------- |
|
402 | #------------------------------------------------------------------------- | |
408 | # set up output traps: catch all output from files, being run, modules |
|
403 | # set up output traps: catch all output from files, being run, modules | |
409 | # loaded, etc. Then give it to the user in a clean form at the end. |
|
404 | # loaded, etc. Then give it to the user in a clean form at the end. | |
410 |
|
405 | |||
411 | msg_out = 'Output messages. ' |
|
406 | msg_out = 'Output messages. ' | |
412 | msg_err = 'Error messages. ' |
|
407 | msg_err = 'Error messages. ' | |
413 | msg_sep = '\n' |
|
408 | msg_sep = '\n' | |
414 | msg = Struct(config = OutputTrap('Configuration Loader',msg_out, |
|
409 | msg = Struct(config = OutputTrap('Configuration Loader',msg_out, | |
415 | msg_err,msg_sep,debug, |
|
410 | msg_err,msg_sep,debug, | |
416 | quiet_out=1), |
|
411 | quiet_out=1), | |
417 | user_exec = OutputTrap('User File Execution',msg_out, |
|
412 | user_exec = OutputTrap('User File Execution',msg_out, | |
418 | msg_err,msg_sep,debug), |
|
413 | msg_err,msg_sep,debug), | |
419 | logplay = OutputTrap('Log Loader',msg_out, |
|
414 | logplay = OutputTrap('Log Loader',msg_out, | |
420 | msg_err,msg_sep,debug), |
|
415 | msg_err,msg_sep,debug), | |
421 | summary = '' |
|
416 | summary = '' | |
422 | ) |
|
417 | ) | |
423 |
|
418 | |||
424 | #------------------------------------------------------------------------- |
|
419 | #------------------------------------------------------------------------- | |
425 | # Process user ipythonrc-type configuration files |
|
420 | # Process user ipythonrc-type configuration files | |
426 |
|
421 | |||
427 | # turn on output trapping and log to msg.config |
|
422 | # turn on output trapping and log to msg.config | |
428 | # remember that with debug on, trapping is actually disabled |
|
423 | # remember that with debug on, trapping is actually disabled | |
429 | msg.config.trap_all() |
|
424 | msg.config.trap_all() | |
430 |
|
425 | |||
431 | # look for rcfile in current or default directory |
|
426 | # look for rcfile in current or default directory | |
432 | try: |
|
427 | try: | |
433 | opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) |
|
428 | opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) | |
434 | except IOError: |
|
429 | except IOError: | |
435 | if opts_all.debug: IP.InteractiveTB() |
|
430 | if opts_all.debug: IP.InteractiveTB() | |
436 | warn('Configuration file %s not found. Ignoring request.' |
|
431 | warn('Configuration file %s not found. Ignoring request.' | |
437 | % (opts_all.rcfile) ) |
|
432 | % (opts_all.rcfile) ) | |
438 |
|
433 | |||
439 | # 'profiles' are a shorthand notation for config filenames |
|
434 | # 'profiles' are a shorthand notation for config filenames | |
440 | profile_handled_by_legacy = False |
|
435 | profile_handled_by_legacy = False | |
441 | if opts_all.profile: |
|
436 | if opts_all.profile: | |
442 |
|
437 | |||
443 | try: |
|
438 | try: | |
444 | opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile |
|
439 | opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile | |
445 | + rc_suffix, |
|
440 | + rc_suffix, | |
446 | opts_all.ipythondir) |
|
441 | opts_all.ipythondir) | |
447 | profile_handled_by_legacy = True |
|
442 | profile_handled_by_legacy = True | |
448 | except IOError: |
|
443 | except IOError: | |
449 | if opts_all.debug: IP.InteractiveTB() |
|
444 | if opts_all.debug: IP.InteractiveTB() | |
450 | opts.profile = '' # remove profile from options if invalid |
|
445 | opts.profile = '' # remove profile from options if invalid | |
451 | # We won't warn anymore, primary method is ipy_profile_PROFNAME |
|
446 | # We won't warn anymore, primary method is ipy_profile_PROFNAME | |
452 | # which does trigger a warning. |
|
447 | # which does trigger a warning. | |
453 |
|
448 | |||
454 | # load the config file |
|
449 | # load the config file | |
455 | rcfiledata = None |
|
450 | rcfiledata = None | |
456 | if opts_all.quick: |
|
451 | if opts_all.quick: | |
457 | print 'Launching IPython in quick mode. No config file read.' |
|
452 | print 'Launching IPython in quick mode. No config file read.' | |
458 | elif opts_all.rcfile: |
|
453 | elif opts_all.rcfile: | |
459 | try: |
|
454 | try: | |
460 | cfg_loader = ConfigLoader(conflict) |
|
455 | cfg_loader = ConfigLoader(conflict) | |
461 | rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, |
|
456 | rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, | |
462 | 'include',opts_all.ipythondir, |
|
457 | 'include',opts_all.ipythondir, | |
463 | purge = 1, |
|
458 | purge = 1, | |
464 | unique = conflict['preserve']) |
|
459 | unique = conflict['preserve']) | |
465 | except: |
|
460 | except: | |
466 | IP.InteractiveTB() |
|
461 | IP.InteractiveTB() | |
467 | warn('Problems loading configuration file '+ |
|
462 | warn('Problems loading configuration file '+ | |
468 | `opts_all.rcfile`+ |
|
463 | `opts_all.rcfile`+ | |
469 | '\nStarting with default -bare bones- configuration.') |
|
464 | '\nStarting with default -bare bones- configuration.') | |
470 | else: |
|
465 | else: | |
471 | warn('No valid configuration file found in either currrent directory\n'+ |
|
466 | warn('No valid configuration file found in either currrent directory\n'+ | |
472 | 'or in the IPython config. directory: '+`opts_all.ipythondir`+ |
|
467 | 'or in the IPython config. directory: '+`opts_all.ipythondir`+ | |
473 | '\nProceeding with internal defaults.') |
|
468 | '\nProceeding with internal defaults.') | |
474 |
|
469 | |||
475 | #------------------------------------------------------------------------ |
|
470 | #------------------------------------------------------------------------ | |
476 | # Set exception handlers in mode requested by user. |
|
471 | # Set exception handlers in mode requested by user. | |
477 | otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode |
|
472 | otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode | |
478 | IP.magic_xmode(opts_all.xmode) |
|
473 | IP.magic_xmode(opts_all.xmode) | |
479 | otrap.release_out() |
|
474 | otrap.release_out() | |
480 |
|
475 | |||
481 | #------------------------------------------------------------------------ |
|
476 | #------------------------------------------------------------------------ | |
482 | # Execute user config |
|
477 | # Execute user config | |
483 |
|
478 | |||
484 | # Create a valid config structure with the right precedence order: |
|
479 | # Create a valid config structure with the right precedence order: | |
485 | # defaults < rcfile < command line. This needs to be in the instance, so |
|
480 | # defaults < rcfile < command line. This needs to be in the instance, so | |
486 | # that method calls below that rely on it find it. |
|
481 | # that method calls below that rely on it find it. | |
487 | IP.rc = rc_def.copy() |
|
482 | IP.rc = rc_def.copy() | |
488 |
|
483 | |||
489 | # Work with a local alias inside this routine to avoid unnecessary |
|
484 | # Work with a local alias inside this routine to avoid unnecessary | |
490 | # attribute lookups. |
|
485 | # attribute lookups. | |
491 | IP_rc = IP.rc |
|
486 | IP_rc = IP.rc | |
492 |
|
487 | |||
493 | IP_rc.update(opts_def) |
|
488 | IP_rc.update(opts_def) | |
494 | if rcfiledata: |
|
489 | if rcfiledata: | |
495 | # now we can update |
|
490 | # now we can update | |
496 | IP_rc.update(rcfiledata) |
|
491 | IP_rc.update(rcfiledata) | |
497 | IP_rc.update(opts) |
|
492 | IP_rc.update(opts) | |
498 | IP_rc.update(rc_override) |
|
493 | IP_rc.update(rc_override) | |
499 |
|
494 | |||
500 | # Store the original cmd line for reference: |
|
495 | # Store the original cmd line for reference: | |
501 | IP_rc.opts = opts |
|
496 | IP_rc.opts = opts | |
502 | IP_rc.args = args |
|
497 | IP_rc.args = args | |
503 |
|
498 | |||
504 | # create a *runtime* Struct like rc for holding parameters which may be |
|
499 | # create a *runtime* Struct like rc for holding parameters which may be | |
505 | # created and/or modified by runtime user extensions. |
|
500 | # created and/or modified by runtime user extensions. | |
506 | IP.runtime_rc = Struct() |
|
501 | IP.runtime_rc = Struct() | |
507 |
|
502 | |||
508 | # from this point on, all config should be handled through IP_rc, |
|
503 | # from this point on, all config should be handled through IP_rc, | |
509 | # opts* shouldn't be used anymore. |
|
504 | # opts* shouldn't be used anymore. | |
510 |
|
505 | |||
511 |
|
506 | |||
512 | # update IP_rc with some special things that need manual |
|
507 | # update IP_rc with some special things that need manual | |
513 | # tweaks. Basically options which affect other options. I guess this |
|
508 | # tweaks. Basically options which affect other options. I guess this | |
514 | # should just be written so that options are fully orthogonal and we |
|
509 | # should just be written so that options are fully orthogonal and we | |
515 | # wouldn't worry about this stuff! |
|
510 | # wouldn't worry about this stuff! | |
516 |
|
511 | |||
517 | if IP_rc.classic: |
|
512 | if IP_rc.classic: | |
518 | IP_rc.quick = 1 |
|
513 | IP_rc.quick = 1 | |
519 | IP_rc.cache_size = 0 |
|
514 | IP_rc.cache_size = 0 | |
520 | IP_rc.pprint = 0 |
|
515 | IP_rc.pprint = 0 | |
521 | IP_rc.prompt_in1 = '>>> ' |
|
516 | IP_rc.prompt_in1 = '>>> ' | |
522 | IP_rc.prompt_in2 = '... ' |
|
517 | IP_rc.prompt_in2 = '... ' | |
523 | IP_rc.prompt_out = '' |
|
518 | IP_rc.prompt_out = '' | |
524 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
519 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' | |
525 | IP_rc.colors = 'NoColor' |
|
520 | IP_rc.colors = 'NoColor' | |
526 | IP_rc.xmode = 'Plain' |
|
521 | IP_rc.xmode = 'Plain' | |
527 |
|
522 | |||
528 | IP.pre_config_initialization() |
|
523 | IP.pre_config_initialization() | |
529 | # configure readline |
|
524 | # configure readline | |
530 |
|
525 | |||
531 | # update exception handlers with rc file status |
|
526 | # update exception handlers with rc file status | |
532 | otrap.trap_out() # I don't want these messages ever. |
|
527 | otrap.trap_out() # I don't want these messages ever. | |
533 | IP.magic_xmode(IP_rc.xmode) |
|
528 | IP.magic_xmode(IP_rc.xmode) | |
534 | otrap.release_out() |
|
529 | otrap.release_out() | |
535 |
|
530 | |||
536 | # activate logging if requested and not reloading a log |
|
531 | # activate logging if requested and not reloading a log | |
537 | if IP_rc.logplay: |
|
532 | if IP_rc.logplay: | |
538 | IP.magic_logstart(IP_rc.logplay + ' append') |
|
533 | IP.magic_logstart(IP_rc.logplay + ' append') | |
539 | elif IP_rc.logfile: |
|
534 | elif IP_rc.logfile: | |
540 | IP.magic_logstart(IP_rc.logfile) |
|
535 | IP.magic_logstart(IP_rc.logfile) | |
541 | elif IP_rc.log: |
|
536 | elif IP_rc.log: | |
542 | IP.magic_logstart() |
|
537 | IP.magic_logstart() | |
543 |
|
538 | |||
544 | # find user editor so that it we don't have to look it up constantly |
|
539 | # find user editor so that it we don't have to look it up constantly | |
545 | if IP_rc.editor.strip()=='0': |
|
540 | if IP_rc.editor.strip()=='0': | |
546 | try: |
|
541 | try: | |
547 | ed = os.environ['EDITOR'] |
|
542 | ed = os.environ['EDITOR'] | |
548 | except KeyError: |
|
543 | except KeyError: | |
549 | if os.name == 'posix': |
|
544 | if os.name == 'posix': | |
550 | ed = 'vi' # the only one guaranteed to be there! |
|
545 | ed = 'vi' # the only one guaranteed to be there! | |
551 | else: |
|
546 | else: | |
552 | ed = 'notepad' # same in Windows! |
|
547 | ed = 'notepad' # same in Windows! | |
553 | IP_rc.editor = ed |
|
548 | IP_rc.editor = ed | |
554 |
|
549 | |||
555 | # Keep track of whether this is an embedded instance or not (useful for |
|
550 | # Keep track of whether this is an embedded instance or not (useful for | |
556 | # post-mortems). |
|
551 | # post-mortems). | |
557 | IP_rc.embedded = IP.embedded |
|
552 | IP_rc.embedded = IP.embedded | |
558 |
|
553 | |||
559 | # Recursive reload |
|
554 | # Recursive reload | |
560 | try: |
|
555 | try: | |
561 | from IPython import deep_reload |
|
556 | from IPython import deep_reload | |
562 | if IP_rc.deep_reload: |
|
557 | if IP_rc.deep_reload: | |
563 | __builtin__.reload = deep_reload.reload |
|
558 | __builtin__.reload = deep_reload.reload | |
564 | else: |
|
559 | else: | |
565 | __builtin__.dreload = deep_reload.reload |
|
560 | __builtin__.dreload = deep_reload.reload | |
566 | del deep_reload |
|
561 | del deep_reload | |
567 | except ImportError: |
|
562 | except ImportError: | |
568 | pass |
|
563 | pass | |
569 |
|
564 | |||
570 | # Save the current state of our namespace so that the interactive shell |
|
565 | # Save the current state of our namespace so that the interactive shell | |
571 | # can later know which variables have been created by us from config files |
|
566 | # can later know which variables have been created by us from config files | |
572 | # and loading. This way, loading a file (in any way) is treated just like |
|
567 | # and loading. This way, loading a file (in any way) is treated just like | |
573 | # defining things on the command line, and %who works as expected. |
|
568 | # defining things on the command line, and %who works as expected. | |
574 |
|
569 | |||
575 | # DON'T do anything that affects the namespace beyond this point! |
|
570 | # DON'T do anything that affects the namespace beyond this point! | |
576 | IP.internal_ns.update(__main__.__dict__) |
|
571 | IP.internal_ns.update(__main__.__dict__) | |
577 |
|
572 | |||
578 | #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who |
|
573 | #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who | |
579 |
|
574 | |||
580 | # Now run through the different sections of the users's config |
|
575 | # Now run through the different sections of the users's config | |
581 | if IP_rc.debug: |
|
576 | if IP_rc.debug: | |
582 | print 'Trying to execute the following configuration structure:' |
|
577 | print 'Trying to execute the following configuration structure:' | |
583 | print '(Things listed first are deeper in the inclusion tree and get' |
|
578 | print '(Things listed first are deeper in the inclusion tree and get' | |
584 | print 'loaded first).\n' |
|
579 | print 'loaded first).\n' | |
585 | pprint(IP_rc.__dict__) |
|
580 | pprint(IP_rc.__dict__) | |
586 |
|
581 | |||
587 | for mod in IP_rc.import_mod: |
|
582 | for mod in IP_rc.import_mod: | |
588 | try: |
|
583 | try: | |
589 | exec 'import '+mod in IP.user_ns |
|
584 | exec 'import '+mod in IP.user_ns | |
590 | except : |
|
585 | except : | |
591 | IP.InteractiveTB() |
|
586 | IP.InteractiveTB() | |
592 | import_fail_info(mod) |
|
587 | import_fail_info(mod) | |
593 |
|
588 | |||
594 | for mod_fn in IP_rc.import_some: |
|
589 | for mod_fn in IP_rc.import_some: | |
595 | if not mod_fn == []: |
|
590 | if not mod_fn == []: | |
596 | mod,fn = mod_fn[0],','.join(mod_fn[1:]) |
|
591 | mod,fn = mod_fn[0],','.join(mod_fn[1:]) | |
597 | try: |
|
592 | try: | |
598 | exec 'from '+mod+' import '+fn in IP.user_ns |
|
593 | exec 'from '+mod+' import '+fn in IP.user_ns | |
599 | except : |
|
594 | except : | |
600 | IP.InteractiveTB() |
|
595 | IP.InteractiveTB() | |
601 | import_fail_info(mod,fn) |
|
596 | import_fail_info(mod,fn) | |
602 |
|
597 | |||
603 | for mod in IP_rc.import_all: |
|
598 | for mod in IP_rc.import_all: | |
604 | try: |
|
599 | try: | |
605 | exec 'from '+mod+' import *' in IP.user_ns |
|
600 | exec 'from '+mod+' import *' in IP.user_ns | |
606 | except : |
|
601 | except : | |
607 | IP.InteractiveTB() |
|
602 | IP.InteractiveTB() | |
608 | import_fail_info(mod) |
|
603 | import_fail_info(mod) | |
609 |
|
604 | |||
610 | for code in IP_rc.execute: |
|
605 | for code in IP_rc.execute: | |
611 | try: |
|
606 | try: | |
612 | exec code in IP.user_ns |
|
607 | exec code in IP.user_ns | |
613 | except: |
|
608 | except: | |
614 | IP.InteractiveTB() |
|
609 | IP.InteractiveTB() | |
615 | warn('Failure executing code: ' + `code`) |
|
610 | warn('Failure executing code: ' + `code`) | |
616 |
|
611 | |||
617 | # Execute the files the user wants in ipythonrc |
|
612 | # Execute the files the user wants in ipythonrc | |
618 | for file in IP_rc.execfile: |
|
613 | for file in IP_rc.execfile: | |
619 | try: |
|
614 | try: | |
620 | file = filefind(file,sys.path+[IPython_dir]) |
|
615 | file = filefind(file,sys.path+[IPython_dir]) | |
621 | except IOError: |
|
616 | except IOError: | |
622 | warn(itpl('File $file not found. Skipping it.')) |
|
617 | warn(itpl('File $file not found. Skipping it.')) | |
623 | else: |
|
618 | else: | |
624 | IP.safe_execfile(os.path.expanduser(file),IP.user_ns) |
|
619 | IP.safe_execfile(os.path.expanduser(file),IP.user_ns) | |
625 |
|
620 | |||
626 | # finally, try importing ipy_*_conf for final configuration |
|
621 | # finally, try importing ipy_*_conf for final configuration | |
627 | try: |
|
622 | try: | |
628 | import ipy_system_conf |
|
623 | import ipy_system_conf | |
629 | except ImportError: |
|
624 | except ImportError: | |
630 | if opts_all.debug: IP.InteractiveTB() |
|
625 | if opts_all.debug: IP.InteractiveTB() | |
631 | warn("Could not import 'ipy_system_conf'") |
|
626 | warn("Could not import 'ipy_system_conf'") | |
632 | except: |
|
627 | except: | |
633 | IP.InteractiveTB() |
|
628 | IP.InteractiveTB() | |
634 | import_fail_info('ipy_system_conf') |
|
629 | import_fail_info('ipy_system_conf') | |
635 |
|
630 | |||
636 | # only import prof module if ipythonrc-PROF was not found |
|
631 | # only import prof module if ipythonrc-PROF was not found | |
637 | if opts_all.profile and not profile_handled_by_legacy: |
|
632 | if opts_all.profile and not profile_handled_by_legacy: | |
638 | profmodname = 'ipy_profile_' + opts_all.profile |
|
633 | profmodname = 'ipy_profile_' + opts_all.profile | |
639 | try: |
|
634 | try: | |
640 |
|
635 | |||
641 | force_import(profmodname) |
|
636 | force_import(profmodname) | |
642 | except: |
|
637 | except: | |
643 | IP.InteractiveTB() |
|
638 | IP.InteractiveTB() | |
644 | print "Error importing",profmodname,"- perhaps you should run %upgrade?" |
|
639 | print "Error importing",profmodname,"- perhaps you should run %upgrade?" | |
645 | import_fail_info(profmodname) |
|
640 | import_fail_info(profmodname) | |
646 | else: |
|
641 | else: | |
647 | opts.profile = opts_all.profile |
|
642 | opts.profile = opts_all.profile | |
648 | else: |
|
643 | else: | |
649 | force_import('ipy_profile_none') |
|
644 | force_import('ipy_profile_none') | |
650 | try: |
|
645 | try: | |
651 |
|
646 | |||
652 | force_import('ipy_user_conf') |
|
647 | force_import('ipy_user_conf') | |
653 |
|
648 | |||
654 | except: |
|
649 | except: | |
655 | conf = opts_all.ipythondir + "/ipy_user_conf.py" |
|
650 | conf = opts_all.ipythondir + "/ipy_user_conf.py" | |
656 | IP.InteractiveTB() |
|
651 | IP.InteractiveTB() | |
657 | if not os.path.isfile(conf): |
|
652 | if not os.path.isfile(conf): | |
658 | warn(conf + ' does not exist, please run %upgrade!') |
|
653 | warn(conf + ' does not exist, please run %upgrade!') | |
659 |
|
654 | |||
660 | import_fail_info("ipy_user_conf") |
|
655 | import_fail_info("ipy_user_conf") | |
661 |
|
656 | |||
662 | # Define the history file for saving commands in between sessions |
|
657 | # Define the history file for saving commands in between sessions | |
663 | try: |
|
658 | try: | |
664 | histfname = 'history-%s' % opts.profile |
|
659 | histfname = 'history-%s' % opts.profile | |
665 | except AttributeError: |
|
660 | except AttributeError: | |
666 | histfname = 'history' |
|
661 | histfname = 'history' | |
667 | IP.histfile = os.path.join(opts_all.ipythondir,histfname) |
|
662 | IP.histfile = os.path.join(opts_all.ipythondir,histfname) | |
668 |
|
663 | |||
669 | # finally, push the argv to options again to ensure highest priority |
|
664 | # finally, push the argv to options again to ensure highest priority | |
670 | IP_rc.update(opts) |
|
665 | IP_rc.update(opts) | |
671 |
|
666 | |||
672 | # release stdout and stderr and save config log into a global summary |
|
667 | # release stdout and stderr and save config log into a global summary | |
673 | msg.config.release_all() |
|
668 | msg.config.release_all() | |
674 | if IP_rc.messages: |
|
669 | if IP_rc.messages: | |
675 | msg.summary += msg.config.summary_all() |
|
670 | msg.summary += msg.config.summary_all() | |
676 |
|
671 | |||
677 | #------------------------------------------------------------------------ |
|
672 | #------------------------------------------------------------------------ | |
678 | # Setup interactive session |
|
673 | # Setup interactive session | |
679 |
|
674 | |||
680 | # Now we should be fully configured. We can then execute files or load |
|
675 | # Now we should be fully configured. We can then execute files or load | |
681 | # things only needed for interactive use. Then we'll open the shell. |
|
676 | # things only needed for interactive use. Then we'll open the shell. | |
682 |
|
677 | |||
683 | # Take a snapshot of the user namespace before opening the shell. That way |
|
678 | # Take a snapshot of the user namespace before opening the shell. That way | |
684 | # we'll be able to identify which things were interactively defined and |
|
679 | # we'll be able to identify which things were interactively defined and | |
685 | # which were defined through config files. |
|
680 | # which were defined through config files. | |
686 | IP.user_config_ns.update(IP.user_ns) |
|
681 | IP.user_config_ns.update(IP.user_ns) | |
687 |
|
682 | |||
688 | # Force reading a file as if it were a session log. Slower but safer. |
|
683 | # Force reading a file as if it were a session log. Slower but safer. | |
689 | if load_logplay: |
|
684 | if load_logplay: | |
690 | print 'Replaying log...' |
|
685 | print 'Replaying log...' | |
691 | try: |
|
686 | try: | |
692 | if IP_rc.debug: |
|
687 | if IP_rc.debug: | |
693 | logplay_quiet = 0 |
|
688 | logplay_quiet = 0 | |
694 | else: |
|
689 | else: | |
695 | logplay_quiet = 1 |
|
690 | logplay_quiet = 1 | |
696 |
|
691 | |||
697 | msg.logplay.trap_all() |
|
692 | msg.logplay.trap_all() | |
698 | IP.safe_execfile(load_logplay,IP.user_ns, |
|
693 | IP.safe_execfile(load_logplay,IP.user_ns, | |
699 | islog = 1, quiet = logplay_quiet) |
|
694 | islog = 1, quiet = logplay_quiet) | |
700 | msg.logplay.release_all() |
|
695 | msg.logplay.release_all() | |
701 | if IP_rc.messages: |
|
696 | if IP_rc.messages: | |
702 | msg.summary += msg.logplay.summary_all() |
|
697 | msg.summary += msg.logplay.summary_all() | |
703 | except: |
|
698 | except: | |
704 | warn('Problems replaying logfile %s.' % load_logplay) |
|
699 | warn('Problems replaying logfile %s.' % load_logplay) | |
705 | IP.InteractiveTB() |
|
700 | IP.InteractiveTB() | |
706 |
|
701 | |||
707 | # Load remaining files in command line |
|
702 | # Load remaining files in command line | |
708 | msg.user_exec.trap_all() |
|
703 | msg.user_exec.trap_all() | |
709 |
|
704 | |||
710 | # Do NOT execute files named in the command line as scripts to be loaded |
|
705 | # Do NOT execute files named in the command line as scripts to be loaded | |
711 | # by embedded instances. Doing so has the potential for an infinite |
|
706 | # by embedded instances. Doing so has the potential for an infinite | |
712 | # recursion if there are exceptions thrown in the process. |
|
707 | # recursion if there are exceptions thrown in the process. | |
713 |
|
708 | |||
714 | # XXX FIXME: the execution of user files should be moved out to after |
|
709 | # XXX FIXME: the execution of user files should be moved out to after | |
715 | # ipython is fully initialized, just as if they were run via %run at the |
|
710 | # ipython is fully initialized, just as if they were run via %run at the | |
716 | # ipython prompt. This would also give them the benefit of ipython's |
|
711 | # ipython prompt. This would also give them the benefit of ipython's | |
717 | # nice tracebacks. |
|
712 | # nice tracebacks. | |
718 |
|
713 | |||
719 | if (not embedded and IP_rc.args and |
|
714 | if (not embedded and IP_rc.args and | |
720 | not IP_rc.args[0].lower().endswith('.ipy')): |
|
715 | not IP_rc.args[0].lower().endswith('.ipy')): | |
721 | name_save = IP.user_ns['__name__'] |
|
716 | name_save = IP.user_ns['__name__'] | |
722 | IP.user_ns['__name__'] = '__main__' |
|
717 | IP.user_ns['__name__'] = '__main__' | |
723 | # Set our own excepthook in case the user code tries to call it |
|
718 | # Set our own excepthook in case the user code tries to call it | |
724 | # directly. This prevents triggering the IPython crash handler. |
|
719 | # directly. This prevents triggering the IPython crash handler. | |
725 | old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook |
|
720 | old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook | |
726 |
|
721 | |||
727 | save_argv = sys.argv[1:] # save it for later restoring |
|
722 | save_argv = sys.argv[1:] # save it for later restoring | |
728 |
|
723 | |||
729 | sys.argv = args |
|
724 | sys.argv = args | |
730 |
|
725 | |||
731 | try: |
|
726 | try: | |
732 | IP.safe_execfile(args[0], IP.user_ns) |
|
727 | IP.safe_execfile(args[0], IP.user_ns) | |
733 | finally: |
|
728 | finally: | |
734 | # Reset our crash handler in place |
|
729 | # Reset our crash handler in place | |
735 | sys.excepthook = old_excepthook |
|
730 | sys.excepthook = old_excepthook | |
736 | sys.argv[:] = save_argv |
|
731 | sys.argv[:] = save_argv | |
737 | IP.user_ns['__name__'] = name_save |
|
732 | IP.user_ns['__name__'] = name_save | |
738 |
|
733 | |||
739 | msg.user_exec.release_all() |
|
734 | msg.user_exec.release_all() | |
740 |
|
735 | |||
741 | if IP_rc.messages: |
|
736 | if IP_rc.messages: | |
742 | msg.summary += msg.user_exec.summary_all() |
|
737 | msg.summary += msg.user_exec.summary_all() | |
743 |
|
738 | |||
744 | # since we can't specify a null string on the cmd line, 0 is the equivalent: |
|
739 | # since we can't specify a null string on the cmd line, 0 is the equivalent: | |
745 | if IP_rc.nosep: |
|
740 | if IP_rc.nosep: | |
746 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
741 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' | |
747 | if IP_rc.separate_in == '0': IP_rc.separate_in = '' |
|
742 | if IP_rc.separate_in == '0': IP_rc.separate_in = '' | |
748 | if IP_rc.separate_out == '0': IP_rc.separate_out = '' |
|
743 | if IP_rc.separate_out == '0': IP_rc.separate_out = '' | |
749 | if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = '' |
|
744 | if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = '' | |
750 | IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n') |
|
745 | IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n') | |
751 | IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n') |
|
746 | IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n') | |
752 | IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n') |
|
747 | IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n') | |
753 |
|
748 | |||
754 | # Determine how many lines at the bottom of the screen are needed for |
|
749 | # Determine how many lines at the bottom of the screen are needed for | |
755 | # showing prompts, so we can know wheter long strings are to be printed or |
|
750 | # showing prompts, so we can know wheter long strings are to be printed or | |
756 | # paged: |
|
751 | # paged: | |
757 | num_lines_bot = IP_rc.separate_in.count('\n')+1 |
|
752 | num_lines_bot = IP_rc.separate_in.count('\n')+1 | |
758 | IP_rc.screen_length = IP_rc.screen_length - num_lines_bot |
|
753 | IP_rc.screen_length = IP_rc.screen_length - num_lines_bot | |
759 |
|
754 | |||
760 | # configure startup banner |
|
755 | # configure startup banner | |
761 | if IP_rc.c: # regular python doesn't print the banner with -c |
|
756 | if IP_rc.c: # regular python doesn't print the banner with -c | |
762 | IP_rc.banner = 0 |
|
757 | IP_rc.banner = 0 | |
763 | if IP_rc.banner: |
|
758 | if IP_rc.banner: | |
764 | BANN_P = IP.BANNER_PARTS |
|
759 | BANN_P = IP.BANNER_PARTS | |
765 | else: |
|
760 | else: | |
766 | BANN_P = [] |
|
761 | BANN_P = [] | |
767 |
|
762 | |||
768 | if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile) |
|
763 | if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile) | |
769 |
|
764 | |||
770 | # add message log (possibly empty) |
|
765 | # add message log (possibly empty) | |
771 | if msg.summary: BANN_P.append(msg.summary) |
|
766 | if msg.summary: BANN_P.append(msg.summary) | |
772 | # Final banner is a string |
|
767 | # Final banner is a string | |
773 | IP.BANNER = '\n'.join(BANN_P) |
|
768 | IP.BANNER = '\n'.join(BANN_P) | |
774 |
|
769 | |||
775 | # Finalize the IPython instance. This assumes the rc structure is fully |
|
770 | # Finalize the IPython instance. This assumes the rc structure is fully | |
776 | # in place. |
|
771 | # in place. | |
777 | IP.post_config_initialization() |
|
772 | IP.post_config_initialization() | |
778 |
|
773 | |||
779 | return IP |
|
774 | return IP | |
780 | #************************ end of file <ipmaker.py> ************************** |
|
775 | #************************ end of file <ipmaker.py> ************************** |
@@ -1,244 +1,254 b'' | |||||
1 | """Decorators for labeling test objects. |
|
1 | """Decorators for labeling test objects. | |
2 |
|
2 | |||
3 | Decorators that merely return a modified version of the original function |
|
3 | Decorators that merely return a modified version of the original function | |
4 | object are straightforward. Decorators that return a new function object need |
|
4 | object are straightforward. Decorators that return a new function object need | |
5 | to use nose.tools.make_decorator(original_function)(decorator) in returning the |
|
5 | to use nose.tools.make_decorator(original_function)(decorator) in returning the | |
6 | decorator, in order to preserve metadata such as function name, setup and |
|
6 | decorator, in order to preserve metadata such as function name, setup and | |
7 | teardown functions and so on - see nose.tools for more information. |
|
7 | teardown functions and so on - see nose.tools for more information. | |
8 |
|
8 | |||
9 | This module provides a set of useful decorators meant to be ready to use in |
|
9 | This module provides a set of useful decorators meant to be ready to use in | |
10 | your own tests. See the bottom of the file for the ready-made ones, and if you |
|
10 | your own tests. See the bottom of the file for the ready-made ones, and if you | |
11 | find yourself writing a new one that may be of generic use, add it here. |
|
11 | find yourself writing a new one that may be of generic use, add it here. | |
12 |
|
12 | |||
13 | NOTE: This file contains IPython-specific decorators and imports the |
|
13 | NOTE: This file contains IPython-specific decorators and imports the | |
14 | numpy.testing.decorators file, which we've copied verbatim. Any of our own |
|
14 | numpy.testing.decorators file, which we've copied verbatim. Any of our own | |
15 | code will be added at the bottom if we end up extending this. |
|
15 | code will be added at the bottom if we end up extending this. | |
16 | """ |
|
16 | """ | |
17 |
|
17 | |||
18 | # Stdlib imports |
|
18 | # Stdlib imports | |
19 | import inspect |
|
19 | import inspect | |
20 | import sys |
|
20 | import sys | |
21 |
|
21 | |||
22 | # Third-party imports |
|
22 | # Third-party imports | |
23 |
|
23 | |||
24 | # This is Michele Simionato's decorator module, also kept verbatim. |
|
24 | # This is Michele Simionato's decorator module, also kept verbatim. | |
25 | from decorator_msim import decorator, update_wrapper |
|
25 | from decorator_msim import decorator, update_wrapper | |
26 |
|
26 | |||
27 | # Grab the numpy-specific decorators which we keep in a file that we |
|
27 | # Grab the numpy-specific decorators which we keep in a file that we | |
28 | # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy |
|
28 | # occasionally update from upstream: decorators_numpy.py is an IDENTICAL copy | |
29 | # of numpy.testing.decorators. |
|
29 | # of numpy.testing.decorators. | |
30 | from decorators_numpy import * |
|
30 | from decorators_numpy import * | |
31 |
|
31 | |||
32 | ############################################################################## |
|
32 | ############################################################################## | |
33 | # Local code begins |
|
33 | # Local code begins | |
34 |
|
34 | |||
35 | # Utility functions |
|
35 | # Utility functions | |
36 |
|
36 | |||
37 | def apply_wrapper(wrapper,func): |
|
37 | def apply_wrapper(wrapper,func): | |
38 | """Apply a wrapper to a function for decoration. |
|
38 | """Apply a wrapper to a function for decoration. | |
39 |
|
39 | |||
40 | This mixes Michele Simionato's decorator tool with nose's make_decorator, |
|
40 | This mixes Michele Simionato's decorator tool with nose's make_decorator, | |
41 | to apply a wrapper in a decorator so that all nose attributes, as well as |
|
41 | to apply a wrapper in a decorator so that all nose attributes, as well as | |
42 | function signature and other properties, survive the decoration cleanly. |
|
42 | function signature and other properties, survive the decoration cleanly. | |
43 | This will ensure that wrapped functions can still be well introspected via |
|
43 | This will ensure that wrapped functions can still be well introspected via | |
44 | IPython, for example. |
|
44 | IPython, for example. | |
45 | """ |
|
45 | """ | |
46 | import nose.tools |
|
46 | import nose.tools | |
47 |
|
47 | |||
48 | return decorator(wrapper,nose.tools.make_decorator(func)(wrapper)) |
|
48 | return decorator(wrapper,nose.tools.make_decorator(func)(wrapper)) | |
49 |
|
49 | |||
50 |
|
50 | |||
51 | def make_label_dec(label,ds=None): |
|
51 | def make_label_dec(label,ds=None): | |
52 | """Factory function to create a decorator that applies one or more labels. |
|
52 | """Factory function to create a decorator that applies one or more labels. | |
53 |
|
53 | |||
54 | :Parameters: |
|
54 | :Parameters: | |
55 | label : string or sequence |
|
55 | label : string or sequence | |
56 | One or more labels that will be applied by the decorator to the functions |
|
56 | One or more labels that will be applied by the decorator to the functions | |
57 | it decorates. Labels are attributes of the decorated function with their |
|
57 | it decorates. Labels are attributes of the decorated function with their | |
58 | value set to True. |
|
58 | value set to True. | |
59 |
|
59 | |||
60 | :Keywords: |
|
60 | :Keywords: | |
61 | ds : string |
|
61 | ds : string | |
62 | An optional docstring for the resulting decorator. If not given, a |
|
62 | An optional docstring for the resulting decorator. If not given, a | |
63 | default docstring is auto-generated. |
|
63 | default docstring is auto-generated. | |
64 |
|
64 | |||
65 | :Returns: |
|
65 | :Returns: | |
66 | A decorator. |
|
66 | A decorator. | |
67 |
|
67 | |||
68 | :Examples: |
|
68 | :Examples: | |
69 |
|
69 | |||
70 | A simple labeling decorator: |
|
70 | A simple labeling decorator: | |
71 | >>> slow = make_label_dec('slow') |
|
71 | >>> slow = make_label_dec('slow') | |
72 | >>> print slow.__doc__ |
|
72 | >>> print slow.__doc__ | |
73 | Labels a test as 'slow'. |
|
73 | Labels a test as 'slow'. | |
74 |
|
74 | |||
75 | And one that uses multiple labels and a custom docstring: |
|
75 | And one that uses multiple labels and a custom docstring: | |
76 | >>> rare = make_label_dec(['slow','hard'], |
|
76 | >>> rare = make_label_dec(['slow','hard'], | |
77 | ... "Mix labels 'slow' and 'hard' for rare tests.") |
|
77 | ... "Mix labels 'slow' and 'hard' for rare tests.") | |
78 | >>> print rare.__doc__ |
|
78 | >>> print rare.__doc__ | |
79 | Mix labels 'slow' and 'hard' for rare tests. |
|
79 | Mix labels 'slow' and 'hard' for rare tests. | |
80 |
|
80 | |||
81 | Now, let's test using this one: |
|
81 | Now, let's test using this one: | |
82 | >>> @rare |
|
82 | >>> @rare | |
83 | ... def f(): pass |
|
83 | ... def f(): pass | |
84 | ... |
|
84 | ... | |
85 | >>> |
|
85 | >>> | |
86 | >>> f.slow |
|
86 | >>> f.slow | |
87 | True |
|
87 | True | |
88 | >>> f.hard |
|
88 | >>> f.hard | |
89 | True |
|
89 | True | |
90 | """ |
|
90 | """ | |
91 |
|
91 | |||
92 | if isinstance(label,basestring): |
|
92 | if isinstance(label,basestring): | |
93 | labels = [label] |
|
93 | labels = [label] | |
94 | else: |
|
94 | else: | |
95 | labels = label |
|
95 | labels = label | |
96 |
|
96 | |||
97 | # Validate that the given label(s) are OK for use in setattr() by doing a |
|
97 | # Validate that the given label(s) are OK for use in setattr() by doing a | |
98 | # dry run on a dummy function. |
|
98 | # dry run on a dummy function. | |
99 | tmp = lambda : None |
|
99 | tmp = lambda : None | |
100 | for label in labels: |
|
100 | for label in labels: | |
101 | setattr(tmp,label,True) |
|
101 | setattr(tmp,label,True) | |
102 |
|
102 | |||
103 | # This is the actual decorator we'll return |
|
103 | # This is the actual decorator we'll return | |
104 | def decor(f): |
|
104 | def decor(f): | |
105 | for label in labels: |
|
105 | for label in labels: | |
106 | setattr(f,label,True) |
|
106 | setattr(f,label,True) | |
107 | return f |
|
107 | return f | |
108 |
|
108 | |||
109 | # Apply the user's docstring, or autogenerate a basic one |
|
109 | # Apply the user's docstring, or autogenerate a basic one | |
110 | if ds is None: |
|
110 | if ds is None: | |
111 | ds = "Labels a test as %r." % label |
|
111 | ds = "Labels a test as %r." % label | |
112 | decor.__doc__ = ds |
|
112 | decor.__doc__ = ds | |
113 |
|
113 | |||
114 | return decor |
|
114 | return decor | |
115 |
|
115 | |||
116 |
|
116 | |||
117 | # Inspired by numpy's skipif, but uses the full apply_wrapper utility to |
|
117 | # Inspired by numpy's skipif, but uses the full apply_wrapper utility to | |
118 | # preserve function metadata better and allows the skip condition to be a |
|
118 | # preserve function metadata better and allows the skip condition to be a | |
119 | # callable. |
|
119 | # callable. | |
120 | def skipif(skip_condition, msg=None): |
|
120 | def skipif(skip_condition, msg=None): | |
121 | ''' Make function raise SkipTest exception if skip_condition is true |
|
121 | ''' Make function raise SkipTest exception if skip_condition is true | |
122 |
|
122 | |||
123 | Parameters |
|
123 | Parameters | |
124 | ---------- |
|
124 | ---------- | |
125 | skip_condition : bool or callable. |
|
125 | skip_condition : bool or callable. | |
126 | Flag to determine whether to skip test. If the condition is a |
|
126 | Flag to determine whether to skip test. If the condition is a | |
127 | callable, it is used at runtime to dynamically make the decision. This |
|
127 | callable, it is used at runtime to dynamically make the decision. This | |
128 | is useful for tests that may require costly imports, to delay the cost |
|
128 | is useful for tests that may require costly imports, to delay the cost | |
129 | until the test suite is actually executed. |
|
129 | until the test suite is actually executed. | |
130 | msg : string |
|
130 | msg : string | |
131 | Message to give on raising a SkipTest exception |
|
131 | Message to give on raising a SkipTest exception | |
132 |
|
132 | |||
133 | Returns |
|
133 | Returns | |
134 | ------- |
|
134 | ------- | |
135 | decorator : function |
|
135 | decorator : function | |
136 | Decorator, which, when applied to a function, causes SkipTest |
|
136 | Decorator, which, when applied to a function, causes SkipTest | |
137 | to be raised when the skip_condition was True, and the function |
|
137 | to be raised when the skip_condition was True, and the function | |
138 | to be called normally otherwise. |
|
138 | to be called normally otherwise. | |
139 |
|
139 | |||
140 | Notes |
|
140 | Notes | |
141 | ----- |
|
141 | ----- | |
142 | You will see from the code that we had to further decorate the |
|
142 | You will see from the code that we had to further decorate the | |
143 | decorator with the nose.tools.make_decorator function in order to |
|
143 | decorator with the nose.tools.make_decorator function in order to | |
144 | transmit function name, and various other metadata. |
|
144 | transmit function name, and various other metadata. | |
145 | ''' |
|
145 | ''' | |
146 |
|
146 | |||
147 | def skip_decorator(f): |
|
147 | def skip_decorator(f): | |
148 | # Local import to avoid a hard nose dependency and only incur the |
|
148 | # Local import to avoid a hard nose dependency and only incur the | |
149 | # import time overhead at actual test-time. |
|
149 | # import time overhead at actual test-time. | |
150 | import nose |
|
150 | import nose | |
151 |
|
151 | |||
152 | # Allow for both boolean or callable skip conditions. |
|
152 | # Allow for both boolean or callable skip conditions. | |
153 | if callable(skip_condition): |
|
153 | if callable(skip_condition): | |
154 | skip_val = lambda : skip_condition() |
|
154 | skip_val = lambda : skip_condition() | |
155 | else: |
|
155 | else: | |
156 | skip_val = lambda : skip_condition |
|
156 | skip_val = lambda : skip_condition | |
157 |
|
157 | |||
158 | def get_msg(func,msg=None): |
|
158 | def get_msg(func,msg=None): | |
159 | """Skip message with information about function being skipped.""" |
|
159 | """Skip message with information about function being skipped.""" | |
160 | if msg is None: out = 'Test skipped due to test condition.' |
|
160 | if msg is None: out = 'Test skipped due to test condition.' | |
161 | else: out = msg |
|
161 | else: out = msg | |
162 | return "Skipping test: %s. %s" % (func.__name__,out) |
|
162 | return "Skipping test: %s. %s" % (func.__name__,out) | |
163 |
|
163 | |||
164 | # We need to define *two* skippers because Python doesn't allow both |
|
164 | # We need to define *two* skippers because Python doesn't allow both | |
165 | # return with value and yield inside the same function. |
|
165 | # return with value and yield inside the same function. | |
166 | def skipper_func(*args, **kwargs): |
|
166 | def skipper_func(*args, **kwargs): | |
167 | """Skipper for normal test functions.""" |
|
167 | """Skipper for normal test functions.""" | |
168 | if skip_val(): |
|
168 | if skip_val(): | |
169 | raise nose.SkipTest(get_msg(f,msg)) |
|
169 | raise nose.SkipTest(get_msg(f,msg)) | |
170 | else: |
|
170 | else: | |
171 | return f(*args, **kwargs) |
|
171 | return f(*args, **kwargs) | |
172 |
|
172 | |||
173 | def skipper_gen(*args, **kwargs): |
|
173 | def skipper_gen(*args, **kwargs): | |
174 | """Skipper for test generators.""" |
|
174 | """Skipper for test generators.""" | |
175 | if skip_val(): |
|
175 | if skip_val(): | |
176 | raise nose.SkipTest(get_msg(f,msg)) |
|
176 | raise nose.SkipTest(get_msg(f,msg)) | |
177 | else: |
|
177 | else: | |
178 | for x in f(*args, **kwargs): |
|
178 | for x in f(*args, **kwargs): | |
179 | yield x |
|
179 | yield x | |
180 |
|
180 | |||
181 | # Choose the right skipper to use when building the actual generator. |
|
181 | # Choose the right skipper to use when building the actual generator. | |
182 | if nose.util.isgenerator(f): |
|
182 | if nose.util.isgenerator(f): | |
183 | skipper = skipper_gen |
|
183 | skipper = skipper_gen | |
184 | else: |
|
184 | else: | |
185 | skipper = skipper_func |
|
185 | skipper = skipper_func | |
186 |
|
186 | |||
187 | return nose.tools.make_decorator(f)(skipper) |
|
187 | return nose.tools.make_decorator(f)(skipper) | |
188 |
|
188 | |||
189 | return skip_decorator |
|
189 | return skip_decorator | |
190 |
|
190 | |||
191 | # A version with the condition set to true, common case just to attacha message |
|
191 | # A version with the condition set to true, common case just to attacha message | |
192 | # to a skip decorator |
|
192 | # to a skip decorator | |
193 | def skip(msg=None): |
|
193 | def skip(msg=None): | |
194 | """Decorator factory - mark a test function for skipping from test suite. |
|
194 | """Decorator factory - mark a test function for skipping from test suite. | |
195 |
|
195 | |||
196 | :Parameters: |
|
196 | :Parameters: | |
197 | msg : string |
|
197 | msg : string | |
198 | Optional message to be added. |
|
198 | Optional message to be added. | |
199 |
|
199 | |||
200 | :Returns: |
|
200 | :Returns: | |
201 | decorator : function |
|
201 | decorator : function | |
202 | Decorator, which, when applied to a function, causes SkipTest |
|
202 | Decorator, which, when applied to a function, causes SkipTest | |
203 | to be raised, with the optional message added. |
|
203 | to be raised, with the optional message added. | |
204 | """ |
|
204 | """ | |
205 |
|
205 | |||
206 | return skipif(True,msg) |
|
206 | return skipif(True,msg) | |
207 |
|
207 | |||
208 |
|
208 | |||
209 | #----------------------------------------------------------------------------- |
|
209 | #----------------------------------------------------------------------------- | |
210 | # Utility functions for decorators |
|
210 | # Utility functions for decorators | |
211 | def numpy_not_available(): |
|
211 | def numpy_not_available(): | |
212 | """Can numpy be imported? Returns true if numpy does NOT import. |
|
212 | """Can numpy be imported? Returns true if numpy does NOT import. | |
213 |
|
213 | |||
214 | This is used to make a decorator to skip tests that require numpy to be |
|
214 | This is used to make a decorator to skip tests that require numpy to be | |
215 | available, but delay the 'import numpy' to test execution time. |
|
215 | available, but delay the 'import numpy' to test execution time. | |
216 | """ |
|
216 | """ | |
217 | try: |
|
217 | try: | |
218 | import numpy |
|
218 | import numpy | |
219 | np_not_avail = False |
|
219 | np_not_avail = False | |
220 | except ImportError: |
|
220 | except ImportError: | |
221 | np_not_avail = True |
|
221 | np_not_avail = True | |
222 |
|
222 | |||
223 | return np_not_avail |
|
223 | return np_not_avail | |
224 |
|
224 | |||
225 | #----------------------------------------------------------------------------- |
|
225 | #----------------------------------------------------------------------------- | |
226 | # Decorators for public use |
|
226 | # Decorators for public use | |
227 |
|
227 | |||
228 | skip_doctest = make_label_dec('skip_doctest', |
|
228 | skip_doctest = make_label_dec('skip_doctest', | |
229 | """Decorator - mark a function or method for skipping its doctest. |
|
229 | """Decorator - mark a function or method for skipping its doctest. | |
230 |
|
230 | |||
231 | This decorator allows you to mark a function whose docstring you wish to |
|
231 | This decorator allows you to mark a function whose docstring you wish to | |
232 | omit from testing, while preserving the docstring for introspection, help, |
|
232 | omit from testing, while preserving the docstring for introspection, help, | |
233 | etc.""") |
|
233 | etc.""") | |
234 |
|
234 | |||
235 | # Decorators to skip certain tests on specific platforms. |
|
235 | # Decorators to skip certain tests on specific platforms. | |
236 | skip_win32 = skipif(sys.platform=='win32', |
|
236 | skip_win32 = skipif(sys.platform == 'win32', | |
237 | "This test does not run under Windows") |
|
237 | "This test does not run under Windows") | |
238 |
skip_linux = skipif(sys.platform=='linux2', |
|
238 | skip_linux = skipif(sys.platform == 'linux2', | |
239 | skip_osx = skipif(sys.platform=='darwin',"This test does not run under OS X") |
|
239 | "This test does not run under Linux") | |
|
240 | skip_osx = skipif(sys.platform == 'darwin',"This test does not run under OS X") | |||
240 |
|
241 | |||
241 |
|
242 | |||
|
243 | # Decorators to skip tests if not on specific platforms. | |||
|
244 | skip_if_not_win32 = skipif(sys.platform != 'win32', | |||
|
245 | "This test only runs under Windows") | |||
|
246 | skip_if_not_linux = skipif(sys.platform != 'linux2', | |||
|
247 | "This test only runs under Linux") | |||
|
248 | skip_if_not_osx = skipif(sys.platform != 'darwin', | |||
|
249 | "This test only runs under OSX") | |||
|
250 | ||||
|
251 | # Other skip decorators | |||
242 | skipif_not_numpy = skipif(numpy_not_available,"This test requires numpy") |
|
252 | skipif_not_numpy = skipif(numpy_not_available,"This test requires numpy") | |
243 |
|
253 | |||
244 | skipknownfailure = skip('This test is known to fail') |
|
254 | skipknownfailure = skip('This test is known to fail') |
@@ -1,32 +1,291 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 |
|
2 | |||
3 | """Tests for genutils.py""" |
|
3 | """Tests for genutils.py""" | |
4 |
|
4 | |||
5 | __docformat__ = "restructuredtext en" |
|
5 | __docformat__ = "restructuredtext en" | |
6 |
|
6 | |||
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2008 The IPython Development Team |
|
8 | # Copyright (C) 2008 The IPython Development Team | |
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 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
|
18 | # stdlib | |||
|
19 | import os | |||
|
20 | import shutil | |||
|
21 | import sys | |||
|
22 | import tempfile | |||
|
23 | ||||
|
24 | from os.path import join, abspath, split | |||
|
25 | ||||
|
26 | # third-party | |||
|
27 | import nose.tools as nt | |||
|
28 | ||||
|
29 | from nose import with_setup | |||
|
30 | from nose.tools import raises | |||
|
31 | ||||
|
32 | # Our own | |||
|
33 | import IPython | |||
18 | from IPython import genutils |
|
34 | from IPython import genutils | |
|
35 | from IPython.testing.decorators import skipif, skip_if_not_win32 | |||
|
36 | ||||
|
37 | # Platform-dependent imports | |||
|
38 | try: | |||
|
39 | import _winreg as wreg | |||
|
40 | except ImportError: | |||
|
41 | #Fake _winreg module on none windows platforms | |||
|
42 | import new | |||
|
43 | sys.modules["_winreg"] = new.module("_winreg") | |||
|
44 | import _winreg as wreg | |||
|
45 | #Add entries that needs to be stubbed by the testing code | |||
|
46 | (wreg.OpenKey, wreg.QueryValueEx,) = (None, None) | |||
|
47 | ||||
|
48 | #----------------------------------------------------------------------------- | |||
|
49 | # Globals | |||
|
50 | #----------------------------------------------------------------------------- | |||
|
51 | env = os.environ | |||
|
52 | TEST_FILE_PATH = split(abspath(__file__))[0] | |||
|
53 | TMP_TEST_DIR = tempfile.mkdtemp() | |||
|
54 | HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir") | |||
|
55 | IP_TEST_DIR = join(HOME_TEST_DIR,'_ipython') | |||
|
56 | # | |||
|
57 | # Setup/teardown functions/decorators | |||
|
58 | # | |||
|
59 | ||||
|
60 | def setup(): | |||
|
61 | """Setup testenvironment for the module: | |||
|
62 | ||||
|
63 | - Adds dummy home dir tree | |||
|
64 | """ | |||
|
65 | # Do not mask exceptions here. In particular, catching WindowsError is a | |||
|
66 | # problem because that exception is only defined on Windows... | |||
|
67 | os.makedirs(IP_TEST_DIR) | |||
|
68 | ||||
|
69 | def teardown(): | |||
|
70 | """Teardown testenvironment for the module: | |||
|
71 | ||||
|
72 | - Remove dummy home dir tree | |||
|
73 | """ | |||
|
74 | # Note: we remove the parent test dir, which is the root of all test | |||
|
75 | # subdirs we may have created. Use shutil instead of os.removedirs, so | |||
|
76 | # that non-empty directories are all recursively removed. | |||
|
77 | shutil.rmtree(TMP_TEST_DIR) | |||
|
78 | ||||
|
79 | ||||
|
80 | def setup_environment(): | |||
|
81 | """Setup testenvironment for some functions that are tested | |||
|
82 | in this module. In particular this functions stores attributes | |||
|
83 | and other things that we need to stub in some test functions. | |||
|
84 | This needs to be done on a function level and not module level because | |||
|
85 | each testfunction needs a pristine environment. | |||
|
86 | """ | |||
|
87 | global oldstuff, platformstuff | |||
|
88 | oldstuff = (env.copy(), os.name, genutils.get_home_dir, IPython.__file__,) | |||
|
89 | ||||
|
90 | if os.name == 'nt': | |||
|
91 | platformstuff = (wreg.OpenKey, wreg.QueryValueEx,) | |||
|
92 | ||||
|
93 | if 'IPYTHONDIR' in env: | |||
|
94 | del env['IPYTHONDIR'] | |||
|
95 | ||||
|
96 | def teardown_environment(): | |||
|
97 | """Restore things that were remebered by the setup_environment function | |||
|
98 | """ | |||
|
99 | (oldenv, os.name, genutils.get_home_dir, IPython.__file__,) = oldstuff | |||
|
100 | for key in env.keys(): | |||
|
101 | if key not in oldenv: | |||
|
102 | del env[key] | |||
|
103 | env.update(oldenv) | |||
|
104 | if hasattr(sys, 'frozen'): | |||
|
105 | del sys.frozen | |||
|
106 | if os.name == 'nt': | |||
|
107 | (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff | |||
|
108 | ||||
|
109 | # Build decorator that uses the setup_environment/setup_environment | |||
|
110 | with_enivronment = with_setup(setup_environment, teardown_environment) | |||
|
111 | ||||
|
112 | ||||
|
113 | # | |||
|
114 | # Tests for get_home_dir | |||
|
115 | # | |||
|
116 | ||||
|
117 | @skip_if_not_win32 | |||
|
118 | @with_enivronment | |||
|
119 | def test_get_home_dir_1(): | |||
|
120 | """Testcase for py2exe logic, un-compressed lib | |||
|
121 | """ | |||
|
122 | sys.frozen = True | |||
|
123 | ||||
|
124 | #fake filename for IPython.__init__ | |||
|
125 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py")) | |||
|
126 | ||||
|
127 | home_dir = genutils.get_home_dir() | |||
|
128 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |||
|
129 | ||||
|
130 | @skip_if_not_win32 | |||
|
131 | @with_enivronment | |||
|
132 | def test_get_home_dir_2(): | |||
|
133 | """Testcase for py2exe logic, compressed lib | |||
|
134 | """ | |||
|
135 | sys.frozen = True | |||
|
136 | #fake filename for IPython.__init__ | |||
|
137 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower() | |||
|
138 | ||||
|
139 | home_dir = genutils.get_home_dir() | |||
|
140 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower()) | |||
|
141 | ||||
|
142 | @with_enivronment | |||
|
143 | def test_get_home_dir_3(): | |||
|
144 | """Testcase $HOME is set, then use its value as home directory.""" | |||
|
145 | env["HOME"] = HOME_TEST_DIR | |||
|
146 | home_dir = genutils.get_home_dir() | |||
|
147 | nt.assert_equal(home_dir, env["HOME"]) | |||
|
148 | ||||
|
149 | @with_enivronment | |||
|
150 | def test_get_home_dir_4(): | |||
|
151 | """Testcase $HOME is not set, os=='poix'. | |||
|
152 | This should fail with HomeDirError""" | |||
|
153 | ||||
|
154 | os.name = 'posix' | |||
|
155 | if 'HOME' in env: del env['HOME'] | |||
|
156 | nt.assert_raises(genutils.HomeDirError, genutils.get_home_dir) | |||
|
157 | ||||
|
158 | @skip_if_not_win32 | |||
|
159 | @with_enivronment | |||
|
160 | def test_get_home_dir_5(): | |||
|
161 | """Testcase $HOME is not set, os=='nt' | |||
|
162 | env['HOMEDRIVE'],env['HOMEPATH'] points to path.""" | |||
|
163 | ||||
|
164 | os.name = 'nt' | |||
|
165 | if 'HOME' in env: del env['HOME'] | |||
|
166 | env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR) | |||
19 |
|
167 | |||
|
168 | home_dir = genutils.get_home_dir() | |||
|
169 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |||
|
170 | ||||
|
171 | @skip_if_not_win32 | |||
|
172 | @with_enivronment | |||
|
173 | def test_get_home_dir_6(): | |||
|
174 | """Testcase $HOME is not set, os=='nt' | |||
|
175 | env['HOMEDRIVE'],env['HOMEPATH'] do not point to path. | |||
|
176 | env['USERPROFILE'] points to path | |||
|
177 | """ | |||
|
178 | ||||
|
179 | os.name = 'nt' | |||
|
180 | if 'HOME' in env: del env['HOME'] | |||
|
181 | env['HOMEDRIVE'], env['HOMEPATH'] = os.path.abspath(TEST_FILE_PATH), "DOES NOT EXIST" | |||
|
182 | env["USERPROFILE"] = abspath(HOME_TEST_DIR) | |||
|
183 | ||||
|
184 | home_dir = genutils.get_home_dir() | |||
|
185 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |||
|
186 | ||||
|
187 | # Should we stub wreg fully so we can run the test on all platforms? | |||
|
188 | @skip_if_not_win32 | |||
|
189 | @with_enivronment | |||
|
190 | def test_get_home_dir_7(): | |||
|
191 | """Testcase $HOME is not set, os=='nt' | |||
|
192 | env['HOMEDRIVE'],env['HOMEPATH'], env['USERPROFILE'] missing | |||
|
193 | """ | |||
|
194 | os.name = 'nt' | |||
|
195 | if 'HOME' in env: del env['HOME'] | |||
|
196 | if 'HOMEDRIVE' in env: del env['HOMEDRIVE'] | |||
|
197 | ||||
|
198 | #Stub windows registry functions | |||
|
199 | def OpenKey(x, y): | |||
|
200 | class key: | |||
|
201 | def Close(self): | |||
|
202 | pass | |||
|
203 | return key() | |||
|
204 | def QueryValueEx(x, y): | |||
|
205 | return [abspath(HOME_TEST_DIR)] | |||
|
206 | ||||
|
207 | wreg.OpenKey = OpenKey | |||
|
208 | wreg.QueryValueEx = QueryValueEx | |||
20 |
|
209 | |||
21 | def test_get_home_dir(): |
|
|||
22 | """Make sure we can get the home directory.""" |
|
|||
23 | home_dir = genutils.get_home_dir() |
|
210 | home_dir = genutils.get_home_dir() | |
|
211 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |||
|
212 | ||||
|
213 | ||||
|
214 | # | |||
|
215 | # Tests for get_ipython_dir | |||
|
216 | # | |||
|
217 | ||||
|
218 | @with_enivronment | |||
|
219 | def test_get_ipython_dir_1(): | |||
|
220 | """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions.""" | |||
|
221 | env['IPYTHONDIR'] = "someplace/.ipython" | |||
|
222 | ipdir = genutils.get_ipython_dir() | |||
|
223 | nt.assert_equal(ipdir, os.path.abspath("someplace/.ipython")) | |||
24 |
|
224 | |||
25 | def test_get_ipython_dir(): |
|
225 | ||
26 | """Make sure we can get the ipython directory.""" |
|
226 | @with_enivronment | |
|
227 | def test_get_ipython_dir_2(): | |||
|
228 | """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions.""" | |||
|
229 | genutils.get_home_dir = lambda : "someplace" | |||
|
230 | os.name = "posix" | |||
|
231 | ipdir = genutils.get_ipython_dir() | |||
|
232 | nt.assert_equal(ipdir, os.path.abspath(os.path.join("someplace", ".ipython"))) | |||
|
233 | ||||
|
234 | @with_enivronment | |||
|
235 | def test_get_ipython_dir_3(): | |||
|
236 | """test_get_ipython_dir_3, Testcase to see if we can call get_ipython_dir without Exceptions.""" | |||
|
237 | genutils.get_home_dir = lambda : "someplace" | |||
|
238 | os.name = "nt" | |||
27 | ipdir = genutils.get_ipython_dir() |
|
239 | ipdir = genutils.get_ipython_dir() | |
|
240 | nt.assert_equal(ipdir, os.path.abspath(os.path.join("someplace", "_ipython"))) | |||
|
241 | ||||
|
242 | ||||
|
243 | # | |||
|
244 | # Tests for get_security_dir | |||
|
245 | # | |||
28 |
|
246 | |||
|
247 | @with_enivronment | |||
29 | def test_get_security_dir(): |
|
248 | def test_get_security_dir(): | |
30 | """Make sure we can get the ipython/security directory.""" |
|
249 | """Testcase to see if we can call get_security_dir without Exceptions.""" | |
31 | sdir = genutils.get_security_dir() |
|
250 | sdir = genutils.get_security_dir() | |
32 | No newline at end of file |
|
251 | ||
|
252 | ||||
|
253 | # | |||
|
254 | # Tests for popkey | |||
|
255 | # | |||
|
256 | ||||
|
257 | def test_popkey_1(): | |||
|
258 | """test_popkey_1, Basic usage test of popkey | |||
|
259 | """ | |||
|
260 | dct = dict(a=1, b=2, c=3) | |||
|
261 | nt.assert_equal(genutils.popkey(dct, "a"), 1) | |||
|
262 | nt.assert_equal(dct, dict(b=2, c=3)) | |||
|
263 | nt.assert_equal(genutils.popkey(dct, "b"), 2) | |||
|
264 | nt.assert_equal(dct, dict(c=3)) | |||
|
265 | nt.assert_equal(genutils.popkey(dct, "c"), 3) | |||
|
266 | nt.assert_equal(dct, dict()) | |||
|
267 | ||||
|
268 | def test_popkey_2(): | |||
|
269 | """test_popkey_2, Test to see that popkey of non occuring keys | |||
|
270 | generates a KeyError exception | |||
|
271 | """ | |||
|
272 | dct = dict(a=1, b=2, c=3) | |||
|
273 | nt.assert_raises(KeyError, genutils.popkey, dct, "d") | |||
|
274 | ||||
|
275 | def test_popkey_3(): | |||
|
276 | """test_popkey_3, Tests to see that popkey calls returns the correct value | |||
|
277 | and that the key/value was removed from the dict. | |||
|
278 | """ | |||
|
279 | dct = dict(a=1, b=2, c=3) | |||
|
280 | nt.assert_equal(genutils.popkey(dct, "A", 13), 13) | |||
|
281 | nt.assert_equal(dct, dict(a=1, b=2, c=3)) | |||
|
282 | nt.assert_equal(genutils.popkey(dct, "B", 14), 14) | |||
|
283 | nt.assert_equal(dct, dict(a=1, b=2, c=3)) | |||
|
284 | nt.assert_equal(genutils.popkey(dct, "C", 15), 15) | |||
|
285 | nt.assert_equal(dct, dict(a=1, b=2, c=3)) | |||
|
286 | nt.assert_equal(genutils.popkey(dct, "a"), 1) | |||
|
287 | nt.assert_equal(dct, dict(b=2, c=3)) | |||
|
288 | nt.assert_equal(genutils.popkey(dct, "b"), 2) | |||
|
289 | nt.assert_equal(dct, dict(c=3)) | |||
|
290 | nt.assert_equal(genutils.popkey(dct, "c"), 3) | |||
|
291 | nt.assert_equal(dct, dict()) |
@@ -1,345 +1,358 b'' | |||||
1 | .. _development: |
|
1 | .. _development: | |
2 |
|
2 | |||
3 | ============================== |
|
3 | ============================== | |
4 | IPython development guidelines |
|
4 | IPython development guidelines | |
5 | ============================== |
|
5 | ============================== | |
6 |
|
6 | |||
7 |
|
7 | |||
8 | Overview |
|
8 | Overview | |
9 | ======== |
|
9 | ======== | |
10 |
|
10 | |||
11 | This document describes IPython from the perspective of developers. Most |
|
11 | This document describes IPython from the perspective of developers. Most | |
12 | importantly, it gives information for people who want to contribute to the |
|
12 | importantly, it gives information for people who want to contribute to the | |
13 | development of IPython. So if you want to help out, read on! |
|
13 | development of IPython. So if you want to help out, read on! | |
14 |
|
14 | |||
15 | How to contribute to IPython |
|
15 | How to contribute to IPython | |
16 | ============================ |
|
16 | ============================ | |
17 |
|
17 | |||
18 | IPython development is done using Bazaar [Bazaar]_ and Launchpad [Launchpad]_. |
|
18 | IPython development is done using Bazaar [Bazaar]_ and Launchpad [Launchpad]_. | |
19 | This makes it easy for people to contribute to the development of IPython. |
|
19 | This makes it easy for people to contribute to the development of IPython. | |
20 | Here is a sketch of how to get going. |
|
20 | Here is a sketch of how to get going. | |
21 |
|
21 | |||
22 | Install Bazaar and create a Launchpad account |
|
22 | Install Bazaar and create a Launchpad account | |
23 | --------------------------------------------- |
|
23 | --------------------------------------------- | |
24 |
|
24 | |||
25 | First make sure you have installed Bazaar (see their `website |
|
25 | First make sure you have installed Bazaar (see their `website | |
26 | <http://bazaar-vcs.org/>`_). To see that Bazaar is installed and knows about |
|
26 | <http://bazaar-vcs.org/>`_). To see that Bazaar is installed and knows about | |
27 | you, try the following:: |
|
27 | you, try the following:: | |
28 |
|
28 | |||
29 | $ bzr whoami |
|
29 | $ bzr whoami | |
30 | Joe Coder <jcoder@gmail.com> |
|
30 | Joe Coder <jcoder@gmail.com> | |
31 |
|
31 | |||
32 | This should display your name and email. Next, you will want to create an |
|
32 | This should display your name and email. Next, you will want to create an | |
33 | account on the `Launchpad website <http://www.launchpad.net>`_ and setup your |
|
33 | account on the `Launchpad website <http://www.launchpad.net>`_ and setup your | |
34 | ssh keys. For more information of setting up your ssh keys, see `this link |
|
34 | ssh keys. For more information of setting up your ssh keys, see `this link | |
35 | <https://help.launchpad.net/YourAccount/CreatingAnSSHKeyPair>`_. |
|
35 | <https://help.launchpad.net/YourAccount/CreatingAnSSHKeyPair>`_. | |
36 |
|
36 | |||
37 | Get the main IPython branch from Launchpad |
|
37 | Get the main IPython branch from Launchpad | |
38 | ------------------------------------------ |
|
38 | ------------------------------------------ | |
39 |
|
39 | |||
40 | Now, you can get a copy of the main IPython development branch (we call this |
|
40 | Now, you can get a copy of the main IPython development branch (we call this | |
41 | the "trunk"):: |
|
41 | the "trunk"):: | |
42 |
|
42 | |||
43 | $ bzr branch lp:ipython |
|
43 | $ bzr branch lp:ipython | |
44 |
|
44 | |||
45 | Create a working branch |
|
45 | Create a working branch | |
46 | ----------------------- |
|
46 | ----------------------- | |
47 |
|
47 | |||
48 | When working on IPython, you won't actually make edits directly to the |
|
48 | When working on IPython, you won't actually make edits directly to the | |
49 | :file:`lp:ipython` branch. Instead, you will create a separate branch for your |
|
49 | :file:`lp:ipython` branch. Instead, you will create a separate branch for your | |
50 | changes. For now, let's assume you want to do your work in a branch named |
|
50 | changes. For now, let's assume you want to do your work in a branch named | |
51 | "ipython-mybranch". Create this branch by doing:: |
|
51 | "ipython-mybranch". Create this branch by doing:: | |
52 |
|
52 | |||
53 | $ bzr branch ipython ipython-mybranch |
|
53 | $ bzr branch ipython ipython-mybranch | |
54 |
|
54 | |||
55 | When you actually create a branch, you will want to give it a name that |
|
55 | When you actually create a branch, you will want to give it a name that | |
56 | reflects the nature of the work that you will be doing in it, like |
|
56 | reflects the nature of the work that you will be doing in it, like | |
57 | "install-docs-update". |
|
57 | "install-docs-update". | |
58 |
|
58 | |||
59 | Make edits in your working branch |
|
59 | Make edits in your working branch | |
60 | --------------------------------- |
|
60 | --------------------------------- | |
61 |
|
61 | |||
62 | Now you are ready to actually make edits in your :file:`ipython-mybranch` |
|
62 | Now you are ready to actually make edits in your :file:`ipython-mybranch` | |
63 | branch. Before doing this, it is helpful to install this branch so you can |
|
63 | branch. Before doing this, it is helpful to install this branch so you can | |
64 | test your changes as you work. This is easiest if you have setuptools |
|
64 | test your changes as you work. This is easiest if you have setuptools | |
65 | installed. Then, just do:: |
|
65 | installed. Then, just do:: | |
66 |
|
66 | |||
67 | $ cd ipython-mybranch |
|
67 | $ cd ipython-mybranch | |
68 | $ python setupegg.py develop |
|
68 | $ python setupegg.py develop | |
69 |
|
69 | |||
70 | Now, make some changes. After a while, you will want to commit your changes. |
|
70 | Now, make some changes. After a while, you will want to commit your changes. | |
71 | This let's Bazaar know that you like the changes you have made and gives you |
|
71 | This let's Bazaar know that you like the changes you have made and gives you | |
72 | an opportunity to keep a nice record of what you have done. This looks like |
|
72 | an opportunity to keep a nice record of what you have done. This looks like | |
73 | this:: |
|
73 | this:: | |
74 |
|
74 | |||
75 | $ ...do work in ipython-mybranch... |
|
75 | $ ...do work in ipython-mybranch... | |
76 | $ bzr commit -m "the commit message goes here" |
|
76 | $ bzr commit -m "the commit message goes here" | |
77 |
|
77 | |||
78 | Please note that since we now don't use an old-style linear ChangeLog (that |
|
78 | Please note that since we now don't use an old-style linear ChangeLog (that | |
79 | tends to cause problems with distributed version control systems), you should |
|
79 | tends to cause problems with distributed version control systems), you should | |
80 | ensure that your log messages are reasonably detailed. Use a docstring-like |
|
80 | ensure that your log messages are reasonably detailed. Use a docstring-like | |
81 | approach in the commit messages (including the second line being left |
|
81 | approach in the commit messages (including the second line being left | |
82 | *blank*):: |
|
82 | *blank*):: | |
83 |
|
83 | |||
84 | Single line summary of changes being committed. |
|
84 | Single line summary of changes being committed. | |
85 |
|
85 | |||
86 | * more details when warranted ... |
|
86 | * more details when warranted ... | |
87 | * including crediting outside contributors if they sent the |
|
87 | * including crediting outside contributors if they sent the | |
88 | code/bug/idea! |
|
88 | code/bug/idea! | |
89 |
|
89 | |||
90 | As you work, you will repeat this edit/commit cycle many times. If you work on |
|
90 | As you work, you will repeat this edit/commit cycle many times. If you work on | |
91 | your branch for a long time, you will also want to get the latest changes from |
|
91 | your branch for a long time, you will also want to get the latest changes from | |
92 | the :file:`lp:ipython` branch. This can be done with the following sequence of |
|
92 | the :file:`lp:ipython` branch. This can be done with the following sequence of | |
93 | commands:: |
|
93 | commands:: | |
94 |
|
94 | |||
95 | $ ls |
|
95 | $ ls | |
96 | ipython |
|
96 | ipython | |
97 | ipython-mybranch |
|
97 | ipython-mybranch | |
98 |
|
98 | |||
99 | $ cd ipython |
|
99 | $ cd ipython | |
100 | $ bzr pull |
|
100 | $ bzr pull | |
101 | $ cd ../ipython-mybranch |
|
101 | $ cd ../ipython-mybranch | |
102 | $ bzr merge ../ipython |
|
102 | $ bzr merge ../ipython | |
103 | $ bzr commit -m "Merging changes from trunk" |
|
103 | $ bzr commit -m "Merging changes from trunk" | |
104 |
|
104 | |||
105 | Along the way, you should also run the IPython test suite. You can do this using the :command:`iptest` command:: |
|
105 | Along the way, you should also run the IPython test suite. You can do this using the :command:`iptest` command:: | |
106 |
|
106 | |||
107 | $ cd |
|
107 | $ cd | |
108 | $ iptest |
|
108 | $ iptest | |
109 |
|
109 | |||
110 | The :command:`iptest` command will also pick up and run any tests you have written. |
|
110 | The :command:`iptest` command will also pick up and run any tests you have written. | |
111 |
|
111 | |||
112 | Post your branch and request a code review |
|
112 | Post your branch and request a code review | |
113 | ------------------------------------------ |
|
113 | ------------------------------------------ | |
114 |
|
114 | |||
115 | Once you are done with your edits, you should post your branch on Launchpad so |
|
115 | Once you are done with your edits, you should post your branch on Launchpad so | |
116 | that other IPython developers can review the changes and help you merge your |
|
116 | that other IPython developers can review the changes and help you merge your | |
117 | changes into the main development branch. To post your branch on Launchpad, |
|
117 | changes into the main development branch. To post your branch on Launchpad, | |
118 | do:: |
|
118 | do:: | |
119 |
|
119 | |||
120 | $ cd ipython-mybranch |
|
120 | $ cd ipython-mybranch | |
121 | $ bzr push lp:~yourusername/ipython/ipython-mybranch |
|
121 | $ bzr push lp:~yourusername/ipython/ipython-mybranch | |
122 |
|
122 | |||
123 | Then, go to the `IPython Launchpad site <www.launchpad.net/ipython>`_, and you |
|
123 | Then, go to the `IPython Launchpad site <www.launchpad.net/ipython>`_, and you | |
124 | should see your branch under the "Code" tab. If you click on your branch, you |
|
124 | should see your branch under the "Code" tab. If you click on your branch, you | |
125 | can provide a short description of the branch as well as mark its status. Most |
|
125 | can provide a short description of the branch as well as mark its status. Most | |
126 | importantly, you should click the link that reads "Propose for merging into |
|
126 | importantly, you should click the link that reads "Propose for merging into | |
127 | another branch". What does this do? |
|
127 | another branch". What does this do? | |
128 |
|
128 | |||
129 | This let's the other IPython developers know that your branch is ready to be |
|
129 | This let's the other IPython developers know that your branch is ready to be | |
130 | reviewed and merged into the main development branch. During this review |
|
130 | reviewed and merged into the main development branch. During this review | |
131 | process, other developers will give you feedback and help you get your code |
|
131 | process, other developers will give you feedback and help you get your code | |
132 | ready to be merged. What types of things will we be looking for: |
|
132 | ready to be merged. What types of things will we be looking for: | |
133 |
|
133 | |||
134 | * All code is documented. |
|
134 | * All code is documented. | |
135 | * All code has tests. |
|
135 | * All code has tests. | |
136 | * The entire IPython test suite passes. |
|
136 | * The entire IPython test suite passes. | |
137 |
|
137 | |||
138 | Once your changes have been reviewed and approved, someone will merge them |
|
138 | Once your changes have been reviewed and approved, someone will merge them | |
139 | into the main development branch. |
|
139 | into the main development branch. | |
140 |
|
140 | |||
141 | Documentation |
|
141 | Documentation | |
142 | ============= |
|
142 | ============= | |
143 |
|
143 | |||
144 | Standalone documentation |
|
144 | Standalone documentation | |
145 | ------------------------ |
|
145 | ------------------------ | |
146 |
|
146 | |||
147 | All standalone documentation should be written in plain text (``.txt``) files |
|
147 | All standalone documentation should be written in plain text (``.txt``) files | |
148 | using reStructuredText [reStructuredText]_ for markup and formatting. All such |
|
148 | using reStructuredText [reStructuredText]_ for markup and formatting. All such | |
149 | documentation should be placed in directory :file:`docs/source` of the IPython |
|
149 | documentation should be placed in directory :file:`docs/source` of the IPython | |
150 | source tree. The documentation in this location will serve as the main source |
|
150 | source tree. The documentation in this location will serve as the main source | |
151 | for IPython documentation and all existing documentation should be converted |
|
151 | for IPython documentation and all existing documentation should be converted | |
152 | to this format. |
|
152 | to this format. | |
153 |
|
153 | |||
154 | To build the final documentation, we use Sphinx [Sphinx]_. Once you have Sphinx installed, you can build the html docs yourself by doing:: |
|
154 | To build the final documentation, we use Sphinx [Sphinx]_. Once you have Sphinx installed, you can build the html docs yourself by doing:: | |
155 |
|
155 | |||
156 | $ cd ipython-mybranch/docs |
|
156 | $ cd ipython-mybranch/docs | |
157 | $ make html |
|
157 | $ make html | |
158 |
|
158 | |||
159 | Docstring format |
|
159 | Docstring format | |
160 | ---------------- |
|
160 | ---------------- | |
161 |
|
161 | |||
162 | Good docstrings are very important. All new code should have docstrings that |
|
162 | Good docstrings are very important. All new code should have docstrings that | |
163 | are formatted using reStructuredText for markup and formatting, since it is |
|
163 | are formatted using reStructuredText for markup and formatting, since it is | |
164 | understood by a wide variety of tools. Details about using reStructuredText |
|
164 | understood by a wide variety of tools. Details about using reStructuredText | |
165 | for docstrings can be found `here |
|
165 | for docstrings can be found `here | |
166 | <http://epydoc.sourceforge.net/manual-othermarkup.html>`_. |
|
166 | <http://epydoc.sourceforge.net/manual-othermarkup.html>`_. | |
167 |
|
167 | |||
168 | Additional PEPs of interest regarding documentation of code: |
|
168 | Additional PEPs of interest regarding documentation of code: | |
169 |
|
169 | |||
170 | * `Docstring Conventions <http://www.python.org/peps/pep-0257.html>`_ |
|
170 | * `Docstring Conventions <http://www.python.org/peps/pep-0257.html>`_ | |
171 | * `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_ |
|
171 | * `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_ | |
172 | * `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_ |
|
172 | * `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_ | |
173 |
|
173 | |||
174 |
|
174 | |||
175 | Coding conventions |
|
175 | Coding conventions | |
176 | ================== |
|
176 | ================== | |
177 |
|
177 | |||
178 | General |
|
178 | General | |
179 | ------- |
|
179 | ------- | |
180 |
|
180 | |||
181 | In general, we'll try to follow the standard Python style conventions as |
|
181 | In general, we'll try to follow the standard Python style conventions as | |
182 | described here: |
|
182 | described here: | |
183 |
|
183 | |||
184 | * `Style Guide for Python Code <http://www.python.org/peps/pep-0008.html>`_ |
|
184 | * `Style Guide for Python Code <http://www.python.org/peps/pep-0008.html>`_ | |
185 |
|
185 | |||
186 |
|
186 | |||
187 | Other comments: |
|
187 | Other comments: | |
188 |
|
188 | |||
189 | * In a large file, top level classes and functions should be |
|
189 | * In a large file, top level classes and functions should be | |
190 | separated by 2-3 lines to make it easier to separate them visually. |
|
190 | separated by 2-3 lines to make it easier to separate them visually. | |
191 | * Use 4 spaces for indentation. |
|
191 | * Use 4 spaces for indentation. | |
192 | * Keep the ordering of methods the same in classes that have the same |
|
192 | * Keep the ordering of methods the same in classes that have the same | |
193 | methods. This is particularly true for classes that implement an interface. |
|
193 | methods. This is particularly true for classes that implement an interface. | |
194 |
|
194 | |||
195 | Naming conventions |
|
195 | Naming conventions | |
196 | ------------------ |
|
196 | ------------------ | |
197 |
|
197 | |||
198 | In terms of naming conventions, we'll follow the guidelines from the `Style |
|
198 | In terms of naming conventions, we'll follow the guidelines from the `Style | |
199 | Guide for Python Code`_. |
|
199 | Guide for Python Code`_. | |
200 |
|
200 | |||
201 | For all new IPython code (and much existing code is being refactored), we'll |
|
201 | For all new IPython code (and much existing code is being refactored), we'll | |
202 | use: |
|
202 | use: | |
203 |
|
203 | |||
204 | * All ``lowercase`` module names. |
|
204 | * All ``lowercase`` module names. | |
205 |
|
205 | |||
206 | * ``CamelCase`` for class names. |
|
206 | * ``CamelCase`` for class names. | |
207 |
|
207 | |||
208 | * ``lowercase_with_underscores`` for methods, functions, variables and |
|
208 | * ``lowercase_with_underscores`` for methods, functions, variables and | |
209 | attributes. |
|
209 | attributes. | |
210 |
|
210 | |||
211 | There are, however, some important exceptions to these rules. In some cases, |
|
211 | There are, however, some important exceptions to these rules. In some cases, | |
212 | IPython code will interface with packages (Twisted, Wx, Qt) that use other |
|
212 | IPython code will interface with packages (Twisted, Wx, Qt) that use other | |
213 | conventions. At some level this makes it impossible to adhere to our own |
|
213 | conventions. At some level this makes it impossible to adhere to our own | |
214 | standards at all times. In particular, when subclassing classes that use other |
|
214 | standards at all times. In particular, when subclassing classes that use other | |
215 | naming conventions, you must follow their naming conventions. To deal with |
|
215 | naming conventions, you must follow their naming conventions. To deal with | |
216 | cases like this, we propose the following policy: |
|
216 | cases like this, we propose the following policy: | |
217 |
|
217 | |||
218 | * If you are subclassing a class that uses different conventions, use its |
|
218 | * If you are subclassing a class that uses different conventions, use its | |
219 | naming conventions throughout your subclass. Thus, if you are creating a |
|
219 | naming conventions throughout your subclass. Thus, if you are creating a | |
220 | Twisted Protocol class, used Twisted's |
|
220 | Twisted Protocol class, used Twisted's | |
221 | ``namingSchemeForMethodsAndAttributes.`` |
|
221 | ``namingSchemeForMethodsAndAttributes.`` | |
222 |
|
222 | |||
223 | * All IPython's official interfaces should use our conventions. In some cases |
|
223 | * All IPython's official interfaces should use our conventions. In some cases | |
224 | this will mean that you need to provide shadow names (first implement |
|
224 | this will mean that you need to provide shadow names (first implement | |
225 | ``fooBar`` and then ``foo_bar = fooBar``). We want to avoid this at all |
|
225 | ``fooBar`` and then ``foo_bar = fooBar``). We want to avoid this at all | |
226 | costs, but it will probably be necessary at times. But, please use this |
|
226 | costs, but it will probably be necessary at times. But, please use this | |
227 | sparingly! |
|
227 | sparingly! | |
228 |
|
228 | |||
229 | Implementation-specific *private* methods will use |
|
229 | Implementation-specific *private* methods will use | |
230 | ``_single_underscore_prefix``. Names with a leading double underscore will |
|
230 | ``_single_underscore_prefix``. Names with a leading double underscore will | |
231 | *only* be used in special cases, as they makes subclassing difficult (such |
|
231 | *only* be used in special cases, as they makes subclassing difficult (such | |
232 | names are not easily seen by child classes). |
|
232 | names are not easily seen by child classes). | |
233 |
|
233 | |||
234 | Occasionally some run-in lowercase names are used, but mostly for very short |
|
234 | Occasionally some run-in lowercase names are used, but mostly for very short | |
235 | names or where we are implementing methods very similar to existing ones in a |
|
235 | names or where we are implementing methods very similar to existing ones in a | |
236 | base class (like ``runlines()`` where ``runsource()`` and ``runcode()`` had |
|
236 | base class (like ``runlines()`` where ``runsource()`` and ``runcode()`` had | |
237 | established precedent). |
|
237 | established precedent). | |
238 |
|
238 | |||
239 | The old IPython codebase has a big mix of classes and modules prefixed with an |
|
239 | The old IPython codebase has a big mix of classes and modules prefixed with an | |
240 | explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned |
|
240 | explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned | |
241 | upon, as namespaces offer cleaner prefixing. The only case where this approach |
|
241 | upon, as namespaces offer cleaner prefixing. The only case where this approach | |
242 | is justified is for classes which are expected to be imported into external |
|
242 | is justified is for classes which are expected to be imported into external | |
243 | namespaces and a very generic name (like Shell) is too likely to clash with |
|
243 | namespaces and a very generic name (like Shell) is too likely to clash with | |
244 | something else. We'll need to revisit this issue as we clean up and refactor |
|
244 | something else. We'll need to revisit this issue as we clean up and refactor | |
245 | the code, but in general we should remove as many unnecessary ``IP``/``ip`` |
|
245 | the code, but in general we should remove as many unnecessary ``IP``/``ip`` | |
246 | prefixes as possible. However, if a prefix seems absolutely necessary the more |
|
246 | prefixes as possible. However, if a prefix seems absolutely necessary the more | |
247 | specific ``IPY`` or ``ipy`` are preferred. |
|
247 | specific ``IPY`` or ``ipy`` are preferred. | |
248 |
|
248 | |||
249 | .. _devel_testing: |
|
249 | .. _devel_testing: | |
250 |
|
250 | |||
251 | Testing system |
|
251 | Testing system | |
252 | ============== |
|
252 | ============== | |
253 |
|
253 | |||
254 | It is extremely important that all code contributed to IPython has tests. |
|
254 | It is extremely important that all code contributed to IPython has tests. | |
255 | Tests should be written as unittests, doctests or as entities that the Nose |
|
255 | Tests should be written as unittests, doctests or as entities that the Nose | |
256 | [Nose]_ testing package will find. Regardless of how the tests are written, we |
|
256 | [Nose]_ testing package will find. Regardless of how the tests are written, we | |
257 | will use Nose for discovering and running the tests. Nose will be required to |
|
257 | will use Nose for discovering and running the tests. Nose will be required to | |
258 | run the IPython test suite, but will not be required to simply use IPython. |
|
258 | run the IPython test suite, but will not be required to simply use IPython. | |
259 |
|
259 | |||
260 | Tests of Twisted using code need to follow two additional guidelines: |
|
260 | Tests of Twisted using code need to follow two additional guidelines: | |
261 |
|
261 | |||
262 | 1. Twisted using tests should be written by subclassing the :class:`TestCase` |
|
262 | 1. Twisted using tests should be written by subclassing the :class:`TestCase` | |
263 | class that comes with :mod:`twisted.trial.unittest`. |
|
263 | class that comes with :mod:`twisted.trial.unittest`. | |
264 |
|
264 | |||
265 | 2. All :class:`Deferred` instances that are created in the test must be |
|
265 | 2. All :class:`Deferred` instances that are created in the test must be | |
266 | properly chained and the final one *must* be the return value of the test |
|
266 | properly chained and the final one *must* be the return value of the test | |
267 | method. |
|
267 | method. | |
268 |
|
268 | |||
269 | When these two things are done, Nose will be able to run the tests and the |
|
269 | When these two things are done, Nose will be able to run the tests and the | |
270 | twisted reactor will be handled correctly. |
|
270 | twisted reactor will be handled correctly. | |
271 |
|
271 | |||
272 | Each subpackage in IPython should have its own :file:`tests` directory that |
|
272 | Each subpackage in IPython should have its own :file:`tests` directory that | |
273 | contains all of the tests for that subpackage. This allows each subpackage to |
|
273 | contains all of the tests for that subpackage. This allows each subpackage to | |
274 | be self-contained. If a subpackage has any dependencies beyond the Python |
|
274 | be self-contained. If a subpackage has any dependencies beyond the Python | |
275 | standard library, the tests for that subpackage should be skipped if the |
|
275 | standard library, the tests for that subpackage should be skipped if the | |
276 | dependencies are not found. This is very important so users don't get tests |
|
276 | dependencies are not found. This is very important so users don't get tests | |
277 | failing simply because they don't have dependencies. |
|
277 | failing simply because they don't have dependencies. | |
278 |
|
278 | |||
279 | To run the IPython test suite, use the :command:`iptest` command that is |
|
279 | To run the IPython test suite, use the :command:`iptest` command that is | |
280 | installed with IPython:: |
|
280 | installed with IPython:: | |
281 |
|
281 | |||
282 | $ iptest |
|
282 | $ iptest | |
283 |
|
283 | |||
284 | This command runs Nose with the proper options and extensions. |
|
284 | This command runs Nose with the proper options and extensions. | |
285 |
|
285 | |||
286 | A few tips for writing tests: |
|
286 | A few tips for writing tests: | |
287 |
|
287 | |||
288 | * You can use IPython examples in your docstrings, including all IPython |
|
288 | * You can use IPython examples in your docstrings, including all IPython | |
289 | prompts. Rather than repeating it all here, see the files |
|
289 | prompts. Rather than repeating it all here, see the files | |
290 | :file:`dtexample.py` and :file:`test_ipdoctest.py` in the |
|
290 | :file:`dtexample.py` and :file:`test_ipdoctest.py` in the | |
291 | :mod:`IPython.testing.plugin` module for examples of how you can use plain |
|
291 | :mod:`IPython.testing.plugin` module for examples of how you can use plain | |
292 | Python or IPython prompts, and what to do with examples whose output could be |
|
292 | Python or IPython prompts, and what to do with examples whose output could be | |
293 | partly or completely random. |
|
293 | partly or completely random. | |
294 |
|
294 | |||
295 | * Use the decorators shipped in the :mod:`IPython.testing` package to tag tests |
|
295 | * Use the decorators shipped in the :mod:`IPython.testing` package to tag tests | |
296 | that may be platform-specific or otherwise may have restrictions. |
|
296 | that may be platform-specific or otherwise may have restrictions. | |
297 |
|
297 | |||
298 | * If a test isn't safe to run inside the main nose process (e.g. because it |
|
298 | * If a test isn't safe to run inside the main nose process (e.g. because it | |
299 | loads a GUI toolkit), consider running it in a subprocess and capturing its |
|
299 | loads a GUI toolkit), consider running it in a subprocess and capturing its | |
300 | output for evaluation and test decision later. Here is an example of how to |
|
300 | output for evaluation and test decision later. Here is an example of how to | |
301 | do it, by relying on the builtin ``_ip`` object that contains the public |
|
301 | do it, by relying on the builtin ``_ip`` object that contains the public | |
302 | IPython api as defined in :mod:`IPython.ipapi`:: |
|
302 | IPython api as defined in :mod:`IPython.ipapi`:: | |
303 |
|
303 | |||
304 | def test_obj_del(): |
|
304 | def test_obj_del(): | |
305 | """Test that object's __del__ methods are called on exit.""" |
|
305 | """Test that object's __del__ methods are called on exit.""" | |
306 | test_dir = os.path.dirname(__file__) |
|
306 | test_dir = os.path.dirname(__file__) | |
307 | del_file = os.path.join(test_dir,'obj_del.py') |
|
307 | del_file = os.path.join(test_dir,'obj_del.py') | |
308 | out = _ip.IP.getoutput('ipython %s' % del_file) |
|
308 | out = _ip.IP.getoutput('ipython %s' % del_file) | |
309 | nt.assert_equals(out,'object A deleted') |
|
309 | nt.assert_equals(out,'object A deleted') | |
310 |
|
310 | |||
311 |
|
311 | |||
312 | * In a file named ``test_X``, functions whose only test is their docstring (as |
|
312 | * In a file named ``test_X``, functions whose only test is their docstring (as | |
313 | a doctest) and which have no test functionality of their own, should be |
|
313 | a doctest) and which have no test functionality of their own, should be | |
314 | called *doctest_foo* instead of *test_foo*, otherwise they get double-counted |
|
314 | called *doctest_foo* instead of *test_foo*, otherwise they get double-counted | |
315 | (the empty function call is counted as a test, which just inflates tests |
|
315 | (the empty function call is counted as a test, which just inflates tests | |
316 | numbers artificially). This restriction does not apply to functions in files |
|
316 | numbers artificially). This restriction does not apply to functions in files | |
317 | with other names, due to how Nose discovers tests. |
|
317 | with other names, due to how Nose discovers tests. | |
318 |
|
318 | |||
319 | .. _devel_config: |
|
319 | .. _devel_config: | |
320 |
|
320 | |||
321 | Release checklist |
|
321 | Release checklist | |
322 | ================= |
|
322 | ================= | |
323 |
|
323 | |||
324 | Most of the release process is automated by the :file:`release` script in the |
|
324 | Most of the release process is automated by the :file:`release` script in the | |
325 | :file:`tools` directory. This is just a handy reminder for the release manager. |
|
325 | :file:`tools` directory. This is just a handy reminder for the release manager. | |
326 |
|
326 | |||
327 | #. Run the release script, which makes the tar.gz, eggs and Win32 .exe |
|
327 | #. Run the release script, which makes the tar.gz, eggs and Win32 .exe | |
328 | installer. It posts them to the site and registers the release with PyPI. |
|
328 | installer. It posts them to the site and registers the release with PyPI. | |
329 |
|
329 | |||
330 | #. Updating the website with announcements and links to the updated |
|
330 | #. Updating the website with announcements and links to the updated | |
331 | changes.txt in html form. Remember to put a short note both on the news |
|
331 | changes.txt in html form. Remember to put a short note both on the news | |
332 | page of the site and on Launcphad. |
|
332 | page of the site and on Launcphad. | |
333 |
|
333 | |||
334 | #. Drafting a short release announcement with i) highlights and ii) a link to |
|
334 | #. Drafting a short release announcement with i) highlights and ii) a link to | |
335 | the html changes.txt. |
|
335 | the html changes.txt. | |
336 |
|
336 | |||
337 | #. Make sure that the released version of the docs is live on the site. |
|
337 | #. Make sure that the released version of the docs is live on the site. | |
338 |
|
338 | |||
339 | #. Celebrate! |
|
339 | #. Celebrate! | |
340 |
|
340 | |||
|
341 | Porting to 3.0 | |||
|
342 | ============== | |||
|
343 | There are no definite plans for porting of IPython to python 3. The major | |||
|
344 | issue is the dependency on twisted framework for the networking/threading | |||
|
345 | stuff. It is possible that it the traditional IPython interactive console | |||
|
346 | could be ported more easily since it has no such dependency. Here are a few | |||
|
347 | things that will need to be considered when doing such a port especially | |||
|
348 | if we want to have a codebase that works directly on both 2.x and 3.x. | |||
|
349 | ||||
|
350 | 1. The syntax for exceptions changed (PEP 3110). The old | |||
|
351 | `except exc, var` changed to `except exc as var`. At last | |||
|
352 | count there was 78 occurences of this usage in the codebase | |||
|
353 | ||||
341 | .. [Bazaar] Bazaar. http://bazaar-vcs.org/ |
|
354 | .. [Bazaar] Bazaar. http://bazaar-vcs.org/ | |
342 | .. [Launchpad] Launchpad. http://www.launchpad.net/ipython |
|
355 | .. [Launchpad] Launchpad. http://www.launchpad.net/ipython | |
343 | .. [reStructuredText] reStructuredText. http://docutils.sourceforge.net/rst.html |
|
356 | .. [reStructuredText] reStructuredText. http://docutils.sourceforge.net/rst.html | |
344 | .. [Sphinx] Sphinx. http://sphinx.pocoo.org/ |
|
357 | .. [Sphinx] Sphinx. http://sphinx.pocoo.org/ | |
345 | .. [Nose] Nose: a discovery based unittest extension. http://code.google.com/p/python-nose/ |
|
358 | .. [Nose] Nose: a discovery based unittest extension. http://code.google.com/p/python-nose/ |
General Comments 0
You need to be logged in to leave comments.
Login now