Show More
@@ -1,263 +1,264 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Logger class for IPython's logging facilities. |
|
3 | Logger class for IPython's logging facilities. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 |
|
13 | |||
14 | #**************************************************************************** |
|
14 | #**************************************************************************** | |
15 | # Modules and globals |
|
15 | # Modules and globals | |
16 |
|
16 | |||
17 | # Python standard modules |
|
17 | # Python standard modules | |
18 | import glob |
|
18 | import glob | |
19 | import os |
|
19 | import os | |
20 | import time |
|
20 | import time | |
|
21 | import sys | |||
21 |
|
22 | |||
22 | #**************************************************************************** |
|
23 | #**************************************************************************** | |
23 | # FIXME: This class isn't a mixin anymore, but it still needs attributes from |
|
24 | # FIXME: This class isn't a mixin anymore, but it still needs attributes from | |
24 | # ipython and does input cache management. Finish cleanup later... |
|
25 | # ipython and does input cache management. Finish cleanup later... | |
25 |
|
26 | |||
26 | class Logger(object): |
|
27 | class Logger(object): | |
27 | """A Logfile class with different policies for file creation""" |
|
28 | """A Logfile class with different policies for file creation""" | |
28 |
|
29 | |||
29 | def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'): |
|
30 | def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'): | |
30 |
|
31 | |||
31 | self._i00,self._i,self._ii,self._iii = '','','','' |
|
32 | self._i00,self._i,self._ii,self._iii = '','','','' | |
32 |
|
33 | |||
33 | # this is the full ipython instance, we need some attributes from it |
|
34 | # this is the full ipython instance, we need some attributes from it | |
34 | # which won't exist until later. What a mess, clean up later... |
|
35 | # which won't exist until later. What a mess, clean up later... | |
35 | self.shell = shell |
|
36 | self.shell = shell | |
36 |
|
37 | |||
37 | self.logfname = logfname |
|
38 | self.logfname = logfname | |
38 | self.loghead = loghead |
|
39 | self.loghead = loghead | |
39 | self.logmode = logmode |
|
40 | self.logmode = logmode | |
40 | self.logfile = None |
|
41 | self.logfile = None | |
41 |
|
42 | |||
42 | # Whether to log raw or processed input |
|
43 | # Whether to log raw or processed input | |
43 | self.log_raw_input = False |
|
44 | self.log_raw_input = False | |
44 |
|
45 | |||
45 | # whether to also log output |
|
46 | # whether to also log output | |
46 | self.log_output = False |
|
47 | self.log_output = False | |
47 |
|
48 | |||
48 | # whether to put timestamps before each log entry |
|
49 | # whether to put timestamps before each log entry | |
49 | self.timestamp = False |
|
50 | self.timestamp = False | |
50 |
|
51 | |||
51 | # activity control flags |
|
52 | # activity control flags | |
52 | self.log_active = False |
|
53 | self.log_active = False | |
53 |
|
54 | |||
54 | # logmode is a validated property |
|
55 | # logmode is a validated property | |
55 | def _set_mode(self,mode): |
|
56 | def _set_mode(self,mode): | |
56 | if mode not in ['append','backup','global','over','rotate']: |
|
57 | if mode not in ['append','backup','global','over','rotate']: | |
57 | raise ValueError,'invalid log mode %s given' % mode |
|
58 | raise ValueError,'invalid log mode %s given' % mode | |
58 | self._logmode = mode |
|
59 | self._logmode = mode | |
59 |
|
60 | |||
60 | def _get_mode(self): |
|
61 | def _get_mode(self): | |
61 | return self._logmode |
|
62 | return self._logmode | |
62 |
|
63 | |||
63 | logmode = property(_get_mode,_set_mode) |
|
64 | logmode = property(_get_mode,_set_mode) | |
64 |
|
65 | |||
65 | def logstart(self,logfname=None,loghead=None,logmode=None, |
|
66 | def logstart(self,logfname=None,loghead=None,logmode=None, | |
66 | log_output=False,timestamp=False,log_raw_input=False): |
|
67 | log_output=False,timestamp=False,log_raw_input=False): | |
67 | """Generate a new log-file with a default header. |
|
68 | """Generate a new log-file with a default header. | |
68 |
|
69 | |||
69 | Raises RuntimeError if the log has already been started""" |
|
70 | Raises RuntimeError if the log has already been started""" | |
70 |
|
71 | |||
71 | if self.logfile is not None: |
|
72 | if self.logfile is not None: | |
72 | raise RuntimeError('Log file is already active: %s' % |
|
73 | raise RuntimeError('Log file is already active: %s' % | |
73 | self.logfname) |
|
74 | self.logfname) | |
74 |
|
75 | |||
75 | self.log_active = True |
|
76 | self.log_active = True | |
76 |
|
77 | |||
77 | # The parameters can override constructor defaults |
|
78 | # The parameters can override constructor defaults | |
78 | if logfname is not None: self.logfname = logfname |
|
79 | if logfname is not None: self.logfname = logfname | |
79 | if loghead is not None: self.loghead = loghead |
|
80 | if loghead is not None: self.loghead = loghead | |
80 | if logmode is not None: self.logmode = logmode |
|
81 | if logmode is not None: self.logmode = logmode | |
81 |
|
82 | |||
82 | # Parameters not part of the constructor |
|
83 | # Parameters not part of the constructor | |
83 | self.timestamp = timestamp |
|
84 | self.timestamp = timestamp | |
84 | self.log_output = log_output |
|
85 | self.log_output = log_output | |
85 | self.log_raw_input = log_raw_input |
|
86 | self.log_raw_input = log_raw_input | |
86 |
|
87 | |||
87 | # init depending on the log mode requested |
|
88 | # init depending on the log mode requested | |
88 | isfile = os.path.isfile |
|
89 | isfile = os.path.isfile | |
89 | logmode = self.logmode |
|
90 | logmode = self.logmode | |
90 |
|
91 | |||
91 | if logmode == 'append': |
|
92 | if logmode == 'append': | |
92 | self.logfile = open(self.logfname,'a') |
|
93 | self.logfile = open(self.logfname,'a') | |
93 |
|
94 | |||
94 | elif logmode == 'backup': |
|
95 | elif logmode == 'backup': | |
95 | if isfile(self.logfname): |
|
96 | if isfile(self.logfname): | |
96 | backup_logname = self.logfname+'~' |
|
97 | backup_logname = self.logfname+'~' | |
97 | # Manually remove any old backup, since os.rename may fail |
|
98 | # Manually remove any old backup, since os.rename may fail | |
98 | # under Windows. |
|
99 | # under Windows. | |
99 | if isfile(backup_logname): |
|
100 | if isfile(backup_logname): | |
100 | os.remove(backup_logname) |
|
101 | os.remove(backup_logname) | |
101 | os.rename(self.logfname,backup_logname) |
|
102 | os.rename(self.logfname,backup_logname) | |
102 | self.logfile = open(self.logfname,'w') |
|
103 | self.logfile = open(self.logfname,'w') | |
103 |
|
104 | |||
104 | elif logmode == 'global': |
|
105 | elif logmode == 'global': | |
105 | self.logfname = os.path.join(self.shell.home_dir,self.logfname) |
|
106 | self.logfname = os.path.join(self.shell.home_dir,self.logfname) | |
106 | self.logfile = open(self.logfname, 'a') |
|
107 | self.logfile = open(self.logfname, 'a') | |
107 |
|
108 | |||
108 | elif logmode == 'over': |
|
109 | elif logmode == 'over': | |
109 | if isfile(self.logfname): |
|
110 | if isfile(self.logfname): | |
110 | os.remove(self.logfname) |
|
111 | os.remove(self.logfname) | |
111 | self.logfile = open(self.logfname,'w') |
|
112 | self.logfile = open(self.logfname,'w') | |
112 |
|
113 | |||
113 | elif logmode == 'rotate': |
|
114 | elif logmode == 'rotate': | |
114 | if isfile(self.logfname): |
|
115 | if isfile(self.logfname): | |
115 | if isfile(self.logfname+'.001~'): |
|
116 | if isfile(self.logfname+'.001~'): | |
116 | old = glob.glob(self.logfname+'.*~') |
|
117 | old = glob.glob(self.logfname+'.*~') | |
117 | old.sort() |
|
118 | old.sort() | |
118 | old.reverse() |
|
119 | old.reverse() | |
119 | for f in old: |
|
120 | for f in old: | |
120 | root, ext = os.path.splitext(f) |
|
121 | root, ext = os.path.splitext(f) | |
121 | num = int(ext[1:-1])+1 |
|
122 | num = int(ext[1:-1])+1 | |
122 | os.rename(f, root+'.'+`num`.zfill(3)+'~') |
|
123 | os.rename(f, root+'.'+`num`.zfill(3)+'~') | |
123 | os.rename(self.logfname, self.logfname+'.001~') |
|
124 | os.rename(self.logfname, self.logfname+'.001~') | |
124 | self.logfile = open(self.logfname,'w') |
|
125 | self.logfile = open(self.logfname,'w') | |
125 |
|
126 | |||
126 | if logmode != 'append': |
|
127 | if logmode != 'append': | |
127 | self.logfile.write(self.loghead) |
|
128 | self.logfile.write(self.loghead) | |
128 |
|
129 | |||
129 | self.logfile.flush() |
|
130 | self.logfile.flush() | |
130 |
|
131 | |||
131 | def switch_log(self,val): |
|
132 | def switch_log(self,val): | |
132 | """Switch logging on/off. val should be ONLY a boolean.""" |
|
133 | """Switch logging on/off. val should be ONLY a boolean.""" | |
133 |
|
134 | |||
134 | if val not in [False,True,0,1]: |
|
135 | if val not in [False,True,0,1]: | |
135 | raise ValueError, \ |
|
136 | raise ValueError, \ | |
136 | 'Call switch_log ONLY with a boolean argument, not with:',val |
|
137 | 'Call switch_log ONLY with a boolean argument, not with:',val | |
137 |
|
138 | |||
138 | label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} |
|
139 | label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} | |
139 |
|
140 | |||
140 | if self.logfile is None: |
|
141 | if self.logfile is None: | |
141 | print """ |
|
142 | print """ | |
142 | Logging hasn't been started yet (use logstart for that). |
|
143 | Logging hasn't been started yet (use logstart for that). | |
143 |
|
144 | |||
144 | %logon/%logoff are for temporarily starting and stopping logging for a logfile |
|
145 | %logon/%logoff are for temporarily starting and stopping logging for a logfile | |
145 | which already exists. But you must first start the logging process with |
|
146 | which already exists. But you must first start the logging process with | |
146 | %logstart (optionally giving a logfile name).""" |
|
147 | %logstart (optionally giving a logfile name).""" | |
147 |
|
148 | |||
148 | else: |
|
149 | else: | |
149 | if self.log_active == val: |
|
150 | if self.log_active == val: | |
150 | print 'Logging is already',label[val] |
|
151 | print 'Logging is already',label[val] | |
151 | else: |
|
152 | else: | |
152 | print 'Switching logging',label[val] |
|
153 | print 'Switching logging',label[val] | |
153 | self.log_active = not self.log_active |
|
154 | self.log_active = not self.log_active | |
154 | self.log_active_out = self.log_active |
|
155 | self.log_active_out = self.log_active | |
155 |
|
156 | |||
156 | def logstate(self): |
|
157 | def logstate(self): | |
157 | """Print a status message about the logger.""" |
|
158 | """Print a status message about the logger.""" | |
158 | if self.logfile is None: |
|
159 | if self.logfile is None: | |
159 | print 'Logging has not been activated.' |
|
160 | print 'Logging has not been activated.' | |
160 | else: |
|
161 | else: | |
161 | state = self.log_active and 'active' or 'temporarily suspended' |
|
162 | state = self.log_active and 'active' or 'temporarily suspended' | |
162 | print 'Filename :',self.logfname |
|
163 | print 'Filename :',self.logfname | |
163 | print 'Mode :',self.logmode |
|
164 | print 'Mode :',self.logmode | |
164 | print 'Output logging :',self.log_output |
|
165 | print 'Output logging :',self.log_output | |
165 | print 'Raw input log :',self.log_raw_input |
|
166 | print 'Raw input log :',self.log_raw_input | |
166 | print 'Timestamping :',self.timestamp |
|
167 | print 'Timestamping :',self.timestamp | |
167 | print 'State :',state |
|
168 | print 'State :',state | |
168 |
|
169 | |||
169 | def log(self,line_ori,line_mod,continuation=None): |
|
170 | def log(self,line_ori,line_mod,continuation=None): | |
170 | """Write the line to a log and create input cache variables _i*. |
|
171 | """Write the line to a log and create input cache variables _i*. | |
171 |
|
172 | |||
172 | Inputs: |
|
173 | Inputs: | |
173 |
|
174 | |||
174 | - line_ori: unmodified input line from the user. This is not |
|
175 | - line_ori: unmodified input line from the user. This is not | |
175 | necessarily valid Python. |
|
176 | necessarily valid Python. | |
176 |
|
177 | |||
177 | - line_mod: possibly modified input, such as the transformations made |
|
178 | - line_mod: possibly modified input, such as the transformations made | |
178 | by input prefilters or input handlers of various kinds. This should |
|
179 | by input prefilters or input handlers of various kinds. This should | |
179 | always be valid Python. |
|
180 | always be valid Python. | |
180 |
|
181 | |||
181 | - continuation: if True, indicates this is part of multi-line input.""" |
|
182 | - continuation: if True, indicates this is part of multi-line input.""" | |
182 |
|
183 | |||
183 | # update the auto _i tables |
|
184 | # update the auto _i tables | |
184 | #print '***logging line',line_mod # dbg |
|
185 | #print '***logging line',line_mod # dbg | |
185 | #print '***cache_count', self.shell.outputcache.prompt_count # dbg |
|
186 | #print '***cache_count', self.shell.outputcache.prompt_count # dbg | |
186 | try: |
|
187 | try: | |
187 | input_hist = self.shell.user_ns['_ih'] |
|
188 | input_hist = self.shell.user_ns['_ih'] | |
188 | except: |
|
189 | except: | |
189 | #print 'userns:',self.shell.user_ns.keys() # dbg |
|
190 | #print 'userns:',self.shell.user_ns.keys() # dbg | |
190 | return |
|
191 | return | |
191 |
|
192 | |||
192 | out_cache = self.shell.outputcache |
|
193 | out_cache = self.shell.outputcache | |
193 |
|
194 | |||
194 | # add blank lines if the input cache fell out of sync. |
|
195 | # add blank lines if the input cache fell out of sync. | |
195 | if out_cache.do_full_cache and \ |
|
196 | if out_cache.do_full_cache and \ | |
196 | out_cache.prompt_count +1 > len(input_hist): |
|
197 | out_cache.prompt_count +1 > len(input_hist): | |
197 | input_hist.extend(['\n'] * (out_cache.prompt_count - len(input_hist))) |
|
198 | input_hist.extend(['\n'] * (out_cache.prompt_count - len(input_hist))) | |
198 |
|
199 | |||
199 | if not continuation and line_mod: |
|
200 | if not continuation and line_mod: | |
200 | self._iii = self._ii |
|
201 | self._iii = self._ii | |
201 | self._ii = self._i |
|
202 | self._ii = self._i | |
202 | self._i = self._i00 |
|
203 | self._i = self._i00 | |
203 | # put back the final \n of every input line |
|
204 | # put back the final \n of every input line | |
204 | self._i00 = line_mod+'\n' |
|
205 | self._i00 = line_mod+'\n' | |
205 | #print 'Logging input:<%s>' % line_mod # dbg |
|
206 | #print 'Logging input:<%s>' % line_mod # dbg | |
206 | input_hist.append(self._i00) |
|
207 | input_hist.append(self._i00) | |
207 | #print '---[%s]' % (len(input_hist)-1,) # dbg |
|
208 | #print '---[%s]' % (len(input_hist)-1,) # dbg | |
208 |
|
209 | |||
209 | # hackish access to top-level namespace to create _i1,_i2... dynamically |
|
210 | # hackish access to top-level namespace to create _i1,_i2... dynamically | |
210 | to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii} |
|
211 | to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii} | |
211 | if self.shell.outputcache.do_full_cache: |
|
212 | if self.shell.outputcache.do_full_cache: | |
212 | in_num = self.shell.outputcache.prompt_count |
|
213 | in_num = self.shell.outputcache.prompt_count | |
213 |
|
214 | |||
214 | # but if the opposite is true (a macro can produce multiple inputs |
|
215 | # but if the opposite is true (a macro can produce multiple inputs | |
215 | # with no output display called), then bring the output counter in |
|
216 | # with no output display called), then bring the output counter in | |
216 | # sync: |
|
217 | # sync: | |
217 | last_num = len(input_hist)-1 |
|
218 | last_num = len(input_hist)-1 | |
218 | if in_num != last_num: |
|
219 | if in_num != last_num: | |
219 | in_num = self.shell.outputcache.prompt_count = last_num |
|
220 | in_num = self.shell.outputcache.prompt_count = last_num | |
220 | new_i = '_i%s' % in_num |
|
221 | new_i = '_i%s' % in_num | |
221 | if continuation: |
|
222 | if continuation: | |
222 | self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod) |
|
223 | self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod) | |
223 | input_hist[in_num] = self._i00 |
|
224 | input_hist[in_num] = self._i00 | |
224 | to_main[new_i] = self._i00 |
|
225 | to_main[new_i] = self._i00 | |
225 | self.shell.user_ns.update(to_main) |
|
226 | self.shell.user_ns.update(to_main) | |
226 |
|
227 | |||
227 | # Write the log line, but decide which one according to the |
|
228 | # Write the log line, but decide which one according to the | |
228 | # log_raw_input flag, set when the log is started. |
|
229 | # log_raw_input flag, set when the log is started. | |
229 | if self.log_raw_input: |
|
230 | if self.log_raw_input: | |
230 | self.log_write(line_ori) |
|
231 | self.log_write(line_ori) | |
231 | else: |
|
232 | else: | |
232 | self.log_write(line_mod) |
|
233 | self.log_write(line_mod) | |
233 |
|
234 | |||
234 | def log_write(self,data,kind='input'): |
|
235 | def log_write(self,data,kind='input'): | |
235 | """Write data to the log file, if active""" |
|
236 | """Write data to the log file, if active""" | |
236 |
|
237 | |||
237 | #print 'data: %r' % data # dbg |
|
238 | #print 'data: %r' % data # dbg | |
238 | if self.log_active and data: |
|
239 | if self.log_active and data: | |
239 | write = self.logfile.write |
|
240 | write = self.logfile.write | |
240 | if kind=='input': |
|
241 | if kind=='input': | |
241 | if self.timestamp: |
|
242 | if self.timestamp: | |
242 | write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', |
|
243 | write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', | |
243 | time.localtime())) |
|
244 | time.localtime())) | |
244 | write('%s\n' % data) |
|
245 | write('%s\n' % data.encode(sys.stdin.encoding)) | |
245 | elif kind=='output' and self.log_output: |
|
246 | elif kind=='output' and self.log_output: | |
246 | odata = '\n'.join(['#[Out]# %s' % s |
|
247 | odata = '\n'.join(['#[Out]# %s' % s | |
247 | for s in data.split('\n')]) |
|
248 | for s in data.split('\n')]) | |
248 | write('%s\n' % odata) |
|
249 | write('%s\n' % odata) | |
249 | self.logfile.flush() |
|
250 | self.logfile.flush() | |
250 |
|
251 | |||
251 | def logstop(self): |
|
252 | def logstop(self): | |
252 | """Fully stop logging and close log file. |
|
253 | """Fully stop logging and close log file. | |
253 |
|
254 | |||
254 | In order to start logging again, a new logstart() call needs to be |
|
255 | In order to start logging again, a new logstart() call needs to be | |
255 | made, possibly (though not necessarily) with a new filename, mode and |
|
256 | made, possibly (though not necessarily) with a new filename, mode and | |
256 | other options.""" |
|
257 | other options.""" | |
257 |
|
258 | |||
258 | self.logfile.close() |
|
259 | self.logfile.close() | |
259 | self.logfile = None |
|
260 | self.logfile = None | |
260 | self.log_active = False |
|
261 | self.log_active = False | |
261 |
|
262 | |||
262 | # For backwards compatibility, in case anyone was using this. |
|
263 | # For backwards compatibility, in case anyone was using this. | |
263 | close_log = logstop |
|
264 | close_log = logstop |
@@ -1,3540 +1,3540 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #***************************************************************************** |
|
5 | #***************************************************************************** | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #***************************************************************************** |
|
11 | #***************************************************************************** | |
12 |
|
12 | |||
13 | #**************************************************************************** |
|
13 | #**************************************************************************** | |
14 | # Modules and globals |
|
14 | # Modules and globals | |
15 |
|
15 | |||
16 | # Python standard modules |
|
16 | # Python standard modules | |
17 | import __builtin__ |
|
17 | import __builtin__ | |
18 | import __future__ |
|
18 | import __future__ | |
19 | import bdb |
|
19 | import bdb | |
20 | import inspect |
|
20 | import inspect | |
21 | import os |
|
21 | import os | |
22 | import pdb |
|
22 | import pdb | |
23 | import pydoc |
|
23 | import pydoc | |
24 | import sys |
|
24 | import sys | |
25 | import re |
|
25 | import re | |
26 | import tempfile |
|
26 | import tempfile | |
27 | import time |
|
27 | import time | |
28 | import cPickle as pickle |
|
28 | import cPickle as pickle | |
29 | import textwrap |
|
29 | import textwrap | |
30 | from cStringIO import StringIO |
|
30 | from cStringIO import StringIO | |
31 | from getopt import getopt,GetoptError |
|
31 | from getopt import getopt,GetoptError | |
32 | from pprint import pprint, pformat |
|
32 | from pprint import pprint, pformat | |
33 |
|
33 | |||
34 | # cProfile was added in Python2.5 |
|
34 | # cProfile was added in Python2.5 | |
35 | try: |
|
35 | try: | |
36 | import cProfile as profile |
|
36 | import cProfile as profile | |
37 | import pstats |
|
37 | import pstats | |
38 | except ImportError: |
|
38 | except ImportError: | |
39 | # profile isn't bundled by default in Debian for license reasons |
|
39 | # profile isn't bundled by default in Debian for license reasons | |
40 | try: |
|
40 | try: | |
41 | import profile,pstats |
|
41 | import profile,pstats | |
42 | except ImportError: |
|
42 | except ImportError: | |
43 | profile = pstats = None |
|
43 | profile = pstats = None | |
44 |
|
44 | |||
45 | # print_function was added to __future__ in Python2.6, remove this when we drop |
|
45 | # print_function was added to __future__ in Python2.6, remove this when we drop | |
46 | # 2.5 compatibility |
|
46 | # 2.5 compatibility | |
47 | if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'): |
|
47 | if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'): | |
48 | __future__.CO_FUTURE_PRINT_FUNCTION = 65536 |
|
48 | __future__.CO_FUTURE_PRINT_FUNCTION = 65536 | |
49 |
|
49 | |||
50 | # Homebrewed |
|
50 | # Homebrewed | |
51 | import IPython |
|
51 | import IPython | |
52 | from IPython import Debugger, OInspect, wildcard |
|
52 | from IPython import Debugger, OInspect, wildcard | |
53 | from IPython.FakeModule import FakeModule |
|
53 | from IPython.FakeModule import FakeModule | |
54 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
54 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
55 | from IPython.PyColorize import Parser |
|
55 | from IPython.PyColorize import Parser | |
56 | from IPython.ipstruct import Struct |
|
56 | from IPython.ipstruct import Struct | |
57 | from IPython.macro import Macro |
|
57 | from IPython.macro import Macro | |
58 | from IPython.genutils import * |
|
58 | from IPython.genutils import * | |
59 | from IPython import platutils |
|
59 | from IPython import platutils | |
60 | import IPython.generics |
|
60 | import IPython.generics | |
61 | import IPython.ipapi |
|
61 | import IPython.ipapi | |
62 | from IPython.ipapi import UsageError |
|
62 | from IPython.ipapi import UsageError | |
63 | from IPython.testing import decorators as testdec |
|
63 | from IPython.testing import decorators as testdec | |
64 |
|
64 | |||
65 | #*************************************************************************** |
|
65 | #*************************************************************************** | |
66 | # Utility functions |
|
66 | # Utility functions | |
67 | def on_off(tag): |
|
67 | def on_off(tag): | |
68 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
68 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
69 | return ['OFF','ON'][tag] |
|
69 | return ['OFF','ON'][tag] | |
70 |
|
70 | |||
71 | class Bunch: pass |
|
71 | class Bunch: pass | |
72 |
|
72 | |||
73 | def compress_dhist(dh): |
|
73 | def compress_dhist(dh): | |
74 | head, tail = dh[:-10], dh[-10:] |
|
74 | head, tail = dh[:-10], dh[-10:] | |
75 |
|
75 | |||
76 | newhead = [] |
|
76 | newhead = [] | |
77 | done = set() |
|
77 | done = set() | |
78 | for h in head: |
|
78 | for h in head: | |
79 | if h in done: |
|
79 | if h in done: | |
80 | continue |
|
80 | continue | |
81 | newhead.append(h) |
|
81 | newhead.append(h) | |
82 | done.add(h) |
|
82 | done.add(h) | |
83 |
|
83 | |||
84 | return newhead + tail |
|
84 | return newhead + tail | |
85 |
|
85 | |||
86 |
|
86 | |||
87 | #*************************************************************************** |
|
87 | #*************************************************************************** | |
88 | # Main class implementing Magic functionality |
|
88 | # Main class implementing Magic functionality | |
89 | class Magic: |
|
89 | class Magic: | |
90 | """Magic functions for InteractiveShell. |
|
90 | """Magic functions for InteractiveShell. | |
91 |
|
91 | |||
92 | Shell functions which can be reached as %function_name. All magic |
|
92 | Shell functions which can be reached as %function_name. All magic | |
93 | functions should accept a string, which they can parse for their own |
|
93 | functions should accept a string, which they can parse for their own | |
94 | needs. This can make some functions easier to type, eg `%cd ../` |
|
94 | needs. This can make some functions easier to type, eg `%cd ../` | |
95 | vs. `%cd("../")` |
|
95 | vs. `%cd("../")` | |
96 |
|
96 | |||
97 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
97 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
98 | at the command line, but it is is needed in the definition. """ |
|
98 | at the command line, but it is is needed in the definition. """ | |
99 |
|
99 | |||
100 | # class globals |
|
100 | # class globals | |
101 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
101 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
102 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
102 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
103 |
|
103 | |||
104 | #...................................................................... |
|
104 | #...................................................................... | |
105 | # some utility functions |
|
105 | # some utility functions | |
106 |
|
106 | |||
107 | def __init__(self,shell): |
|
107 | def __init__(self,shell): | |
108 |
|
108 | |||
109 | self.options_table = {} |
|
109 | self.options_table = {} | |
110 | if profile is None: |
|
110 | if profile is None: | |
111 | self.magic_prun = self.profile_missing_notice |
|
111 | self.magic_prun = self.profile_missing_notice | |
112 | self.shell = shell |
|
112 | self.shell = shell | |
113 |
|
113 | |||
114 | # namespace for holding state we may need |
|
114 | # namespace for holding state we may need | |
115 | self._magic_state = Bunch() |
|
115 | self._magic_state = Bunch() | |
116 |
|
116 | |||
117 | def profile_missing_notice(self, *args, **kwargs): |
|
117 | def profile_missing_notice(self, *args, **kwargs): | |
118 | error("""\ |
|
118 | error("""\ | |
119 | The profile module could not be found. It has been removed from the standard |
|
119 | The profile module could not be found. It has been removed from the standard | |
120 | python packages because of its non-free license. To use profiling, install the |
|
120 | python packages because of its non-free license. To use profiling, install the | |
121 | python-profiler package from non-free.""") |
|
121 | python-profiler package from non-free.""") | |
122 |
|
122 | |||
123 | def default_option(self,fn,optstr): |
|
123 | def default_option(self,fn,optstr): | |
124 | """Make an entry in the options_table for fn, with value optstr""" |
|
124 | """Make an entry in the options_table for fn, with value optstr""" | |
125 |
|
125 | |||
126 | if fn not in self.lsmagic(): |
|
126 | if fn not in self.lsmagic(): | |
127 | error("%s is not a magic function" % fn) |
|
127 | error("%s is not a magic function" % fn) | |
128 | self.options_table[fn] = optstr |
|
128 | self.options_table[fn] = optstr | |
129 |
|
129 | |||
130 | def lsmagic(self): |
|
130 | def lsmagic(self): | |
131 | """Return a list of currently available magic functions. |
|
131 | """Return a list of currently available magic functions. | |
132 |
|
132 | |||
133 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
133 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
134 | ['magic_ls','magic_cd',...]""" |
|
134 | ['magic_ls','magic_cd',...]""" | |
135 |
|
135 | |||
136 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
136 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
137 |
|
137 | |||
138 | # magics in class definition |
|
138 | # magics in class definition | |
139 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
139 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
140 | callable(Magic.__dict__[fn]) |
|
140 | callable(Magic.__dict__[fn]) | |
141 | # in instance namespace (run-time user additions) |
|
141 | # in instance namespace (run-time user additions) | |
142 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
142 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
143 | callable(self.__dict__[fn]) |
|
143 | callable(self.__dict__[fn]) | |
144 | # and bound magics by user (so they can access self): |
|
144 | # and bound magics by user (so they can access self): | |
145 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
145 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
146 | callable(self.__class__.__dict__[fn]) |
|
146 | callable(self.__class__.__dict__[fn]) | |
147 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
147 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
148 | filter(inst_magic,self.__dict__.keys()) + \ |
|
148 | filter(inst_magic,self.__dict__.keys()) + \ | |
149 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
149 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
150 | out = [] |
|
150 | out = [] | |
151 | for fn in set(magics): |
|
151 | for fn in set(magics): | |
152 | out.append(fn.replace('magic_','',1)) |
|
152 | out.append(fn.replace('magic_','',1)) | |
153 | out.sort() |
|
153 | out.sort() | |
154 | return out |
|
154 | return out | |
155 |
|
155 | |||
156 | def extract_input_slices(self,slices,raw=False): |
|
156 | def extract_input_slices(self,slices,raw=False): | |
157 | """Return as a string a set of input history slices. |
|
157 | """Return as a string a set of input history slices. | |
158 |
|
158 | |||
159 | Inputs: |
|
159 | Inputs: | |
160 |
|
160 | |||
161 | - slices: the set of slices is given as a list of strings (like |
|
161 | - slices: the set of slices is given as a list of strings (like | |
162 | ['1','4:8','9'], since this function is for use by magic functions |
|
162 | ['1','4:8','9'], since this function is for use by magic functions | |
163 | which get their arguments as strings. |
|
163 | which get their arguments as strings. | |
164 |
|
164 | |||
165 | Optional inputs: |
|
165 | Optional inputs: | |
166 |
|
166 | |||
167 | - raw(False): by default, the processed input is used. If this is |
|
167 | - raw(False): by default, the processed input is used. If this is | |
168 | true, the raw input history is used instead. |
|
168 | true, the raw input history is used instead. | |
169 |
|
169 | |||
170 | Note that slices can be called with two notations: |
|
170 | Note that slices can be called with two notations: | |
171 |
|
171 | |||
172 | N:M -> standard python form, means including items N...(M-1). |
|
172 | N:M -> standard python form, means including items N...(M-1). | |
173 |
|
173 | |||
174 | N-M -> include items N..M (closed endpoint).""" |
|
174 | N-M -> include items N..M (closed endpoint).""" | |
175 |
|
175 | |||
176 | if raw: |
|
176 | if raw: | |
177 | hist = self.shell.input_hist_raw |
|
177 | hist = self.shell.input_hist_raw | |
178 | else: |
|
178 | else: | |
179 | hist = self.shell.input_hist |
|
179 | hist = self.shell.input_hist | |
180 |
|
180 | |||
181 | cmds = [] |
|
181 | cmds = [] | |
182 | for chunk in slices: |
|
182 | for chunk in slices: | |
183 | if ':' in chunk: |
|
183 | if ':' in chunk: | |
184 | ini,fin = map(int,chunk.split(':')) |
|
184 | ini,fin = map(int,chunk.split(':')) | |
185 | elif '-' in chunk: |
|
185 | elif '-' in chunk: | |
186 | ini,fin = map(int,chunk.split('-')) |
|
186 | ini,fin = map(int,chunk.split('-')) | |
187 | fin += 1 |
|
187 | fin += 1 | |
188 | else: |
|
188 | else: | |
189 | ini = int(chunk) |
|
189 | ini = int(chunk) | |
190 | fin = ini+1 |
|
190 | fin = ini+1 | |
191 | cmds.append(hist[ini:fin]) |
|
191 | cmds.append(hist[ini:fin]) | |
192 | return cmds |
|
192 | return cmds | |
193 |
|
193 | |||
194 | def _ofind(self, oname, namespaces=None): |
|
194 | def _ofind(self, oname, namespaces=None): | |
195 | """Find an object in the available namespaces. |
|
195 | """Find an object in the available namespaces. | |
196 |
|
196 | |||
197 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
197 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
198 |
|
198 | |||
199 | Has special code to detect magic functions. |
|
199 | Has special code to detect magic functions. | |
200 | """ |
|
200 | """ | |
201 | oname = oname.strip() |
|
201 | oname = oname.strip() | |
202 | alias_ns = None |
|
202 | alias_ns = None | |
203 | if namespaces is None: |
|
203 | if namespaces is None: | |
204 | # Namespaces to search in: |
|
204 | # Namespaces to search in: | |
205 | # Put them in a list. The order is important so that we |
|
205 | # Put them in a list. The order is important so that we | |
206 | # find things in the same order that Python finds them. |
|
206 | # find things in the same order that Python finds them. | |
207 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
207 | namespaces = [ ('Interactive', self.shell.user_ns), | |
208 | ('IPython internal', self.shell.internal_ns), |
|
208 | ('IPython internal', self.shell.internal_ns), | |
209 | ('Python builtin', __builtin__.__dict__), |
|
209 | ('Python builtin', __builtin__.__dict__), | |
210 | ('Alias', self.shell.alias_table), |
|
210 | ('Alias', self.shell.alias_table), | |
211 | ] |
|
211 | ] | |
212 | alias_ns = self.shell.alias_table |
|
212 | alias_ns = self.shell.alias_table | |
213 |
|
213 | |||
214 | # initialize results to 'null' |
|
214 | # initialize results to 'null' | |
215 | found = False; obj = None; ospace = None; ds = None; |
|
215 | found = False; obj = None; ospace = None; ds = None; | |
216 | ismagic = False; isalias = False; parent = None |
|
216 | ismagic = False; isalias = False; parent = None | |
217 |
|
217 | |||
218 | # We need to special-case 'print', which as of python2.6 registers as a |
|
218 | # We need to special-case 'print', which as of python2.6 registers as a | |
219 | # function but should only be treated as one if print_function was |
|
219 | # function but should only be treated as one if print_function was | |
220 | # loaded with a future import. In this case, just bail. |
|
220 | # loaded with a future import. In this case, just bail. | |
221 | if (oname == 'print' and not (self.shell.compile.compiler.flags & |
|
221 | if (oname == 'print' and not (self.shell.compile.compiler.flags & | |
222 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
222 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
223 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
223 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
224 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
224 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
225 |
|
225 | |||
226 | # Look for the given name by splitting it in parts. If the head is |
|
226 | # Look for the given name by splitting it in parts. If the head is | |
227 | # found, then we look for all the remaining parts as members, and only |
|
227 | # found, then we look for all the remaining parts as members, and only | |
228 | # declare success if we can find them all. |
|
228 | # declare success if we can find them all. | |
229 | oname_parts = oname.split('.') |
|
229 | oname_parts = oname.split('.') | |
230 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
230 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
231 | for nsname,ns in namespaces: |
|
231 | for nsname,ns in namespaces: | |
232 | try: |
|
232 | try: | |
233 | obj = ns[oname_head] |
|
233 | obj = ns[oname_head] | |
234 | except KeyError: |
|
234 | except KeyError: | |
235 | continue |
|
235 | continue | |
236 | else: |
|
236 | else: | |
237 | #print 'oname_rest:', oname_rest # dbg |
|
237 | #print 'oname_rest:', oname_rest # dbg | |
238 | for part in oname_rest: |
|
238 | for part in oname_rest: | |
239 | try: |
|
239 | try: | |
240 | parent = obj |
|
240 | parent = obj | |
241 | obj = getattr(obj,part) |
|
241 | obj = getattr(obj,part) | |
242 | except: |
|
242 | except: | |
243 | # Blanket except b/c some badly implemented objects |
|
243 | # Blanket except b/c some badly implemented objects | |
244 | # allow __getattr__ to raise exceptions other than |
|
244 | # allow __getattr__ to raise exceptions other than | |
245 | # AttributeError, which then crashes IPython. |
|
245 | # AttributeError, which then crashes IPython. | |
246 | break |
|
246 | break | |
247 | else: |
|
247 | else: | |
248 | # If we finish the for loop (no break), we got all members |
|
248 | # If we finish the for loop (no break), we got all members | |
249 | found = True |
|
249 | found = True | |
250 | ospace = nsname |
|
250 | ospace = nsname | |
251 | if ns == alias_ns: |
|
251 | if ns == alias_ns: | |
252 | isalias = True |
|
252 | isalias = True | |
253 | break # namespace loop |
|
253 | break # namespace loop | |
254 |
|
254 | |||
255 | # Try to see if it's magic |
|
255 | # Try to see if it's magic | |
256 | if not found: |
|
256 | if not found: | |
257 | if oname.startswith(self.shell.ESC_MAGIC): |
|
257 | if oname.startswith(self.shell.ESC_MAGIC): | |
258 | oname = oname[1:] |
|
258 | oname = oname[1:] | |
259 | obj = getattr(self,'magic_'+oname,None) |
|
259 | obj = getattr(self,'magic_'+oname,None) | |
260 | if obj is not None: |
|
260 | if obj is not None: | |
261 | found = True |
|
261 | found = True | |
262 | ospace = 'IPython internal' |
|
262 | ospace = 'IPython internal' | |
263 | ismagic = True |
|
263 | ismagic = True | |
264 |
|
264 | |||
265 | # Last try: special-case some literals like '', [], {}, etc: |
|
265 | # Last try: special-case some literals like '', [], {}, etc: | |
266 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
266 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
267 | obj = eval(oname_head) |
|
267 | obj = eval(oname_head) | |
268 | found = True |
|
268 | found = True | |
269 | ospace = 'Interactive' |
|
269 | ospace = 'Interactive' | |
270 |
|
270 | |||
271 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
271 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
272 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
272 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
273 |
|
273 | |||
274 | def arg_err(self,func): |
|
274 | def arg_err(self,func): | |
275 | """Print docstring if incorrect arguments were passed""" |
|
275 | """Print docstring if incorrect arguments were passed""" | |
276 | print 'Error in arguments:' |
|
276 | print 'Error in arguments:' | |
277 | print OInspect.getdoc(func) |
|
277 | print OInspect.getdoc(func) | |
278 |
|
278 | |||
279 | def format_latex(self,strng): |
|
279 | def format_latex(self,strng): | |
280 | """Format a string for latex inclusion.""" |
|
280 | """Format a string for latex inclusion.""" | |
281 |
|
281 | |||
282 | # Characters that need to be escaped for latex: |
|
282 | # Characters that need to be escaped for latex: | |
283 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
283 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
284 | # Magic command names as headers: |
|
284 | # Magic command names as headers: | |
285 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
285 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
286 | re.MULTILINE) |
|
286 | re.MULTILINE) | |
287 | # Magic commands |
|
287 | # Magic commands | |
288 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
288 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
289 | re.MULTILINE) |
|
289 | re.MULTILINE) | |
290 | # Paragraph continue |
|
290 | # Paragraph continue | |
291 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
291 | par_re = re.compile(r'\\$',re.MULTILINE) | |
292 |
|
292 | |||
293 | # The "\n" symbol |
|
293 | # The "\n" symbol | |
294 | newline_re = re.compile(r'\\n') |
|
294 | newline_re = re.compile(r'\\n') | |
295 |
|
295 | |||
296 | # Now build the string for output: |
|
296 | # Now build the string for output: | |
297 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
297 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
298 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
298 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
299 | strng) |
|
299 | strng) | |
300 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
300 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
301 | strng = par_re.sub(r'\\\\',strng) |
|
301 | strng = par_re.sub(r'\\\\',strng) | |
302 | strng = escape_re.sub(r'\\\1',strng) |
|
302 | strng = escape_re.sub(r'\\\1',strng) | |
303 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
303 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
304 | return strng |
|
304 | return strng | |
305 |
|
305 | |||
306 | def format_screen(self,strng): |
|
306 | def format_screen(self,strng): | |
307 | """Format a string for screen printing. |
|
307 | """Format a string for screen printing. | |
308 |
|
308 | |||
309 | This removes some latex-type format codes.""" |
|
309 | This removes some latex-type format codes.""" | |
310 | # Paragraph continue |
|
310 | # Paragraph continue | |
311 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
311 | par_re = re.compile(r'\\$',re.MULTILINE) | |
312 | strng = par_re.sub('',strng) |
|
312 | strng = par_re.sub('',strng) | |
313 | return strng |
|
313 | return strng | |
314 |
|
314 | |||
315 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
315 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
316 | """Parse options passed to an argument string. |
|
316 | """Parse options passed to an argument string. | |
317 |
|
317 | |||
318 | The interface is similar to that of getopt(), but it returns back a |
|
318 | The interface is similar to that of getopt(), but it returns back a | |
319 | Struct with the options as keys and the stripped argument string still |
|
319 | Struct with the options as keys and the stripped argument string still | |
320 | as a string. |
|
320 | as a string. | |
321 |
|
321 | |||
322 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
322 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
323 | This allows us to easily expand variables, glob files, quote |
|
323 | This allows us to easily expand variables, glob files, quote | |
324 | arguments, etc. |
|
324 | arguments, etc. | |
325 |
|
325 | |||
326 | Options: |
|
326 | Options: | |
327 | -mode: default 'string'. If given as 'list', the argument string is |
|
327 | -mode: default 'string'. If given as 'list', the argument string is | |
328 | returned as a list (split on whitespace) instead of a string. |
|
328 | returned as a list (split on whitespace) instead of a string. | |
329 |
|
329 | |||
330 | -list_all: put all option values in lists. Normally only options |
|
330 | -list_all: put all option values in lists. Normally only options | |
331 | appearing more than once are put in a list. |
|
331 | appearing more than once are put in a list. | |
332 |
|
332 | |||
333 | -posix (True): whether to split the input line in POSIX mode or not, |
|
333 | -posix (True): whether to split the input line in POSIX mode or not, | |
334 | as per the conventions outlined in the shlex module from the |
|
334 | as per the conventions outlined in the shlex module from the | |
335 | standard library.""" |
|
335 | standard library.""" | |
336 |
|
336 | |||
337 | # inject default options at the beginning of the input line |
|
337 | # inject default options at the beginning of the input line | |
338 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
338 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
339 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
339 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
340 |
|
340 | |||
341 | mode = kw.get('mode','string') |
|
341 | mode = kw.get('mode','string') | |
342 | if mode not in ['string','list']: |
|
342 | if mode not in ['string','list']: | |
343 | raise ValueError,'incorrect mode given: %s' % mode |
|
343 | raise ValueError,'incorrect mode given: %s' % mode | |
344 | # Get options |
|
344 | # Get options | |
345 | list_all = kw.get('list_all',0) |
|
345 | list_all = kw.get('list_all',0) | |
346 | posix = kw.get('posix',True) |
|
346 | posix = kw.get('posix',True) | |
347 |
|
347 | |||
348 | # Check if we have more than one argument to warrant extra processing: |
|
348 | # Check if we have more than one argument to warrant extra processing: | |
349 | odict = {} # Dictionary with options |
|
349 | odict = {} # Dictionary with options | |
350 | args = arg_str.split() |
|
350 | args = arg_str.split() | |
351 | if len(args) >= 1: |
|
351 | if len(args) >= 1: | |
352 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
352 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
353 | # need to look for options |
|
353 | # need to look for options | |
354 | argv = arg_split(arg_str,posix) |
|
354 | argv = arg_split(arg_str,posix) | |
355 | # Do regular option processing |
|
355 | # Do regular option processing | |
356 | try: |
|
356 | try: | |
357 | opts,args = getopt(argv,opt_str,*long_opts) |
|
357 | opts,args = getopt(argv,opt_str,*long_opts) | |
358 | except GetoptError,e: |
|
358 | except GetoptError,e: | |
359 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
359 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
360 | " ".join(long_opts))) |
|
360 | " ".join(long_opts))) | |
361 | for o,a in opts: |
|
361 | for o,a in opts: | |
362 | if o.startswith('--'): |
|
362 | if o.startswith('--'): | |
363 | o = o[2:] |
|
363 | o = o[2:] | |
364 | else: |
|
364 | else: | |
365 | o = o[1:] |
|
365 | o = o[1:] | |
366 | try: |
|
366 | try: | |
367 | odict[o].append(a) |
|
367 | odict[o].append(a) | |
368 | except AttributeError: |
|
368 | except AttributeError: | |
369 | odict[o] = [odict[o],a] |
|
369 | odict[o] = [odict[o],a] | |
370 | except KeyError: |
|
370 | except KeyError: | |
371 | if list_all: |
|
371 | if list_all: | |
372 | odict[o] = [a] |
|
372 | odict[o] = [a] | |
373 | else: |
|
373 | else: | |
374 | odict[o] = a |
|
374 | odict[o] = a | |
375 |
|
375 | |||
376 | # Prepare opts,args for return |
|
376 | # Prepare opts,args for return | |
377 | opts = Struct(odict) |
|
377 | opts = Struct(odict) | |
378 | if mode == 'string': |
|
378 | if mode == 'string': | |
379 | args = ' '.join(args) |
|
379 | args = ' '.join(args) | |
380 |
|
380 | |||
381 | return opts,args |
|
381 | return opts,args | |
382 |
|
382 | |||
383 | #...................................................................... |
|
383 | #...................................................................... | |
384 | # And now the actual magic functions |
|
384 | # And now the actual magic functions | |
385 |
|
385 | |||
386 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
386 | # Functions for IPython shell work (vars,funcs, config, etc) | |
387 | def magic_lsmagic(self, parameter_s = ''): |
|
387 | def magic_lsmagic(self, parameter_s = ''): | |
388 | """List currently available magic functions.""" |
|
388 | """List currently available magic functions.""" | |
389 | mesc = self.shell.ESC_MAGIC |
|
389 | mesc = self.shell.ESC_MAGIC | |
390 | print 'Available magic functions:\n'+mesc+\ |
|
390 | print 'Available magic functions:\n'+mesc+\ | |
391 | (' '+mesc).join(self.lsmagic()) |
|
391 | (' '+mesc).join(self.lsmagic()) | |
392 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
392 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
393 | return None |
|
393 | return None | |
394 |
|
394 | |||
395 | def magic_magic(self, parameter_s = ''): |
|
395 | def magic_magic(self, parameter_s = ''): | |
396 | """Print information about the magic function system. |
|
396 | """Print information about the magic function system. | |
397 |
|
397 | |||
398 | Supported formats: -latex, -brief, -rest |
|
398 | Supported formats: -latex, -brief, -rest | |
399 | """ |
|
399 | """ | |
400 |
|
400 | |||
401 | mode = '' |
|
401 | mode = '' | |
402 | try: |
|
402 | try: | |
403 | if parameter_s.split()[0] == '-latex': |
|
403 | if parameter_s.split()[0] == '-latex': | |
404 | mode = 'latex' |
|
404 | mode = 'latex' | |
405 | if parameter_s.split()[0] == '-brief': |
|
405 | if parameter_s.split()[0] == '-brief': | |
406 | mode = 'brief' |
|
406 | mode = 'brief' | |
407 | if parameter_s.split()[0] == '-rest': |
|
407 | if parameter_s.split()[0] == '-rest': | |
408 | mode = 'rest' |
|
408 | mode = 'rest' | |
409 | rest_docs = [] |
|
409 | rest_docs = [] | |
410 | except: |
|
410 | except: | |
411 | pass |
|
411 | pass | |
412 |
|
412 | |||
413 | magic_docs = [] |
|
413 | magic_docs = [] | |
414 | for fname in self.lsmagic(): |
|
414 | for fname in self.lsmagic(): | |
415 | mname = 'magic_' + fname |
|
415 | mname = 'magic_' + fname | |
416 | for space in (Magic,self,self.__class__): |
|
416 | for space in (Magic,self,self.__class__): | |
417 | try: |
|
417 | try: | |
418 | fn = space.__dict__[mname] |
|
418 | fn = space.__dict__[mname] | |
419 | except KeyError: |
|
419 | except KeyError: | |
420 | pass |
|
420 | pass | |
421 | else: |
|
421 | else: | |
422 | break |
|
422 | break | |
423 | if mode == 'brief': |
|
423 | if mode == 'brief': | |
424 | # only first line |
|
424 | # only first line | |
425 | if fn.__doc__: |
|
425 | if fn.__doc__: | |
426 | fndoc = fn.__doc__.split('\n',1)[0] |
|
426 | fndoc = fn.__doc__.split('\n',1)[0] | |
427 | else: |
|
427 | else: | |
428 | fndoc = 'No documentation' |
|
428 | fndoc = 'No documentation' | |
429 | else: |
|
429 | else: | |
430 | if fn.__doc__: |
|
430 | if fn.__doc__: | |
431 | fndoc = fn.__doc__.rstrip() |
|
431 | fndoc = fn.__doc__.rstrip() | |
432 | else: |
|
432 | else: | |
433 | fndoc = 'No documentation' |
|
433 | fndoc = 'No documentation' | |
434 |
|
434 | |||
435 |
|
435 | |||
436 | if mode == 'rest': |
|
436 | if mode == 'rest': | |
437 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, |
|
437 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC, | |
438 | fname,fndoc)) |
|
438 | fname,fndoc)) | |
439 |
|
439 | |||
440 | else: |
|
440 | else: | |
441 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
441 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
442 | fname,fndoc)) |
|
442 | fname,fndoc)) | |
443 |
|
443 | |||
444 | magic_docs = ''.join(magic_docs) |
|
444 | magic_docs = ''.join(magic_docs) | |
445 |
|
445 | |||
446 | if mode == 'rest': |
|
446 | if mode == 'rest': | |
447 | return "".join(rest_docs) |
|
447 | return "".join(rest_docs) | |
448 |
|
448 | |||
449 | if mode == 'latex': |
|
449 | if mode == 'latex': | |
450 | print self.format_latex(magic_docs) |
|
450 | print self.format_latex(magic_docs) | |
451 | return |
|
451 | return | |
452 | else: |
|
452 | else: | |
453 | magic_docs = self.format_screen(magic_docs) |
|
453 | magic_docs = self.format_screen(magic_docs) | |
454 | if mode == 'brief': |
|
454 | if mode == 'brief': | |
455 | return magic_docs |
|
455 | return magic_docs | |
456 |
|
456 | |||
457 | outmsg = """ |
|
457 | outmsg = """ | |
458 | IPython's 'magic' functions |
|
458 | IPython's 'magic' functions | |
459 | =========================== |
|
459 | =========================== | |
460 |
|
460 | |||
461 | The magic function system provides a series of functions which allow you to |
|
461 | The magic function system provides a series of functions which allow you to | |
462 | control the behavior of IPython itself, plus a lot of system-type |
|
462 | control the behavior of IPython itself, plus a lot of system-type | |
463 | features. All these functions are prefixed with a % character, but parameters |
|
463 | features. All these functions are prefixed with a % character, but parameters | |
464 | are given without parentheses or quotes. |
|
464 | are given without parentheses or quotes. | |
465 |
|
465 | |||
466 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
466 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
467 | %automagic function), you don't need to type in the % explicitly. By default, |
|
467 | %automagic function), you don't need to type in the % explicitly. By default, | |
468 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
468 | IPython ships with automagic on, so you should only rarely need the % escape. | |
469 |
|
469 | |||
470 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
470 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
471 | to 'mydir', if it exists. |
|
471 | to 'mydir', if it exists. | |
472 |
|
472 | |||
473 | You can define your own magic functions to extend the system. See the supplied |
|
473 | You can define your own magic functions to extend the system. See the supplied | |
474 | ipythonrc and example-magic.py files for details (in your ipython |
|
474 | ipythonrc and example-magic.py files for details (in your ipython | |
475 | configuration directory, typically $HOME/.ipython/). |
|
475 | configuration directory, typically $HOME/.ipython/). | |
476 |
|
476 | |||
477 | You can also define your own aliased names for magic functions. In your |
|
477 | You can also define your own aliased names for magic functions. In your | |
478 | ipythonrc file, placing a line like: |
|
478 | ipythonrc file, placing a line like: | |
479 |
|
479 | |||
480 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
480 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
481 |
|
481 | |||
482 | will define %pf as a new name for %profile. |
|
482 | will define %pf as a new name for %profile. | |
483 |
|
483 | |||
484 | You can also call magics in code using the ipmagic() function, which IPython |
|
484 | You can also call magics in code using the ipmagic() function, which IPython | |
485 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
485 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
486 |
|
486 | |||
487 | For a list of the available magic functions, use %lsmagic. For a description |
|
487 | For a list of the available magic functions, use %lsmagic. For a description | |
488 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
488 | of any of them, type %magic_name?, e.g. '%cd?'. | |
489 |
|
489 | |||
490 | Currently the magic system has the following functions:\n""" |
|
490 | Currently the magic system has the following functions:\n""" | |
491 |
|
491 | |||
492 | mesc = self.shell.ESC_MAGIC |
|
492 | mesc = self.shell.ESC_MAGIC | |
493 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
493 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
494 | "\n\n%s%s\n\n%s" % (outmsg, |
|
494 | "\n\n%s%s\n\n%s" % (outmsg, | |
495 | magic_docs,mesc,mesc, |
|
495 | magic_docs,mesc,mesc, | |
496 | (' '+mesc).join(self.lsmagic()), |
|
496 | (' '+mesc).join(self.lsmagic()), | |
497 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
497 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
498 |
|
498 | |||
499 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
499 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
500 |
|
500 | |||
501 |
|
501 | |||
502 | def magic_autoindent(self, parameter_s = ''): |
|
502 | def magic_autoindent(self, parameter_s = ''): | |
503 | """Toggle autoindent on/off (if available).""" |
|
503 | """Toggle autoindent on/off (if available).""" | |
504 |
|
504 | |||
505 | self.shell.set_autoindent() |
|
505 | self.shell.set_autoindent() | |
506 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
506 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
507 |
|
507 | |||
508 |
|
508 | |||
509 | def magic_automagic(self, parameter_s = ''): |
|
509 | def magic_automagic(self, parameter_s = ''): | |
510 | """Make magic functions callable without having to type the initial %. |
|
510 | """Make magic functions callable without having to type the initial %. | |
511 |
|
511 | |||
512 | Without argumentsl toggles on/off (when off, you must call it as |
|
512 | Without argumentsl toggles on/off (when off, you must call it as | |
513 | %automagic, of course). With arguments it sets the value, and you can |
|
513 | %automagic, of course). With arguments it sets the value, and you can | |
514 | use any of (case insensitive): |
|
514 | use any of (case insensitive): | |
515 |
|
515 | |||
516 | - on,1,True: to activate |
|
516 | - on,1,True: to activate | |
517 |
|
517 | |||
518 | - off,0,False: to deactivate. |
|
518 | - off,0,False: to deactivate. | |
519 |
|
519 | |||
520 | Note that magic functions have lowest priority, so if there's a |
|
520 | Note that magic functions have lowest priority, so if there's a | |
521 | variable whose name collides with that of a magic fn, automagic won't |
|
521 | variable whose name collides with that of a magic fn, automagic won't | |
522 | work for that function (you get the variable instead). However, if you |
|
522 | work for that function (you get the variable instead). However, if you | |
523 | delete the variable (del var), the previously shadowed magic function |
|
523 | delete the variable (del var), the previously shadowed magic function | |
524 | becomes visible to automagic again.""" |
|
524 | becomes visible to automagic again.""" | |
525 |
|
525 | |||
526 | rc = self.shell.rc |
|
526 | rc = self.shell.rc | |
527 | arg = parameter_s.lower() |
|
527 | arg = parameter_s.lower() | |
528 | if parameter_s in ('on','1','true'): |
|
528 | if parameter_s in ('on','1','true'): | |
529 | rc.automagic = True |
|
529 | rc.automagic = True | |
530 | elif parameter_s in ('off','0','false'): |
|
530 | elif parameter_s in ('off','0','false'): | |
531 | rc.automagic = False |
|
531 | rc.automagic = False | |
532 | else: |
|
532 | else: | |
533 | rc.automagic = not rc.automagic |
|
533 | rc.automagic = not rc.automagic | |
534 | print '\n' + Magic.auto_status[rc.automagic] |
|
534 | print '\n' + Magic.auto_status[rc.automagic] | |
535 |
|
535 | |||
536 | @testdec.skip_doctest |
|
536 | @testdec.skip_doctest | |
537 | def magic_autocall(self, parameter_s = ''): |
|
537 | def magic_autocall(self, parameter_s = ''): | |
538 | """Make functions callable without having to type parentheses. |
|
538 | """Make functions callable without having to type parentheses. | |
539 |
|
539 | |||
540 | Usage: |
|
540 | Usage: | |
541 |
|
541 | |||
542 | %autocall [mode] |
|
542 | %autocall [mode] | |
543 |
|
543 | |||
544 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
544 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
545 | value is toggled on and off (remembering the previous state). |
|
545 | value is toggled on and off (remembering the previous state). | |
546 |
|
546 | |||
547 | In more detail, these values mean: |
|
547 | In more detail, these values mean: | |
548 |
|
548 | |||
549 | 0 -> fully disabled |
|
549 | 0 -> fully disabled | |
550 |
|
550 | |||
551 | 1 -> active, but do not apply if there are no arguments on the line. |
|
551 | 1 -> active, but do not apply if there are no arguments on the line. | |
552 |
|
552 | |||
553 | In this mode, you get: |
|
553 | In this mode, you get: | |
554 |
|
554 | |||
555 | In [1]: callable |
|
555 | In [1]: callable | |
556 | Out[1]: <built-in function callable> |
|
556 | Out[1]: <built-in function callable> | |
557 |
|
557 | |||
558 | In [2]: callable 'hello' |
|
558 | In [2]: callable 'hello' | |
559 | ------> callable('hello') |
|
559 | ------> callable('hello') | |
560 | Out[2]: False |
|
560 | Out[2]: False | |
561 |
|
561 | |||
562 | 2 -> Active always. Even if no arguments are present, the callable |
|
562 | 2 -> Active always. Even if no arguments are present, the callable | |
563 | object is called: |
|
563 | object is called: | |
564 |
|
564 | |||
565 | In [2]: float |
|
565 | In [2]: float | |
566 | ------> float() |
|
566 | ------> float() | |
567 | Out[2]: 0.0 |
|
567 | Out[2]: 0.0 | |
568 |
|
568 | |||
569 | Note that even with autocall off, you can still use '/' at the start of |
|
569 | Note that even with autocall off, you can still use '/' at the start of | |
570 | a line to treat the first argument on the command line as a function |
|
570 | a line to treat the first argument on the command line as a function | |
571 | and add parentheses to it: |
|
571 | and add parentheses to it: | |
572 |
|
572 | |||
573 | In [8]: /str 43 |
|
573 | In [8]: /str 43 | |
574 | ------> str(43) |
|
574 | ------> str(43) | |
575 | Out[8]: '43' |
|
575 | Out[8]: '43' | |
576 |
|
576 | |||
577 | # all-random (note for auto-testing) |
|
577 | # all-random (note for auto-testing) | |
578 | """ |
|
578 | """ | |
579 |
|
579 | |||
580 | rc = self.shell.rc |
|
580 | rc = self.shell.rc | |
581 |
|
581 | |||
582 | if parameter_s: |
|
582 | if parameter_s: | |
583 | arg = int(parameter_s) |
|
583 | arg = int(parameter_s) | |
584 | else: |
|
584 | else: | |
585 | arg = 'toggle' |
|
585 | arg = 'toggle' | |
586 |
|
586 | |||
587 | if not arg in (0,1,2,'toggle'): |
|
587 | if not arg in (0,1,2,'toggle'): | |
588 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
588 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
589 | return |
|
589 | return | |
590 |
|
590 | |||
591 | if arg in (0,1,2): |
|
591 | if arg in (0,1,2): | |
592 | rc.autocall = arg |
|
592 | rc.autocall = arg | |
593 | else: # toggle |
|
593 | else: # toggle | |
594 | if rc.autocall: |
|
594 | if rc.autocall: | |
595 | self._magic_state.autocall_save = rc.autocall |
|
595 | self._magic_state.autocall_save = rc.autocall | |
596 | rc.autocall = 0 |
|
596 | rc.autocall = 0 | |
597 | else: |
|
597 | else: | |
598 | try: |
|
598 | try: | |
599 | rc.autocall = self._magic_state.autocall_save |
|
599 | rc.autocall = self._magic_state.autocall_save | |
600 | except AttributeError: |
|
600 | except AttributeError: | |
601 | rc.autocall = self._magic_state.autocall_save = 1 |
|
601 | rc.autocall = self._magic_state.autocall_save = 1 | |
602 |
|
602 | |||
603 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
603 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] | |
604 |
|
604 | |||
605 | def magic_system_verbose(self, parameter_s = ''): |
|
605 | def magic_system_verbose(self, parameter_s = ''): | |
606 | """Set verbose printing of system calls. |
|
606 | """Set verbose printing of system calls. | |
607 |
|
607 | |||
608 | If called without an argument, act as a toggle""" |
|
608 | If called without an argument, act as a toggle""" | |
609 |
|
609 | |||
610 | if parameter_s: |
|
610 | if parameter_s: | |
611 | val = bool(eval(parameter_s)) |
|
611 | val = bool(eval(parameter_s)) | |
612 | else: |
|
612 | else: | |
613 | val = None |
|
613 | val = None | |
614 |
|
614 | |||
615 | self.shell.rc_set_toggle('system_verbose',val) |
|
615 | self.shell.rc_set_toggle('system_verbose',val) | |
616 | print "System verbose printing is:",\ |
|
616 | print "System verbose printing is:",\ | |
617 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
617 | ['OFF','ON'][self.shell.rc.system_verbose] | |
618 |
|
618 | |||
619 |
|
619 | |||
620 | def magic_page(self, parameter_s=''): |
|
620 | def magic_page(self, parameter_s=''): | |
621 | """Pretty print the object and display it through a pager. |
|
621 | """Pretty print the object and display it through a pager. | |
622 |
|
622 | |||
623 | %page [options] OBJECT |
|
623 | %page [options] OBJECT | |
624 |
|
624 | |||
625 | If no object is given, use _ (last output). |
|
625 | If no object is given, use _ (last output). | |
626 |
|
626 | |||
627 | Options: |
|
627 | Options: | |
628 |
|
628 | |||
629 | -r: page str(object), don't pretty-print it.""" |
|
629 | -r: page str(object), don't pretty-print it.""" | |
630 |
|
630 | |||
631 | # After a function contributed by Olivier Aubert, slightly modified. |
|
631 | # After a function contributed by Olivier Aubert, slightly modified. | |
632 |
|
632 | |||
633 | # Process options/args |
|
633 | # Process options/args | |
634 | opts,args = self.parse_options(parameter_s,'r') |
|
634 | opts,args = self.parse_options(parameter_s,'r') | |
635 | raw = 'r' in opts |
|
635 | raw = 'r' in opts | |
636 |
|
636 | |||
637 | oname = args and args or '_' |
|
637 | oname = args and args or '_' | |
638 | info = self._ofind(oname) |
|
638 | info = self._ofind(oname) | |
639 | if info['found']: |
|
639 | if info['found']: | |
640 | txt = (raw and str or pformat)( info['obj'] ) |
|
640 | txt = (raw and str or pformat)( info['obj'] ) | |
641 | page(txt) |
|
641 | page(txt) | |
642 | else: |
|
642 | else: | |
643 | print 'Object `%s` not found' % oname |
|
643 | print 'Object `%s` not found' % oname | |
644 |
|
644 | |||
645 | def magic_profile(self, parameter_s=''): |
|
645 | def magic_profile(self, parameter_s=''): | |
646 | """Print your currently active IPyhton profile.""" |
|
646 | """Print your currently active IPyhton profile.""" | |
647 | if self.shell.rc.profile: |
|
647 | if self.shell.rc.profile: | |
648 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
648 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
649 | else: |
|
649 | else: | |
650 | print 'No profile active.' |
|
650 | print 'No profile active.' | |
651 |
|
651 | |||
652 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
652 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
653 | """Provide detailed information about an object. |
|
653 | """Provide detailed information about an object. | |
654 |
|
654 | |||
655 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
655 | '%pinfo object' is just a synonym for object? or ?object.""" | |
656 |
|
656 | |||
657 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
657 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
658 |
|
658 | |||
659 |
|
659 | |||
660 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
660 | # detail_level: 0 -> obj? , 1 -> obj?? | |
661 | detail_level = 0 |
|
661 | detail_level = 0 | |
662 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
662 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
663 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
663 | # happen if the user types 'pinfo foo?' at the cmd line. | |
664 | pinfo,qmark1,oname,qmark2 = \ |
|
664 | pinfo,qmark1,oname,qmark2 = \ | |
665 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
665 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
666 | if pinfo or qmark1 or qmark2: |
|
666 | if pinfo or qmark1 or qmark2: | |
667 | detail_level = 1 |
|
667 | detail_level = 1 | |
668 | if "*" in oname: |
|
668 | if "*" in oname: | |
669 | self.magic_psearch(oname) |
|
669 | self.magic_psearch(oname) | |
670 | else: |
|
670 | else: | |
671 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
671 | self._inspect('pinfo', oname, detail_level=detail_level, | |
672 | namespaces=namespaces) |
|
672 | namespaces=namespaces) | |
673 |
|
673 | |||
674 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
674 | def magic_pdef(self, parameter_s='', namespaces=None): | |
675 | """Print the definition header for any callable object. |
|
675 | """Print the definition header for any callable object. | |
676 |
|
676 | |||
677 | If the object is a class, print the constructor information.""" |
|
677 | If the object is a class, print the constructor information.""" | |
678 | self._inspect('pdef',parameter_s, namespaces) |
|
678 | self._inspect('pdef',parameter_s, namespaces) | |
679 |
|
679 | |||
680 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
680 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
681 | """Print the docstring for an object. |
|
681 | """Print the docstring for an object. | |
682 |
|
682 | |||
683 | If the given object is a class, it will print both the class and the |
|
683 | If the given object is a class, it will print both the class and the | |
684 | constructor docstrings.""" |
|
684 | constructor docstrings.""" | |
685 | self._inspect('pdoc',parameter_s, namespaces) |
|
685 | self._inspect('pdoc',parameter_s, namespaces) | |
686 |
|
686 | |||
687 | def magic_psource(self, parameter_s='', namespaces=None): |
|
687 | def magic_psource(self, parameter_s='', namespaces=None): | |
688 | """Print (or run through pager) the source code for an object.""" |
|
688 | """Print (or run through pager) the source code for an object.""" | |
689 | self._inspect('psource',parameter_s, namespaces) |
|
689 | self._inspect('psource',parameter_s, namespaces) | |
690 |
|
690 | |||
691 | def magic_pfile(self, parameter_s=''): |
|
691 | def magic_pfile(self, parameter_s=''): | |
692 | """Print (or run through pager) the file where an object is defined. |
|
692 | """Print (or run through pager) the file where an object is defined. | |
693 |
|
693 | |||
694 | The file opens at the line where the object definition begins. IPython |
|
694 | The file opens at the line where the object definition begins. IPython | |
695 | will honor the environment variable PAGER if set, and otherwise will |
|
695 | will honor the environment variable PAGER if set, and otherwise will | |
696 | do its best to print the file in a convenient form. |
|
696 | do its best to print the file in a convenient form. | |
697 |
|
697 | |||
698 | If the given argument is not an object currently defined, IPython will |
|
698 | If the given argument is not an object currently defined, IPython will | |
699 | try to interpret it as a filename (automatically adding a .py extension |
|
699 | try to interpret it as a filename (automatically adding a .py extension | |
700 | if needed). You can thus use %pfile as a syntax highlighting code |
|
700 | if needed). You can thus use %pfile as a syntax highlighting code | |
701 | viewer.""" |
|
701 | viewer.""" | |
702 |
|
702 | |||
703 | # first interpret argument as an object name |
|
703 | # first interpret argument as an object name | |
704 | out = self._inspect('pfile',parameter_s) |
|
704 | out = self._inspect('pfile',parameter_s) | |
705 | # if not, try the input as a filename |
|
705 | # if not, try the input as a filename | |
706 | if out == 'not found': |
|
706 | if out == 'not found': | |
707 | try: |
|
707 | try: | |
708 | filename = get_py_filename(parameter_s) |
|
708 | filename = get_py_filename(parameter_s) | |
709 | except IOError,msg: |
|
709 | except IOError,msg: | |
710 | print msg |
|
710 | print msg | |
711 | return |
|
711 | return | |
712 | page(self.shell.inspector.format(file(filename).read())) |
|
712 | page(self.shell.inspector.format(file(filename).read())) | |
713 |
|
713 | |||
714 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
714 | def _inspect(self,meth,oname,namespaces=None,**kw): | |
715 | """Generic interface to the inspector system. |
|
715 | """Generic interface to the inspector system. | |
716 |
|
716 | |||
717 | This function is meant to be called by pdef, pdoc & friends.""" |
|
717 | This function is meant to be called by pdef, pdoc & friends.""" | |
718 |
|
718 | |||
719 | #oname = oname.strip() |
|
719 | #oname = oname.strip() | |
720 | #print '1- oname: <%r>' % oname # dbg |
|
720 | #print '1- oname: <%r>' % oname # dbg | |
721 | try: |
|
721 | try: | |
722 | oname = oname.strip().encode('ascii') |
|
722 | oname = oname.strip().encode('ascii') | |
723 | #print '2- oname: <%r>' % oname # dbg |
|
723 | #print '2- oname: <%r>' % oname # dbg | |
724 | except UnicodeEncodeError: |
|
724 | except UnicodeEncodeError: | |
725 | print 'Python identifiers can only contain ascii characters.' |
|
725 | print 'Python identifiers can only contain ascii characters.' | |
726 | return 'not found' |
|
726 | return 'not found' | |
727 |
|
727 | |||
728 | info = Struct(self._ofind(oname, namespaces)) |
|
728 | info = Struct(self._ofind(oname, namespaces)) | |
729 |
|
729 | |||
730 | if info.found: |
|
730 | if info.found: | |
731 | try: |
|
731 | try: | |
732 | IPython.generics.inspect_object(info.obj) |
|
732 | IPython.generics.inspect_object(info.obj) | |
733 | return |
|
733 | return | |
734 | except IPython.ipapi.TryNext: |
|
734 | except IPython.ipapi.TryNext: | |
735 | pass |
|
735 | pass | |
736 | # Get the docstring of the class property if it exists. |
|
736 | # Get the docstring of the class property if it exists. | |
737 | path = oname.split('.') |
|
737 | path = oname.split('.') | |
738 | root = '.'.join(path[:-1]) |
|
738 | root = '.'.join(path[:-1]) | |
739 | if info.parent is not None: |
|
739 | if info.parent is not None: | |
740 | try: |
|
740 | try: | |
741 | target = getattr(info.parent, '__class__') |
|
741 | target = getattr(info.parent, '__class__') | |
742 | # The object belongs to a class instance. |
|
742 | # The object belongs to a class instance. | |
743 | try: |
|
743 | try: | |
744 | target = getattr(target, path[-1]) |
|
744 | target = getattr(target, path[-1]) | |
745 | # The class defines the object. |
|
745 | # The class defines the object. | |
746 | if isinstance(target, property): |
|
746 | if isinstance(target, property): | |
747 | oname = root + '.__class__.' + path[-1] |
|
747 | oname = root + '.__class__.' + path[-1] | |
748 | info = Struct(self._ofind(oname)) |
|
748 | info = Struct(self._ofind(oname)) | |
749 | except AttributeError: pass |
|
749 | except AttributeError: pass | |
750 | except AttributeError: pass |
|
750 | except AttributeError: pass | |
751 |
|
751 | |||
752 | pmethod = getattr(self.shell.inspector,meth) |
|
752 | pmethod = getattr(self.shell.inspector,meth) | |
753 | formatter = info.ismagic and self.format_screen or None |
|
753 | formatter = info.ismagic and self.format_screen or None | |
754 | if meth == 'pdoc': |
|
754 | if meth == 'pdoc': | |
755 | pmethod(info.obj,oname,formatter) |
|
755 | pmethod(info.obj,oname,formatter) | |
756 | elif meth == 'pinfo': |
|
756 | elif meth == 'pinfo': | |
757 | pmethod(info.obj,oname,formatter,info,**kw) |
|
757 | pmethod(info.obj,oname,formatter,info,**kw) | |
758 | else: |
|
758 | else: | |
759 | pmethod(info.obj,oname) |
|
759 | pmethod(info.obj,oname) | |
760 | else: |
|
760 | else: | |
761 | print 'Object `%s` not found.' % oname |
|
761 | print 'Object `%s` not found.' % oname | |
762 | return 'not found' # so callers can take other action |
|
762 | return 'not found' # so callers can take other action | |
763 |
|
763 | |||
764 | def magic_psearch(self, parameter_s=''): |
|
764 | def magic_psearch(self, parameter_s=''): | |
765 | """Search for object in namespaces by wildcard. |
|
765 | """Search for object in namespaces by wildcard. | |
766 |
|
766 | |||
767 | %psearch [options] PATTERN [OBJECT TYPE] |
|
767 | %psearch [options] PATTERN [OBJECT TYPE] | |
768 |
|
768 | |||
769 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
769 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
770 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
770 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
771 | rest of the command line must be unchanged (options come first), so |
|
771 | rest of the command line must be unchanged (options come first), so | |
772 | for example the following forms are equivalent |
|
772 | for example the following forms are equivalent | |
773 |
|
773 | |||
774 | %psearch -i a* function |
|
774 | %psearch -i a* function | |
775 | -i a* function? |
|
775 | -i a* function? | |
776 | ?-i a* function |
|
776 | ?-i a* function | |
777 |
|
777 | |||
778 | Arguments: |
|
778 | Arguments: | |
779 |
|
779 | |||
780 | PATTERN |
|
780 | PATTERN | |
781 |
|
781 | |||
782 | where PATTERN is a string containing * as a wildcard similar to its |
|
782 | where PATTERN is a string containing * as a wildcard similar to its | |
783 | use in a shell. The pattern is matched in all namespaces on the |
|
783 | use in a shell. The pattern is matched in all namespaces on the | |
784 | search path. By default objects starting with a single _ are not |
|
784 | search path. By default objects starting with a single _ are not | |
785 | matched, many IPython generated objects have a single |
|
785 | matched, many IPython generated objects have a single | |
786 | underscore. The default is case insensitive matching. Matching is |
|
786 | underscore. The default is case insensitive matching. Matching is | |
787 | also done on the attributes of objects and not only on the objects |
|
787 | also done on the attributes of objects and not only on the objects | |
788 | in a module. |
|
788 | in a module. | |
789 |
|
789 | |||
790 | [OBJECT TYPE] |
|
790 | [OBJECT TYPE] | |
791 |
|
791 | |||
792 | Is the name of a python type from the types module. The name is |
|
792 | Is the name of a python type from the types module. The name is | |
793 | given in lowercase without the ending type, ex. StringType is |
|
793 | given in lowercase without the ending type, ex. StringType is | |
794 | written string. By adding a type here only objects matching the |
|
794 | written string. By adding a type here only objects matching the | |
795 | given type are matched. Using all here makes the pattern match all |
|
795 | given type are matched. Using all here makes the pattern match all | |
796 | types (this is the default). |
|
796 | types (this is the default). | |
797 |
|
797 | |||
798 | Options: |
|
798 | Options: | |
799 |
|
799 | |||
800 | -a: makes the pattern match even objects whose names start with a |
|
800 | -a: makes the pattern match even objects whose names start with a | |
801 | single underscore. These names are normally ommitted from the |
|
801 | single underscore. These names are normally ommitted from the | |
802 | search. |
|
802 | search. | |
803 |
|
803 | |||
804 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
804 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
805 | these options is given, the default is read from your ipythonrc |
|
805 | these options is given, the default is read from your ipythonrc | |
806 | file. The option name which sets this value is |
|
806 | file. The option name which sets this value is | |
807 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
807 | 'wildcards_case_sensitive'. If this option is not specified in your | |
808 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
808 | ipythonrc file, IPython's internal default is to do a case sensitive | |
809 | search. |
|
809 | search. | |
810 |
|
810 | |||
811 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
811 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
812 | specifiy can be searched in any of the following namespaces: |
|
812 | specifiy can be searched in any of the following namespaces: | |
813 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
813 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
814 | 'builtin' and 'user' are the search defaults. Note that you should |
|
814 | 'builtin' and 'user' are the search defaults. Note that you should | |
815 | not use quotes when specifying namespaces. |
|
815 | not use quotes when specifying namespaces. | |
816 |
|
816 | |||
817 | 'Builtin' contains the python module builtin, 'user' contains all |
|
817 | 'Builtin' contains the python module builtin, 'user' contains all | |
818 | user data, 'alias' only contain the shell aliases and no python |
|
818 | user data, 'alias' only contain the shell aliases and no python | |
819 | objects, 'internal' contains objects used by IPython. The |
|
819 | objects, 'internal' contains objects used by IPython. The | |
820 | 'user_global' namespace is only used by embedded IPython instances, |
|
820 | 'user_global' namespace is only used by embedded IPython instances, | |
821 | and it contains module-level globals. You can add namespaces to the |
|
821 | and it contains module-level globals. You can add namespaces to the | |
822 | search with -s or exclude them with -e (these options can be given |
|
822 | search with -s or exclude them with -e (these options can be given | |
823 | more than once). |
|
823 | more than once). | |
824 |
|
824 | |||
825 | Examples: |
|
825 | Examples: | |
826 |
|
826 | |||
827 | %psearch a* -> objects beginning with an a |
|
827 | %psearch a* -> objects beginning with an a | |
828 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
828 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
829 | %psearch a* function -> all functions beginning with an a |
|
829 | %psearch a* function -> all functions beginning with an a | |
830 | %psearch re.e* -> objects beginning with an e in module re |
|
830 | %psearch re.e* -> objects beginning with an e in module re | |
831 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
831 | %psearch r*.e* -> objects that start with e in modules starting in r | |
832 | %psearch r*.* string -> all strings in modules beginning with r |
|
832 | %psearch r*.* string -> all strings in modules beginning with r | |
833 |
|
833 | |||
834 | Case sensitve search: |
|
834 | Case sensitve search: | |
835 |
|
835 | |||
836 | %psearch -c a* list all object beginning with lower case a |
|
836 | %psearch -c a* list all object beginning with lower case a | |
837 |
|
837 | |||
838 | Show objects beginning with a single _: |
|
838 | Show objects beginning with a single _: | |
839 |
|
839 | |||
840 | %psearch -a _* list objects beginning with a single underscore""" |
|
840 | %psearch -a _* list objects beginning with a single underscore""" | |
841 | try: |
|
841 | try: | |
842 | parameter_s = parameter_s.encode('ascii') |
|
842 | parameter_s = parameter_s.encode('ascii') | |
843 | except UnicodeEncodeError: |
|
843 | except UnicodeEncodeError: | |
844 | print 'Python identifiers can only contain ascii characters.' |
|
844 | print 'Python identifiers can only contain ascii characters.' | |
845 | return |
|
845 | return | |
846 |
|
846 | |||
847 | # default namespaces to be searched |
|
847 | # default namespaces to be searched | |
848 | def_search = ['user','builtin'] |
|
848 | def_search = ['user','builtin'] | |
849 |
|
849 | |||
850 | # Process options/args |
|
850 | # Process options/args | |
851 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
851 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
852 | opt = opts.get |
|
852 | opt = opts.get | |
853 | shell = self.shell |
|
853 | shell = self.shell | |
854 | psearch = shell.inspector.psearch |
|
854 | psearch = shell.inspector.psearch | |
855 |
|
855 | |||
856 | # select case options |
|
856 | # select case options | |
857 | if opts.has_key('i'): |
|
857 | if opts.has_key('i'): | |
858 | ignore_case = True |
|
858 | ignore_case = True | |
859 | elif opts.has_key('c'): |
|
859 | elif opts.has_key('c'): | |
860 | ignore_case = False |
|
860 | ignore_case = False | |
861 | else: |
|
861 | else: | |
862 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
862 | ignore_case = not shell.rc.wildcards_case_sensitive | |
863 |
|
863 | |||
864 | # Build list of namespaces to search from user options |
|
864 | # Build list of namespaces to search from user options | |
865 | def_search.extend(opt('s',[])) |
|
865 | def_search.extend(opt('s',[])) | |
866 | ns_exclude = ns_exclude=opt('e',[]) |
|
866 | ns_exclude = ns_exclude=opt('e',[]) | |
867 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
867 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
868 |
|
868 | |||
869 | # Call the actual search |
|
869 | # Call the actual search | |
870 | try: |
|
870 | try: | |
871 | psearch(args,shell.ns_table,ns_search, |
|
871 | psearch(args,shell.ns_table,ns_search, | |
872 | show_all=opt('a'),ignore_case=ignore_case) |
|
872 | show_all=opt('a'),ignore_case=ignore_case) | |
873 | except: |
|
873 | except: | |
874 | shell.showtraceback() |
|
874 | shell.showtraceback() | |
875 |
|
875 | |||
876 | def magic_who_ls(self, parameter_s=''): |
|
876 | def magic_who_ls(self, parameter_s=''): | |
877 | """Return a sorted list of all interactive variables. |
|
877 | """Return a sorted list of all interactive variables. | |
878 |
|
878 | |||
879 | If arguments are given, only variables of types matching these |
|
879 | If arguments are given, only variables of types matching these | |
880 | arguments are returned.""" |
|
880 | arguments are returned.""" | |
881 |
|
881 | |||
882 | user_ns = self.shell.user_ns |
|
882 | user_ns = self.shell.user_ns | |
883 | internal_ns = self.shell.internal_ns |
|
883 | internal_ns = self.shell.internal_ns | |
884 | user_config_ns = self.shell.user_config_ns |
|
884 | user_config_ns = self.shell.user_config_ns | |
885 | out = [] |
|
885 | out = [] | |
886 | typelist = parameter_s.split() |
|
886 | typelist = parameter_s.split() | |
887 |
|
887 | |||
888 | for i in user_ns: |
|
888 | for i in user_ns: | |
889 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
889 | if not (i.startswith('_') or i.startswith('_i')) \ | |
890 | and not (i in internal_ns or i in user_config_ns): |
|
890 | and not (i in internal_ns or i in user_config_ns): | |
891 | if typelist: |
|
891 | if typelist: | |
892 | if type(user_ns[i]).__name__ in typelist: |
|
892 | if type(user_ns[i]).__name__ in typelist: | |
893 | out.append(i) |
|
893 | out.append(i) | |
894 | else: |
|
894 | else: | |
895 | out.append(i) |
|
895 | out.append(i) | |
896 | out.sort() |
|
896 | out.sort() | |
897 | return out |
|
897 | return out | |
898 |
|
898 | |||
899 | def magic_who(self, parameter_s=''): |
|
899 | def magic_who(self, parameter_s=''): | |
900 | """Print all interactive variables, with some minimal formatting. |
|
900 | """Print all interactive variables, with some minimal formatting. | |
901 |
|
901 | |||
902 | If any arguments are given, only variables whose type matches one of |
|
902 | If any arguments are given, only variables whose type matches one of | |
903 | these are printed. For example: |
|
903 | these are printed. For example: | |
904 |
|
904 | |||
905 | %who function str |
|
905 | %who function str | |
906 |
|
906 | |||
907 | will only list functions and strings, excluding all other types of |
|
907 | will only list functions and strings, excluding all other types of | |
908 | variables. To find the proper type names, simply use type(var) at a |
|
908 | variables. To find the proper type names, simply use type(var) at a | |
909 | command line to see how python prints type names. For example: |
|
909 | command line to see how python prints type names. For example: | |
910 |
|
910 | |||
911 | In [1]: type('hello')\\ |
|
911 | In [1]: type('hello')\\ | |
912 | Out[1]: <type 'str'> |
|
912 | Out[1]: <type 'str'> | |
913 |
|
913 | |||
914 | indicates that the type name for strings is 'str'. |
|
914 | indicates that the type name for strings is 'str'. | |
915 |
|
915 | |||
916 | %who always excludes executed names loaded through your configuration |
|
916 | %who always excludes executed names loaded through your configuration | |
917 | file and things which are internal to IPython. |
|
917 | file and things which are internal to IPython. | |
918 |
|
918 | |||
919 | This is deliberate, as typically you may load many modules and the |
|
919 | This is deliberate, as typically you may load many modules and the | |
920 | purpose of %who is to show you only what you've manually defined.""" |
|
920 | purpose of %who is to show you only what you've manually defined.""" | |
921 |
|
921 | |||
922 | varlist = self.magic_who_ls(parameter_s) |
|
922 | varlist = self.magic_who_ls(parameter_s) | |
923 | if not varlist: |
|
923 | if not varlist: | |
924 | if parameter_s: |
|
924 | if parameter_s: | |
925 | print 'No variables match your requested type.' |
|
925 | print 'No variables match your requested type.' | |
926 | else: |
|
926 | else: | |
927 | print 'Interactive namespace is empty.' |
|
927 | print 'Interactive namespace is empty.' | |
928 | return |
|
928 | return | |
929 |
|
929 | |||
930 | # if we have variables, move on... |
|
930 | # if we have variables, move on... | |
931 | count = 0 |
|
931 | count = 0 | |
932 | for i in varlist: |
|
932 | for i in varlist: | |
933 | print i+'\t', |
|
933 | print i+'\t', | |
934 | count += 1 |
|
934 | count += 1 | |
935 | if count > 8: |
|
935 | if count > 8: | |
936 | count = 0 |
|
936 | count = 0 | |
937 |
|
937 | |||
938 |
|
938 | |||
939 |
|
939 | |||
940 | def magic_whos(self, parameter_s=''): |
|
940 | def magic_whos(self, parameter_s=''): | |
941 | """Like %who, but gives some extra information about each variable. |
|
941 | """Like %who, but gives some extra information about each variable. | |
942 |
|
942 | |||
943 | The same type filtering of %who can be applied here. |
|
943 | The same type filtering of %who can be applied here. | |
944 |
|
944 | |||
945 | For all variables, the type is printed. Additionally it prints: |
|
945 | For all variables, the type is printed. Additionally it prints: | |
946 |
|
946 | |||
947 | - For {},[],(): their length. |
|
947 | - For {},[],(): their length. | |
948 |
|
948 | |||
949 | - For numpy and Numeric arrays, a summary with shape, number of |
|
949 | - For numpy and Numeric arrays, a summary with shape, number of | |
950 | elements, typecode and size in memory. |
|
950 | elements, typecode and size in memory. | |
951 |
|
951 | |||
952 | - Everything else: a string representation, snipping their middle if |
|
952 | - Everything else: a string representation, snipping their middle if | |
953 | too long.""" |
|
953 | too long.""" | |
954 |
|
954 | |||
955 | varnames = self.magic_who_ls(parameter_s) |
|
955 | varnames = self.magic_who_ls(parameter_s) | |
956 | if not varnames: |
|
956 | if not varnames: | |
957 | if parameter_s: |
|
957 | if parameter_s: | |
958 | print 'No variables match your requested type.' |
|
958 | print 'No variables match your requested type.' | |
959 | else: |
|
959 | else: | |
960 | print 'Interactive namespace is empty.' |
|
960 | print 'Interactive namespace is empty.' | |
961 | return |
|
961 | return | |
962 |
|
962 | |||
963 | # if we have variables, move on... |
|
963 | # if we have variables, move on... | |
964 |
|
964 | |||
965 | # for these types, show len() instead of data: |
|
965 | # for these types, show len() instead of data: | |
966 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
966 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
967 |
|
967 | |||
968 | # for numpy/Numeric arrays, display summary info |
|
968 | # for numpy/Numeric arrays, display summary info | |
969 | try: |
|
969 | try: | |
970 | import numpy |
|
970 | import numpy | |
971 | except ImportError: |
|
971 | except ImportError: | |
972 | ndarray_type = None |
|
972 | ndarray_type = None | |
973 | else: |
|
973 | else: | |
974 | ndarray_type = numpy.ndarray.__name__ |
|
974 | ndarray_type = numpy.ndarray.__name__ | |
975 | try: |
|
975 | try: | |
976 | import Numeric |
|
976 | import Numeric | |
977 | except ImportError: |
|
977 | except ImportError: | |
978 | array_type = None |
|
978 | array_type = None | |
979 | else: |
|
979 | else: | |
980 | array_type = Numeric.ArrayType.__name__ |
|
980 | array_type = Numeric.ArrayType.__name__ | |
981 |
|
981 | |||
982 | # Find all variable names and types so we can figure out column sizes |
|
982 | # Find all variable names and types so we can figure out column sizes | |
983 | def get_vars(i): |
|
983 | def get_vars(i): | |
984 | return self.shell.user_ns[i] |
|
984 | return self.shell.user_ns[i] | |
985 |
|
985 | |||
986 | # some types are well known and can be shorter |
|
986 | # some types are well known and can be shorter | |
987 | abbrevs = {'IPython.macro.Macro' : 'Macro'} |
|
987 | abbrevs = {'IPython.macro.Macro' : 'Macro'} | |
988 | def type_name(v): |
|
988 | def type_name(v): | |
989 | tn = type(v).__name__ |
|
989 | tn = type(v).__name__ | |
990 | return abbrevs.get(tn,tn) |
|
990 | return abbrevs.get(tn,tn) | |
991 |
|
991 | |||
992 | varlist = map(get_vars,varnames) |
|
992 | varlist = map(get_vars,varnames) | |
993 |
|
993 | |||
994 | typelist = [] |
|
994 | typelist = [] | |
995 | for vv in varlist: |
|
995 | for vv in varlist: | |
996 | tt = type_name(vv) |
|
996 | tt = type_name(vv) | |
997 |
|
997 | |||
998 | if tt=='instance': |
|
998 | if tt=='instance': | |
999 | typelist.append( abbrevs.get(str(vv.__class__), |
|
999 | typelist.append( abbrevs.get(str(vv.__class__), | |
1000 | str(vv.__class__))) |
|
1000 | str(vv.__class__))) | |
1001 | else: |
|
1001 | else: | |
1002 | typelist.append(tt) |
|
1002 | typelist.append(tt) | |
1003 |
|
1003 | |||
1004 | # column labels and # of spaces as separator |
|
1004 | # column labels and # of spaces as separator | |
1005 | varlabel = 'Variable' |
|
1005 | varlabel = 'Variable' | |
1006 | typelabel = 'Type' |
|
1006 | typelabel = 'Type' | |
1007 | datalabel = 'Data/Info' |
|
1007 | datalabel = 'Data/Info' | |
1008 | colsep = 3 |
|
1008 | colsep = 3 | |
1009 | # variable format strings |
|
1009 | # variable format strings | |
1010 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
1010 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
1011 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
1011 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
1012 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1012 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
1013 | # find the size of the columns to format the output nicely |
|
1013 | # find the size of the columns to format the output nicely | |
1014 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1014 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
1015 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1015 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
1016 | # table header |
|
1016 | # table header | |
1017 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1017 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
1018 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1018 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
1019 | # and the table itself |
|
1019 | # and the table itself | |
1020 | kb = 1024 |
|
1020 | kb = 1024 | |
1021 | Mb = 1048576 # kb**2 |
|
1021 | Mb = 1048576 # kb**2 | |
1022 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1022 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
1023 | print itpl(vformat), |
|
1023 | print itpl(vformat), | |
1024 | if vtype in seq_types: |
|
1024 | if vtype in seq_types: | |
1025 | print len(var) |
|
1025 | print len(var) | |
1026 | elif vtype in [array_type,ndarray_type]: |
|
1026 | elif vtype in [array_type,ndarray_type]: | |
1027 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1027 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
1028 | if vtype==ndarray_type: |
|
1028 | if vtype==ndarray_type: | |
1029 | # numpy |
|
1029 | # numpy | |
1030 | vsize = var.size |
|
1030 | vsize = var.size | |
1031 | vbytes = vsize*var.itemsize |
|
1031 | vbytes = vsize*var.itemsize | |
1032 | vdtype = var.dtype |
|
1032 | vdtype = var.dtype | |
1033 | else: |
|
1033 | else: | |
1034 | # Numeric |
|
1034 | # Numeric | |
1035 | vsize = Numeric.size(var) |
|
1035 | vsize = Numeric.size(var) | |
1036 | vbytes = vsize*var.itemsize() |
|
1036 | vbytes = vsize*var.itemsize() | |
1037 | vdtype = var.typecode() |
|
1037 | vdtype = var.typecode() | |
1038 |
|
1038 | |||
1039 | if vbytes < 100000: |
|
1039 | if vbytes < 100000: | |
1040 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1040 | print aformat % (vshape,vsize,vdtype,vbytes) | |
1041 | else: |
|
1041 | else: | |
1042 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1042 | print aformat % (vshape,vsize,vdtype,vbytes), | |
1043 | if vbytes < Mb: |
|
1043 | if vbytes < Mb: | |
1044 | print '(%s kb)' % (vbytes/kb,) |
|
1044 | print '(%s kb)' % (vbytes/kb,) | |
1045 | else: |
|
1045 | else: | |
1046 | print '(%s Mb)' % (vbytes/Mb,) |
|
1046 | print '(%s Mb)' % (vbytes/Mb,) | |
1047 | else: |
|
1047 | else: | |
1048 | try: |
|
1048 | try: | |
1049 | vstr = str(var) |
|
1049 | vstr = str(var) | |
1050 | except UnicodeEncodeError: |
|
1050 | except UnicodeEncodeError: | |
1051 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1051 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
1052 | 'backslashreplace') |
|
1052 | 'backslashreplace') | |
1053 | vstr = vstr.replace('\n','\\n') |
|
1053 | vstr = vstr.replace('\n','\\n') | |
1054 | if len(vstr) < 50: |
|
1054 | if len(vstr) < 50: | |
1055 | print vstr |
|
1055 | print vstr | |
1056 | else: |
|
1056 | else: | |
1057 | printpl(vfmt_short) |
|
1057 | printpl(vfmt_short) | |
1058 |
|
1058 | |||
1059 | def magic_reset(self, parameter_s=''): |
|
1059 | def magic_reset(self, parameter_s=''): | |
1060 | """Resets the namespace by removing all names defined by the user. |
|
1060 | """Resets the namespace by removing all names defined by the user. | |
1061 |
|
1061 | |||
1062 | Input/Output history are left around in case you need them. |
|
1062 | Input/Output history are left around in case you need them. | |
1063 |
|
1063 | |||
1064 | Parameters |
|
1064 | Parameters | |
1065 | ---------- |
|
1065 | ---------- | |
1066 | -f : force reset without asking for confirmation. |
|
1066 | -f : force reset without asking for confirmation. | |
1067 |
|
1067 | |||
1068 | Examples |
|
1068 | Examples | |
1069 | -------- |
|
1069 | -------- | |
1070 | In [6]: a = 1 |
|
1070 | In [6]: a = 1 | |
1071 |
|
1071 | |||
1072 | In [7]: a |
|
1072 | In [7]: a | |
1073 | Out[7]: 1 |
|
1073 | Out[7]: 1 | |
1074 |
|
1074 | |||
1075 | In [8]: 'a' in _ip.user_ns |
|
1075 | In [8]: 'a' in _ip.user_ns | |
1076 | Out[8]: True |
|
1076 | Out[8]: True | |
1077 |
|
1077 | |||
1078 | In [9]: %reset -f |
|
1078 | In [9]: %reset -f | |
1079 |
|
1079 | |||
1080 | In [10]: 'a' in _ip.user_ns |
|
1080 | In [10]: 'a' in _ip.user_ns | |
1081 | Out[10]: False |
|
1081 | Out[10]: False | |
1082 | """ |
|
1082 | """ | |
1083 |
|
1083 | |||
1084 | if parameter_s == '-f': |
|
1084 | if parameter_s == '-f': | |
1085 | ans = True |
|
1085 | ans = True | |
1086 | else: |
|
1086 | else: | |
1087 | ans = self.shell.ask_yes_no( |
|
1087 | ans = self.shell.ask_yes_no( | |
1088 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1088 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1089 | if not ans: |
|
1089 | if not ans: | |
1090 | print 'Nothing done.' |
|
1090 | print 'Nothing done.' | |
1091 | return |
|
1091 | return | |
1092 | user_ns = self.shell.user_ns |
|
1092 | user_ns = self.shell.user_ns | |
1093 | for i in self.magic_who_ls(): |
|
1093 | for i in self.magic_who_ls(): | |
1094 | del(user_ns[i]) |
|
1094 | del(user_ns[i]) | |
1095 |
|
1095 | |||
1096 | # Also flush the private list of module references kept for script |
|
1096 | # Also flush the private list of module references kept for script | |
1097 | # execution protection |
|
1097 | # execution protection | |
1098 | self.shell.clear_main_mod_cache() |
|
1098 | self.shell.clear_main_mod_cache() | |
1099 |
|
1099 | |||
1100 | def magic_logstart(self,parameter_s=''): |
|
1100 | def magic_logstart(self,parameter_s=''): | |
1101 | """Start logging anywhere in a session. |
|
1101 | """Start logging anywhere in a session. | |
1102 |
|
1102 | |||
1103 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1103 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1104 |
|
1104 | |||
1105 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1105 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1106 | current directory, in 'rotate' mode (see below). |
|
1106 | current directory, in 'rotate' mode (see below). | |
1107 |
|
1107 | |||
1108 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1108 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1109 | history up to that point and then continues logging. |
|
1109 | history up to that point and then continues logging. | |
1110 |
|
1110 | |||
1111 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1111 | %logstart takes a second optional parameter: logging mode. This can be one | |
1112 | of (note that the modes are given unquoted):\\ |
|
1112 | of (note that the modes are given unquoted):\\ | |
1113 | append: well, that says it.\\ |
|
1113 | append: well, that says it.\\ | |
1114 | backup: rename (if exists) to name~ and start name.\\ |
|
1114 | backup: rename (if exists) to name~ and start name.\\ | |
1115 | global: single logfile in your home dir, appended to.\\ |
|
1115 | global: single logfile in your home dir, appended to.\\ | |
1116 | over : overwrite existing log.\\ |
|
1116 | over : overwrite existing log.\\ | |
1117 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1117 | rotate: create rotating logs name.1~, name.2~, etc. | |
1118 |
|
1118 | |||
1119 | Options: |
|
1119 | Options: | |
1120 |
|
1120 | |||
1121 | -o: log also IPython's output. In this mode, all commands which |
|
1121 | -o: log also IPython's output. In this mode, all commands which | |
1122 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1122 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1123 | their corresponding input line. The output lines are always |
|
1123 | their corresponding input line. The output lines are always | |
1124 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1124 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1125 | Python code. |
|
1125 | Python code. | |
1126 |
|
1126 | |||
1127 | Since this marker is always the same, filtering only the output from |
|
1127 | Since this marker is always the same, filtering only the output from | |
1128 | a log is very easy, using for example a simple awk call: |
|
1128 | a log is very easy, using for example a simple awk call: | |
1129 |
|
1129 | |||
1130 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1130 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1131 |
|
1131 | |||
1132 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1132 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1133 | input, so that user lines are logged in their final form, converted |
|
1133 | input, so that user lines are logged in their final form, converted | |
1134 | into valid Python. For example, %Exit is logged as |
|
1134 | into valid Python. For example, %Exit is logged as | |
1135 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1135 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1136 | exactly as typed, with no transformations applied. |
|
1136 | exactly as typed, with no transformations applied. | |
1137 |
|
1137 | |||
1138 | -t: put timestamps before each input line logged (these are put in |
|
1138 | -t: put timestamps before each input line logged (these are put in | |
1139 | comments).""" |
|
1139 | comments).""" | |
1140 |
|
1140 | |||
1141 | opts,par = self.parse_options(parameter_s,'ort') |
|
1141 | opts,par = self.parse_options(parameter_s,'ort') | |
1142 | log_output = 'o' in opts |
|
1142 | log_output = 'o' in opts | |
1143 | log_raw_input = 'r' in opts |
|
1143 | log_raw_input = 'r' in opts | |
1144 | timestamp = 't' in opts |
|
1144 | timestamp = 't' in opts | |
1145 |
|
1145 | |||
1146 | rc = self.shell.rc |
|
1146 | rc = self.shell.rc | |
1147 | logger = self.shell.logger |
|
1147 | logger = self.shell.logger | |
1148 |
|
1148 | |||
1149 | # if no args are given, the defaults set in the logger constructor by |
|
1149 | # if no args are given, the defaults set in the logger constructor by | |
1150 | # ipytohn remain valid |
|
1150 | # ipytohn remain valid | |
1151 | if par: |
|
1151 | if par: | |
1152 | try: |
|
1152 | try: | |
1153 | logfname,logmode = par.split() |
|
1153 | logfname,logmode = par.split() | |
1154 | except: |
|
1154 | except: | |
1155 | logfname = par |
|
1155 | logfname = par | |
1156 | logmode = 'backup' |
|
1156 | logmode = 'backup' | |
1157 | else: |
|
1157 | else: | |
1158 | logfname = logger.logfname |
|
1158 | logfname = logger.logfname | |
1159 | logmode = logger.logmode |
|
1159 | logmode = logger.logmode | |
1160 | # put logfname into rc struct as if it had been called on the command |
|
1160 | # put logfname into rc struct as if it had been called on the command | |
1161 | # line, so it ends up saved in the log header Save it in case we need |
|
1161 | # line, so it ends up saved in the log header Save it in case we need | |
1162 | # to restore it... |
|
1162 | # to restore it... | |
1163 | old_logfile = rc.opts.get('logfile','') |
|
1163 | old_logfile = rc.opts.get('logfile','') | |
1164 | if logfname: |
|
1164 | if logfname: | |
1165 | logfname = os.path.expanduser(logfname) |
|
1165 | logfname = os.path.expanduser(logfname) | |
1166 | rc.opts.logfile = logfname |
|
1166 | rc.opts.logfile = logfname | |
1167 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1167 | loghead = self.shell.loghead_tpl % (sys.stdin.encoding, rc.opts, rc.args) | |
1168 | try: |
|
1168 | try: | |
1169 | started = logger.logstart(logfname,loghead,logmode, |
|
1169 | started = logger.logstart(logfname,loghead,logmode, | |
1170 | log_output,timestamp,log_raw_input) |
|
1170 | log_output,timestamp,log_raw_input) | |
1171 | except: |
|
1171 | except: | |
1172 | rc.opts.logfile = old_logfile |
|
1172 | rc.opts.logfile = old_logfile | |
1173 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1173 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1174 | else: |
|
1174 | else: | |
1175 | # log input history up to this point, optionally interleaving |
|
1175 | # log input history up to this point, optionally interleaving | |
1176 | # output if requested |
|
1176 | # output if requested | |
1177 |
|
1177 | |||
1178 | if timestamp: |
|
1178 | if timestamp: | |
1179 | # disable timestamping for the previous history, since we've |
|
1179 | # disable timestamping for the previous history, since we've | |
1180 | # lost those already (no time machine here). |
|
1180 | # lost those already (no time machine here). | |
1181 | logger.timestamp = False |
|
1181 | logger.timestamp = False | |
1182 |
|
1182 | |||
1183 | if log_raw_input: |
|
1183 | if log_raw_input: | |
1184 | input_hist = self.shell.input_hist_raw |
|
1184 | input_hist = self.shell.input_hist_raw | |
1185 | else: |
|
1185 | else: | |
1186 | input_hist = self.shell.input_hist |
|
1186 | input_hist = self.shell.input_hist | |
1187 |
|
1187 | |||
1188 | if log_output: |
|
1188 | if log_output: | |
1189 | log_write = logger.log_write |
|
1189 | log_write = logger.log_write | |
1190 | output_hist = self.shell.output_hist |
|
1190 | output_hist = self.shell.output_hist | |
1191 | for n in range(1,len(input_hist)-1): |
|
1191 | for n in range(1,len(input_hist)-1): | |
1192 | log_write(input_hist[n].rstrip()) |
|
1192 | log_write(input_hist[n].rstrip()) | |
1193 | if n in output_hist: |
|
1193 | if n in output_hist: | |
1194 | log_write(repr(output_hist[n]),'output') |
|
1194 | log_write(repr(output_hist[n]),'output') | |
1195 | else: |
|
1195 | else: | |
1196 | logger.log_write(input_hist[1:]) |
|
1196 | logger.log_write(input_hist[1:]) | |
1197 | if timestamp: |
|
1197 | if timestamp: | |
1198 | # re-enable timestamping |
|
1198 | # re-enable timestamping | |
1199 | logger.timestamp = True |
|
1199 | logger.timestamp = True | |
1200 |
|
1200 | |||
1201 | print ('Activating auto-logging. ' |
|
1201 | print ('Activating auto-logging. ' | |
1202 | 'Current session state plus future input saved.') |
|
1202 | 'Current session state plus future input saved.') | |
1203 | logger.logstate() |
|
1203 | logger.logstate() | |
1204 |
|
1204 | |||
1205 | def magic_logstop(self,parameter_s=''): |
|
1205 | def magic_logstop(self,parameter_s=''): | |
1206 | """Fully stop logging and close log file. |
|
1206 | """Fully stop logging and close log file. | |
1207 |
|
1207 | |||
1208 | In order to start logging again, a new %logstart call needs to be made, |
|
1208 | In order to start logging again, a new %logstart call needs to be made, | |
1209 | possibly (though not necessarily) with a new filename, mode and other |
|
1209 | possibly (though not necessarily) with a new filename, mode and other | |
1210 | options.""" |
|
1210 | options.""" | |
1211 | self.logger.logstop() |
|
1211 | self.logger.logstop() | |
1212 |
|
1212 | |||
1213 | def magic_logoff(self,parameter_s=''): |
|
1213 | def magic_logoff(self,parameter_s=''): | |
1214 | """Temporarily stop logging. |
|
1214 | """Temporarily stop logging. | |
1215 |
|
1215 | |||
1216 | You must have previously started logging.""" |
|
1216 | You must have previously started logging.""" | |
1217 | self.shell.logger.switch_log(0) |
|
1217 | self.shell.logger.switch_log(0) | |
1218 |
|
1218 | |||
1219 | def magic_logon(self,parameter_s=''): |
|
1219 | def magic_logon(self,parameter_s=''): | |
1220 | """Restart logging. |
|
1220 | """Restart logging. | |
1221 |
|
1221 | |||
1222 | This function is for restarting logging which you've temporarily |
|
1222 | This function is for restarting logging which you've temporarily | |
1223 | stopped with %logoff. For starting logging for the first time, you |
|
1223 | stopped with %logoff. For starting logging for the first time, you | |
1224 | must use the %logstart function, which allows you to specify an |
|
1224 | must use the %logstart function, which allows you to specify an | |
1225 | optional log filename.""" |
|
1225 | optional log filename.""" | |
1226 |
|
1226 | |||
1227 | self.shell.logger.switch_log(1) |
|
1227 | self.shell.logger.switch_log(1) | |
1228 |
|
1228 | |||
1229 | def magic_logstate(self,parameter_s=''): |
|
1229 | def magic_logstate(self,parameter_s=''): | |
1230 | """Print the status of the logging system.""" |
|
1230 | """Print the status of the logging system.""" | |
1231 |
|
1231 | |||
1232 | self.shell.logger.logstate() |
|
1232 | self.shell.logger.logstate() | |
1233 |
|
1233 | |||
1234 | def magic_pdb(self, parameter_s=''): |
|
1234 | def magic_pdb(self, parameter_s=''): | |
1235 | """Control the automatic calling of the pdb interactive debugger. |
|
1235 | """Control the automatic calling of the pdb interactive debugger. | |
1236 |
|
1236 | |||
1237 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1237 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1238 | argument it works as a toggle. |
|
1238 | argument it works as a toggle. | |
1239 |
|
1239 | |||
1240 | When an exception is triggered, IPython can optionally call the |
|
1240 | When an exception is triggered, IPython can optionally call the | |
1241 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1241 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1242 | this feature on and off. |
|
1242 | this feature on and off. | |
1243 |
|
1243 | |||
1244 | The initial state of this feature is set in your ipythonrc |
|
1244 | The initial state of this feature is set in your ipythonrc | |
1245 | configuration file (the variable is called 'pdb'). |
|
1245 | configuration file (the variable is called 'pdb'). | |
1246 |
|
1246 | |||
1247 | If you want to just activate the debugger AFTER an exception has fired, |
|
1247 | If you want to just activate the debugger AFTER an exception has fired, | |
1248 | without having to type '%pdb on' and rerunning your code, you can use |
|
1248 | without having to type '%pdb on' and rerunning your code, you can use | |
1249 | the %debug magic.""" |
|
1249 | the %debug magic.""" | |
1250 |
|
1250 | |||
1251 | par = parameter_s.strip().lower() |
|
1251 | par = parameter_s.strip().lower() | |
1252 |
|
1252 | |||
1253 | if par: |
|
1253 | if par: | |
1254 | try: |
|
1254 | try: | |
1255 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1255 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1256 | except KeyError: |
|
1256 | except KeyError: | |
1257 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1257 | print ('Incorrect argument. Use on/1, off/0, ' | |
1258 | 'or nothing for a toggle.') |
|
1258 | 'or nothing for a toggle.') | |
1259 | return |
|
1259 | return | |
1260 | else: |
|
1260 | else: | |
1261 | # toggle |
|
1261 | # toggle | |
1262 | new_pdb = not self.shell.call_pdb |
|
1262 | new_pdb = not self.shell.call_pdb | |
1263 |
|
1263 | |||
1264 | # set on the shell |
|
1264 | # set on the shell | |
1265 | self.shell.call_pdb = new_pdb |
|
1265 | self.shell.call_pdb = new_pdb | |
1266 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1266 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1267 |
|
1267 | |||
1268 | def magic_debug(self, parameter_s=''): |
|
1268 | def magic_debug(self, parameter_s=''): | |
1269 | """Activate the interactive debugger in post-mortem mode. |
|
1269 | """Activate the interactive debugger in post-mortem mode. | |
1270 |
|
1270 | |||
1271 | If an exception has just occurred, this lets you inspect its stack |
|
1271 | If an exception has just occurred, this lets you inspect its stack | |
1272 | frames interactively. Note that this will always work only on the last |
|
1272 | frames interactively. Note that this will always work only on the last | |
1273 | traceback that occurred, so you must call this quickly after an |
|
1273 | traceback that occurred, so you must call this quickly after an | |
1274 | exception that you wish to inspect has fired, because if another one |
|
1274 | exception that you wish to inspect has fired, because if another one | |
1275 | occurs, it clobbers the previous one. |
|
1275 | occurs, it clobbers the previous one. | |
1276 |
|
1276 | |||
1277 | If you want IPython to automatically do this on every exception, see |
|
1277 | If you want IPython to automatically do this on every exception, see | |
1278 | the %pdb magic for more details. |
|
1278 | the %pdb magic for more details. | |
1279 | """ |
|
1279 | """ | |
1280 |
|
1280 | |||
1281 | self.shell.debugger(force=True) |
|
1281 | self.shell.debugger(force=True) | |
1282 |
|
1282 | |||
1283 | @testdec.skip_doctest |
|
1283 | @testdec.skip_doctest | |
1284 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1284 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1285 | opts=None,arg_lst=None,prog_ns=None): |
|
1285 | opts=None,arg_lst=None,prog_ns=None): | |
1286 |
|
1286 | |||
1287 | """Run a statement through the python code profiler. |
|
1287 | """Run a statement through the python code profiler. | |
1288 |
|
1288 | |||
1289 | Usage: |
|
1289 | Usage: | |
1290 | %prun [options] statement |
|
1290 | %prun [options] statement | |
1291 |
|
1291 | |||
1292 | The given statement (which doesn't require quote marks) is run via the |
|
1292 | The given statement (which doesn't require quote marks) is run via the | |
1293 | python profiler in a manner similar to the profile.run() function. |
|
1293 | python profiler in a manner similar to the profile.run() function. | |
1294 | Namespaces are internally managed to work correctly; profile.run |
|
1294 | Namespaces are internally managed to work correctly; profile.run | |
1295 | cannot be used in IPython because it makes certain assumptions about |
|
1295 | cannot be used in IPython because it makes certain assumptions about | |
1296 | namespaces which do not hold under IPython. |
|
1296 | namespaces which do not hold under IPython. | |
1297 |
|
1297 | |||
1298 | Options: |
|
1298 | Options: | |
1299 |
|
1299 | |||
1300 | -l <limit>: you can place restrictions on what or how much of the |
|
1300 | -l <limit>: you can place restrictions on what or how much of the | |
1301 | profile gets printed. The limit value can be: |
|
1301 | profile gets printed. The limit value can be: | |
1302 |
|
1302 | |||
1303 | * A string: only information for function names containing this string |
|
1303 | * A string: only information for function names containing this string | |
1304 | is printed. |
|
1304 | is printed. | |
1305 |
|
1305 | |||
1306 | * An integer: only these many lines are printed. |
|
1306 | * An integer: only these many lines are printed. | |
1307 |
|
1307 | |||
1308 | * A float (between 0 and 1): this fraction of the report is printed |
|
1308 | * A float (between 0 and 1): this fraction of the report is printed | |
1309 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1309 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1310 |
|
1310 | |||
1311 | You can combine several limits with repeated use of the option. For |
|
1311 | You can combine several limits with repeated use of the option. For | |
1312 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1312 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1313 | information about class constructors. |
|
1313 | information about class constructors. | |
1314 |
|
1314 | |||
1315 | -r: return the pstats.Stats object generated by the profiling. This |
|
1315 | -r: return the pstats.Stats object generated by the profiling. This | |
1316 | object has all the information about the profile in it, and you can |
|
1316 | object has all the information about the profile in it, and you can | |
1317 | later use it for further analysis or in other functions. |
|
1317 | later use it for further analysis or in other functions. | |
1318 |
|
1318 | |||
1319 | -s <key>: sort profile by given key. You can provide more than one key |
|
1319 | -s <key>: sort profile by given key. You can provide more than one key | |
1320 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1320 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1321 | default sorting key is 'time'. |
|
1321 | default sorting key is 'time'. | |
1322 |
|
1322 | |||
1323 | The following is copied verbatim from the profile documentation |
|
1323 | The following is copied verbatim from the profile documentation | |
1324 | referenced below: |
|
1324 | referenced below: | |
1325 |
|
1325 | |||
1326 | When more than one key is provided, additional keys are used as |
|
1326 | When more than one key is provided, additional keys are used as | |
1327 | secondary criteria when the there is equality in all keys selected |
|
1327 | secondary criteria when the there is equality in all keys selected | |
1328 | before them. |
|
1328 | before them. | |
1329 |
|
1329 | |||
1330 | Abbreviations can be used for any key names, as long as the |
|
1330 | Abbreviations can be used for any key names, as long as the | |
1331 | abbreviation is unambiguous. The following are the keys currently |
|
1331 | abbreviation is unambiguous. The following are the keys currently | |
1332 | defined: |
|
1332 | defined: | |
1333 |
|
1333 | |||
1334 | Valid Arg Meaning |
|
1334 | Valid Arg Meaning | |
1335 | "calls" call count |
|
1335 | "calls" call count | |
1336 | "cumulative" cumulative time |
|
1336 | "cumulative" cumulative time | |
1337 | "file" file name |
|
1337 | "file" file name | |
1338 | "module" file name |
|
1338 | "module" file name | |
1339 | "pcalls" primitive call count |
|
1339 | "pcalls" primitive call count | |
1340 | "line" line number |
|
1340 | "line" line number | |
1341 | "name" function name |
|
1341 | "name" function name | |
1342 | "nfl" name/file/line |
|
1342 | "nfl" name/file/line | |
1343 | "stdname" standard name |
|
1343 | "stdname" standard name | |
1344 | "time" internal time |
|
1344 | "time" internal time | |
1345 |
|
1345 | |||
1346 | Note that all sorts on statistics are in descending order (placing |
|
1346 | Note that all sorts on statistics are in descending order (placing | |
1347 | most time consuming items first), where as name, file, and line number |
|
1347 | most time consuming items first), where as name, file, and line number | |
1348 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1348 | searches are in ascending order (i.e., alphabetical). The subtle | |
1349 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1349 | distinction between "nfl" and "stdname" is that the standard name is a | |
1350 | sort of the name as printed, which means that the embedded line |
|
1350 | sort of the name as printed, which means that the embedded line | |
1351 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1351 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1352 | would (if the file names were the same) appear in the string order |
|
1352 | would (if the file names were the same) appear in the string order | |
1353 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1353 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1354 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1354 | line numbers. In fact, sort_stats("nfl") is the same as | |
1355 | sort_stats("name", "file", "line"). |
|
1355 | sort_stats("name", "file", "line"). | |
1356 |
|
1356 | |||
1357 | -T <filename>: save profile results as shown on screen to a text |
|
1357 | -T <filename>: save profile results as shown on screen to a text | |
1358 | file. The profile is still shown on screen. |
|
1358 | file. The profile is still shown on screen. | |
1359 |
|
1359 | |||
1360 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1360 | -D <filename>: save (via dump_stats) profile statistics to given | |
1361 | filename. This data is in a format understod by the pstats module, and |
|
1361 | filename. This data is in a format understod by the pstats module, and | |
1362 | is generated by a call to the dump_stats() method of profile |
|
1362 | is generated by a call to the dump_stats() method of profile | |
1363 | objects. The profile is still shown on screen. |
|
1363 | objects. The profile is still shown on screen. | |
1364 |
|
1364 | |||
1365 | If you want to run complete programs under the profiler's control, use |
|
1365 | If you want to run complete programs under the profiler's control, use | |
1366 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1366 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1367 | contains profiler specific options as described here. |
|
1367 | contains profiler specific options as described here. | |
1368 |
|
1368 | |||
1369 | You can read the complete documentation for the profile module with:: |
|
1369 | You can read the complete documentation for the profile module with:: | |
1370 |
|
1370 | |||
1371 | In [1]: import profile; profile.help() |
|
1371 | In [1]: import profile; profile.help() | |
1372 | """ |
|
1372 | """ | |
1373 |
|
1373 | |||
1374 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1374 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1375 | # protect user quote marks |
|
1375 | # protect user quote marks | |
1376 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1376 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1377 |
|
1377 | |||
1378 | if user_mode: # regular user call |
|
1378 | if user_mode: # regular user call | |
1379 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1379 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1380 | list_all=1) |
|
1380 | list_all=1) | |
1381 | namespace = self.shell.user_ns |
|
1381 | namespace = self.shell.user_ns | |
1382 | else: # called to run a program by %run -p |
|
1382 | else: # called to run a program by %run -p | |
1383 | try: |
|
1383 | try: | |
1384 | filename = get_py_filename(arg_lst[0]) |
|
1384 | filename = get_py_filename(arg_lst[0]) | |
1385 | except IOError,msg: |
|
1385 | except IOError,msg: | |
1386 | error(msg) |
|
1386 | error(msg) | |
1387 | return |
|
1387 | return | |
1388 |
|
1388 | |||
1389 | arg_str = 'execfile(filename,prog_ns)' |
|
1389 | arg_str = 'execfile(filename,prog_ns)' | |
1390 | namespace = locals() |
|
1390 | namespace = locals() | |
1391 |
|
1391 | |||
1392 | opts.merge(opts_def) |
|
1392 | opts.merge(opts_def) | |
1393 |
|
1393 | |||
1394 | prof = profile.Profile() |
|
1394 | prof = profile.Profile() | |
1395 | try: |
|
1395 | try: | |
1396 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1396 | prof = prof.runctx(arg_str,namespace,namespace) | |
1397 | sys_exit = '' |
|
1397 | sys_exit = '' | |
1398 | except SystemExit: |
|
1398 | except SystemExit: | |
1399 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1399 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1400 |
|
1400 | |||
1401 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1401 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1402 |
|
1402 | |||
1403 | lims = opts.l |
|
1403 | lims = opts.l | |
1404 | if lims: |
|
1404 | if lims: | |
1405 | lims = [] # rebuild lims with ints/floats/strings |
|
1405 | lims = [] # rebuild lims with ints/floats/strings | |
1406 | for lim in opts.l: |
|
1406 | for lim in opts.l: | |
1407 | try: |
|
1407 | try: | |
1408 | lims.append(int(lim)) |
|
1408 | lims.append(int(lim)) | |
1409 | except ValueError: |
|
1409 | except ValueError: | |
1410 | try: |
|
1410 | try: | |
1411 | lims.append(float(lim)) |
|
1411 | lims.append(float(lim)) | |
1412 | except ValueError: |
|
1412 | except ValueError: | |
1413 | lims.append(lim) |
|
1413 | lims.append(lim) | |
1414 |
|
1414 | |||
1415 | # Trap output. |
|
1415 | # Trap output. | |
1416 | stdout_trap = StringIO() |
|
1416 | stdout_trap = StringIO() | |
1417 |
|
1417 | |||
1418 | if hasattr(stats,'stream'): |
|
1418 | if hasattr(stats,'stream'): | |
1419 | # In newer versions of python, the stats object has a 'stream' |
|
1419 | # In newer versions of python, the stats object has a 'stream' | |
1420 | # attribute to write into. |
|
1420 | # attribute to write into. | |
1421 | stats.stream = stdout_trap |
|
1421 | stats.stream = stdout_trap | |
1422 | stats.print_stats(*lims) |
|
1422 | stats.print_stats(*lims) | |
1423 | else: |
|
1423 | else: | |
1424 | # For older versions, we manually redirect stdout during printing |
|
1424 | # For older versions, we manually redirect stdout during printing | |
1425 | sys_stdout = sys.stdout |
|
1425 | sys_stdout = sys.stdout | |
1426 | try: |
|
1426 | try: | |
1427 | sys.stdout = stdout_trap |
|
1427 | sys.stdout = stdout_trap | |
1428 | stats.print_stats(*lims) |
|
1428 | stats.print_stats(*lims) | |
1429 | finally: |
|
1429 | finally: | |
1430 | sys.stdout = sys_stdout |
|
1430 | sys.stdout = sys_stdout | |
1431 |
|
1431 | |||
1432 | output = stdout_trap.getvalue() |
|
1432 | output = stdout_trap.getvalue() | |
1433 | output = output.rstrip() |
|
1433 | output = output.rstrip() | |
1434 |
|
1434 | |||
1435 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1435 | page(output,screen_lines=self.shell.rc.screen_length) | |
1436 | print sys_exit, |
|
1436 | print sys_exit, | |
1437 |
|
1437 | |||
1438 | dump_file = opts.D[0] |
|
1438 | dump_file = opts.D[0] | |
1439 | text_file = opts.T[0] |
|
1439 | text_file = opts.T[0] | |
1440 | if dump_file: |
|
1440 | if dump_file: | |
1441 | prof.dump_stats(dump_file) |
|
1441 | prof.dump_stats(dump_file) | |
1442 | print '\n*** Profile stats marshalled to file',\ |
|
1442 | print '\n*** Profile stats marshalled to file',\ | |
1443 | `dump_file`+'.',sys_exit |
|
1443 | `dump_file`+'.',sys_exit | |
1444 | if text_file: |
|
1444 | if text_file: | |
1445 | pfile = file(text_file,'w') |
|
1445 | pfile = file(text_file,'w') | |
1446 | pfile.write(output) |
|
1446 | pfile.write(output) | |
1447 | pfile.close() |
|
1447 | pfile.close() | |
1448 | print '\n*** Profile printout saved to text file',\ |
|
1448 | print '\n*** Profile printout saved to text file',\ | |
1449 | `text_file`+'.',sys_exit |
|
1449 | `text_file`+'.',sys_exit | |
1450 |
|
1450 | |||
1451 | if opts.has_key('r'): |
|
1451 | if opts.has_key('r'): | |
1452 | return stats |
|
1452 | return stats | |
1453 | else: |
|
1453 | else: | |
1454 | return None |
|
1454 | return None | |
1455 |
|
1455 | |||
1456 | @testdec.skip_doctest |
|
1456 | @testdec.skip_doctest | |
1457 | def magic_run(self, parameter_s ='',runner=None, |
|
1457 | def magic_run(self, parameter_s ='',runner=None, | |
1458 | file_finder=get_py_filename): |
|
1458 | file_finder=get_py_filename): | |
1459 | """Run the named file inside IPython as a program. |
|
1459 | """Run the named file inside IPython as a program. | |
1460 |
|
1460 | |||
1461 | Usage:\\ |
|
1461 | Usage:\\ | |
1462 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1462 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1463 |
|
1463 | |||
1464 | Parameters after the filename are passed as command-line arguments to |
|
1464 | Parameters after the filename are passed as command-line arguments to | |
1465 | the program (put in sys.argv). Then, control returns to IPython's |
|
1465 | the program (put in sys.argv). Then, control returns to IPython's | |
1466 | prompt. |
|
1466 | prompt. | |
1467 |
|
1467 | |||
1468 | This is similar to running at a system prompt:\\ |
|
1468 | This is similar to running at a system prompt:\\ | |
1469 | $ python file args\\ |
|
1469 | $ python file args\\ | |
1470 | but with the advantage of giving you IPython's tracebacks, and of |
|
1470 | but with the advantage of giving you IPython's tracebacks, and of | |
1471 | loading all variables into your interactive namespace for further use |
|
1471 | loading all variables into your interactive namespace for further use | |
1472 | (unless -p is used, see below). |
|
1472 | (unless -p is used, see below). | |
1473 |
|
1473 | |||
1474 | The file is executed in a namespace initially consisting only of |
|
1474 | The file is executed in a namespace initially consisting only of | |
1475 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1475 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1476 | sees its environment as if it were being run as a stand-alone program |
|
1476 | sees its environment as if it were being run as a stand-alone program | |
1477 | (except for sharing global objects such as previously imported |
|
1477 | (except for sharing global objects such as previously imported | |
1478 | modules). But after execution, the IPython interactive namespace gets |
|
1478 | modules). But after execution, the IPython interactive namespace gets | |
1479 | updated with all variables defined in the program (except for __name__ |
|
1479 | updated with all variables defined in the program (except for __name__ | |
1480 | and sys.argv). This allows for very convenient loading of code for |
|
1480 | and sys.argv). This allows for very convenient loading of code for | |
1481 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1481 | interactive work, while giving each program a 'clean sheet' to run in. | |
1482 |
|
1482 | |||
1483 | Options: |
|
1483 | Options: | |
1484 |
|
1484 | |||
1485 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1485 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1486 | without extension (as python does under import). This allows running |
|
1486 | without extension (as python does under import). This allows running | |
1487 | scripts and reloading the definitions in them without calling code |
|
1487 | scripts and reloading the definitions in them without calling code | |
1488 | protected by an ' if __name__ == "__main__" ' clause. |
|
1488 | protected by an ' if __name__ == "__main__" ' clause. | |
1489 |
|
1489 | |||
1490 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1490 | -i: run the file in IPython's namespace instead of an empty one. This | |
1491 | is useful if you are experimenting with code written in a text editor |
|
1491 | is useful if you are experimenting with code written in a text editor | |
1492 | which depends on variables defined interactively. |
|
1492 | which depends on variables defined interactively. | |
1493 |
|
1493 | |||
1494 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1494 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1495 | being run. This is particularly useful if IPython is being used to |
|
1495 | being run. This is particularly useful if IPython is being used to | |
1496 | run unittests, which always exit with a sys.exit() call. In such |
|
1496 | run unittests, which always exit with a sys.exit() call. In such | |
1497 | cases you are interested in the output of the test results, not in |
|
1497 | cases you are interested in the output of the test results, not in | |
1498 | seeing a traceback of the unittest module. |
|
1498 | seeing a traceback of the unittest module. | |
1499 |
|
1499 | |||
1500 | -t: print timing information at the end of the run. IPython will give |
|
1500 | -t: print timing information at the end of the run. IPython will give | |
1501 | you an estimated CPU time consumption for your script, which under |
|
1501 | you an estimated CPU time consumption for your script, which under | |
1502 | Unix uses the resource module to avoid the wraparound problems of |
|
1502 | Unix uses the resource module to avoid the wraparound problems of | |
1503 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1503 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1504 | is also given (for Windows platforms this is reported as 0.0). |
|
1504 | is also given (for Windows platforms this is reported as 0.0). | |
1505 |
|
1505 | |||
1506 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1506 | If -t is given, an additional -N<N> option can be given, where <N> | |
1507 | must be an integer indicating how many times you want the script to |
|
1507 | must be an integer indicating how many times you want the script to | |
1508 | run. The final timing report will include total and per run results. |
|
1508 | run. The final timing report will include total and per run results. | |
1509 |
|
1509 | |||
1510 | For example (testing the script uniq_stable.py): |
|
1510 | For example (testing the script uniq_stable.py): | |
1511 |
|
1511 | |||
1512 | In [1]: run -t uniq_stable |
|
1512 | In [1]: run -t uniq_stable | |
1513 |
|
1513 | |||
1514 | IPython CPU timings (estimated):\\ |
|
1514 | IPython CPU timings (estimated):\\ | |
1515 | User : 0.19597 s.\\ |
|
1515 | User : 0.19597 s.\\ | |
1516 | System: 0.0 s.\\ |
|
1516 | System: 0.0 s.\\ | |
1517 |
|
1517 | |||
1518 | In [2]: run -t -N5 uniq_stable |
|
1518 | In [2]: run -t -N5 uniq_stable | |
1519 |
|
1519 | |||
1520 | IPython CPU timings (estimated):\\ |
|
1520 | IPython CPU timings (estimated):\\ | |
1521 | Total runs performed: 5\\ |
|
1521 | Total runs performed: 5\\ | |
1522 | Times : Total Per run\\ |
|
1522 | Times : Total Per run\\ | |
1523 | User : 0.910862 s, 0.1821724 s.\\ |
|
1523 | User : 0.910862 s, 0.1821724 s.\\ | |
1524 | System: 0.0 s, 0.0 s. |
|
1524 | System: 0.0 s, 0.0 s. | |
1525 |
|
1525 | |||
1526 | -d: run your program under the control of pdb, the Python debugger. |
|
1526 | -d: run your program under the control of pdb, the Python debugger. | |
1527 | This allows you to execute your program step by step, watch variables, |
|
1527 | This allows you to execute your program step by step, watch variables, | |
1528 | etc. Internally, what IPython does is similar to calling: |
|
1528 | etc. Internally, what IPython does is similar to calling: | |
1529 |
|
1529 | |||
1530 | pdb.run('execfile("YOURFILENAME")') |
|
1530 | pdb.run('execfile("YOURFILENAME")') | |
1531 |
|
1531 | |||
1532 | with a breakpoint set on line 1 of your file. You can change the line |
|
1532 | with a breakpoint set on line 1 of your file. You can change the line | |
1533 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1533 | number for this automatic breakpoint to be <N> by using the -bN option | |
1534 | (where N must be an integer). For example: |
|
1534 | (where N must be an integer). For example: | |
1535 |
|
1535 | |||
1536 | %run -d -b40 myscript |
|
1536 | %run -d -b40 myscript | |
1537 |
|
1537 | |||
1538 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1538 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1539 | the first breakpoint must be set on a line which actually does |
|
1539 | the first breakpoint must be set on a line which actually does | |
1540 | something (not a comment or docstring) for it to stop execution. |
|
1540 | something (not a comment or docstring) for it to stop execution. | |
1541 |
|
1541 | |||
1542 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1542 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1543 | first enter 'c' (without qoutes) to start execution up to the first |
|
1543 | first enter 'c' (without qoutes) to start execution up to the first | |
1544 | breakpoint. |
|
1544 | breakpoint. | |
1545 |
|
1545 | |||
1546 | Entering 'help' gives information about the use of the debugger. You |
|
1546 | Entering 'help' gives information about the use of the debugger. You | |
1547 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1547 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1548 | at a prompt. |
|
1548 | at a prompt. | |
1549 |
|
1549 | |||
1550 | -p: run program under the control of the Python profiler module (which |
|
1550 | -p: run program under the control of the Python profiler module (which | |
1551 | prints a detailed report of execution times, function calls, etc). |
|
1551 | prints a detailed report of execution times, function calls, etc). | |
1552 |
|
1552 | |||
1553 | You can pass other options after -p which affect the behavior of the |
|
1553 | You can pass other options after -p which affect the behavior of the | |
1554 | profiler itself. See the docs for %prun for details. |
|
1554 | profiler itself. See the docs for %prun for details. | |
1555 |
|
1555 | |||
1556 | In this mode, the program's variables do NOT propagate back to the |
|
1556 | In this mode, the program's variables do NOT propagate back to the | |
1557 | IPython interactive namespace (because they remain in the namespace |
|
1557 | IPython interactive namespace (because they remain in the namespace | |
1558 | where the profiler executes them). |
|
1558 | where the profiler executes them). | |
1559 |
|
1559 | |||
1560 | Internally this triggers a call to %prun, see its documentation for |
|
1560 | Internally this triggers a call to %prun, see its documentation for | |
1561 | details on the options available specifically for profiling. |
|
1561 | details on the options available specifically for profiling. | |
1562 |
|
1562 | |||
1563 | There is one special usage for which the text above doesn't apply: |
|
1563 | There is one special usage for which the text above doesn't apply: | |
1564 | if the filename ends with .ipy, the file is run as ipython script, |
|
1564 | if the filename ends with .ipy, the file is run as ipython script, | |
1565 | just as if the commands were written on IPython prompt. |
|
1565 | just as if the commands were written on IPython prompt. | |
1566 | """ |
|
1566 | """ | |
1567 |
|
1567 | |||
1568 | # get arguments and set sys.argv for program to be run. |
|
1568 | # get arguments and set sys.argv for program to be run. | |
1569 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1569 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1570 | mode='list',list_all=1) |
|
1570 | mode='list',list_all=1) | |
1571 |
|
1571 | |||
1572 | try: |
|
1572 | try: | |
1573 | filename = file_finder(arg_lst[0]) |
|
1573 | filename = file_finder(arg_lst[0]) | |
1574 | except IndexError: |
|
1574 | except IndexError: | |
1575 | warn('you must provide at least a filename.') |
|
1575 | warn('you must provide at least a filename.') | |
1576 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1576 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1577 | return |
|
1577 | return | |
1578 | except IOError,msg: |
|
1578 | except IOError,msg: | |
1579 | error(msg) |
|
1579 | error(msg) | |
1580 | return |
|
1580 | return | |
1581 |
|
1581 | |||
1582 | if filename.lower().endswith('.ipy'): |
|
1582 | if filename.lower().endswith('.ipy'): | |
1583 | self.api.runlines(open(filename).read()) |
|
1583 | self.api.runlines(open(filename).read()) | |
1584 | return |
|
1584 | return | |
1585 |
|
1585 | |||
1586 | # Control the response to exit() calls made by the script being run |
|
1586 | # Control the response to exit() calls made by the script being run | |
1587 | exit_ignore = opts.has_key('e') |
|
1587 | exit_ignore = opts.has_key('e') | |
1588 |
|
1588 | |||
1589 | # Make sure that the running script gets a proper sys.argv as if it |
|
1589 | # Make sure that the running script gets a proper sys.argv as if it | |
1590 | # were run from a system shell. |
|
1590 | # were run from a system shell. | |
1591 | save_argv = sys.argv # save it for later restoring |
|
1591 | save_argv = sys.argv # save it for later restoring | |
1592 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1592 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1593 |
|
1593 | |||
1594 | if opts.has_key('i'): |
|
1594 | if opts.has_key('i'): | |
1595 | # Run in user's interactive namespace |
|
1595 | # Run in user's interactive namespace | |
1596 | prog_ns = self.shell.user_ns |
|
1596 | prog_ns = self.shell.user_ns | |
1597 | __name__save = self.shell.user_ns['__name__'] |
|
1597 | __name__save = self.shell.user_ns['__name__'] | |
1598 | prog_ns['__name__'] = '__main__' |
|
1598 | prog_ns['__name__'] = '__main__' | |
1599 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1599 | main_mod = self.shell.new_main_mod(prog_ns) | |
1600 | else: |
|
1600 | else: | |
1601 | # Run in a fresh, empty namespace |
|
1601 | # Run in a fresh, empty namespace | |
1602 | if opts.has_key('n'): |
|
1602 | if opts.has_key('n'): | |
1603 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1603 | name = os.path.splitext(os.path.basename(filename))[0] | |
1604 | else: |
|
1604 | else: | |
1605 | name = '__main__' |
|
1605 | name = '__main__' | |
1606 |
|
1606 | |||
1607 | main_mod = self.shell.new_main_mod() |
|
1607 | main_mod = self.shell.new_main_mod() | |
1608 | prog_ns = main_mod.__dict__ |
|
1608 | prog_ns = main_mod.__dict__ | |
1609 | prog_ns['__name__'] = name |
|
1609 | prog_ns['__name__'] = name | |
1610 |
|
1610 | |||
1611 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1611 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1612 | # set the __file__ global in the script's namespace |
|
1612 | # set the __file__ global in the script's namespace | |
1613 | prog_ns['__file__'] = filename |
|
1613 | prog_ns['__file__'] = filename | |
1614 |
|
1614 | |||
1615 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1615 | # pickle fix. See iplib for an explanation. But we need to make sure | |
1616 | # that, if we overwrite __main__, we replace it at the end |
|
1616 | # that, if we overwrite __main__, we replace it at the end | |
1617 | main_mod_name = prog_ns['__name__'] |
|
1617 | main_mod_name = prog_ns['__name__'] | |
1618 |
|
1618 | |||
1619 | if main_mod_name == '__main__': |
|
1619 | if main_mod_name == '__main__': | |
1620 | restore_main = sys.modules['__main__'] |
|
1620 | restore_main = sys.modules['__main__'] | |
1621 | else: |
|
1621 | else: | |
1622 | restore_main = False |
|
1622 | restore_main = False | |
1623 |
|
1623 | |||
1624 | # This needs to be undone at the end to prevent holding references to |
|
1624 | # This needs to be undone at the end to prevent holding references to | |
1625 | # every single object ever created. |
|
1625 | # every single object ever created. | |
1626 | sys.modules[main_mod_name] = main_mod |
|
1626 | sys.modules[main_mod_name] = main_mod | |
1627 |
|
1627 | |||
1628 | stats = None |
|
1628 | stats = None | |
1629 | try: |
|
1629 | try: | |
1630 | self.shell.savehist() |
|
1630 | self.shell.savehist() | |
1631 |
|
1631 | |||
1632 | if opts.has_key('p'): |
|
1632 | if opts.has_key('p'): | |
1633 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1633 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1634 | else: |
|
1634 | else: | |
1635 | if opts.has_key('d'): |
|
1635 | if opts.has_key('d'): | |
1636 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1636 | deb = Debugger.Pdb(self.shell.rc.colors) | |
1637 | # reset Breakpoint state, which is moronically kept |
|
1637 | # reset Breakpoint state, which is moronically kept | |
1638 | # in a class |
|
1638 | # in a class | |
1639 | bdb.Breakpoint.next = 1 |
|
1639 | bdb.Breakpoint.next = 1 | |
1640 | bdb.Breakpoint.bplist = {} |
|
1640 | bdb.Breakpoint.bplist = {} | |
1641 | bdb.Breakpoint.bpbynumber = [None] |
|
1641 | bdb.Breakpoint.bpbynumber = [None] | |
1642 | # Set an initial breakpoint to stop execution |
|
1642 | # Set an initial breakpoint to stop execution | |
1643 | maxtries = 10 |
|
1643 | maxtries = 10 | |
1644 | bp = int(opts.get('b',[1])[0]) |
|
1644 | bp = int(opts.get('b',[1])[0]) | |
1645 | checkline = deb.checkline(filename,bp) |
|
1645 | checkline = deb.checkline(filename,bp) | |
1646 | if not checkline: |
|
1646 | if not checkline: | |
1647 | for bp in range(bp+1,bp+maxtries+1): |
|
1647 | for bp in range(bp+1,bp+maxtries+1): | |
1648 | if deb.checkline(filename,bp): |
|
1648 | if deb.checkline(filename,bp): | |
1649 | break |
|
1649 | break | |
1650 | else: |
|
1650 | else: | |
1651 | msg = ("\nI failed to find a valid line to set " |
|
1651 | msg = ("\nI failed to find a valid line to set " | |
1652 | "a breakpoint\n" |
|
1652 | "a breakpoint\n" | |
1653 | "after trying up to line: %s.\n" |
|
1653 | "after trying up to line: %s.\n" | |
1654 | "Please set a valid breakpoint manually " |
|
1654 | "Please set a valid breakpoint manually " | |
1655 | "with the -b option." % bp) |
|
1655 | "with the -b option." % bp) | |
1656 | error(msg) |
|
1656 | error(msg) | |
1657 | return |
|
1657 | return | |
1658 | # if we find a good linenumber, set the breakpoint |
|
1658 | # if we find a good linenumber, set the breakpoint | |
1659 | deb.do_break('%s:%s' % (filename,bp)) |
|
1659 | deb.do_break('%s:%s' % (filename,bp)) | |
1660 | # Start file run |
|
1660 | # Start file run | |
1661 | print "NOTE: Enter 'c' at the", |
|
1661 | print "NOTE: Enter 'c' at the", | |
1662 | print "%s prompt to start your script." % deb.prompt |
|
1662 | print "%s prompt to start your script." % deb.prompt | |
1663 | try: |
|
1663 | try: | |
1664 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1664 | deb.run('execfile("%s")' % filename,prog_ns) | |
1665 |
|
1665 | |||
1666 | except: |
|
1666 | except: | |
1667 | etype, value, tb = sys.exc_info() |
|
1667 | etype, value, tb = sys.exc_info() | |
1668 | # Skip three frames in the traceback: the %run one, |
|
1668 | # Skip three frames in the traceback: the %run one, | |
1669 | # one inside bdb.py, and the command-line typed by the |
|
1669 | # one inside bdb.py, and the command-line typed by the | |
1670 | # user (run by exec in pdb itself). |
|
1670 | # user (run by exec in pdb itself). | |
1671 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1671 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1672 | else: |
|
1672 | else: | |
1673 | if runner is None: |
|
1673 | if runner is None: | |
1674 | runner = self.shell.safe_execfile |
|
1674 | runner = self.shell.safe_execfile | |
1675 | if opts.has_key('t'): |
|
1675 | if opts.has_key('t'): | |
1676 | # timed execution |
|
1676 | # timed execution | |
1677 | try: |
|
1677 | try: | |
1678 | nruns = int(opts['N'][0]) |
|
1678 | nruns = int(opts['N'][0]) | |
1679 | if nruns < 1: |
|
1679 | if nruns < 1: | |
1680 | error('Number of runs must be >=1') |
|
1680 | error('Number of runs must be >=1') | |
1681 | return |
|
1681 | return | |
1682 | except (KeyError): |
|
1682 | except (KeyError): | |
1683 | nruns = 1 |
|
1683 | nruns = 1 | |
1684 | if nruns == 1: |
|
1684 | if nruns == 1: | |
1685 | t0 = clock2() |
|
1685 | t0 = clock2() | |
1686 | runner(filename,prog_ns,prog_ns, |
|
1686 | runner(filename,prog_ns,prog_ns, | |
1687 | exit_ignore=exit_ignore) |
|
1687 | exit_ignore=exit_ignore) | |
1688 | t1 = clock2() |
|
1688 | t1 = clock2() | |
1689 | t_usr = t1[0]-t0[0] |
|
1689 | t_usr = t1[0]-t0[0] | |
1690 | t_sys = t1[1]-t0[1] |
|
1690 | t_sys = t1[1]-t0[1] | |
1691 | print "\nIPython CPU timings (estimated):" |
|
1691 | print "\nIPython CPU timings (estimated):" | |
1692 | print " User : %10s s." % t_usr |
|
1692 | print " User : %10s s." % t_usr | |
1693 | print " System: %10s s." % t_sys |
|
1693 | print " System: %10s s." % t_sys | |
1694 | else: |
|
1694 | else: | |
1695 | runs = range(nruns) |
|
1695 | runs = range(nruns) | |
1696 | t0 = clock2() |
|
1696 | t0 = clock2() | |
1697 | for nr in runs: |
|
1697 | for nr in runs: | |
1698 | runner(filename,prog_ns,prog_ns, |
|
1698 | runner(filename,prog_ns,prog_ns, | |
1699 | exit_ignore=exit_ignore) |
|
1699 | exit_ignore=exit_ignore) | |
1700 | t1 = clock2() |
|
1700 | t1 = clock2() | |
1701 | t_usr = t1[0]-t0[0] |
|
1701 | t_usr = t1[0]-t0[0] | |
1702 | t_sys = t1[1]-t0[1] |
|
1702 | t_sys = t1[1]-t0[1] | |
1703 | print "\nIPython CPU timings (estimated):" |
|
1703 | print "\nIPython CPU timings (estimated):" | |
1704 | print "Total runs performed:",nruns |
|
1704 | print "Total runs performed:",nruns | |
1705 | print " Times : %10s %10s" % ('Total','Per run') |
|
1705 | print " Times : %10s %10s" % ('Total','Per run') | |
1706 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1706 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1707 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1707 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1708 |
|
1708 | |||
1709 | else: |
|
1709 | else: | |
1710 | # regular execution |
|
1710 | # regular execution | |
1711 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1711 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1712 |
|
1712 | |||
1713 | if opts.has_key('i'): |
|
1713 | if opts.has_key('i'): | |
1714 | self.shell.user_ns['__name__'] = __name__save |
|
1714 | self.shell.user_ns['__name__'] = __name__save | |
1715 | else: |
|
1715 | else: | |
1716 | # The shell MUST hold a reference to prog_ns so after %run |
|
1716 | # The shell MUST hold a reference to prog_ns so after %run | |
1717 | # exits, the python deletion mechanism doesn't zero it out |
|
1717 | # exits, the python deletion mechanism doesn't zero it out | |
1718 | # (leaving dangling references). |
|
1718 | # (leaving dangling references). | |
1719 | self.shell.cache_main_mod(prog_ns,filename) |
|
1719 | self.shell.cache_main_mod(prog_ns,filename) | |
1720 | # update IPython interactive namespace |
|
1720 | # update IPython interactive namespace | |
1721 |
|
1721 | |||
1722 | # Some forms of read errors on the file may mean the |
|
1722 | # Some forms of read errors on the file may mean the | |
1723 | # __name__ key was never set; using pop we don't have to |
|
1723 | # __name__ key was never set; using pop we don't have to | |
1724 | # worry about a possible KeyError. |
|
1724 | # worry about a possible KeyError. | |
1725 | prog_ns.pop('__name__', None) |
|
1725 | prog_ns.pop('__name__', None) | |
1726 |
|
1726 | |||
1727 | self.shell.user_ns.update(prog_ns) |
|
1727 | self.shell.user_ns.update(prog_ns) | |
1728 | finally: |
|
1728 | finally: | |
1729 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1729 | # It's a bit of a mystery why, but __builtins__ can change from | |
1730 | # being a module to becoming a dict missing some key data after |
|
1730 | # being a module to becoming a dict missing some key data after | |
1731 | # %run. As best I can see, this is NOT something IPython is doing |
|
1731 | # %run. As best I can see, this is NOT something IPython is doing | |
1732 | # at all, and similar problems have been reported before: |
|
1732 | # at all, and similar problems have been reported before: | |
1733 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1733 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1734 | # Since this seems to be done by the interpreter itself, the best |
|
1734 | # Since this seems to be done by the interpreter itself, the best | |
1735 | # we can do is to at least restore __builtins__ for the user on |
|
1735 | # we can do is to at least restore __builtins__ for the user on | |
1736 | # exit. |
|
1736 | # exit. | |
1737 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1737 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1738 |
|
1738 | |||
1739 | # Ensure key global structures are restored |
|
1739 | # Ensure key global structures are restored | |
1740 | sys.argv = save_argv |
|
1740 | sys.argv = save_argv | |
1741 | if restore_main: |
|
1741 | if restore_main: | |
1742 | sys.modules['__main__'] = restore_main |
|
1742 | sys.modules['__main__'] = restore_main | |
1743 | else: |
|
1743 | else: | |
1744 | # Remove from sys.modules the reference to main_mod we'd |
|
1744 | # Remove from sys.modules the reference to main_mod we'd | |
1745 | # added. Otherwise it will trap references to objects |
|
1745 | # added. Otherwise it will trap references to objects | |
1746 | # contained therein. |
|
1746 | # contained therein. | |
1747 | del sys.modules[main_mod_name] |
|
1747 | del sys.modules[main_mod_name] | |
1748 |
|
1748 | |||
1749 | self.shell.reloadhist() |
|
1749 | self.shell.reloadhist() | |
1750 |
|
1750 | |||
1751 | return stats |
|
1751 | return stats | |
1752 |
|
1752 | |||
1753 | def magic_runlog(self, parameter_s =''): |
|
1753 | def magic_runlog(self, parameter_s =''): | |
1754 | """Run files as logs. |
|
1754 | """Run files as logs. | |
1755 |
|
1755 | |||
1756 | Usage:\\ |
|
1756 | Usage:\\ | |
1757 | %runlog file1 file2 ... |
|
1757 | %runlog file1 file2 ... | |
1758 |
|
1758 | |||
1759 | Run the named files (treating them as log files) in sequence inside |
|
1759 | Run the named files (treating them as log files) in sequence inside | |
1760 | the interpreter, and return to the prompt. This is much slower than |
|
1760 | the interpreter, and return to the prompt. This is much slower than | |
1761 | %run because each line is executed in a try/except block, but it |
|
1761 | %run because each line is executed in a try/except block, but it | |
1762 | allows running files with syntax errors in them. |
|
1762 | allows running files with syntax errors in them. | |
1763 |
|
1763 | |||
1764 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1764 | Normally IPython will guess when a file is one of its own logfiles, so | |
1765 | you can typically use %run even for logs. This shorthand allows you to |
|
1765 | you can typically use %run even for logs. This shorthand allows you to | |
1766 | force any file to be treated as a log file.""" |
|
1766 | force any file to be treated as a log file.""" | |
1767 |
|
1767 | |||
1768 | for f in parameter_s.split(): |
|
1768 | for f in parameter_s.split(): | |
1769 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1769 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1770 | self.shell.user_ns,islog=1) |
|
1770 | self.shell.user_ns,islog=1) | |
1771 |
|
1771 | |||
1772 | @testdec.skip_doctest |
|
1772 | @testdec.skip_doctest | |
1773 | def magic_timeit(self, parameter_s =''): |
|
1773 | def magic_timeit(self, parameter_s =''): | |
1774 | """Time execution of a Python statement or expression |
|
1774 | """Time execution of a Python statement or expression | |
1775 |
|
1775 | |||
1776 | Usage:\\ |
|
1776 | Usage:\\ | |
1777 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1777 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1778 |
|
1778 | |||
1779 | Time execution of a Python statement or expression using the timeit |
|
1779 | Time execution of a Python statement or expression using the timeit | |
1780 | module. |
|
1780 | module. | |
1781 |
|
1781 | |||
1782 | Options: |
|
1782 | Options: | |
1783 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1783 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1784 | is not given, a fitting value is chosen. |
|
1784 | is not given, a fitting value is chosen. | |
1785 |
|
1785 | |||
1786 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1786 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1787 | Default: 3 |
|
1787 | Default: 3 | |
1788 |
|
1788 | |||
1789 | -t: use time.time to measure the time, which is the default on Unix. |
|
1789 | -t: use time.time to measure the time, which is the default on Unix. | |
1790 | This function measures wall time. |
|
1790 | This function measures wall time. | |
1791 |
|
1791 | |||
1792 | -c: use time.clock to measure the time, which is the default on |
|
1792 | -c: use time.clock to measure the time, which is the default on | |
1793 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1793 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1794 | instead and returns the CPU user time. |
|
1794 | instead and returns the CPU user time. | |
1795 |
|
1795 | |||
1796 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1796 | -p<P>: use a precision of <P> digits to display the timing result. | |
1797 | Default: 3 |
|
1797 | Default: 3 | |
1798 |
|
1798 | |||
1799 |
|
1799 | |||
1800 | Examples: |
|
1800 | Examples: | |
1801 |
|
1801 | |||
1802 | In [1]: %timeit pass |
|
1802 | In [1]: %timeit pass | |
1803 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1803 | 10000000 loops, best of 3: 53.3 ns per loop | |
1804 |
|
1804 | |||
1805 | In [2]: u = None |
|
1805 | In [2]: u = None | |
1806 |
|
1806 | |||
1807 | In [3]: %timeit u is None |
|
1807 | In [3]: %timeit u is None | |
1808 | 10000000 loops, best of 3: 184 ns per loop |
|
1808 | 10000000 loops, best of 3: 184 ns per loop | |
1809 |
|
1809 | |||
1810 | In [4]: %timeit -r 4 u == None |
|
1810 | In [4]: %timeit -r 4 u == None | |
1811 | 1000000 loops, best of 4: 242 ns per loop |
|
1811 | 1000000 loops, best of 4: 242 ns per loop | |
1812 |
|
1812 | |||
1813 | In [5]: import time |
|
1813 | In [5]: import time | |
1814 |
|
1814 | |||
1815 | In [6]: %timeit -n1 time.sleep(2) |
|
1815 | In [6]: %timeit -n1 time.sleep(2) | |
1816 | 1 loops, best of 3: 2 s per loop |
|
1816 | 1 loops, best of 3: 2 s per loop | |
1817 |
|
1817 | |||
1818 |
|
1818 | |||
1819 | The times reported by %timeit will be slightly higher than those |
|
1819 | The times reported by %timeit will be slightly higher than those | |
1820 | reported by the timeit.py script when variables are accessed. This is |
|
1820 | reported by the timeit.py script when variables are accessed. This is | |
1821 | due to the fact that %timeit executes the statement in the namespace |
|
1821 | due to the fact that %timeit executes the statement in the namespace | |
1822 | of the shell, compared with timeit.py, which uses a single setup |
|
1822 | of the shell, compared with timeit.py, which uses a single setup | |
1823 | statement to import function or create variables. Generally, the bias |
|
1823 | statement to import function or create variables. Generally, the bias | |
1824 | does not matter as long as results from timeit.py are not mixed with |
|
1824 | does not matter as long as results from timeit.py are not mixed with | |
1825 | those from %timeit.""" |
|
1825 | those from %timeit.""" | |
1826 |
|
1826 | |||
1827 | import timeit |
|
1827 | import timeit | |
1828 | import math |
|
1828 | import math | |
1829 |
|
1829 | |||
1830 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1830 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1831 | # certain terminals. Until we figure out a robust way of |
|
1831 | # certain terminals. Until we figure out a robust way of | |
1832 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1832 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1833 | # microseconds. I am really NOT happy about disabling the proper |
|
1833 | # microseconds. I am really NOT happy about disabling the proper | |
1834 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1834 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1835 | # right solution for this is, I'm all ears... |
|
1835 | # right solution for this is, I'm all ears... | |
1836 | # |
|
1836 | # | |
1837 | # Note: using |
|
1837 | # Note: using | |
1838 | # |
|
1838 | # | |
1839 | # s = u'\xb5' |
|
1839 | # s = u'\xb5' | |
1840 | # s.encode(sys.getdefaultencoding()) |
|
1840 | # s.encode(sys.getdefaultencoding()) | |
1841 | # |
|
1841 | # | |
1842 | # is not sufficient, as I've seen terminals where that fails but |
|
1842 | # is not sufficient, as I've seen terminals where that fails but | |
1843 | # print s |
|
1843 | # print s | |
1844 | # |
|
1844 | # | |
1845 | # succeeds |
|
1845 | # succeeds | |
1846 | # |
|
1846 | # | |
1847 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1847 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1848 |
|
1848 | |||
1849 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1849 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1850 | units = [u"s", u"ms",u'us',"ns"] |
|
1850 | units = [u"s", u"ms",u'us',"ns"] | |
1851 |
|
1851 | |||
1852 | scaling = [1, 1e3, 1e6, 1e9] |
|
1852 | scaling = [1, 1e3, 1e6, 1e9] | |
1853 |
|
1853 | |||
1854 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1854 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1855 | posix=False) |
|
1855 | posix=False) | |
1856 | if stmt == "": |
|
1856 | if stmt == "": | |
1857 | return |
|
1857 | return | |
1858 | timefunc = timeit.default_timer |
|
1858 | timefunc = timeit.default_timer | |
1859 | number = int(getattr(opts, "n", 0)) |
|
1859 | number = int(getattr(opts, "n", 0)) | |
1860 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1860 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1861 | precision = int(getattr(opts, "p", 3)) |
|
1861 | precision = int(getattr(opts, "p", 3)) | |
1862 | if hasattr(opts, "t"): |
|
1862 | if hasattr(opts, "t"): | |
1863 | timefunc = time.time |
|
1863 | timefunc = time.time | |
1864 | if hasattr(opts, "c"): |
|
1864 | if hasattr(opts, "c"): | |
1865 | timefunc = clock |
|
1865 | timefunc = clock | |
1866 |
|
1866 | |||
1867 | timer = timeit.Timer(timer=timefunc) |
|
1867 | timer = timeit.Timer(timer=timefunc) | |
1868 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1868 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1869 | # but is there a better way to achieve that the code stmt has access |
|
1869 | # but is there a better way to achieve that the code stmt has access | |
1870 | # to the shell namespace? |
|
1870 | # to the shell namespace? | |
1871 |
|
1871 | |||
1872 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1872 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1873 | 'setup': "pass"} |
|
1873 | 'setup': "pass"} | |
1874 | # Track compilation time so it can be reported if too long |
|
1874 | # Track compilation time so it can be reported if too long | |
1875 | # Minimum time above which compilation time will be reported |
|
1875 | # Minimum time above which compilation time will be reported | |
1876 | tc_min = 0.1 |
|
1876 | tc_min = 0.1 | |
1877 |
|
1877 | |||
1878 | t0 = clock() |
|
1878 | t0 = clock() | |
1879 | code = compile(src, "<magic-timeit>", "exec") |
|
1879 | code = compile(src, "<magic-timeit>", "exec") | |
1880 | tc = clock()-t0 |
|
1880 | tc = clock()-t0 | |
1881 |
|
1881 | |||
1882 | ns = {} |
|
1882 | ns = {} | |
1883 | exec code in self.shell.user_ns, ns |
|
1883 | exec code in self.shell.user_ns, ns | |
1884 | timer.inner = ns["inner"] |
|
1884 | timer.inner = ns["inner"] | |
1885 |
|
1885 | |||
1886 | if number == 0: |
|
1886 | if number == 0: | |
1887 | # determine number so that 0.2 <= total time < 2.0 |
|
1887 | # determine number so that 0.2 <= total time < 2.0 | |
1888 | number = 1 |
|
1888 | number = 1 | |
1889 | for i in range(1, 10): |
|
1889 | for i in range(1, 10): | |
1890 | if timer.timeit(number) >= 0.2: |
|
1890 | if timer.timeit(number) >= 0.2: | |
1891 | break |
|
1891 | break | |
1892 | number *= 10 |
|
1892 | number *= 10 | |
1893 |
|
1893 | |||
1894 | best = min(timer.repeat(repeat, number)) / number |
|
1894 | best = min(timer.repeat(repeat, number)) / number | |
1895 |
|
1895 | |||
1896 | if best > 0.0 and best < 1000.0: |
|
1896 | if best > 0.0 and best < 1000.0: | |
1897 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1897 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1898 | elif best >= 1000.0: |
|
1898 | elif best >= 1000.0: | |
1899 | order = 0 |
|
1899 | order = 0 | |
1900 | else: |
|
1900 | else: | |
1901 | order = 3 |
|
1901 | order = 3 | |
1902 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1902 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1903 | precision, |
|
1903 | precision, | |
1904 | best * scaling[order], |
|
1904 | best * scaling[order], | |
1905 | units[order]) |
|
1905 | units[order]) | |
1906 | if tc > tc_min: |
|
1906 | if tc > tc_min: | |
1907 | print "Compiler time: %.2f s" % tc |
|
1907 | print "Compiler time: %.2f s" % tc | |
1908 |
|
1908 | |||
1909 | @testdec.skip_doctest |
|
1909 | @testdec.skip_doctest | |
1910 | def magic_time(self,parameter_s = ''): |
|
1910 | def magic_time(self,parameter_s = ''): | |
1911 | """Time execution of a Python statement or expression. |
|
1911 | """Time execution of a Python statement or expression. | |
1912 |
|
1912 | |||
1913 | The CPU and wall clock times are printed, and the value of the |
|
1913 | The CPU and wall clock times are printed, and the value of the | |
1914 | expression (if any) is returned. Note that under Win32, system time |
|
1914 | expression (if any) is returned. Note that under Win32, system time | |
1915 | is always reported as 0, since it can not be measured. |
|
1915 | is always reported as 0, since it can not be measured. | |
1916 |
|
1916 | |||
1917 | This function provides very basic timing functionality. In Python |
|
1917 | This function provides very basic timing functionality. In Python | |
1918 | 2.3, the timeit module offers more control and sophistication, so this |
|
1918 | 2.3, the timeit module offers more control and sophistication, so this | |
1919 | could be rewritten to use it (patches welcome). |
|
1919 | could be rewritten to use it (patches welcome). | |
1920 |
|
1920 | |||
1921 | Some examples: |
|
1921 | Some examples: | |
1922 |
|
1922 | |||
1923 | In [1]: time 2**128 |
|
1923 | In [1]: time 2**128 | |
1924 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1924 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1925 | Wall time: 0.00 |
|
1925 | Wall time: 0.00 | |
1926 | Out[1]: 340282366920938463463374607431768211456L |
|
1926 | Out[1]: 340282366920938463463374607431768211456L | |
1927 |
|
1927 | |||
1928 | In [2]: n = 1000000 |
|
1928 | In [2]: n = 1000000 | |
1929 |
|
1929 | |||
1930 | In [3]: time sum(range(n)) |
|
1930 | In [3]: time sum(range(n)) | |
1931 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1931 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1932 | Wall time: 1.37 |
|
1932 | Wall time: 1.37 | |
1933 | Out[3]: 499999500000L |
|
1933 | Out[3]: 499999500000L | |
1934 |
|
1934 | |||
1935 | In [4]: time print 'hello world' |
|
1935 | In [4]: time print 'hello world' | |
1936 | hello world |
|
1936 | hello world | |
1937 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1937 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1938 | Wall time: 0.00 |
|
1938 | Wall time: 0.00 | |
1939 |
|
1939 | |||
1940 | Note that the time needed by Python to compile the given expression |
|
1940 | Note that the time needed by Python to compile the given expression | |
1941 | will be reported if it is more than 0.1s. In this example, the |
|
1941 | will be reported if it is more than 0.1s. In this example, the | |
1942 | actual exponentiation is done by Python at compilation time, so while |
|
1942 | actual exponentiation is done by Python at compilation time, so while | |
1943 | the expression can take a noticeable amount of time to compute, that |
|
1943 | the expression can take a noticeable amount of time to compute, that | |
1944 | time is purely due to the compilation: |
|
1944 | time is purely due to the compilation: | |
1945 |
|
1945 | |||
1946 | In [5]: time 3**9999; |
|
1946 | In [5]: time 3**9999; | |
1947 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1947 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1948 | Wall time: 0.00 s |
|
1948 | Wall time: 0.00 s | |
1949 |
|
1949 | |||
1950 | In [6]: time 3**999999; |
|
1950 | In [6]: time 3**999999; | |
1951 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1951 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1952 | Wall time: 0.00 s |
|
1952 | Wall time: 0.00 s | |
1953 | Compiler : 0.78 s |
|
1953 | Compiler : 0.78 s | |
1954 | """ |
|
1954 | """ | |
1955 |
|
1955 | |||
1956 | # fail immediately if the given expression can't be compiled |
|
1956 | # fail immediately if the given expression can't be compiled | |
1957 |
|
1957 | |||
1958 | expr = self.shell.prefilter(parameter_s,False) |
|
1958 | expr = self.shell.prefilter(parameter_s,False) | |
1959 |
|
1959 | |||
1960 | # Minimum time above which compilation time will be reported |
|
1960 | # Minimum time above which compilation time will be reported | |
1961 | tc_min = 0.1 |
|
1961 | tc_min = 0.1 | |
1962 |
|
1962 | |||
1963 | try: |
|
1963 | try: | |
1964 | mode = 'eval' |
|
1964 | mode = 'eval' | |
1965 | t0 = clock() |
|
1965 | t0 = clock() | |
1966 | code = compile(expr,'<timed eval>',mode) |
|
1966 | code = compile(expr,'<timed eval>',mode) | |
1967 | tc = clock()-t0 |
|
1967 | tc = clock()-t0 | |
1968 | except SyntaxError: |
|
1968 | except SyntaxError: | |
1969 | mode = 'exec' |
|
1969 | mode = 'exec' | |
1970 | t0 = clock() |
|
1970 | t0 = clock() | |
1971 | code = compile(expr,'<timed exec>',mode) |
|
1971 | code = compile(expr,'<timed exec>',mode) | |
1972 | tc = clock()-t0 |
|
1972 | tc = clock()-t0 | |
1973 | # skew measurement as little as possible |
|
1973 | # skew measurement as little as possible | |
1974 | glob = self.shell.user_ns |
|
1974 | glob = self.shell.user_ns | |
1975 | clk = clock2 |
|
1975 | clk = clock2 | |
1976 | wtime = time.time |
|
1976 | wtime = time.time | |
1977 | # time execution |
|
1977 | # time execution | |
1978 | wall_st = wtime() |
|
1978 | wall_st = wtime() | |
1979 | if mode=='eval': |
|
1979 | if mode=='eval': | |
1980 | st = clk() |
|
1980 | st = clk() | |
1981 | out = eval(code,glob) |
|
1981 | out = eval(code,glob) | |
1982 | end = clk() |
|
1982 | end = clk() | |
1983 | else: |
|
1983 | else: | |
1984 | st = clk() |
|
1984 | st = clk() | |
1985 | exec code in glob |
|
1985 | exec code in glob | |
1986 | end = clk() |
|
1986 | end = clk() | |
1987 | out = None |
|
1987 | out = None | |
1988 | wall_end = wtime() |
|
1988 | wall_end = wtime() | |
1989 | # Compute actual times and report |
|
1989 | # Compute actual times and report | |
1990 | wall_time = wall_end-wall_st |
|
1990 | wall_time = wall_end-wall_st | |
1991 | cpu_user = end[0]-st[0] |
|
1991 | cpu_user = end[0]-st[0] | |
1992 | cpu_sys = end[1]-st[1] |
|
1992 | cpu_sys = end[1]-st[1] | |
1993 | cpu_tot = cpu_user+cpu_sys |
|
1993 | cpu_tot = cpu_user+cpu_sys | |
1994 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1994 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1995 | (cpu_user,cpu_sys,cpu_tot) |
|
1995 | (cpu_user,cpu_sys,cpu_tot) | |
1996 | print "Wall time: %.2f s" % wall_time |
|
1996 | print "Wall time: %.2f s" % wall_time | |
1997 | if tc > tc_min: |
|
1997 | if tc > tc_min: | |
1998 | print "Compiler : %.2f s" % tc |
|
1998 | print "Compiler : %.2f s" % tc | |
1999 | return out |
|
1999 | return out | |
2000 |
|
2000 | |||
2001 | @testdec.skip_doctest |
|
2001 | @testdec.skip_doctest | |
2002 | def magic_macro(self,parameter_s = ''): |
|
2002 | def magic_macro(self,parameter_s = ''): | |
2003 | """Define a set of input lines as a macro for future re-execution. |
|
2003 | """Define a set of input lines as a macro for future re-execution. | |
2004 |
|
2004 | |||
2005 | Usage:\\ |
|
2005 | Usage:\\ | |
2006 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
2006 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
2007 |
|
2007 | |||
2008 | Options: |
|
2008 | Options: | |
2009 |
|
2009 | |||
2010 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2010 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2011 | so that magics are loaded in their transformed version to valid |
|
2011 | so that magics are loaded in their transformed version to valid | |
2012 | Python. If this option is given, the raw input as typed as the |
|
2012 | Python. If this option is given, the raw input as typed as the | |
2013 | command line is used instead. |
|
2013 | command line is used instead. | |
2014 |
|
2014 | |||
2015 | This will define a global variable called `name` which is a string |
|
2015 | This will define a global variable called `name` which is a string | |
2016 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
2016 | made of joining the slices and lines you specify (n1,n2,... numbers | |
2017 | above) from your input history into a single string. This variable |
|
2017 | above) from your input history into a single string. This variable | |
2018 | acts like an automatic function which re-executes those lines as if |
|
2018 | acts like an automatic function which re-executes those lines as if | |
2019 | you had typed them. You just type 'name' at the prompt and the code |
|
2019 | you had typed them. You just type 'name' at the prompt and the code | |
2020 | executes. |
|
2020 | executes. | |
2021 |
|
2021 | |||
2022 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
2022 | The notation for indicating number ranges is: n1-n2 means 'use line | |
2023 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
2023 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
2024 | using the lines numbered 5,6 and 7. |
|
2024 | using the lines numbered 5,6 and 7. | |
2025 |
|
2025 | |||
2026 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2026 | Note: as a 'hidden' feature, you can also use traditional python slice | |
2027 | notation, where N:M means numbers N through M-1. |
|
2027 | notation, where N:M means numbers N through M-1. | |
2028 |
|
2028 | |||
2029 | For example, if your history contains (%hist prints it): |
|
2029 | For example, if your history contains (%hist prints it): | |
2030 |
|
2030 | |||
2031 | 44: x=1 |
|
2031 | 44: x=1 | |
2032 | 45: y=3 |
|
2032 | 45: y=3 | |
2033 | 46: z=x+y |
|
2033 | 46: z=x+y | |
2034 | 47: print x |
|
2034 | 47: print x | |
2035 | 48: a=5 |
|
2035 | 48: a=5 | |
2036 | 49: print 'x',x,'y',y |
|
2036 | 49: print 'x',x,'y',y | |
2037 |
|
2037 | |||
2038 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2038 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2039 | called my_macro with: |
|
2039 | called my_macro with: | |
2040 |
|
2040 | |||
2041 | In [55]: %macro my_macro 44-47 49 |
|
2041 | In [55]: %macro my_macro 44-47 49 | |
2042 |
|
2042 | |||
2043 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2043 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2044 | in one pass. |
|
2044 | in one pass. | |
2045 |
|
2045 | |||
2046 | You don't need to give the line-numbers in order, and any given line |
|
2046 | You don't need to give the line-numbers in order, and any given line | |
2047 | number can appear multiple times. You can assemble macros with any |
|
2047 | number can appear multiple times. You can assemble macros with any | |
2048 | lines from your input history in any order. |
|
2048 | lines from your input history in any order. | |
2049 |
|
2049 | |||
2050 | The macro is a simple object which holds its value in an attribute, |
|
2050 | The macro is a simple object which holds its value in an attribute, | |
2051 | but IPython's display system checks for macros and executes them as |
|
2051 | but IPython's display system checks for macros and executes them as | |
2052 | code instead of printing them when you type their name. |
|
2052 | code instead of printing them when you type their name. | |
2053 |
|
2053 | |||
2054 | You can view a macro's contents by explicitly printing it with: |
|
2054 | You can view a macro's contents by explicitly printing it with: | |
2055 |
|
2055 | |||
2056 | 'print macro_name'. |
|
2056 | 'print macro_name'. | |
2057 |
|
2057 | |||
2058 | For one-off cases which DON'T contain magic function calls in them you |
|
2058 | For one-off cases which DON'T contain magic function calls in them you | |
2059 | can obtain similar results by explicitly executing slices from your |
|
2059 | can obtain similar results by explicitly executing slices from your | |
2060 | input history with: |
|
2060 | input history with: | |
2061 |
|
2061 | |||
2062 | In [60]: exec In[44:48]+In[49]""" |
|
2062 | In [60]: exec In[44:48]+In[49]""" | |
2063 |
|
2063 | |||
2064 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2064 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2065 | if not args: |
|
2065 | if not args: | |
2066 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2066 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
2067 | macs.sort() |
|
2067 | macs.sort() | |
2068 | return macs |
|
2068 | return macs | |
2069 | if len(args) == 1: |
|
2069 | if len(args) == 1: | |
2070 | raise UsageError( |
|
2070 | raise UsageError( | |
2071 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2071 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2072 | name,ranges = args[0], args[1:] |
|
2072 | name,ranges = args[0], args[1:] | |
2073 |
|
2073 | |||
2074 | #print 'rng',ranges # dbg |
|
2074 | #print 'rng',ranges # dbg | |
2075 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2075 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
2076 | macro = Macro(lines) |
|
2076 | macro = Macro(lines) | |
2077 | self.shell.user_ns.update({name:macro}) |
|
2077 | self.shell.user_ns.update({name:macro}) | |
2078 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2078 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2079 | print 'Macro contents:' |
|
2079 | print 'Macro contents:' | |
2080 | print macro, |
|
2080 | print macro, | |
2081 |
|
2081 | |||
2082 | def magic_save(self,parameter_s = ''): |
|
2082 | def magic_save(self,parameter_s = ''): | |
2083 | """Save a set of lines to a given filename. |
|
2083 | """Save a set of lines to a given filename. | |
2084 |
|
2084 | |||
2085 | Usage:\\ |
|
2085 | Usage:\\ | |
2086 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2086 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2087 |
|
2087 | |||
2088 | Options: |
|
2088 | Options: | |
2089 |
|
2089 | |||
2090 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2090 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2091 | so that magics are loaded in their transformed version to valid |
|
2091 | so that magics are loaded in their transformed version to valid | |
2092 | Python. If this option is given, the raw input as typed as the |
|
2092 | Python. If this option is given, the raw input as typed as the | |
2093 | command line is used instead. |
|
2093 | command line is used instead. | |
2094 |
|
2094 | |||
2095 | This function uses the same syntax as %macro for line extraction, but |
|
2095 | This function uses the same syntax as %macro for line extraction, but | |
2096 | instead of creating a macro it saves the resulting string to the |
|
2096 | instead of creating a macro it saves the resulting string to the | |
2097 | filename you specify. |
|
2097 | filename you specify. | |
2098 |
|
2098 | |||
2099 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2099 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2100 | it asks for confirmation before overwriting existing files.""" |
|
2100 | it asks for confirmation before overwriting existing files.""" | |
2101 |
|
2101 | |||
2102 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2102 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2103 | fname,ranges = args[0], args[1:] |
|
2103 | fname,ranges = args[0], args[1:] | |
2104 | if not fname.endswith('.py'): |
|
2104 | if not fname.endswith('.py'): | |
2105 | fname += '.py' |
|
2105 | fname += '.py' | |
2106 | if os.path.isfile(fname): |
|
2106 | if os.path.isfile(fname): | |
2107 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2107 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2108 | if ans.lower() not in ['y','yes']: |
|
2108 | if ans.lower() not in ['y','yes']: | |
2109 | print 'Operation cancelled.' |
|
2109 | print 'Operation cancelled.' | |
2110 | return |
|
2110 | return | |
2111 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2111 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2112 | f = file(fname,'w') |
|
2112 | f = file(fname,'w') | |
2113 | f.write(cmds) |
|
2113 | f.write(cmds) | |
2114 | f.close() |
|
2114 | f.close() | |
2115 | print 'The following commands were written to file `%s`:' % fname |
|
2115 | print 'The following commands were written to file `%s`:' % fname | |
2116 | print cmds |
|
2116 | print cmds | |
2117 |
|
2117 | |||
2118 | def _edit_macro(self,mname,macro): |
|
2118 | def _edit_macro(self,mname,macro): | |
2119 | """open an editor with the macro data in a file""" |
|
2119 | """open an editor with the macro data in a file""" | |
2120 | filename = self.shell.mktempfile(macro.value) |
|
2120 | filename = self.shell.mktempfile(macro.value) | |
2121 | self.shell.hooks.editor(filename) |
|
2121 | self.shell.hooks.editor(filename) | |
2122 |
|
2122 | |||
2123 | # and make a new macro object, to replace the old one |
|
2123 | # and make a new macro object, to replace the old one | |
2124 | mfile = open(filename) |
|
2124 | mfile = open(filename) | |
2125 | mvalue = mfile.read() |
|
2125 | mvalue = mfile.read() | |
2126 | mfile.close() |
|
2126 | mfile.close() | |
2127 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2127 | self.shell.user_ns[mname] = Macro(mvalue) | |
2128 |
|
2128 | |||
2129 | def magic_ed(self,parameter_s=''): |
|
2129 | def magic_ed(self,parameter_s=''): | |
2130 | """Alias to %edit.""" |
|
2130 | """Alias to %edit.""" | |
2131 | return self.magic_edit(parameter_s) |
|
2131 | return self.magic_edit(parameter_s) | |
2132 |
|
2132 | |||
2133 | @testdec.skip_doctest |
|
2133 | @testdec.skip_doctest | |
2134 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2134 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2135 | """Bring up an editor and execute the resulting code. |
|
2135 | """Bring up an editor and execute the resulting code. | |
2136 |
|
2136 | |||
2137 | Usage: |
|
2137 | Usage: | |
2138 | %edit [options] [args] |
|
2138 | %edit [options] [args] | |
2139 |
|
2139 | |||
2140 | %edit runs IPython's editor hook. The default version of this hook is |
|
2140 | %edit runs IPython's editor hook. The default version of this hook is | |
2141 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2141 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2142 | environment variable $EDITOR. If this isn't found, it will default to |
|
2142 | environment variable $EDITOR. If this isn't found, it will default to | |
2143 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2143 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2144 | docstring for how to change the editor hook. |
|
2144 | docstring for how to change the editor hook. | |
2145 |
|
2145 | |||
2146 | You can also set the value of this editor via the command line option |
|
2146 | You can also set the value of this editor via the command line option | |
2147 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2147 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2148 | specifically for IPython an editor different from your typical default |
|
2148 | specifically for IPython an editor different from your typical default | |
2149 | (and for Windows users who typically don't set environment variables). |
|
2149 | (and for Windows users who typically don't set environment variables). | |
2150 |
|
2150 | |||
2151 | This command allows you to conveniently edit multi-line code right in |
|
2151 | This command allows you to conveniently edit multi-line code right in | |
2152 | your IPython session. |
|
2152 | your IPython session. | |
2153 |
|
2153 | |||
2154 | If called without arguments, %edit opens up an empty editor with a |
|
2154 | If called without arguments, %edit opens up an empty editor with a | |
2155 | temporary file and will execute the contents of this file when you |
|
2155 | temporary file and will execute the contents of this file when you | |
2156 | close it (don't forget to save it!). |
|
2156 | close it (don't forget to save it!). | |
2157 |
|
2157 | |||
2158 |
|
2158 | |||
2159 | Options: |
|
2159 | Options: | |
2160 |
|
2160 | |||
2161 | -n <number>: open the editor at a specified line number. By default, |
|
2161 | -n <number>: open the editor at a specified line number. By default, | |
2162 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2162 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2163 | you can configure this by providing your own modified hook if your |
|
2163 | you can configure this by providing your own modified hook if your | |
2164 | favorite editor supports line-number specifications with a different |
|
2164 | favorite editor supports line-number specifications with a different | |
2165 | syntax. |
|
2165 | syntax. | |
2166 |
|
2166 | |||
2167 | -p: this will call the editor with the same data as the previous time |
|
2167 | -p: this will call the editor with the same data as the previous time | |
2168 | it was used, regardless of how long ago (in your current session) it |
|
2168 | it was used, regardless of how long ago (in your current session) it | |
2169 | was. |
|
2169 | was. | |
2170 |
|
2170 | |||
2171 | -r: use 'raw' input. This option only applies to input taken from the |
|
2171 | -r: use 'raw' input. This option only applies to input taken from the | |
2172 | user's history. By default, the 'processed' history is used, so that |
|
2172 | user's history. By default, the 'processed' history is used, so that | |
2173 | magics are loaded in their transformed version to valid Python. If |
|
2173 | magics are loaded in their transformed version to valid Python. If | |
2174 | this option is given, the raw input as typed as the command line is |
|
2174 | this option is given, the raw input as typed as the command line is | |
2175 | used instead. When you exit the editor, it will be executed by |
|
2175 | used instead. When you exit the editor, it will be executed by | |
2176 | IPython's own processor. |
|
2176 | IPython's own processor. | |
2177 |
|
2177 | |||
2178 | -x: do not execute the edited code immediately upon exit. This is |
|
2178 | -x: do not execute the edited code immediately upon exit. This is | |
2179 | mainly useful if you are editing programs which need to be called with |
|
2179 | mainly useful if you are editing programs which need to be called with | |
2180 | command line arguments, which you can then do using %run. |
|
2180 | command line arguments, which you can then do using %run. | |
2181 |
|
2181 | |||
2182 |
|
2182 | |||
2183 | Arguments: |
|
2183 | Arguments: | |
2184 |
|
2184 | |||
2185 | If arguments are given, the following possibilites exist: |
|
2185 | If arguments are given, the following possibilites exist: | |
2186 |
|
2186 | |||
2187 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2187 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2188 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2188 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2189 | loaded into the editor. The syntax is the same of the %macro command. |
|
2189 | loaded into the editor. The syntax is the same of the %macro command. | |
2190 |
|
2190 | |||
2191 | - If the argument doesn't start with a number, it is evaluated as a |
|
2191 | - If the argument doesn't start with a number, it is evaluated as a | |
2192 | variable and its contents loaded into the editor. You can thus edit |
|
2192 | variable and its contents loaded into the editor. You can thus edit | |
2193 | any string which contains python code (including the result of |
|
2193 | any string which contains python code (including the result of | |
2194 | previous edits). |
|
2194 | previous edits). | |
2195 |
|
2195 | |||
2196 | - If the argument is the name of an object (other than a string), |
|
2196 | - If the argument is the name of an object (other than a string), | |
2197 | IPython will try to locate the file where it was defined and open the |
|
2197 | IPython will try to locate the file where it was defined and open the | |
2198 | editor at the point where it is defined. You can use `%edit function` |
|
2198 | editor at the point where it is defined. You can use `%edit function` | |
2199 | to load an editor exactly at the point where 'function' is defined, |
|
2199 | to load an editor exactly at the point where 'function' is defined, | |
2200 | edit it and have the file be executed automatically. |
|
2200 | edit it and have the file be executed automatically. | |
2201 |
|
2201 | |||
2202 | If the object is a macro (see %macro for details), this opens up your |
|
2202 | If the object is a macro (see %macro for details), this opens up your | |
2203 | specified editor with a temporary file containing the macro's data. |
|
2203 | specified editor with a temporary file containing the macro's data. | |
2204 | Upon exit, the macro is reloaded with the contents of the file. |
|
2204 | Upon exit, the macro is reloaded with the contents of the file. | |
2205 |
|
2205 | |||
2206 | Note: opening at an exact line is only supported under Unix, and some |
|
2206 | Note: opening at an exact line is only supported under Unix, and some | |
2207 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2207 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2208 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2208 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2209 | (X)Emacs, vi, jed, pico and joe all do. |
|
2209 | (X)Emacs, vi, jed, pico and joe all do. | |
2210 |
|
2210 | |||
2211 | - If the argument is not found as a variable, IPython will look for a |
|
2211 | - If the argument is not found as a variable, IPython will look for a | |
2212 | file with that name (adding .py if necessary) and load it into the |
|
2212 | file with that name (adding .py if necessary) and load it into the | |
2213 | editor. It will execute its contents with execfile() when you exit, |
|
2213 | editor. It will execute its contents with execfile() when you exit, | |
2214 | loading any code in the file into your interactive namespace. |
|
2214 | loading any code in the file into your interactive namespace. | |
2215 |
|
2215 | |||
2216 | After executing your code, %edit will return as output the code you |
|
2216 | After executing your code, %edit will return as output the code you | |
2217 | typed in the editor (except when it was an existing file). This way |
|
2217 | typed in the editor (except when it was an existing file). This way | |
2218 | you can reload the code in further invocations of %edit as a variable, |
|
2218 | you can reload the code in further invocations of %edit as a variable, | |
2219 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2219 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2220 | the output. |
|
2220 | the output. | |
2221 |
|
2221 | |||
2222 | Note that %edit is also available through the alias %ed. |
|
2222 | Note that %edit is also available through the alias %ed. | |
2223 |
|
2223 | |||
2224 | This is an example of creating a simple function inside the editor and |
|
2224 | This is an example of creating a simple function inside the editor and | |
2225 | then modifying it. First, start up the editor: |
|
2225 | then modifying it. First, start up the editor: | |
2226 |
|
2226 | |||
2227 | In [1]: ed |
|
2227 | In [1]: ed | |
2228 | Editing... done. Executing edited code... |
|
2228 | Editing... done. Executing edited code... | |
2229 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2229 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2230 |
|
2230 | |||
2231 | We can then call the function foo(): |
|
2231 | We can then call the function foo(): | |
2232 |
|
2232 | |||
2233 | In [2]: foo() |
|
2233 | In [2]: foo() | |
2234 | foo() was defined in an editing session |
|
2234 | foo() was defined in an editing session | |
2235 |
|
2235 | |||
2236 | Now we edit foo. IPython automatically loads the editor with the |
|
2236 | Now we edit foo. IPython automatically loads the editor with the | |
2237 | (temporary) file where foo() was previously defined: |
|
2237 | (temporary) file where foo() was previously defined: | |
2238 |
|
2238 | |||
2239 | In [3]: ed foo |
|
2239 | In [3]: ed foo | |
2240 | Editing... done. Executing edited code... |
|
2240 | Editing... done. Executing edited code... | |
2241 |
|
2241 | |||
2242 | And if we call foo() again we get the modified version: |
|
2242 | And if we call foo() again we get the modified version: | |
2243 |
|
2243 | |||
2244 | In [4]: foo() |
|
2244 | In [4]: foo() | |
2245 | foo() has now been changed! |
|
2245 | foo() has now been changed! | |
2246 |
|
2246 | |||
2247 | Here is an example of how to edit a code snippet successive |
|
2247 | Here is an example of how to edit a code snippet successive | |
2248 | times. First we call the editor: |
|
2248 | times. First we call the editor: | |
2249 |
|
2249 | |||
2250 | In [5]: ed |
|
2250 | In [5]: ed | |
2251 | Editing... done. Executing edited code... |
|
2251 | Editing... done. Executing edited code... | |
2252 | hello |
|
2252 | hello | |
2253 | Out[5]: "print 'hello'n" |
|
2253 | Out[5]: "print 'hello'n" | |
2254 |
|
2254 | |||
2255 | Now we call it again with the previous output (stored in _): |
|
2255 | Now we call it again with the previous output (stored in _): | |
2256 |
|
2256 | |||
2257 | In [6]: ed _ |
|
2257 | In [6]: ed _ | |
2258 | Editing... done. Executing edited code... |
|
2258 | Editing... done. Executing edited code... | |
2259 | hello world |
|
2259 | hello world | |
2260 | Out[6]: "print 'hello world'n" |
|
2260 | Out[6]: "print 'hello world'n" | |
2261 |
|
2261 | |||
2262 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2262 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2263 |
|
2263 | |||
2264 | In [7]: ed _8 |
|
2264 | In [7]: ed _8 | |
2265 | Editing... done. Executing edited code... |
|
2265 | Editing... done. Executing edited code... | |
2266 | hello again |
|
2266 | hello again | |
2267 | Out[7]: "print 'hello again'n" |
|
2267 | Out[7]: "print 'hello again'n" | |
2268 |
|
2268 | |||
2269 |
|
2269 | |||
2270 | Changing the default editor hook: |
|
2270 | Changing the default editor hook: | |
2271 |
|
2271 | |||
2272 | If you wish to write your own editor hook, you can put it in a |
|
2272 | If you wish to write your own editor hook, you can put it in a | |
2273 | configuration file which you load at startup time. The default hook |
|
2273 | configuration file which you load at startup time. The default hook | |
2274 | is defined in the IPython.hooks module, and you can use that as a |
|
2274 | is defined in the IPython.hooks module, and you can use that as a | |
2275 | starting example for further modifications. That file also has |
|
2275 | starting example for further modifications. That file also has | |
2276 | general instructions on how to set a new hook for use once you've |
|
2276 | general instructions on how to set a new hook for use once you've | |
2277 | defined it.""" |
|
2277 | defined it.""" | |
2278 |
|
2278 | |||
2279 | # FIXME: This function has become a convoluted mess. It needs a |
|
2279 | # FIXME: This function has become a convoluted mess. It needs a | |
2280 | # ground-up rewrite with clean, simple logic. |
|
2280 | # ground-up rewrite with clean, simple logic. | |
2281 |
|
2281 | |||
2282 | def make_filename(arg): |
|
2282 | def make_filename(arg): | |
2283 | "Make a filename from the given args" |
|
2283 | "Make a filename from the given args" | |
2284 | try: |
|
2284 | try: | |
2285 | filename = get_py_filename(arg) |
|
2285 | filename = get_py_filename(arg) | |
2286 | except IOError: |
|
2286 | except IOError: | |
2287 | if args.endswith('.py'): |
|
2287 | if args.endswith('.py'): | |
2288 | filename = arg |
|
2288 | filename = arg | |
2289 | else: |
|
2289 | else: | |
2290 | filename = None |
|
2290 | filename = None | |
2291 | return filename |
|
2291 | return filename | |
2292 |
|
2292 | |||
2293 | # custom exceptions |
|
2293 | # custom exceptions | |
2294 | class DataIsObject(Exception): pass |
|
2294 | class DataIsObject(Exception): pass | |
2295 |
|
2295 | |||
2296 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2296 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2297 | # Set a few locals from the options for convenience: |
|
2297 | # Set a few locals from the options for convenience: | |
2298 | opts_p = opts.has_key('p') |
|
2298 | opts_p = opts.has_key('p') | |
2299 | opts_r = opts.has_key('r') |
|
2299 | opts_r = opts.has_key('r') | |
2300 |
|
2300 | |||
2301 | # Default line number value |
|
2301 | # Default line number value | |
2302 | lineno = opts.get('n',None) |
|
2302 | lineno = opts.get('n',None) | |
2303 |
|
2303 | |||
2304 | if opts_p: |
|
2304 | if opts_p: | |
2305 | args = '_%s' % last_call[0] |
|
2305 | args = '_%s' % last_call[0] | |
2306 | if not self.shell.user_ns.has_key(args): |
|
2306 | if not self.shell.user_ns.has_key(args): | |
2307 | args = last_call[1] |
|
2307 | args = last_call[1] | |
2308 |
|
2308 | |||
2309 | # use last_call to remember the state of the previous call, but don't |
|
2309 | # use last_call to remember the state of the previous call, but don't | |
2310 | # let it be clobbered by successive '-p' calls. |
|
2310 | # let it be clobbered by successive '-p' calls. | |
2311 | try: |
|
2311 | try: | |
2312 | last_call[0] = self.shell.outputcache.prompt_count |
|
2312 | last_call[0] = self.shell.outputcache.prompt_count | |
2313 | if not opts_p: |
|
2313 | if not opts_p: | |
2314 | last_call[1] = parameter_s |
|
2314 | last_call[1] = parameter_s | |
2315 | except: |
|
2315 | except: | |
2316 | pass |
|
2316 | pass | |
2317 |
|
2317 | |||
2318 | # by default this is done with temp files, except when the given |
|
2318 | # by default this is done with temp files, except when the given | |
2319 | # arg is a filename |
|
2319 | # arg is a filename | |
2320 | use_temp = 1 |
|
2320 | use_temp = 1 | |
2321 |
|
2321 | |||
2322 | if re.match(r'\d',args): |
|
2322 | if re.match(r'\d',args): | |
2323 | # Mode where user specifies ranges of lines, like in %macro. |
|
2323 | # Mode where user specifies ranges of lines, like in %macro. | |
2324 | # This means that you can't edit files whose names begin with |
|
2324 | # This means that you can't edit files whose names begin with | |
2325 | # numbers this way. Tough. |
|
2325 | # numbers this way. Tough. | |
2326 | ranges = args.split() |
|
2326 | ranges = args.split() | |
2327 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2327 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2328 | elif args.endswith('.py'): |
|
2328 | elif args.endswith('.py'): | |
2329 | filename = make_filename(args) |
|
2329 | filename = make_filename(args) | |
2330 | data = '' |
|
2330 | data = '' | |
2331 | use_temp = 0 |
|
2331 | use_temp = 0 | |
2332 | elif args: |
|
2332 | elif args: | |
2333 | try: |
|
2333 | try: | |
2334 | # Load the parameter given as a variable. If not a string, |
|
2334 | # Load the parameter given as a variable. If not a string, | |
2335 | # process it as an object instead (below) |
|
2335 | # process it as an object instead (below) | |
2336 |
|
2336 | |||
2337 | #print '*** args',args,'type',type(args) # dbg |
|
2337 | #print '*** args',args,'type',type(args) # dbg | |
2338 | data = eval(args,self.shell.user_ns) |
|
2338 | data = eval(args,self.shell.user_ns) | |
2339 | if not type(data) in StringTypes: |
|
2339 | if not type(data) in StringTypes: | |
2340 | raise DataIsObject |
|
2340 | raise DataIsObject | |
2341 |
|
2341 | |||
2342 | except (NameError,SyntaxError): |
|
2342 | except (NameError,SyntaxError): | |
2343 | # given argument is not a variable, try as a filename |
|
2343 | # given argument is not a variable, try as a filename | |
2344 | filename = make_filename(args) |
|
2344 | filename = make_filename(args) | |
2345 | if filename is None: |
|
2345 | if filename is None: | |
2346 | warn("Argument given (%s) can't be found as a variable " |
|
2346 | warn("Argument given (%s) can't be found as a variable " | |
2347 | "or as a filename." % args) |
|
2347 | "or as a filename." % args) | |
2348 | return |
|
2348 | return | |
2349 |
|
2349 | |||
2350 | data = '' |
|
2350 | data = '' | |
2351 | use_temp = 0 |
|
2351 | use_temp = 0 | |
2352 | except DataIsObject: |
|
2352 | except DataIsObject: | |
2353 |
|
2353 | |||
2354 | # macros have a special edit function |
|
2354 | # macros have a special edit function | |
2355 | if isinstance(data,Macro): |
|
2355 | if isinstance(data,Macro): | |
2356 | self._edit_macro(args,data) |
|
2356 | self._edit_macro(args,data) | |
2357 | return |
|
2357 | return | |
2358 |
|
2358 | |||
2359 | # For objects, try to edit the file where they are defined |
|
2359 | # For objects, try to edit the file where they are defined | |
2360 | try: |
|
2360 | try: | |
2361 | filename = inspect.getabsfile(data) |
|
2361 | filename = inspect.getabsfile(data) | |
2362 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2362 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2363 | # class created by %edit? Try to find source |
|
2363 | # class created by %edit? Try to find source | |
2364 | # by looking for method definitions instead, the |
|
2364 | # by looking for method definitions instead, the | |
2365 | # __module__ in those classes is FakeModule. |
|
2365 | # __module__ in those classes is FakeModule. | |
2366 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2366 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2367 | for attr in attrs: |
|
2367 | for attr in attrs: | |
2368 | if not inspect.ismethod(attr): |
|
2368 | if not inspect.ismethod(attr): | |
2369 | continue |
|
2369 | continue | |
2370 | filename = inspect.getabsfile(attr) |
|
2370 | filename = inspect.getabsfile(attr) | |
2371 | if filename and 'fakemodule' not in filename.lower(): |
|
2371 | if filename and 'fakemodule' not in filename.lower(): | |
2372 | # change the attribute to be the edit target instead |
|
2372 | # change the attribute to be the edit target instead | |
2373 | data = attr |
|
2373 | data = attr | |
2374 | break |
|
2374 | break | |
2375 |
|
2375 | |||
2376 | datafile = 1 |
|
2376 | datafile = 1 | |
2377 | except TypeError: |
|
2377 | except TypeError: | |
2378 | filename = make_filename(args) |
|
2378 | filename = make_filename(args) | |
2379 | datafile = 1 |
|
2379 | datafile = 1 | |
2380 | warn('Could not find file where `%s` is defined.\n' |
|
2380 | warn('Could not find file where `%s` is defined.\n' | |
2381 | 'Opening a file named `%s`' % (args,filename)) |
|
2381 | 'Opening a file named `%s`' % (args,filename)) | |
2382 | # Now, make sure we can actually read the source (if it was in |
|
2382 | # Now, make sure we can actually read the source (if it was in | |
2383 | # a temp file it's gone by now). |
|
2383 | # a temp file it's gone by now). | |
2384 | if datafile: |
|
2384 | if datafile: | |
2385 | try: |
|
2385 | try: | |
2386 | if lineno is None: |
|
2386 | if lineno is None: | |
2387 | lineno = inspect.getsourcelines(data)[1] |
|
2387 | lineno = inspect.getsourcelines(data)[1] | |
2388 | except IOError: |
|
2388 | except IOError: | |
2389 | filename = make_filename(args) |
|
2389 | filename = make_filename(args) | |
2390 | if filename is None: |
|
2390 | if filename is None: | |
2391 | warn('The file `%s` where `%s` was defined cannot ' |
|
2391 | warn('The file `%s` where `%s` was defined cannot ' | |
2392 | 'be read.' % (filename,data)) |
|
2392 | 'be read.' % (filename,data)) | |
2393 | return |
|
2393 | return | |
2394 | use_temp = 0 |
|
2394 | use_temp = 0 | |
2395 | else: |
|
2395 | else: | |
2396 | data = '' |
|
2396 | data = '' | |
2397 |
|
2397 | |||
2398 | if use_temp: |
|
2398 | if use_temp: | |
2399 | filename = self.shell.mktempfile(data) |
|
2399 | filename = self.shell.mktempfile(data) | |
2400 | print 'IPython will make a temporary file named:',filename |
|
2400 | print 'IPython will make a temporary file named:',filename | |
2401 |
|
2401 | |||
2402 | # do actual editing here |
|
2402 | # do actual editing here | |
2403 | print 'Editing...', |
|
2403 | print 'Editing...', | |
2404 | sys.stdout.flush() |
|
2404 | sys.stdout.flush() | |
2405 | try: |
|
2405 | try: | |
2406 | self.shell.hooks.editor(filename,lineno) |
|
2406 | self.shell.hooks.editor(filename,lineno) | |
2407 | except IPython.ipapi.TryNext: |
|
2407 | except IPython.ipapi.TryNext: | |
2408 | warn('Could not open editor') |
|
2408 | warn('Could not open editor') | |
2409 | return |
|
2409 | return | |
2410 |
|
2410 | |||
2411 | # XXX TODO: should this be generalized for all string vars? |
|
2411 | # XXX TODO: should this be generalized for all string vars? | |
2412 | # For now, this is special-cased to blocks created by cpaste |
|
2412 | # For now, this is special-cased to blocks created by cpaste | |
2413 | if args.strip() == 'pasted_block': |
|
2413 | if args.strip() == 'pasted_block': | |
2414 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2414 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2415 |
|
2415 | |||
2416 | if opts.has_key('x'): # -x prevents actual execution |
|
2416 | if opts.has_key('x'): # -x prevents actual execution | |
2417 |
|
2417 | |||
2418 | else: |
|
2418 | else: | |
2419 | print 'done. Executing edited code...' |
|
2419 | print 'done. Executing edited code...' | |
2420 | if opts_r: |
|
2420 | if opts_r: | |
2421 | self.shell.runlines(file_read(filename)) |
|
2421 | self.shell.runlines(file_read(filename)) | |
2422 | else: |
|
2422 | else: | |
2423 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2423 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2424 | self.shell.user_ns) |
|
2424 | self.shell.user_ns) | |
2425 |
|
2425 | |||
2426 |
|
2426 | |||
2427 | if use_temp: |
|
2427 | if use_temp: | |
2428 | try: |
|
2428 | try: | |
2429 | return open(filename).read() |
|
2429 | return open(filename).read() | |
2430 | except IOError,msg: |
|
2430 | except IOError,msg: | |
2431 | if msg.filename == filename: |
|
2431 | if msg.filename == filename: | |
2432 | warn('File not found. Did you forget to save?') |
|
2432 | warn('File not found. Did you forget to save?') | |
2433 | return |
|
2433 | return | |
2434 | else: |
|
2434 | else: | |
2435 | self.shell.showtraceback() |
|
2435 | self.shell.showtraceback() | |
2436 |
|
2436 | |||
2437 | def magic_xmode(self,parameter_s = ''): |
|
2437 | def magic_xmode(self,parameter_s = ''): | |
2438 | """Switch modes for the exception handlers. |
|
2438 | """Switch modes for the exception handlers. | |
2439 |
|
2439 | |||
2440 | Valid modes: Plain, Context and Verbose. |
|
2440 | Valid modes: Plain, Context and Verbose. | |
2441 |
|
2441 | |||
2442 | If called without arguments, acts as a toggle.""" |
|
2442 | If called without arguments, acts as a toggle.""" | |
2443 |
|
2443 | |||
2444 | def xmode_switch_err(name): |
|
2444 | def xmode_switch_err(name): | |
2445 | warn('Error changing %s exception modes.\n%s' % |
|
2445 | warn('Error changing %s exception modes.\n%s' % | |
2446 | (name,sys.exc_info()[1])) |
|
2446 | (name,sys.exc_info()[1])) | |
2447 |
|
2447 | |||
2448 | shell = self.shell |
|
2448 | shell = self.shell | |
2449 | new_mode = parameter_s.strip().capitalize() |
|
2449 | new_mode = parameter_s.strip().capitalize() | |
2450 | try: |
|
2450 | try: | |
2451 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2451 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2452 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2452 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2453 | except: |
|
2453 | except: | |
2454 | xmode_switch_err('user') |
|
2454 | xmode_switch_err('user') | |
2455 |
|
2455 | |||
2456 | # threaded shells use a special handler in sys.excepthook |
|
2456 | # threaded shells use a special handler in sys.excepthook | |
2457 | if shell.isthreaded: |
|
2457 | if shell.isthreaded: | |
2458 | try: |
|
2458 | try: | |
2459 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2459 | shell.sys_excepthook.set_mode(mode=new_mode) | |
2460 | except: |
|
2460 | except: | |
2461 | xmode_switch_err('threaded') |
|
2461 | xmode_switch_err('threaded') | |
2462 |
|
2462 | |||
2463 | def magic_colors(self,parameter_s = ''): |
|
2463 | def magic_colors(self,parameter_s = ''): | |
2464 | """Switch color scheme for prompts, info system and exception handlers. |
|
2464 | """Switch color scheme for prompts, info system and exception handlers. | |
2465 |
|
2465 | |||
2466 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2466 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2467 |
|
2467 | |||
2468 | Color scheme names are not case-sensitive.""" |
|
2468 | Color scheme names are not case-sensitive.""" | |
2469 |
|
2469 | |||
2470 | def color_switch_err(name): |
|
2470 | def color_switch_err(name): | |
2471 | warn('Error changing %s color schemes.\n%s' % |
|
2471 | warn('Error changing %s color schemes.\n%s' % | |
2472 | (name,sys.exc_info()[1])) |
|
2472 | (name,sys.exc_info()[1])) | |
2473 |
|
2473 | |||
2474 |
|
2474 | |||
2475 | new_scheme = parameter_s.strip() |
|
2475 | new_scheme = parameter_s.strip() | |
2476 | if not new_scheme: |
|
2476 | if not new_scheme: | |
2477 | raise UsageError( |
|
2477 | raise UsageError( | |
2478 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2478 | "%colors: you must specify a color scheme. See '%colors?'") | |
2479 | return |
|
2479 | return | |
2480 | # local shortcut |
|
2480 | # local shortcut | |
2481 | shell = self.shell |
|
2481 | shell = self.shell | |
2482 |
|
2482 | |||
2483 | import IPython.rlineimpl as readline |
|
2483 | import IPython.rlineimpl as readline | |
2484 |
|
2484 | |||
2485 | if not readline.have_readline and sys.platform == "win32": |
|
2485 | if not readline.have_readline and sys.platform == "win32": | |
2486 | msg = """\ |
|
2486 | msg = """\ | |
2487 | Proper color support under MS Windows requires the pyreadline library. |
|
2487 | Proper color support under MS Windows requires the pyreadline library. | |
2488 | You can find it at: |
|
2488 | You can find it at: | |
2489 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2489 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2490 | Gary's readline needs the ctypes module, from: |
|
2490 | Gary's readline needs the ctypes module, from: | |
2491 | http://starship.python.net/crew/theller/ctypes |
|
2491 | http://starship.python.net/crew/theller/ctypes | |
2492 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2492 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2493 |
|
2493 | |||
2494 | Defaulting color scheme to 'NoColor'""" |
|
2494 | Defaulting color scheme to 'NoColor'""" | |
2495 | new_scheme = 'NoColor' |
|
2495 | new_scheme = 'NoColor' | |
2496 | warn(msg) |
|
2496 | warn(msg) | |
2497 |
|
2497 | |||
2498 | # readline option is 0 |
|
2498 | # readline option is 0 | |
2499 | if not shell.has_readline: |
|
2499 | if not shell.has_readline: | |
2500 | new_scheme = 'NoColor' |
|
2500 | new_scheme = 'NoColor' | |
2501 |
|
2501 | |||
2502 | # Set prompt colors |
|
2502 | # Set prompt colors | |
2503 | try: |
|
2503 | try: | |
2504 | shell.outputcache.set_colors(new_scheme) |
|
2504 | shell.outputcache.set_colors(new_scheme) | |
2505 | except: |
|
2505 | except: | |
2506 | color_switch_err('prompt') |
|
2506 | color_switch_err('prompt') | |
2507 | else: |
|
2507 | else: | |
2508 | shell.rc.colors = \ |
|
2508 | shell.rc.colors = \ | |
2509 | shell.outputcache.color_table.active_scheme_name |
|
2509 | shell.outputcache.color_table.active_scheme_name | |
2510 | # Set exception colors |
|
2510 | # Set exception colors | |
2511 | try: |
|
2511 | try: | |
2512 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2512 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2513 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2513 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2514 | except: |
|
2514 | except: | |
2515 | color_switch_err('exception') |
|
2515 | color_switch_err('exception') | |
2516 |
|
2516 | |||
2517 | # threaded shells use a verbose traceback in sys.excepthook |
|
2517 | # threaded shells use a verbose traceback in sys.excepthook | |
2518 | if shell.isthreaded: |
|
2518 | if shell.isthreaded: | |
2519 | try: |
|
2519 | try: | |
2520 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2520 | shell.sys_excepthook.set_colors(scheme=new_scheme) | |
2521 | except: |
|
2521 | except: | |
2522 | color_switch_err('system exception handler') |
|
2522 | color_switch_err('system exception handler') | |
2523 |
|
2523 | |||
2524 | # Set info (for 'object?') colors |
|
2524 | # Set info (for 'object?') colors | |
2525 | if shell.rc.color_info: |
|
2525 | if shell.rc.color_info: | |
2526 | try: |
|
2526 | try: | |
2527 | shell.inspector.set_active_scheme(new_scheme) |
|
2527 | shell.inspector.set_active_scheme(new_scheme) | |
2528 | except: |
|
2528 | except: | |
2529 | color_switch_err('object inspector') |
|
2529 | color_switch_err('object inspector') | |
2530 | else: |
|
2530 | else: | |
2531 | shell.inspector.set_active_scheme('NoColor') |
|
2531 | shell.inspector.set_active_scheme('NoColor') | |
2532 |
|
2532 | |||
2533 | def magic_color_info(self,parameter_s = ''): |
|
2533 | def magic_color_info(self,parameter_s = ''): | |
2534 | """Toggle color_info. |
|
2534 | """Toggle color_info. | |
2535 |
|
2535 | |||
2536 | The color_info configuration parameter controls whether colors are |
|
2536 | The color_info configuration parameter controls whether colors are | |
2537 | used for displaying object details (by things like %psource, %pfile or |
|
2537 | used for displaying object details (by things like %psource, %pfile or | |
2538 | the '?' system). This function toggles this value with each call. |
|
2538 | the '?' system). This function toggles this value with each call. | |
2539 |
|
2539 | |||
2540 | Note that unless you have a fairly recent pager (less works better |
|
2540 | Note that unless you have a fairly recent pager (less works better | |
2541 | than more) in your system, using colored object information displays |
|
2541 | than more) in your system, using colored object information displays | |
2542 | will not work properly. Test it and see.""" |
|
2542 | will not work properly. Test it and see.""" | |
2543 |
|
2543 | |||
2544 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2544 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
2545 | self.magic_colors(self.shell.rc.colors) |
|
2545 | self.magic_colors(self.shell.rc.colors) | |
2546 | print 'Object introspection functions have now coloring:', |
|
2546 | print 'Object introspection functions have now coloring:', | |
2547 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2547 | print ['OFF','ON'][self.shell.rc.color_info] | |
2548 |
|
2548 | |||
2549 | def magic_Pprint(self, parameter_s=''): |
|
2549 | def magic_Pprint(self, parameter_s=''): | |
2550 | """Toggle pretty printing on/off.""" |
|
2550 | """Toggle pretty printing on/off.""" | |
2551 |
|
2551 | |||
2552 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2552 | self.shell.rc.pprint = 1 - self.shell.rc.pprint | |
2553 | print 'Pretty printing has been turned', \ |
|
2553 | print 'Pretty printing has been turned', \ | |
2554 | ['OFF','ON'][self.shell.rc.pprint] |
|
2554 | ['OFF','ON'][self.shell.rc.pprint] | |
2555 |
|
2555 | |||
2556 | def magic_exit(self, parameter_s=''): |
|
2556 | def magic_exit(self, parameter_s=''): | |
2557 | """Exit IPython, confirming if configured to do so. |
|
2557 | """Exit IPython, confirming if configured to do so. | |
2558 |
|
2558 | |||
2559 | You can configure whether IPython asks for confirmation upon exit by |
|
2559 | You can configure whether IPython asks for confirmation upon exit by | |
2560 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2560 | setting the confirm_exit flag in the ipythonrc file.""" | |
2561 |
|
2561 | |||
2562 | self.shell.exit() |
|
2562 | self.shell.exit() | |
2563 |
|
2563 | |||
2564 | def magic_quit(self, parameter_s=''): |
|
2564 | def magic_quit(self, parameter_s=''): | |
2565 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2565 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
2566 |
|
2566 | |||
2567 | self.shell.exit() |
|
2567 | self.shell.exit() | |
2568 |
|
2568 | |||
2569 | def magic_Exit(self, parameter_s=''): |
|
2569 | def magic_Exit(self, parameter_s=''): | |
2570 | """Exit IPython without confirmation.""" |
|
2570 | """Exit IPython without confirmation.""" | |
2571 |
|
2571 | |||
2572 | self.shell.ask_exit() |
|
2572 | self.shell.ask_exit() | |
2573 |
|
2573 | |||
2574 | #...................................................................... |
|
2574 | #...................................................................... | |
2575 | # Functions to implement unix shell-type things |
|
2575 | # Functions to implement unix shell-type things | |
2576 |
|
2576 | |||
2577 | @testdec.skip_doctest |
|
2577 | @testdec.skip_doctest | |
2578 | def magic_alias(self, parameter_s = ''): |
|
2578 | def magic_alias(self, parameter_s = ''): | |
2579 | """Define an alias for a system command. |
|
2579 | """Define an alias for a system command. | |
2580 |
|
2580 | |||
2581 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2581 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2582 |
|
2582 | |||
2583 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2583 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2584 | params' (from your underlying operating system). |
|
2584 | params' (from your underlying operating system). | |
2585 |
|
2585 | |||
2586 | Aliases have lower precedence than magic functions and Python normal |
|
2586 | Aliases have lower precedence than magic functions and Python normal | |
2587 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2587 | variables, so if 'foo' is both a Python variable and an alias, the | |
2588 | alias can not be executed until 'del foo' removes the Python variable. |
|
2588 | alias can not be executed until 'del foo' removes the Python variable. | |
2589 |
|
2589 | |||
2590 | You can use the %l specifier in an alias definition to represent the |
|
2590 | You can use the %l specifier in an alias definition to represent the | |
2591 | whole line when the alias is called. For example: |
|
2591 | whole line when the alias is called. For example: | |
2592 |
|
2592 | |||
2593 | In [2]: alias all echo "Input in brackets: <%l>" |
|
2593 | In [2]: alias all echo "Input in brackets: <%l>" | |
2594 | In [3]: all hello world |
|
2594 | In [3]: all hello world | |
2595 | Input in brackets: <hello world> |
|
2595 | Input in brackets: <hello world> | |
2596 |
|
2596 | |||
2597 | You can also define aliases with parameters using %s specifiers (one |
|
2597 | You can also define aliases with parameters using %s specifiers (one | |
2598 | per parameter): |
|
2598 | per parameter): | |
2599 |
|
2599 | |||
2600 | In [1]: alias parts echo first %s second %s |
|
2600 | In [1]: alias parts echo first %s second %s | |
2601 | In [2]: %parts A B |
|
2601 | In [2]: %parts A B | |
2602 | first A second B |
|
2602 | first A second B | |
2603 | In [3]: %parts A |
|
2603 | In [3]: %parts A | |
2604 | Incorrect number of arguments: 2 expected. |
|
2604 | Incorrect number of arguments: 2 expected. | |
2605 | parts is an alias to: 'echo first %s second %s' |
|
2605 | parts is an alias to: 'echo first %s second %s' | |
2606 |
|
2606 | |||
2607 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2607 | Note that %l and %s are mutually exclusive. You can only use one or | |
2608 | the other in your aliases. |
|
2608 | the other in your aliases. | |
2609 |
|
2609 | |||
2610 | Aliases expand Python variables just like system calls using ! or !! |
|
2610 | Aliases expand Python variables just like system calls using ! or !! | |
2611 | do: all expressions prefixed with '$' get expanded. For details of |
|
2611 | do: all expressions prefixed with '$' get expanded. For details of | |
2612 | the semantic rules, see PEP-215: |
|
2612 | the semantic rules, see PEP-215: | |
2613 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2613 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2614 | IPython for variable expansion. If you want to access a true shell |
|
2614 | IPython for variable expansion. If you want to access a true shell | |
2615 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2615 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2616 |
|
2616 | |||
2617 | In [6]: alias show echo |
|
2617 | In [6]: alias show echo | |
2618 | In [7]: PATH='A Python string' |
|
2618 | In [7]: PATH='A Python string' | |
2619 | In [8]: show $PATH |
|
2619 | In [8]: show $PATH | |
2620 | A Python string |
|
2620 | A Python string | |
2621 | In [9]: show $$PATH |
|
2621 | In [9]: show $$PATH | |
2622 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2622 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2623 |
|
2623 | |||
2624 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2624 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2625 | and %rehashx functions, which automatically create aliases for the |
|
2625 | and %rehashx functions, which automatically create aliases for the | |
2626 | contents of your $PATH. |
|
2626 | contents of your $PATH. | |
2627 |
|
2627 | |||
2628 | If called with no parameters, %alias prints the current alias table.""" |
|
2628 | If called with no parameters, %alias prints the current alias table.""" | |
2629 |
|
2629 | |||
2630 | par = parameter_s.strip() |
|
2630 | par = parameter_s.strip() | |
2631 | if not par: |
|
2631 | if not par: | |
2632 | stored = self.db.get('stored_aliases', {} ) |
|
2632 | stored = self.db.get('stored_aliases', {} ) | |
2633 | atab = self.shell.alias_table |
|
2633 | atab = self.shell.alias_table | |
2634 | aliases = atab.keys() |
|
2634 | aliases = atab.keys() | |
2635 | aliases.sort() |
|
2635 | aliases.sort() | |
2636 | res = [] |
|
2636 | res = [] | |
2637 | showlast = [] |
|
2637 | showlast = [] | |
2638 | for alias in aliases: |
|
2638 | for alias in aliases: | |
2639 | special = False |
|
2639 | special = False | |
2640 | try: |
|
2640 | try: | |
2641 | tgt = atab[alias][1] |
|
2641 | tgt = atab[alias][1] | |
2642 | except (TypeError, AttributeError): |
|
2642 | except (TypeError, AttributeError): | |
2643 | # unsubscriptable? probably a callable |
|
2643 | # unsubscriptable? probably a callable | |
2644 | tgt = atab[alias] |
|
2644 | tgt = atab[alias] | |
2645 | special = True |
|
2645 | special = True | |
2646 | # 'interesting' aliases |
|
2646 | # 'interesting' aliases | |
2647 | if (alias in stored or |
|
2647 | if (alias in stored or | |
2648 | special or |
|
2648 | special or | |
2649 | alias.lower() != os.path.splitext(tgt)[0].lower() or |
|
2649 | alias.lower() != os.path.splitext(tgt)[0].lower() or | |
2650 | ' ' in tgt): |
|
2650 | ' ' in tgt): | |
2651 | showlast.append((alias, tgt)) |
|
2651 | showlast.append((alias, tgt)) | |
2652 | else: |
|
2652 | else: | |
2653 | res.append((alias, tgt )) |
|
2653 | res.append((alias, tgt )) | |
2654 |
|
2654 | |||
2655 | # show most interesting aliases last |
|
2655 | # show most interesting aliases last | |
2656 | res.extend(showlast) |
|
2656 | res.extend(showlast) | |
2657 | print "Total number of aliases:",len(aliases) |
|
2657 | print "Total number of aliases:",len(aliases) | |
2658 | return res |
|
2658 | return res | |
2659 | try: |
|
2659 | try: | |
2660 | alias,cmd = par.split(None,1) |
|
2660 | alias,cmd = par.split(None,1) | |
2661 | except: |
|
2661 | except: | |
2662 | print OInspect.getdoc(self.magic_alias) |
|
2662 | print OInspect.getdoc(self.magic_alias) | |
2663 | else: |
|
2663 | else: | |
2664 | nargs = cmd.count('%s') |
|
2664 | nargs = cmd.count('%s') | |
2665 | if nargs>0 and cmd.find('%l')>=0: |
|
2665 | if nargs>0 and cmd.find('%l')>=0: | |
2666 | error('The %s and %l specifiers are mutually exclusive ' |
|
2666 | error('The %s and %l specifiers are mutually exclusive ' | |
2667 | 'in alias definitions.') |
|
2667 | 'in alias definitions.') | |
2668 | else: # all looks OK |
|
2668 | else: # all looks OK | |
2669 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2669 | self.shell.alias_table[alias] = (nargs,cmd) | |
2670 | self.shell.alias_table_validate(verbose=0) |
|
2670 | self.shell.alias_table_validate(verbose=0) | |
2671 | # end magic_alias |
|
2671 | # end magic_alias | |
2672 |
|
2672 | |||
2673 | def magic_unalias(self, parameter_s = ''): |
|
2673 | def magic_unalias(self, parameter_s = ''): | |
2674 | """Remove an alias""" |
|
2674 | """Remove an alias""" | |
2675 |
|
2675 | |||
2676 | aname = parameter_s.strip() |
|
2676 | aname = parameter_s.strip() | |
2677 | if aname in self.shell.alias_table: |
|
2677 | if aname in self.shell.alias_table: | |
2678 | del self.shell.alias_table[aname] |
|
2678 | del self.shell.alias_table[aname] | |
2679 | stored = self.db.get('stored_aliases', {} ) |
|
2679 | stored = self.db.get('stored_aliases', {} ) | |
2680 | if aname in stored: |
|
2680 | if aname in stored: | |
2681 | print "Removing %stored alias",aname |
|
2681 | print "Removing %stored alias",aname | |
2682 | del stored[aname] |
|
2682 | del stored[aname] | |
2683 | self.db['stored_aliases'] = stored |
|
2683 | self.db['stored_aliases'] = stored | |
2684 |
|
2684 | |||
2685 |
|
2685 | |||
2686 | def magic_rehashx(self, parameter_s = ''): |
|
2686 | def magic_rehashx(self, parameter_s = ''): | |
2687 | """Update the alias table with all executable files in $PATH. |
|
2687 | """Update the alias table with all executable files in $PATH. | |
2688 |
|
2688 | |||
2689 | This version explicitly checks that every entry in $PATH is a file |
|
2689 | This version explicitly checks that every entry in $PATH is a file | |
2690 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2690 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2691 |
|
2691 | |||
2692 | Under Windows, it checks executability as a match agains a |
|
2692 | Under Windows, it checks executability as a match agains a | |
2693 | '|'-separated string of extensions, stored in the IPython config |
|
2693 | '|'-separated string of extensions, stored in the IPython config | |
2694 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2694 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2695 |
|
2695 | |||
2696 | This function also resets the root module cache of module completer, |
|
2696 | This function also resets the root module cache of module completer, | |
2697 | used on slow filesystems. |
|
2697 | used on slow filesystems. | |
2698 | """ |
|
2698 | """ | |
2699 |
|
2699 | |||
2700 |
|
2700 | |||
2701 | ip = self.api |
|
2701 | ip = self.api | |
2702 |
|
2702 | |||
2703 | # for the benefit of module completer in ipy_completers.py |
|
2703 | # for the benefit of module completer in ipy_completers.py | |
2704 | del ip.db['rootmodules'] |
|
2704 | del ip.db['rootmodules'] | |
2705 |
|
2705 | |||
2706 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2706 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2707 | os.environ.get('PATH','').split(os.pathsep)] |
|
2707 | os.environ.get('PATH','').split(os.pathsep)] | |
2708 | path = filter(os.path.isdir,path) |
|
2708 | path = filter(os.path.isdir,path) | |
2709 |
|
2709 | |||
2710 | alias_table = self.shell.alias_table |
|
2710 | alias_table = self.shell.alias_table | |
2711 | syscmdlist = [] |
|
2711 | syscmdlist = [] | |
2712 | if os.name == 'posix': |
|
2712 | if os.name == 'posix': | |
2713 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2713 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2714 | os.access(fname,os.X_OK) |
|
2714 | os.access(fname,os.X_OK) | |
2715 | else: |
|
2715 | else: | |
2716 |
|
2716 | |||
2717 | try: |
|
2717 | try: | |
2718 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2718 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2719 | except KeyError: |
|
2719 | except KeyError: | |
2720 | winext = 'exe|com|bat|py' |
|
2720 | winext = 'exe|com|bat|py' | |
2721 | if 'py' not in winext: |
|
2721 | if 'py' not in winext: | |
2722 | winext += '|py' |
|
2722 | winext += '|py' | |
2723 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2723 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2724 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2724 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2725 | savedir = os.getcwd() |
|
2725 | savedir = os.getcwd() | |
2726 | try: |
|
2726 | try: | |
2727 | # write the whole loop for posix/Windows so we don't have an if in |
|
2727 | # write the whole loop for posix/Windows so we don't have an if in | |
2728 | # the innermost part |
|
2728 | # the innermost part | |
2729 | if os.name == 'posix': |
|
2729 | if os.name == 'posix': | |
2730 | for pdir in path: |
|
2730 | for pdir in path: | |
2731 | os.chdir(pdir) |
|
2731 | os.chdir(pdir) | |
2732 | for ff in os.listdir(pdir): |
|
2732 | for ff in os.listdir(pdir): | |
2733 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2733 | if isexec(ff) and ff not in self.shell.no_alias: | |
2734 | # each entry in the alias table must be (N,name), |
|
2734 | # each entry in the alias table must be (N,name), | |
2735 | # where N is the number of positional arguments of the |
|
2735 | # where N is the number of positional arguments of the | |
2736 | # alias. |
|
2736 | # alias. | |
2737 | # Dots will be removed from alias names, since ipython |
|
2737 | # Dots will be removed from alias names, since ipython | |
2738 | # assumes names with dots to be python code |
|
2738 | # assumes names with dots to be python code | |
2739 | alias_table[ff.replace('.','')] = (0,ff) |
|
2739 | alias_table[ff.replace('.','')] = (0,ff) | |
2740 | syscmdlist.append(ff) |
|
2740 | syscmdlist.append(ff) | |
2741 | else: |
|
2741 | else: | |
2742 | for pdir in path: |
|
2742 | for pdir in path: | |
2743 | os.chdir(pdir) |
|
2743 | os.chdir(pdir) | |
2744 | for ff in os.listdir(pdir): |
|
2744 | for ff in os.listdir(pdir): | |
2745 | base, ext = os.path.splitext(ff) |
|
2745 | base, ext = os.path.splitext(ff) | |
2746 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2746 | if isexec(ff) and base.lower() not in self.shell.no_alias: | |
2747 | if ext.lower() == '.exe': |
|
2747 | if ext.lower() == '.exe': | |
2748 | ff = base |
|
2748 | ff = base | |
2749 | alias_table[base.lower().replace('.','')] = (0,ff) |
|
2749 | alias_table[base.lower().replace('.','')] = (0,ff) | |
2750 | syscmdlist.append(ff) |
|
2750 | syscmdlist.append(ff) | |
2751 | # Make sure the alias table doesn't contain keywords or builtins |
|
2751 | # Make sure the alias table doesn't contain keywords or builtins | |
2752 | self.shell.alias_table_validate() |
|
2752 | self.shell.alias_table_validate() | |
2753 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2753 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2754 | # modified aliases since %rehashx will probably clobber them |
|
2754 | # modified aliases since %rehashx will probably clobber them | |
2755 |
|
2755 | |||
2756 | # no, we don't want them. if %rehashx clobbers them, good, |
|
2756 | # no, we don't want them. if %rehashx clobbers them, good, | |
2757 | # we'll probably get better versions |
|
2757 | # we'll probably get better versions | |
2758 | # self.shell.init_auto_alias() |
|
2758 | # self.shell.init_auto_alias() | |
2759 | db = ip.db |
|
2759 | db = ip.db | |
2760 | db['syscmdlist'] = syscmdlist |
|
2760 | db['syscmdlist'] = syscmdlist | |
2761 | finally: |
|
2761 | finally: | |
2762 | os.chdir(savedir) |
|
2762 | os.chdir(savedir) | |
2763 |
|
2763 | |||
2764 | def magic_pwd(self, parameter_s = ''): |
|
2764 | def magic_pwd(self, parameter_s = ''): | |
2765 | """Return the current working directory path.""" |
|
2765 | """Return the current working directory path.""" | |
2766 | return os.getcwd() |
|
2766 | return os.getcwd() | |
2767 |
|
2767 | |||
2768 | def magic_cd(self, parameter_s=''): |
|
2768 | def magic_cd(self, parameter_s=''): | |
2769 | """Change the current working directory. |
|
2769 | """Change the current working directory. | |
2770 |
|
2770 | |||
2771 | This command automatically maintains an internal list of directories |
|
2771 | This command automatically maintains an internal list of directories | |
2772 | you visit during your IPython session, in the variable _dh. The |
|
2772 | you visit during your IPython session, in the variable _dh. The | |
2773 | command %dhist shows this history nicely formatted. You can also |
|
2773 | command %dhist shows this history nicely formatted. You can also | |
2774 | do 'cd -<tab>' to see directory history conveniently. |
|
2774 | do 'cd -<tab>' to see directory history conveniently. | |
2775 |
|
2775 | |||
2776 | Usage: |
|
2776 | Usage: | |
2777 |
|
2777 | |||
2778 | cd 'dir': changes to directory 'dir'. |
|
2778 | cd 'dir': changes to directory 'dir'. | |
2779 |
|
2779 | |||
2780 | cd -: changes to the last visited directory. |
|
2780 | cd -: changes to the last visited directory. | |
2781 |
|
2781 | |||
2782 | cd -<n>: changes to the n-th directory in the directory history. |
|
2782 | cd -<n>: changes to the n-th directory in the directory history. | |
2783 |
|
2783 | |||
2784 | cd --foo: change to directory that matches 'foo' in history |
|
2784 | cd --foo: change to directory that matches 'foo' in history | |
2785 |
|
2785 | |||
2786 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2786 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2787 | (note: cd <bookmark_name> is enough if there is no |
|
2787 | (note: cd <bookmark_name> is enough if there is no | |
2788 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2788 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2789 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2789 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2790 |
|
2790 | |||
2791 | Options: |
|
2791 | Options: | |
2792 |
|
2792 | |||
2793 | -q: quiet. Do not print the working directory after the cd command is |
|
2793 | -q: quiet. Do not print the working directory after the cd command is | |
2794 | executed. By default IPython's cd command does print this directory, |
|
2794 | executed. By default IPython's cd command does print this directory, | |
2795 | since the default prompts do not display path information. |
|
2795 | since the default prompts do not display path information. | |
2796 |
|
2796 | |||
2797 | Note that !cd doesn't work for this purpose because the shell where |
|
2797 | Note that !cd doesn't work for this purpose because the shell where | |
2798 | !command runs is immediately discarded after executing 'command'.""" |
|
2798 | !command runs is immediately discarded after executing 'command'.""" | |
2799 |
|
2799 | |||
2800 | parameter_s = parameter_s.strip() |
|
2800 | parameter_s = parameter_s.strip() | |
2801 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2801 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2802 |
|
2802 | |||
2803 | oldcwd = os.getcwd() |
|
2803 | oldcwd = os.getcwd() | |
2804 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2804 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2805 | # jump in directory history by number |
|
2805 | # jump in directory history by number | |
2806 | if numcd: |
|
2806 | if numcd: | |
2807 | nn = int(numcd.group(2)) |
|
2807 | nn = int(numcd.group(2)) | |
2808 | try: |
|
2808 | try: | |
2809 | ps = self.shell.user_ns['_dh'][nn] |
|
2809 | ps = self.shell.user_ns['_dh'][nn] | |
2810 | except IndexError: |
|
2810 | except IndexError: | |
2811 | print 'The requested directory does not exist in history.' |
|
2811 | print 'The requested directory does not exist in history.' | |
2812 | return |
|
2812 | return | |
2813 | else: |
|
2813 | else: | |
2814 | opts = {} |
|
2814 | opts = {} | |
2815 | elif parameter_s.startswith('--'): |
|
2815 | elif parameter_s.startswith('--'): | |
2816 | ps = None |
|
2816 | ps = None | |
2817 | fallback = None |
|
2817 | fallback = None | |
2818 | pat = parameter_s[2:] |
|
2818 | pat = parameter_s[2:] | |
2819 | dh = self.shell.user_ns['_dh'] |
|
2819 | dh = self.shell.user_ns['_dh'] | |
2820 | # first search only by basename (last component) |
|
2820 | # first search only by basename (last component) | |
2821 | for ent in reversed(dh): |
|
2821 | for ent in reversed(dh): | |
2822 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2822 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2823 | ps = ent |
|
2823 | ps = ent | |
2824 | break |
|
2824 | break | |
2825 |
|
2825 | |||
2826 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2826 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2827 | fallback = ent |
|
2827 | fallback = ent | |
2828 |
|
2828 | |||
2829 | # if we have no last part match, pick the first full path match |
|
2829 | # if we have no last part match, pick the first full path match | |
2830 | if ps is None: |
|
2830 | if ps is None: | |
2831 | ps = fallback |
|
2831 | ps = fallback | |
2832 |
|
2832 | |||
2833 | if ps is None: |
|
2833 | if ps is None: | |
2834 | print "No matching entry in directory history" |
|
2834 | print "No matching entry in directory history" | |
2835 | return |
|
2835 | return | |
2836 | else: |
|
2836 | else: | |
2837 | opts = {} |
|
2837 | opts = {} | |
2838 |
|
2838 | |||
2839 |
|
2839 | |||
2840 | else: |
|
2840 | else: | |
2841 | #turn all non-space-escaping backslashes to slashes, |
|
2841 | #turn all non-space-escaping backslashes to slashes, | |
2842 | # for c:\windows\directory\names\ |
|
2842 | # for c:\windows\directory\names\ | |
2843 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2843 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2844 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2844 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2845 | # jump to previous |
|
2845 | # jump to previous | |
2846 | if ps == '-': |
|
2846 | if ps == '-': | |
2847 | try: |
|
2847 | try: | |
2848 | ps = self.shell.user_ns['_dh'][-2] |
|
2848 | ps = self.shell.user_ns['_dh'][-2] | |
2849 | except IndexError: |
|
2849 | except IndexError: | |
2850 | raise UsageError('%cd -: No previous directory to change to.') |
|
2850 | raise UsageError('%cd -: No previous directory to change to.') | |
2851 | # jump to bookmark if needed |
|
2851 | # jump to bookmark if needed | |
2852 | else: |
|
2852 | else: | |
2853 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2853 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2854 | bkms = self.db.get('bookmarks', {}) |
|
2854 | bkms = self.db.get('bookmarks', {}) | |
2855 |
|
2855 | |||
2856 | if bkms.has_key(ps): |
|
2856 | if bkms.has_key(ps): | |
2857 | target = bkms[ps] |
|
2857 | target = bkms[ps] | |
2858 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2858 | print '(bookmark:%s) -> %s' % (ps,target) | |
2859 | ps = target |
|
2859 | ps = target | |
2860 | else: |
|
2860 | else: | |
2861 | if opts.has_key('b'): |
|
2861 | if opts.has_key('b'): | |
2862 | raise UsageError("Bookmark '%s' not found. " |
|
2862 | raise UsageError("Bookmark '%s' not found. " | |
2863 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2863 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2864 |
|
2864 | |||
2865 | # at this point ps should point to the target dir |
|
2865 | # at this point ps should point to the target dir | |
2866 | if ps: |
|
2866 | if ps: | |
2867 | try: |
|
2867 | try: | |
2868 | os.chdir(os.path.expanduser(ps)) |
|
2868 | os.chdir(os.path.expanduser(ps)) | |
2869 | if self.shell.rc.term_title: |
|
2869 | if self.shell.rc.term_title: | |
2870 | #print 'set term title:',self.shell.rc.term_title # dbg |
|
2870 | #print 'set term title:',self.shell.rc.term_title # dbg | |
2871 | platutils.set_term_title('IPy ' + abbrev_cwd()) |
|
2871 | platutils.set_term_title('IPy ' + abbrev_cwd()) | |
2872 | except OSError: |
|
2872 | except OSError: | |
2873 | print sys.exc_info()[1] |
|
2873 | print sys.exc_info()[1] | |
2874 | else: |
|
2874 | else: | |
2875 | cwd = os.getcwd() |
|
2875 | cwd = os.getcwd() | |
2876 | dhist = self.shell.user_ns['_dh'] |
|
2876 | dhist = self.shell.user_ns['_dh'] | |
2877 | if oldcwd != cwd: |
|
2877 | if oldcwd != cwd: | |
2878 | dhist.append(cwd) |
|
2878 | dhist.append(cwd) | |
2879 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2879 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2880 |
|
2880 | |||
2881 | else: |
|
2881 | else: | |
2882 | os.chdir(self.shell.home_dir) |
|
2882 | os.chdir(self.shell.home_dir) | |
2883 | if self.shell.rc.term_title: |
|
2883 | if self.shell.rc.term_title: | |
2884 | platutils.set_term_title("IPy ~") |
|
2884 | platutils.set_term_title("IPy ~") | |
2885 | cwd = os.getcwd() |
|
2885 | cwd = os.getcwd() | |
2886 | dhist = self.shell.user_ns['_dh'] |
|
2886 | dhist = self.shell.user_ns['_dh'] | |
2887 |
|
2887 | |||
2888 | if oldcwd != cwd: |
|
2888 | if oldcwd != cwd: | |
2889 | dhist.append(cwd) |
|
2889 | dhist.append(cwd) | |
2890 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2890 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2891 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2891 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2892 | print self.shell.user_ns['_dh'][-1] |
|
2892 | print self.shell.user_ns['_dh'][-1] | |
2893 |
|
2893 | |||
2894 |
|
2894 | |||
2895 | def magic_env(self, parameter_s=''): |
|
2895 | def magic_env(self, parameter_s=''): | |
2896 | """List environment variables.""" |
|
2896 | """List environment variables.""" | |
2897 |
|
2897 | |||
2898 | return os.environ.data |
|
2898 | return os.environ.data | |
2899 |
|
2899 | |||
2900 | def magic_pushd(self, parameter_s=''): |
|
2900 | def magic_pushd(self, parameter_s=''): | |
2901 | """Place the current dir on stack and change directory. |
|
2901 | """Place the current dir on stack and change directory. | |
2902 |
|
2902 | |||
2903 | Usage:\\ |
|
2903 | Usage:\\ | |
2904 | %pushd ['dirname'] |
|
2904 | %pushd ['dirname'] | |
2905 | """ |
|
2905 | """ | |
2906 |
|
2906 | |||
2907 | dir_s = self.shell.dir_stack |
|
2907 | dir_s = self.shell.dir_stack | |
2908 | tgt = os.path.expanduser(parameter_s) |
|
2908 | tgt = os.path.expanduser(parameter_s) | |
2909 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2909 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2910 | if tgt: |
|
2910 | if tgt: | |
2911 | self.magic_cd(parameter_s) |
|
2911 | self.magic_cd(parameter_s) | |
2912 | dir_s.insert(0,cwd) |
|
2912 | dir_s.insert(0,cwd) | |
2913 | return self.magic_dirs() |
|
2913 | return self.magic_dirs() | |
2914 |
|
2914 | |||
2915 | def magic_popd(self, parameter_s=''): |
|
2915 | def magic_popd(self, parameter_s=''): | |
2916 | """Change to directory popped off the top of the stack. |
|
2916 | """Change to directory popped off the top of the stack. | |
2917 | """ |
|
2917 | """ | |
2918 | if not self.shell.dir_stack: |
|
2918 | if not self.shell.dir_stack: | |
2919 | raise UsageError("%popd on empty stack") |
|
2919 | raise UsageError("%popd on empty stack") | |
2920 | top = self.shell.dir_stack.pop(0) |
|
2920 | top = self.shell.dir_stack.pop(0) | |
2921 | self.magic_cd(top) |
|
2921 | self.magic_cd(top) | |
2922 | print "popd ->",top |
|
2922 | print "popd ->",top | |
2923 |
|
2923 | |||
2924 | def magic_dirs(self, parameter_s=''): |
|
2924 | def magic_dirs(self, parameter_s=''): | |
2925 | """Return the current directory stack.""" |
|
2925 | """Return the current directory stack.""" | |
2926 |
|
2926 | |||
2927 | return self.shell.dir_stack |
|
2927 | return self.shell.dir_stack | |
2928 |
|
2928 | |||
2929 | def magic_dhist(self, parameter_s=''): |
|
2929 | def magic_dhist(self, parameter_s=''): | |
2930 | """Print your history of visited directories. |
|
2930 | """Print your history of visited directories. | |
2931 |
|
2931 | |||
2932 | %dhist -> print full history\\ |
|
2932 | %dhist -> print full history\\ | |
2933 | %dhist n -> print last n entries only\\ |
|
2933 | %dhist n -> print last n entries only\\ | |
2934 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2934 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2935 |
|
2935 | |||
2936 | This history is automatically maintained by the %cd command, and |
|
2936 | This history is automatically maintained by the %cd command, and | |
2937 | always available as the global list variable _dh. You can use %cd -<n> |
|
2937 | always available as the global list variable _dh. You can use %cd -<n> | |
2938 | to go to directory number <n>. |
|
2938 | to go to directory number <n>. | |
2939 |
|
2939 | |||
2940 | Note that most of time, you should view directory history by entering |
|
2940 | Note that most of time, you should view directory history by entering | |
2941 | cd -<TAB>. |
|
2941 | cd -<TAB>. | |
2942 |
|
2942 | |||
2943 | """ |
|
2943 | """ | |
2944 |
|
2944 | |||
2945 | dh = self.shell.user_ns['_dh'] |
|
2945 | dh = self.shell.user_ns['_dh'] | |
2946 | if parameter_s: |
|
2946 | if parameter_s: | |
2947 | try: |
|
2947 | try: | |
2948 | args = map(int,parameter_s.split()) |
|
2948 | args = map(int,parameter_s.split()) | |
2949 | except: |
|
2949 | except: | |
2950 | self.arg_err(Magic.magic_dhist) |
|
2950 | self.arg_err(Magic.magic_dhist) | |
2951 | return |
|
2951 | return | |
2952 | if len(args) == 1: |
|
2952 | if len(args) == 1: | |
2953 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2953 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2954 | elif len(args) == 2: |
|
2954 | elif len(args) == 2: | |
2955 | ini,fin = args |
|
2955 | ini,fin = args | |
2956 | else: |
|
2956 | else: | |
2957 | self.arg_err(Magic.magic_dhist) |
|
2957 | self.arg_err(Magic.magic_dhist) | |
2958 | return |
|
2958 | return | |
2959 | else: |
|
2959 | else: | |
2960 | ini,fin = 0,len(dh) |
|
2960 | ini,fin = 0,len(dh) | |
2961 | nlprint(dh, |
|
2961 | nlprint(dh, | |
2962 | header = 'Directory history (kept in _dh)', |
|
2962 | header = 'Directory history (kept in _dh)', | |
2963 | start=ini,stop=fin) |
|
2963 | start=ini,stop=fin) | |
2964 |
|
2964 | |||
2965 | @testdec.skip_doctest |
|
2965 | @testdec.skip_doctest | |
2966 | def magic_sc(self, parameter_s=''): |
|
2966 | def magic_sc(self, parameter_s=''): | |
2967 | """Shell capture - execute a shell command and capture its output. |
|
2967 | """Shell capture - execute a shell command and capture its output. | |
2968 |
|
2968 | |||
2969 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2969 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2970 |
|
2970 | |||
2971 | You should use the form 'var = !command' instead. Example: |
|
2971 | You should use the form 'var = !command' instead. Example: | |
2972 |
|
2972 | |||
2973 | "%sc -l myfiles = ls ~" should now be written as |
|
2973 | "%sc -l myfiles = ls ~" should now be written as | |
2974 |
|
2974 | |||
2975 | "myfiles = !ls ~" |
|
2975 | "myfiles = !ls ~" | |
2976 |
|
2976 | |||
2977 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2977 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2978 | below. |
|
2978 | below. | |
2979 |
|
2979 | |||
2980 | -- |
|
2980 | -- | |
2981 | %sc [options] varname=command |
|
2981 | %sc [options] varname=command | |
2982 |
|
2982 | |||
2983 | IPython will run the given command using commands.getoutput(), and |
|
2983 | IPython will run the given command using commands.getoutput(), and | |
2984 | will then update the user's interactive namespace with a variable |
|
2984 | will then update the user's interactive namespace with a variable | |
2985 | called varname, containing the value of the call. Your command can |
|
2985 | called varname, containing the value of the call. Your command can | |
2986 | contain shell wildcards, pipes, etc. |
|
2986 | contain shell wildcards, pipes, etc. | |
2987 |
|
2987 | |||
2988 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2988 | The '=' sign in the syntax is mandatory, and the variable name you | |
2989 | supply must follow Python's standard conventions for valid names. |
|
2989 | supply must follow Python's standard conventions for valid names. | |
2990 |
|
2990 | |||
2991 | (A special format without variable name exists for internal use) |
|
2991 | (A special format without variable name exists for internal use) | |
2992 |
|
2992 | |||
2993 | Options: |
|
2993 | Options: | |
2994 |
|
2994 | |||
2995 | -l: list output. Split the output on newlines into a list before |
|
2995 | -l: list output. Split the output on newlines into a list before | |
2996 | assigning it to the given variable. By default the output is stored |
|
2996 | assigning it to the given variable. By default the output is stored | |
2997 | as a single string. |
|
2997 | as a single string. | |
2998 |
|
2998 | |||
2999 | -v: verbose. Print the contents of the variable. |
|
2999 | -v: verbose. Print the contents of the variable. | |
3000 |
|
3000 | |||
3001 | In most cases you should not need to split as a list, because the |
|
3001 | In most cases you should not need to split as a list, because the | |
3002 | returned value is a special type of string which can automatically |
|
3002 | returned value is a special type of string which can automatically | |
3003 | provide its contents either as a list (split on newlines) or as a |
|
3003 | provide its contents either as a list (split on newlines) or as a | |
3004 | space-separated string. These are convenient, respectively, either |
|
3004 | space-separated string. These are convenient, respectively, either | |
3005 | for sequential processing or to be passed to a shell command. |
|
3005 | for sequential processing or to be passed to a shell command. | |
3006 |
|
3006 | |||
3007 | For example: |
|
3007 | For example: | |
3008 |
|
3008 | |||
3009 | # all-random |
|
3009 | # all-random | |
3010 |
|
3010 | |||
3011 | # Capture into variable a |
|
3011 | # Capture into variable a | |
3012 | In [1]: sc a=ls *py |
|
3012 | In [1]: sc a=ls *py | |
3013 |
|
3013 | |||
3014 | # a is a string with embedded newlines |
|
3014 | # a is a string with embedded newlines | |
3015 | In [2]: a |
|
3015 | In [2]: a | |
3016 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
3016 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
3017 |
|
3017 | |||
3018 | # which can be seen as a list: |
|
3018 | # which can be seen as a list: | |
3019 | In [3]: a.l |
|
3019 | In [3]: a.l | |
3020 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
3020 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
3021 |
|
3021 | |||
3022 | # or as a whitespace-separated string: |
|
3022 | # or as a whitespace-separated string: | |
3023 | In [4]: a.s |
|
3023 | In [4]: a.s | |
3024 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
3024 | Out[4]: 'setup.py win32_manual_post_install.py' | |
3025 |
|
3025 | |||
3026 | # a.s is useful to pass as a single command line: |
|
3026 | # a.s is useful to pass as a single command line: | |
3027 | In [5]: !wc -l $a.s |
|
3027 | In [5]: !wc -l $a.s | |
3028 | 146 setup.py |
|
3028 | 146 setup.py | |
3029 | 130 win32_manual_post_install.py |
|
3029 | 130 win32_manual_post_install.py | |
3030 | 276 total |
|
3030 | 276 total | |
3031 |
|
3031 | |||
3032 | # while the list form is useful to loop over: |
|
3032 | # while the list form is useful to loop over: | |
3033 | In [6]: for f in a.l: |
|
3033 | In [6]: for f in a.l: | |
3034 | ...: !wc -l $f |
|
3034 | ...: !wc -l $f | |
3035 | ...: |
|
3035 | ...: | |
3036 | 146 setup.py |
|
3036 | 146 setup.py | |
3037 | 130 win32_manual_post_install.py |
|
3037 | 130 win32_manual_post_install.py | |
3038 |
|
3038 | |||
3039 | Similiarly, the lists returned by the -l option are also special, in |
|
3039 | Similiarly, the lists returned by the -l option are also special, in | |
3040 | the sense that you can equally invoke the .s attribute on them to |
|
3040 | the sense that you can equally invoke the .s attribute on them to | |
3041 | automatically get a whitespace-separated string from their contents: |
|
3041 | automatically get a whitespace-separated string from their contents: | |
3042 |
|
3042 | |||
3043 | In [7]: sc -l b=ls *py |
|
3043 | In [7]: sc -l b=ls *py | |
3044 |
|
3044 | |||
3045 | In [8]: b |
|
3045 | In [8]: b | |
3046 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3046 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
3047 |
|
3047 | |||
3048 | In [9]: b.s |
|
3048 | In [9]: b.s | |
3049 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3049 | Out[9]: 'setup.py win32_manual_post_install.py' | |
3050 |
|
3050 | |||
3051 | In summary, both the lists and strings used for ouptut capture have |
|
3051 | In summary, both the lists and strings used for ouptut capture have | |
3052 | the following special attributes: |
|
3052 | the following special attributes: | |
3053 |
|
3053 | |||
3054 | .l (or .list) : value as list. |
|
3054 | .l (or .list) : value as list. | |
3055 | .n (or .nlstr): value as newline-separated string. |
|
3055 | .n (or .nlstr): value as newline-separated string. | |
3056 | .s (or .spstr): value as space-separated string. |
|
3056 | .s (or .spstr): value as space-separated string. | |
3057 | """ |
|
3057 | """ | |
3058 |
|
3058 | |||
3059 | opts,args = self.parse_options(parameter_s,'lv') |
|
3059 | opts,args = self.parse_options(parameter_s,'lv') | |
3060 | # Try to get a variable name and command to run |
|
3060 | # Try to get a variable name and command to run | |
3061 | try: |
|
3061 | try: | |
3062 | # the variable name must be obtained from the parse_options |
|
3062 | # the variable name must be obtained from the parse_options | |
3063 | # output, which uses shlex.split to strip options out. |
|
3063 | # output, which uses shlex.split to strip options out. | |
3064 | var,_ = args.split('=',1) |
|
3064 | var,_ = args.split('=',1) | |
3065 | var = var.strip() |
|
3065 | var = var.strip() | |
3066 | # But the the command has to be extracted from the original input |
|
3066 | # But the the command has to be extracted from the original input | |
3067 | # parameter_s, not on what parse_options returns, to avoid the |
|
3067 | # parameter_s, not on what parse_options returns, to avoid the | |
3068 | # quote stripping which shlex.split performs on it. |
|
3068 | # quote stripping which shlex.split performs on it. | |
3069 | _,cmd = parameter_s.split('=',1) |
|
3069 | _,cmd = parameter_s.split('=',1) | |
3070 | except ValueError: |
|
3070 | except ValueError: | |
3071 | var,cmd = '','' |
|
3071 | var,cmd = '','' | |
3072 | # If all looks ok, proceed |
|
3072 | # If all looks ok, proceed | |
3073 | out,err = self.shell.getoutputerror(cmd) |
|
3073 | out,err = self.shell.getoutputerror(cmd) | |
3074 | if err: |
|
3074 | if err: | |
3075 | print >> Term.cerr,err |
|
3075 | print >> Term.cerr,err | |
3076 | if opts.has_key('l'): |
|
3076 | if opts.has_key('l'): | |
3077 | out = SList(out.split('\n')) |
|
3077 | out = SList(out.split('\n')) | |
3078 | else: |
|
3078 | else: | |
3079 | out = LSString(out) |
|
3079 | out = LSString(out) | |
3080 | if opts.has_key('v'): |
|
3080 | if opts.has_key('v'): | |
3081 | print '%s ==\n%s' % (var,pformat(out)) |
|
3081 | print '%s ==\n%s' % (var,pformat(out)) | |
3082 | if var: |
|
3082 | if var: | |
3083 | self.shell.user_ns.update({var:out}) |
|
3083 | self.shell.user_ns.update({var:out}) | |
3084 | else: |
|
3084 | else: | |
3085 | return out |
|
3085 | return out | |
3086 |
|
3086 | |||
3087 | def magic_sx(self, parameter_s=''): |
|
3087 | def magic_sx(self, parameter_s=''): | |
3088 | """Shell execute - run a shell command and capture its output. |
|
3088 | """Shell execute - run a shell command and capture its output. | |
3089 |
|
3089 | |||
3090 | %sx command |
|
3090 | %sx command | |
3091 |
|
3091 | |||
3092 | IPython will run the given command using commands.getoutput(), and |
|
3092 | IPython will run the given command using commands.getoutput(), and | |
3093 | return the result formatted as a list (split on '\\n'). Since the |
|
3093 | return the result formatted as a list (split on '\\n'). Since the | |
3094 | output is _returned_, it will be stored in ipython's regular output |
|
3094 | output is _returned_, it will be stored in ipython's regular output | |
3095 | cache Out[N] and in the '_N' automatic variables. |
|
3095 | cache Out[N] and in the '_N' automatic variables. | |
3096 |
|
3096 | |||
3097 | Notes: |
|
3097 | Notes: | |
3098 |
|
3098 | |||
3099 | 1) If an input line begins with '!!', then %sx is automatically |
|
3099 | 1) If an input line begins with '!!', then %sx is automatically | |
3100 | invoked. That is, while: |
|
3100 | invoked. That is, while: | |
3101 | !ls |
|
3101 | !ls | |
3102 | causes ipython to simply issue system('ls'), typing |
|
3102 | causes ipython to simply issue system('ls'), typing | |
3103 | !!ls |
|
3103 | !!ls | |
3104 | is a shorthand equivalent to: |
|
3104 | is a shorthand equivalent to: | |
3105 | %sx ls |
|
3105 | %sx ls | |
3106 |
|
3106 | |||
3107 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3107 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3108 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3108 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3109 | to process line-oriented shell output via further python commands. |
|
3109 | to process line-oriented shell output via further python commands. | |
3110 | %sc is meant to provide much finer control, but requires more |
|
3110 | %sc is meant to provide much finer control, but requires more | |
3111 | typing. |
|
3111 | typing. | |
3112 |
|
3112 | |||
3113 | 3) Just like %sc -l, this is a list with special attributes: |
|
3113 | 3) Just like %sc -l, this is a list with special attributes: | |
3114 |
|
3114 | |||
3115 | .l (or .list) : value as list. |
|
3115 | .l (or .list) : value as list. | |
3116 | .n (or .nlstr): value as newline-separated string. |
|
3116 | .n (or .nlstr): value as newline-separated string. | |
3117 | .s (or .spstr): value as whitespace-separated string. |
|
3117 | .s (or .spstr): value as whitespace-separated string. | |
3118 |
|
3118 | |||
3119 | This is very useful when trying to use such lists as arguments to |
|
3119 | This is very useful when trying to use such lists as arguments to | |
3120 | system commands.""" |
|
3120 | system commands.""" | |
3121 |
|
3121 | |||
3122 | if parameter_s: |
|
3122 | if parameter_s: | |
3123 | out,err = self.shell.getoutputerror(parameter_s) |
|
3123 | out,err = self.shell.getoutputerror(parameter_s) | |
3124 | if err: |
|
3124 | if err: | |
3125 | print >> Term.cerr,err |
|
3125 | print >> Term.cerr,err | |
3126 | return SList(out.split('\n')) |
|
3126 | return SList(out.split('\n')) | |
3127 |
|
3127 | |||
3128 | def magic_bg(self, parameter_s=''): |
|
3128 | def magic_bg(self, parameter_s=''): | |
3129 | """Run a job in the background, in a separate thread. |
|
3129 | """Run a job in the background, in a separate thread. | |
3130 |
|
3130 | |||
3131 | For example, |
|
3131 | For example, | |
3132 |
|
3132 | |||
3133 | %bg myfunc(x,y,z=1) |
|
3133 | %bg myfunc(x,y,z=1) | |
3134 |
|
3134 | |||
3135 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
3135 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
3136 | execution starts, a message will be printed indicating the job |
|
3136 | execution starts, a message will be printed indicating the job | |
3137 | number. If your job number is 5, you can use |
|
3137 | number. If your job number is 5, you can use | |
3138 |
|
3138 | |||
3139 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
3139 | myvar = jobs.result(5) or myvar = jobs[5].result | |
3140 |
|
3140 | |||
3141 | to assign this result to variable 'myvar'. |
|
3141 | to assign this result to variable 'myvar'. | |
3142 |
|
3142 | |||
3143 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3143 | IPython has a job manager, accessible via the 'jobs' object. You can | |
3144 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3144 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
3145 | its attributes. All attributes not starting with an underscore are |
|
3145 | its attributes. All attributes not starting with an underscore are | |
3146 | meant for public use. |
|
3146 | meant for public use. | |
3147 |
|
3147 | |||
3148 | In particular, look at the jobs.new() method, which is used to create |
|
3148 | In particular, look at the jobs.new() method, which is used to create | |
3149 | new jobs. This magic %bg function is just a convenience wrapper |
|
3149 | new jobs. This magic %bg function is just a convenience wrapper | |
3150 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3150 | around jobs.new(), for expression-based jobs. If you want to create a | |
3151 | new job with an explicit function object and arguments, you must call |
|
3151 | new job with an explicit function object and arguments, you must call | |
3152 | jobs.new() directly. |
|
3152 | jobs.new() directly. | |
3153 |
|
3153 | |||
3154 | The jobs.new docstring also describes in detail several important |
|
3154 | The jobs.new docstring also describes in detail several important | |
3155 | caveats associated with a thread-based model for background job |
|
3155 | caveats associated with a thread-based model for background job | |
3156 | execution. Type jobs.new? for details. |
|
3156 | execution. Type jobs.new? for details. | |
3157 |
|
3157 | |||
3158 | You can check the status of all jobs with jobs.status(). |
|
3158 | You can check the status of all jobs with jobs.status(). | |
3159 |
|
3159 | |||
3160 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3160 | The jobs variable is set by IPython into the Python builtin namespace. | |
3161 | If you ever declare a variable named 'jobs', you will shadow this |
|
3161 | If you ever declare a variable named 'jobs', you will shadow this | |
3162 | name. You can either delete your global jobs variable to regain |
|
3162 | name. You can either delete your global jobs variable to regain | |
3163 | access to the job manager, or make a new name and assign it manually |
|
3163 | access to the job manager, or make a new name and assign it manually | |
3164 | to the manager (stored in IPython's namespace). For example, to |
|
3164 | to the manager (stored in IPython's namespace). For example, to | |
3165 | assign the job manager to the Jobs name, use: |
|
3165 | assign the job manager to the Jobs name, use: | |
3166 |
|
3166 | |||
3167 | Jobs = __builtins__.jobs""" |
|
3167 | Jobs = __builtins__.jobs""" | |
3168 |
|
3168 | |||
3169 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3169 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
3170 |
|
3170 | |||
3171 | def magic_r(self, parameter_s=''): |
|
3171 | def magic_r(self, parameter_s=''): | |
3172 | """Repeat previous input. |
|
3172 | """Repeat previous input. | |
3173 |
|
3173 | |||
3174 | Note: Consider using the more powerfull %rep instead! |
|
3174 | Note: Consider using the more powerfull %rep instead! | |
3175 |
|
3175 | |||
3176 | If given an argument, repeats the previous command which starts with |
|
3176 | If given an argument, repeats the previous command which starts with | |
3177 | the same string, otherwise it just repeats the previous input. |
|
3177 | the same string, otherwise it just repeats the previous input. | |
3178 |
|
3178 | |||
3179 | Shell escaped commands (with ! as first character) are not recognized |
|
3179 | Shell escaped commands (with ! as first character) are not recognized | |
3180 | by this system, only pure python code and magic commands. |
|
3180 | by this system, only pure python code and magic commands. | |
3181 | """ |
|
3181 | """ | |
3182 |
|
3182 | |||
3183 | start = parameter_s.strip() |
|
3183 | start = parameter_s.strip() | |
3184 | esc_magic = self.shell.ESC_MAGIC |
|
3184 | esc_magic = self.shell.ESC_MAGIC | |
3185 | # Identify magic commands even if automagic is on (which means |
|
3185 | # Identify magic commands even if automagic is on (which means | |
3186 | # the in-memory version is different from that typed by the user). |
|
3186 | # the in-memory version is different from that typed by the user). | |
3187 | if self.shell.rc.automagic: |
|
3187 | if self.shell.rc.automagic: | |
3188 | start_magic = esc_magic+start |
|
3188 | start_magic = esc_magic+start | |
3189 | else: |
|
3189 | else: | |
3190 | start_magic = start |
|
3190 | start_magic = start | |
3191 | # Look through the input history in reverse |
|
3191 | # Look through the input history in reverse | |
3192 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3192 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
3193 | input = self.shell.input_hist[n] |
|
3193 | input = self.shell.input_hist[n] | |
3194 | # skip plain 'r' lines so we don't recurse to infinity |
|
3194 | # skip plain 'r' lines so we don't recurse to infinity | |
3195 | if input != '_ip.magic("r")\n' and \ |
|
3195 | if input != '_ip.magic("r")\n' and \ | |
3196 | (input.startswith(start) or input.startswith(start_magic)): |
|
3196 | (input.startswith(start) or input.startswith(start_magic)): | |
3197 | #print 'match',`input` # dbg |
|
3197 | #print 'match',`input` # dbg | |
3198 | print 'Executing:',input, |
|
3198 | print 'Executing:',input, | |
3199 | self.shell.runlines(input) |
|
3199 | self.shell.runlines(input) | |
3200 | return |
|
3200 | return | |
3201 | print 'No previous input matching `%s` found.' % start |
|
3201 | print 'No previous input matching `%s` found.' % start | |
3202 |
|
3202 | |||
3203 |
|
3203 | |||
3204 | def magic_bookmark(self, parameter_s=''): |
|
3204 | def magic_bookmark(self, parameter_s=''): | |
3205 | """Manage IPython's bookmark system. |
|
3205 | """Manage IPython's bookmark system. | |
3206 |
|
3206 | |||
3207 | %bookmark <name> - set bookmark to current dir |
|
3207 | %bookmark <name> - set bookmark to current dir | |
3208 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3208 | %bookmark <name> <dir> - set bookmark to <dir> | |
3209 | %bookmark -l - list all bookmarks |
|
3209 | %bookmark -l - list all bookmarks | |
3210 | %bookmark -d <name> - remove bookmark |
|
3210 | %bookmark -d <name> - remove bookmark | |
3211 | %bookmark -r - remove all bookmarks |
|
3211 | %bookmark -r - remove all bookmarks | |
3212 |
|
3212 | |||
3213 | You can later on access a bookmarked folder with: |
|
3213 | You can later on access a bookmarked folder with: | |
3214 | %cd -b <name> |
|
3214 | %cd -b <name> | |
3215 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3215 | or simply '%cd <name>' if there is no directory called <name> AND | |
3216 | there is such a bookmark defined. |
|
3216 | there is such a bookmark defined. | |
3217 |
|
3217 | |||
3218 | Your bookmarks persist through IPython sessions, but they are |
|
3218 | Your bookmarks persist through IPython sessions, but they are | |
3219 | associated with each profile.""" |
|
3219 | associated with each profile.""" | |
3220 |
|
3220 | |||
3221 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3221 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3222 | if len(args) > 2: |
|
3222 | if len(args) > 2: | |
3223 | raise UsageError("%bookmark: too many arguments") |
|
3223 | raise UsageError("%bookmark: too many arguments") | |
3224 |
|
3224 | |||
3225 | bkms = self.db.get('bookmarks',{}) |
|
3225 | bkms = self.db.get('bookmarks',{}) | |
3226 |
|
3226 | |||
3227 | if opts.has_key('d'): |
|
3227 | if opts.has_key('d'): | |
3228 | try: |
|
3228 | try: | |
3229 | todel = args[0] |
|
3229 | todel = args[0] | |
3230 | except IndexError: |
|
3230 | except IndexError: | |
3231 | raise UsageError( |
|
3231 | raise UsageError( | |
3232 | "%bookmark -d: must provide a bookmark to delete") |
|
3232 | "%bookmark -d: must provide a bookmark to delete") | |
3233 | else: |
|
3233 | else: | |
3234 | try: |
|
3234 | try: | |
3235 | del bkms[todel] |
|
3235 | del bkms[todel] | |
3236 | except KeyError: |
|
3236 | except KeyError: | |
3237 | raise UsageError( |
|
3237 | raise UsageError( | |
3238 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3238 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3239 |
|
3239 | |||
3240 | elif opts.has_key('r'): |
|
3240 | elif opts.has_key('r'): | |
3241 | bkms = {} |
|
3241 | bkms = {} | |
3242 | elif opts.has_key('l'): |
|
3242 | elif opts.has_key('l'): | |
3243 | bks = bkms.keys() |
|
3243 | bks = bkms.keys() | |
3244 | bks.sort() |
|
3244 | bks.sort() | |
3245 | if bks: |
|
3245 | if bks: | |
3246 | size = max(map(len,bks)) |
|
3246 | size = max(map(len,bks)) | |
3247 | else: |
|
3247 | else: | |
3248 | size = 0 |
|
3248 | size = 0 | |
3249 | fmt = '%-'+str(size)+'s -> %s' |
|
3249 | fmt = '%-'+str(size)+'s -> %s' | |
3250 | print 'Current bookmarks:' |
|
3250 | print 'Current bookmarks:' | |
3251 | for bk in bks: |
|
3251 | for bk in bks: | |
3252 | print fmt % (bk,bkms[bk]) |
|
3252 | print fmt % (bk,bkms[bk]) | |
3253 | else: |
|
3253 | else: | |
3254 | if not args: |
|
3254 | if not args: | |
3255 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3255 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3256 | elif len(args)==1: |
|
3256 | elif len(args)==1: | |
3257 | bkms[args[0]] = os.getcwd() |
|
3257 | bkms[args[0]] = os.getcwd() | |
3258 | elif len(args)==2: |
|
3258 | elif len(args)==2: | |
3259 | bkms[args[0]] = args[1] |
|
3259 | bkms[args[0]] = args[1] | |
3260 | self.db['bookmarks'] = bkms |
|
3260 | self.db['bookmarks'] = bkms | |
3261 |
|
3261 | |||
3262 | def magic_pycat(self, parameter_s=''): |
|
3262 | def magic_pycat(self, parameter_s=''): | |
3263 | """Show a syntax-highlighted file through a pager. |
|
3263 | """Show a syntax-highlighted file through a pager. | |
3264 |
|
3264 | |||
3265 | This magic is similar to the cat utility, but it will assume the file |
|
3265 | This magic is similar to the cat utility, but it will assume the file | |
3266 | to be Python source and will show it with syntax highlighting. """ |
|
3266 | to be Python source and will show it with syntax highlighting. """ | |
3267 |
|
3267 | |||
3268 | try: |
|
3268 | try: | |
3269 | filename = get_py_filename(parameter_s) |
|
3269 | filename = get_py_filename(parameter_s) | |
3270 | cont = file_read(filename) |
|
3270 | cont = file_read(filename) | |
3271 | except IOError: |
|
3271 | except IOError: | |
3272 | try: |
|
3272 | try: | |
3273 | cont = eval(parameter_s,self.user_ns) |
|
3273 | cont = eval(parameter_s,self.user_ns) | |
3274 | except NameError: |
|
3274 | except NameError: | |
3275 | cont = None |
|
3275 | cont = None | |
3276 | if cont is None: |
|
3276 | if cont is None: | |
3277 | print "Error: no such file or variable" |
|
3277 | print "Error: no such file or variable" | |
3278 | return |
|
3278 | return | |
3279 |
|
3279 | |||
3280 | page(self.shell.pycolorize(cont), |
|
3280 | page(self.shell.pycolorize(cont), | |
3281 | screen_lines=self.shell.rc.screen_length) |
|
3281 | screen_lines=self.shell.rc.screen_length) | |
3282 |
|
3282 | |||
3283 | def _rerun_pasted(self): |
|
3283 | def _rerun_pasted(self): | |
3284 | """ Rerun a previously pasted command. |
|
3284 | """ Rerun a previously pasted command. | |
3285 | """ |
|
3285 | """ | |
3286 | b = self.user_ns.get('pasted_block', None) |
|
3286 | b = self.user_ns.get('pasted_block', None) | |
3287 | if b is None: |
|
3287 | if b is None: | |
3288 | raise UsageError('No previous pasted block available') |
|
3288 | raise UsageError('No previous pasted block available') | |
3289 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3289 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3290 | exec b in self.user_ns |
|
3290 | exec b in self.user_ns | |
3291 |
|
3291 | |||
3292 | def _get_pasted_lines(self, sentinel): |
|
3292 | def _get_pasted_lines(self, sentinel): | |
3293 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3293 | """ Yield pasted lines until the user enters the given sentinel value. | |
3294 | """ |
|
3294 | """ | |
3295 | from IPython import iplib |
|
3295 | from IPython import iplib | |
3296 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3296 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3297 | while True: |
|
3297 | while True: | |
3298 | l = iplib.raw_input_original(':') |
|
3298 | l = iplib.raw_input_original(':') | |
3299 | if l == sentinel: |
|
3299 | if l == sentinel: | |
3300 | return |
|
3300 | return | |
3301 | else: |
|
3301 | else: | |
3302 | yield l |
|
3302 | yield l | |
3303 |
|
3303 | |||
3304 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3304 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3305 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3305 | """ Strip non-code parts of a sequence of lines to return a block of | |
3306 | code. |
|
3306 | code. | |
3307 | """ |
|
3307 | """ | |
3308 | # Regular expressions that declare text we strip from the input: |
|
3308 | # Regular expressions that declare text we strip from the input: | |
3309 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3309 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3310 | r'^\s*(\s?>)+', # Python input prompt |
|
3310 | r'^\s*(\s?>)+', # Python input prompt | |
3311 | r'^\s*\.{3,}', # Continuation prompts |
|
3311 | r'^\s*\.{3,}', # Continuation prompts | |
3312 | r'^\++', |
|
3312 | r'^\++', | |
3313 | ] |
|
3313 | ] | |
3314 |
|
3314 | |||
3315 | strip_from_start = map(re.compile,strip_re) |
|
3315 | strip_from_start = map(re.compile,strip_re) | |
3316 |
|
3316 | |||
3317 | lines = [] |
|
3317 | lines = [] | |
3318 | for l in raw_lines: |
|
3318 | for l in raw_lines: | |
3319 | for pat in strip_from_start: |
|
3319 | for pat in strip_from_start: | |
3320 | l = pat.sub('',l) |
|
3320 | l = pat.sub('',l) | |
3321 | lines.append(l) |
|
3321 | lines.append(l) | |
3322 |
|
3322 | |||
3323 | block = "\n".join(lines) + '\n' |
|
3323 | block = "\n".join(lines) + '\n' | |
3324 | #print "block:\n",block |
|
3324 | #print "block:\n",block | |
3325 | return block |
|
3325 | return block | |
3326 |
|
3326 | |||
3327 | def _execute_block(self, block, par): |
|
3327 | def _execute_block(self, block, par): | |
3328 | """ Execute a block, or store it in a variable, per the user's request. |
|
3328 | """ Execute a block, or store it in a variable, per the user's request. | |
3329 | """ |
|
3329 | """ | |
3330 | if not par: |
|
3330 | if not par: | |
3331 | b = textwrap.dedent(block) |
|
3331 | b = textwrap.dedent(block) | |
3332 | self.user_ns['pasted_block'] = b |
|
3332 | self.user_ns['pasted_block'] = b | |
3333 | exec b in self.user_ns |
|
3333 | exec b in self.user_ns | |
3334 | else: |
|
3334 | else: | |
3335 | self.user_ns[par] = SList(block.splitlines()) |
|
3335 | self.user_ns[par] = SList(block.splitlines()) | |
3336 | print "Block assigned to '%s'" % par |
|
3336 | print "Block assigned to '%s'" % par | |
3337 |
|
3337 | |||
3338 | def magic_cpaste(self, parameter_s=''): |
|
3338 | def magic_cpaste(self, parameter_s=''): | |
3339 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3339 | """Allows you to paste & execute a pre-formatted code block from clipboard. | |
3340 |
|
3340 | |||
3341 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3341 | You must terminate the block with '--' (two minus-signs) alone on the | |
3342 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3342 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
3343 | is the new sentinel for this operation) |
|
3343 | is the new sentinel for this operation) | |
3344 |
|
3344 | |||
3345 | The block is dedented prior to execution to enable execution of method |
|
3345 | The block is dedented prior to execution to enable execution of method | |
3346 | definitions. '>' and '+' characters at the beginning of a line are |
|
3346 | definitions. '>' and '+' characters at the beginning of a line are | |
3347 | ignored, to allow pasting directly from e-mails, diff files and |
|
3347 | ignored, to allow pasting directly from e-mails, diff files and | |
3348 | doctests (the '...' continuation prompt is also stripped). The |
|
3348 | doctests (the '...' continuation prompt is also stripped). The | |
3349 | executed block is also assigned to variable named 'pasted_block' for |
|
3349 | executed block is also assigned to variable named 'pasted_block' for | |
3350 | later editing with '%edit pasted_block'. |
|
3350 | later editing with '%edit pasted_block'. | |
3351 |
|
3351 | |||
3352 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3352 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
3353 | This assigns the pasted block to variable 'foo' as string, without |
|
3353 | This assigns the pasted block to variable 'foo' as string, without | |
3354 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3354 | dedenting or executing it (preceding >>> and + is still stripped) | |
3355 |
|
3355 | |||
3356 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
3356 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
3357 |
|
3357 | |||
3358 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3358 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
3359 | Just press enter and type -- (and press enter again) and the block |
|
3359 | Just press enter and type -- (and press enter again) and the block | |
3360 | will be what was just pasted. |
|
3360 | will be what was just pasted. | |
3361 |
|
3361 | |||
3362 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3362 | IPython statements (magics, shell escapes) are not supported (yet). | |
3363 |
|
3363 | |||
3364 | See also |
|
3364 | See also | |
3365 | -------- |
|
3365 | -------- | |
3366 | paste: automatically pull code from clipboard. |
|
3366 | paste: automatically pull code from clipboard. | |
3367 | """ |
|
3367 | """ | |
3368 |
|
3368 | |||
3369 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
3369 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |
3370 | par = args.strip() |
|
3370 | par = args.strip() | |
3371 | if opts.has_key('r'): |
|
3371 | if opts.has_key('r'): | |
3372 | self._rerun_pasted() |
|
3372 | self._rerun_pasted() | |
3373 | return |
|
3373 | return | |
3374 |
|
3374 | |||
3375 | sentinel = opts.get('s','--') |
|
3375 | sentinel = opts.get('s','--') | |
3376 |
|
3376 | |||
3377 | block = self._strip_pasted_lines_for_code( |
|
3377 | block = self._strip_pasted_lines_for_code( | |
3378 | self._get_pasted_lines(sentinel)) |
|
3378 | self._get_pasted_lines(sentinel)) | |
3379 |
|
3379 | |||
3380 | self._execute_block(block, par) |
|
3380 | self._execute_block(block, par) | |
3381 |
|
3381 | |||
3382 | def magic_paste(self, parameter_s=''): |
|
3382 | def magic_paste(self, parameter_s=''): | |
3383 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3383 | """Allows you to paste & execute a pre-formatted code block from clipboard. | |
3384 |
|
3384 | |||
3385 | The text is pulled directly from the clipboard without user |
|
3385 | The text is pulled directly from the clipboard without user | |
3386 | intervention. |
|
3386 | intervention. | |
3387 |
|
3387 | |||
3388 | The block is dedented prior to execution to enable execution of method |
|
3388 | The block is dedented prior to execution to enable execution of method | |
3389 | definitions. '>' and '+' characters at the beginning of a line are |
|
3389 | definitions. '>' and '+' characters at the beginning of a line are | |
3390 | ignored, to allow pasting directly from e-mails, diff files and |
|
3390 | ignored, to allow pasting directly from e-mails, diff files and | |
3391 | doctests (the '...' continuation prompt is also stripped). The |
|
3391 | doctests (the '...' continuation prompt is also stripped). The | |
3392 | executed block is also assigned to variable named 'pasted_block' for |
|
3392 | executed block is also assigned to variable named 'pasted_block' for | |
3393 | later editing with '%edit pasted_block'. |
|
3393 | later editing with '%edit pasted_block'. | |
3394 |
|
3394 | |||
3395 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
3395 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |
3396 | This assigns the pasted block to variable 'foo' as string, without |
|
3396 | This assigns the pasted block to variable 'foo' as string, without | |
3397 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3397 | dedenting or executing it (preceding >>> and + is still stripped) | |
3398 |
|
3398 | |||
3399 | '%paste -r' re-executes the block previously entered by cpaste. |
|
3399 | '%paste -r' re-executes the block previously entered by cpaste. | |
3400 |
|
3400 | |||
3401 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3401 | IPython statements (magics, shell escapes) are not supported (yet). | |
3402 |
|
3402 | |||
3403 | See also |
|
3403 | See also | |
3404 | -------- |
|
3404 | -------- | |
3405 | cpaste: manually paste code into terminal until you mark its end. |
|
3405 | cpaste: manually paste code into terminal until you mark its end. | |
3406 | """ |
|
3406 | """ | |
3407 | opts,args = self.parse_options(parameter_s,'r:',mode='string') |
|
3407 | opts,args = self.parse_options(parameter_s,'r:',mode='string') | |
3408 | par = args.strip() |
|
3408 | par = args.strip() | |
3409 | if opts.has_key('r'): |
|
3409 | if opts.has_key('r'): | |
3410 | self._rerun_pasted() |
|
3410 | self._rerun_pasted() | |
3411 | return |
|
3411 | return | |
3412 |
|
3412 | |||
3413 | text = self.shell.hooks.clipboard_get() |
|
3413 | text = self.shell.hooks.clipboard_get() | |
3414 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
3414 | block = self._strip_pasted_lines_for_code(text.splitlines()) | |
3415 | self._execute_block(block, par) |
|
3415 | self._execute_block(block, par) | |
3416 |
|
3416 | |||
3417 | def magic_quickref(self,arg): |
|
3417 | def magic_quickref(self,arg): | |
3418 | """ Show a quick reference sheet """ |
|
3418 | """ Show a quick reference sheet """ | |
3419 | import IPython.usage |
|
3419 | import IPython.usage | |
3420 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
3420 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') | |
3421 |
|
3421 | |||
3422 | page(qr) |
|
3422 | page(qr) | |
3423 |
|
3423 | |||
3424 | def magic_upgrade(self,arg): |
|
3424 | def magic_upgrade(self,arg): | |
3425 | """ Upgrade your IPython installation |
|
3425 | """ Upgrade your IPython installation | |
3426 |
|
3426 | |||
3427 | This will copy the config files that don't yet exist in your |
|
3427 | This will copy the config files that don't yet exist in your | |
3428 | ipython dir from the system config dir. Use this after upgrading |
|
3428 | ipython dir from the system config dir. Use this after upgrading | |
3429 | IPython if you don't wish to delete your .ipython dir. |
|
3429 | IPython if you don't wish to delete your .ipython dir. | |
3430 |
|
3430 | |||
3431 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3431 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
3432 | new users) |
|
3432 | new users) | |
3433 |
|
3433 | |||
3434 | """ |
|
3434 | """ | |
3435 | ip = self.getapi() |
|
3435 | ip = self.getapi() | |
3436 | ipinstallation = path(IPython.__file__).dirname() |
|
3436 | ipinstallation = path(IPython.__file__).dirname() | |
3437 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') |
|
3437 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') | |
3438 | src_config = ipinstallation / 'UserConfig' |
|
3438 | src_config = ipinstallation / 'UserConfig' | |
3439 | userdir = path(ip.options.ipythondir) |
|
3439 | userdir = path(ip.options.ipythondir) | |
3440 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3440 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
3441 | print ">",cmd |
|
3441 | print ">",cmd | |
3442 | shell(cmd) |
|
3442 | shell(cmd) | |
3443 | if arg == '-nolegacy': |
|
3443 | if arg == '-nolegacy': | |
3444 | legacy = userdir.files('ipythonrc*') |
|
3444 | legacy = userdir.files('ipythonrc*') | |
3445 | print "Nuking legacy files:",legacy |
|
3445 | print "Nuking legacy files:",legacy | |
3446 |
|
3446 | |||
3447 | [p.remove() for p in legacy] |
|
3447 | [p.remove() for p in legacy] | |
3448 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3448 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
3449 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3449 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
3450 |
|
3450 | |||
3451 |
|
3451 | |||
3452 | def magic_doctest_mode(self,parameter_s=''): |
|
3452 | def magic_doctest_mode(self,parameter_s=''): | |
3453 | """Toggle doctest mode on and off. |
|
3453 | """Toggle doctest mode on and off. | |
3454 |
|
3454 | |||
3455 | This mode allows you to toggle the prompt behavior between normal |
|
3455 | This mode allows you to toggle the prompt behavior between normal | |
3456 | IPython prompts and ones that are as similar to the default IPython |
|
3456 | IPython prompts and ones that are as similar to the default IPython | |
3457 | interpreter as possible. |
|
3457 | interpreter as possible. | |
3458 |
|
3458 | |||
3459 | It also supports the pasting of code snippets that have leading '>>>' |
|
3459 | It also supports the pasting of code snippets that have leading '>>>' | |
3460 | and '...' prompts in them. This means that you can paste doctests from |
|
3460 | and '...' prompts in them. This means that you can paste doctests from | |
3461 | files or docstrings (even if they have leading whitespace), and the |
|
3461 | files or docstrings (even if they have leading whitespace), and the | |
3462 | code will execute correctly. You can then use '%history -tn' to see |
|
3462 | code will execute correctly. You can then use '%history -tn' to see | |
3463 | the translated history without line numbers; this will give you the |
|
3463 | the translated history without line numbers; this will give you the | |
3464 | input after removal of all the leading prompts and whitespace, which |
|
3464 | input after removal of all the leading prompts and whitespace, which | |
3465 | can be pasted back into an editor. |
|
3465 | can be pasted back into an editor. | |
3466 |
|
3466 | |||
3467 | With these features, you can switch into this mode easily whenever you |
|
3467 | With these features, you can switch into this mode easily whenever you | |
3468 | need to do testing and changes to doctests, without having to leave |
|
3468 | need to do testing and changes to doctests, without having to leave | |
3469 | your existing IPython session. |
|
3469 | your existing IPython session. | |
3470 | """ |
|
3470 | """ | |
3471 |
|
3471 | |||
3472 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3472 | # XXX - Fix this to have cleaner activate/deactivate calls. | |
3473 | from IPython.Extensions import InterpreterPasteInput as ipaste |
|
3473 | from IPython.Extensions import InterpreterPasteInput as ipaste | |
3474 | from IPython.ipstruct import Struct |
|
3474 | from IPython.ipstruct import Struct | |
3475 |
|
3475 | |||
3476 | # Shorthands |
|
3476 | # Shorthands | |
3477 | shell = self.shell |
|
3477 | shell = self.shell | |
3478 | oc = shell.outputcache |
|
3478 | oc = shell.outputcache | |
3479 | rc = shell.rc |
|
3479 | rc = shell.rc | |
3480 | meta = shell.meta |
|
3480 | meta = shell.meta | |
3481 | # dstore is a data store kept in the instance metadata bag to track any |
|
3481 | # dstore is a data store kept in the instance metadata bag to track any | |
3482 | # changes we make, so we can undo them later. |
|
3482 | # changes we make, so we can undo them later. | |
3483 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3483 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3484 | save_dstore = dstore.setdefault |
|
3484 | save_dstore = dstore.setdefault | |
3485 |
|
3485 | |||
3486 | # save a few values we'll need to recover later |
|
3486 | # save a few values we'll need to recover later | |
3487 | mode = save_dstore('mode',False) |
|
3487 | mode = save_dstore('mode',False) | |
3488 | save_dstore('rc_pprint',rc.pprint) |
|
3488 | save_dstore('rc_pprint',rc.pprint) | |
3489 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3489 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3490 | save_dstore('rc_separate_out',rc.separate_out) |
|
3490 | save_dstore('rc_separate_out',rc.separate_out) | |
3491 | save_dstore('rc_separate_out2',rc.separate_out2) |
|
3491 | save_dstore('rc_separate_out2',rc.separate_out2) | |
3492 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) |
|
3492 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) | |
3493 | save_dstore('rc_separate_in',rc.separate_in) |
|
3493 | save_dstore('rc_separate_in',rc.separate_in) | |
3494 |
|
3494 | |||
3495 | if mode == False: |
|
3495 | if mode == False: | |
3496 | # turn on |
|
3496 | # turn on | |
3497 | ipaste.activate_prefilter() |
|
3497 | ipaste.activate_prefilter() | |
3498 |
|
3498 | |||
3499 | oc.prompt1.p_template = '>>> ' |
|
3499 | oc.prompt1.p_template = '>>> ' | |
3500 | oc.prompt2.p_template = '... ' |
|
3500 | oc.prompt2.p_template = '... ' | |
3501 | oc.prompt_out.p_template = '' |
|
3501 | oc.prompt_out.p_template = '' | |
3502 |
|
3502 | |||
3503 | # Prompt separators like plain python |
|
3503 | # Prompt separators like plain python | |
3504 | oc.input_sep = oc.prompt1.sep = '' |
|
3504 | oc.input_sep = oc.prompt1.sep = '' | |
3505 | oc.output_sep = '' |
|
3505 | oc.output_sep = '' | |
3506 | oc.output_sep2 = '' |
|
3506 | oc.output_sep2 = '' | |
3507 |
|
3507 | |||
3508 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3508 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3509 | oc.prompt_out.pad_left = False |
|
3509 | oc.prompt_out.pad_left = False | |
3510 |
|
3510 | |||
3511 | rc.pprint = False |
|
3511 | rc.pprint = False | |
3512 |
|
3512 | |||
3513 | shell.magic_xmode('Plain') |
|
3513 | shell.magic_xmode('Plain') | |
3514 |
|
3514 | |||
3515 | else: |
|
3515 | else: | |
3516 | # turn off |
|
3516 | # turn off | |
3517 | ipaste.deactivate_prefilter() |
|
3517 | ipaste.deactivate_prefilter() | |
3518 |
|
3518 | |||
3519 | oc.prompt1.p_template = rc.prompt_in1 |
|
3519 | oc.prompt1.p_template = rc.prompt_in1 | |
3520 | oc.prompt2.p_template = rc.prompt_in2 |
|
3520 | oc.prompt2.p_template = rc.prompt_in2 | |
3521 | oc.prompt_out.p_template = rc.prompt_out |
|
3521 | oc.prompt_out.p_template = rc.prompt_out | |
3522 |
|
3522 | |||
3523 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3523 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3524 |
|
3524 | |||
3525 | oc.output_sep = dstore.rc_separate_out |
|
3525 | oc.output_sep = dstore.rc_separate_out | |
3526 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3526 | oc.output_sep2 = dstore.rc_separate_out2 | |
3527 |
|
3527 | |||
3528 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3528 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3529 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3529 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3530 |
|
3530 | |||
3531 | rc.pprint = dstore.rc_pprint |
|
3531 | rc.pprint = dstore.rc_pprint | |
3532 |
|
3532 | |||
3533 | shell.magic_xmode(dstore.xmode) |
|
3533 | shell.magic_xmode(dstore.xmode) | |
3534 |
|
3534 | |||
3535 | # Store new mode and inform |
|
3535 | # Store new mode and inform | |
3536 | dstore.mode = bool(1-int(mode)) |
|
3536 | dstore.mode = bool(1-int(mode)) | |
3537 | print 'Doctest mode is:', |
|
3537 | print 'Doctest mode is:', | |
3538 | print ['OFF','ON'][dstore.mode] |
|
3538 | print ['OFF','ON'][dstore.mode] | |
3539 |
|
3539 | |||
3540 | # end Magic |
|
3540 | # end Magic |
@@ -1,2873 +1,2873 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, init_fakemod_dict |
|
57 | from IPython.FakeModule import FakeModule, init_fakemod_dict | |
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 | def user_setup(ipythondir,rc_suffix,mode='install',interactive=True): |
|
111 | def user_setup(ipythondir,rc_suffix,mode='install',interactive=True): | |
112 | """Install or upgrade the user configuration directory. |
|
112 | """Install or upgrade the user configuration directory. | |
113 |
|
113 | |||
114 | Can be called when running for the first time or to upgrade the user's |
|
114 | Can be called when running for the first time or to upgrade the user's | |
115 | .ipython/ directory. |
|
115 | .ipython/ directory. | |
116 |
|
116 | |||
117 | Parameters |
|
117 | Parameters | |
118 | ---------- |
|
118 | ---------- | |
119 | ipythondir : path |
|
119 | ipythondir : path | |
120 | The directory to be used for installation/upgrade. In 'install' mode, |
|
120 | The directory to be used for installation/upgrade. In 'install' mode, | |
121 | if this path already exists, the function exits immediately. |
|
121 | if this path already exists, the function exits immediately. | |
122 |
|
122 | |||
123 | rc_suffix : str |
|
123 | rc_suffix : str | |
124 | Extension for the config files. On *nix platforms it is typically the |
|
124 | Extension for the config files. On *nix platforms it is typically the | |
125 | empty string, while Windows normally uses '.ini'. |
|
125 | empty string, while Windows normally uses '.ini'. | |
126 |
|
126 | |||
127 | mode : str, optional |
|
127 | mode : str, optional | |
128 | Valid modes are 'install' and 'upgrade'. |
|
128 | Valid modes are 'install' and 'upgrade'. | |
129 |
|
129 | |||
130 | interactive : bool, optional |
|
130 | interactive : bool, optional | |
131 | If False, do not wait for user input on any errors. Normally after |
|
131 | If False, do not wait for user input on any errors. Normally after | |
132 | printing its status information, this function waits for the user to |
|
132 | printing its status information, this function waits for the user to | |
133 | hit Return before proceeding. This is because the default use case is |
|
133 | hit Return before proceeding. This is because the default use case is | |
134 | when first installing the IPython configuration, so we want the user to |
|
134 | when first installing the IPython configuration, so we want the user to | |
135 | acknowledge the initial message, which contains some useful |
|
135 | acknowledge the initial message, which contains some useful | |
136 | information. |
|
136 | information. | |
137 | """ |
|
137 | """ | |
138 |
|
138 | |||
139 | # For automatic use, deactivate all i/o |
|
139 | # For automatic use, deactivate all i/o | |
140 | if interactive: |
|
140 | if interactive: | |
141 | def wait(): |
|
141 | def wait(): | |
142 | try: |
|
142 | try: | |
143 | raw_input("Please press <RETURN> to start IPython.") |
|
143 | raw_input("Please press <RETURN> to start IPython.") | |
144 | except EOFError: |
|
144 | except EOFError: | |
145 | print >> Term.cout |
|
145 | print >> Term.cout | |
146 | print '*'*70 |
|
146 | print '*'*70 | |
147 |
|
147 | |||
148 | def printf(s): |
|
148 | def printf(s): | |
149 | print s |
|
149 | print s | |
150 | else: |
|
150 | else: | |
151 | wait = lambda : None |
|
151 | wait = lambda : None | |
152 | printf = lambda s : None |
|
152 | printf = lambda s : None | |
153 |
|
153 | |||
154 | # Install mode should be re-entrant: if the install dir already exists, |
|
154 | # Install mode should be re-entrant: if the install dir already exists, | |
155 | # bail out cleanly. |
|
155 | # bail out cleanly. | |
156 | # XXX. This is too hasty to return. We need to check to make sure that |
|
156 | # XXX. This is too hasty to return. We need to check to make sure that | |
157 | # all the expected config files and directories are actually there. We |
|
157 | # all the expected config files and directories are actually there. We | |
158 | # currently have a failure mode if someone deletes a needed config file |
|
158 | # currently have a failure mode if someone deletes a needed config file | |
159 | # but still has the ipythondir. |
|
159 | # but still has the ipythondir. | |
160 | if mode == 'install' and os.path.isdir(ipythondir): |
|
160 | if mode == 'install' and os.path.isdir(ipythondir): | |
161 | return |
|
161 | return | |
162 |
|
162 | |||
163 | cwd = os.getcwd() # remember where we started |
|
163 | cwd = os.getcwd() # remember where we started | |
164 | glb = glob.glob |
|
164 | glb = glob.glob | |
165 |
|
165 | |||
166 | printf('*'*70) |
|
166 | printf('*'*70) | |
167 | if mode == 'install': |
|
167 | if mode == 'install': | |
168 | printf( |
|
168 | printf( | |
169 | """Welcome to IPython. I will try to create a personal configuration directory |
|
169 | """Welcome to IPython. I will try to create a personal configuration directory | |
170 | where you can customize many aspects of IPython's functionality in:\n""") |
|
170 | where you can customize many aspects of IPython's functionality in:\n""") | |
171 | else: |
|
171 | else: | |
172 | printf('I am going to upgrade your configuration in:') |
|
172 | printf('I am going to upgrade your configuration in:') | |
173 |
|
173 | |||
174 | printf(ipythondir) |
|
174 | printf(ipythondir) | |
175 |
|
175 | |||
176 | rcdirend = os.path.join('IPython','UserConfig') |
|
176 | rcdirend = os.path.join('IPython','UserConfig') | |
177 | cfg = lambda d: os.path.join(d,rcdirend) |
|
177 | cfg = lambda d: os.path.join(d,rcdirend) | |
178 | try: |
|
178 | try: | |
179 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
179 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
180 | printf("Initializing from configuration: %s" % rcdir) |
|
180 | printf("Initializing from configuration: %s" % rcdir) | |
181 | except IndexError: |
|
181 | except IndexError: | |
182 | warning = """ |
|
182 | warning = """ | |
183 | Installation error. IPython's directory was not found. |
|
183 | Installation error. IPython's directory was not found. | |
184 |
|
184 | |||
185 | Check the following: |
|
185 | Check the following: | |
186 |
|
186 | |||
187 | The ipython/IPython directory should be in a directory belonging to your |
|
187 | The ipython/IPython directory should be in a directory belonging to your | |
188 | PYTHONPATH environment variable (that is, it should be in a directory |
|
188 | PYTHONPATH environment variable (that is, it should be in a directory | |
189 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
189 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
190 |
|
190 | |||
191 | IPython will create a minimal default configuration for you. |
|
191 | IPython will create a minimal default configuration for you. | |
192 |
|
192 | |||
193 | """ |
|
193 | """ | |
194 | warn(warning) |
|
194 | warn(warning) | |
195 | wait() |
|
195 | wait() | |
196 |
|
196 | |||
197 | if sys.platform =='win32': |
|
197 | if sys.platform =='win32': | |
198 | inif = 'ipythonrc.ini' |
|
198 | inif = 'ipythonrc.ini' | |
199 | else: |
|
199 | else: | |
200 | inif = 'ipythonrc' |
|
200 | inif = 'ipythonrc' | |
201 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', |
|
201 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', | |
202 | inif : '# intentionally left blank' } |
|
202 | inif : '# intentionally left blank' } | |
203 | os.makedirs(ipythondir, mode = 0777) |
|
203 | os.makedirs(ipythondir, mode = 0777) | |
204 | for f, cont in minimal_setup.items(): |
|
204 | for f, cont in minimal_setup.items(): | |
205 | # In 2.5, this can be more cleanly done using 'with' |
|
205 | # In 2.5, this can be more cleanly done using 'with' | |
206 | fobj = file(ipythondir + '/' + f,'w') |
|
206 | fobj = file(ipythondir + '/' + f,'w') | |
207 | fobj.write(cont) |
|
207 | fobj.write(cont) | |
208 | fobj.close() |
|
208 | fobj.close() | |
209 |
|
209 | |||
210 | return |
|
210 | return | |
211 |
|
211 | |||
212 | if mode == 'install': |
|
212 | if mode == 'install': | |
213 | try: |
|
213 | try: | |
214 | shutil.copytree(rcdir,ipythondir) |
|
214 | shutil.copytree(rcdir,ipythondir) | |
215 | os.chdir(ipythondir) |
|
215 | os.chdir(ipythondir) | |
216 | rc_files = glb("ipythonrc*") |
|
216 | rc_files = glb("ipythonrc*") | |
217 | for rc_file in rc_files: |
|
217 | for rc_file in rc_files: | |
218 | os.rename(rc_file,rc_file+rc_suffix) |
|
218 | os.rename(rc_file,rc_file+rc_suffix) | |
219 | except: |
|
219 | except: | |
220 | warning = """ |
|
220 | warning = """ | |
221 |
|
221 | |||
222 | There was a problem with the installation: |
|
222 | There was a problem with the installation: | |
223 | %s |
|
223 | %s | |
224 | Try to correct it or contact the developers if you think it's a bug. |
|
224 | Try to correct it or contact the developers if you think it's a bug. | |
225 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
225 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
226 | warn(warning) |
|
226 | warn(warning) | |
227 | wait() |
|
227 | wait() | |
228 | return |
|
228 | return | |
229 |
|
229 | |||
230 | elif mode == 'upgrade': |
|
230 | elif mode == 'upgrade': | |
231 | try: |
|
231 | try: | |
232 | os.chdir(ipythondir) |
|
232 | os.chdir(ipythondir) | |
233 | except: |
|
233 | except: | |
234 | printf(""" |
|
234 | printf(""" | |
235 | Can not upgrade: changing to directory %s failed. Details: |
|
235 | Can not upgrade: changing to directory %s failed. Details: | |
236 | %s |
|
236 | %s | |
237 | """ % (ipythondir,sys.exc_info()[1]) ) |
|
237 | """ % (ipythondir,sys.exc_info()[1]) ) | |
238 | wait() |
|
238 | wait() | |
239 | return |
|
239 | return | |
240 | else: |
|
240 | else: | |
241 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
241 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
242 | for new_full_path in sources: |
|
242 | for new_full_path in sources: | |
243 | new_filename = os.path.basename(new_full_path) |
|
243 | new_filename = os.path.basename(new_full_path) | |
244 | if new_filename.startswith('ipythonrc'): |
|
244 | if new_filename.startswith('ipythonrc'): | |
245 | new_filename = new_filename + rc_suffix |
|
245 | new_filename = new_filename + rc_suffix | |
246 | # The config directory should only contain files, skip any |
|
246 | # The config directory should only contain files, skip any | |
247 | # directories which may be there (like CVS) |
|
247 | # directories which may be there (like CVS) | |
248 | if os.path.isdir(new_full_path): |
|
248 | if os.path.isdir(new_full_path): | |
249 | continue |
|
249 | continue | |
250 | if os.path.exists(new_filename): |
|
250 | if os.path.exists(new_filename): | |
251 | old_file = new_filename+'.old' |
|
251 | old_file = new_filename+'.old' | |
252 | if os.path.exists(old_file): |
|
252 | if os.path.exists(old_file): | |
253 | os.remove(old_file) |
|
253 | os.remove(old_file) | |
254 | os.rename(new_filename,old_file) |
|
254 | os.rename(new_filename,old_file) | |
255 | shutil.copy(new_full_path,new_filename) |
|
255 | shutil.copy(new_full_path,new_filename) | |
256 | else: |
|
256 | else: | |
257 | raise ValueError('unrecognized mode for install: %r' % mode) |
|
257 | raise ValueError('unrecognized mode for install: %r' % mode) | |
258 |
|
258 | |||
259 | # Fix line-endings to those native to each platform in the config |
|
259 | # Fix line-endings to those native to each platform in the config | |
260 | # directory. |
|
260 | # directory. | |
261 | try: |
|
261 | try: | |
262 | os.chdir(ipythondir) |
|
262 | os.chdir(ipythondir) | |
263 | except: |
|
263 | except: | |
264 | printf(""" |
|
264 | printf(""" | |
265 | Problem: changing to directory %s failed. |
|
265 | Problem: changing to directory %s failed. | |
266 | Details: |
|
266 | Details: | |
267 | %s |
|
267 | %s | |
268 |
|
268 | |||
269 | Some configuration files may have incorrect line endings. This should not |
|
269 | Some configuration files may have incorrect line endings. This should not | |
270 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) ) |
|
270 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) ) | |
271 | wait() |
|
271 | wait() | |
272 | else: |
|
272 | else: | |
273 | for fname in glb('ipythonrc*'): |
|
273 | for fname in glb('ipythonrc*'): | |
274 | try: |
|
274 | try: | |
275 | native_line_ends(fname,backup=0) |
|
275 | native_line_ends(fname,backup=0) | |
276 | except IOError: |
|
276 | except IOError: | |
277 | pass |
|
277 | pass | |
278 |
|
278 | |||
279 | if mode == 'install': |
|
279 | if mode == 'install': | |
280 | printf(""" |
|
280 | printf(""" | |
281 | Successful installation! |
|
281 | Successful installation! | |
282 |
|
282 | |||
283 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
283 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
284 | IPython manual (there are both HTML and PDF versions supplied with the |
|
284 | IPython manual (there are both HTML and PDF versions supplied with the | |
285 | distribution) to make sure that your system environment is properly configured |
|
285 | distribution) to make sure that your system environment is properly configured | |
286 | to take advantage of IPython's features. |
|
286 | to take advantage of IPython's features. | |
287 |
|
287 | |||
288 | Important note: the configuration system has changed! The old system is |
|
288 | Important note: the configuration system has changed! The old system is | |
289 | still in place, but its setting may be partly overridden by the settings in |
|
289 | still in place, but its setting may be partly overridden by the settings in | |
290 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
290 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
291 | if some of the new settings bother you. |
|
291 | if some of the new settings bother you. | |
292 |
|
292 | |||
293 | """) |
|
293 | """) | |
294 | else: |
|
294 | else: | |
295 | printf(""" |
|
295 | printf(""" | |
296 | Successful upgrade! |
|
296 | Successful upgrade! | |
297 |
|
297 | |||
298 | All files in your directory: |
|
298 | All files in your directory: | |
299 | %(ipythondir)s |
|
299 | %(ipythondir)s | |
300 | which would have been overwritten by the upgrade were backed up with a .old |
|
300 | which would have been overwritten by the upgrade were backed up with a .old | |
301 | extension. If you had made particular customizations in those files you may |
|
301 | extension. If you had made particular customizations in those files you may | |
302 | want to merge them back into the new files.""" % locals() ) |
|
302 | want to merge them back into the new files.""" % locals() ) | |
303 | wait() |
|
303 | wait() | |
304 | os.chdir(cwd) |
|
304 | os.chdir(cwd) | |
305 |
|
305 | |||
306 | #**************************************************************************** |
|
306 | #**************************************************************************** | |
307 | # Local use exceptions |
|
307 | # Local use exceptions | |
308 | class SpaceInInput(exceptions.Exception): pass |
|
308 | class SpaceInInput(exceptions.Exception): pass | |
309 |
|
309 | |||
310 |
|
310 | |||
311 | #**************************************************************************** |
|
311 | #**************************************************************************** | |
312 | # Local use classes |
|
312 | # Local use classes | |
313 | class Bunch: pass |
|
313 | class Bunch: pass | |
314 |
|
314 | |||
315 | class Undefined: pass |
|
315 | class Undefined: pass | |
316 |
|
316 | |||
317 | class Quitter(object): |
|
317 | class Quitter(object): | |
318 | """Simple class to handle exit, similar to Python 2.5's. |
|
318 | """Simple class to handle exit, similar to Python 2.5's. | |
319 |
|
319 | |||
320 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
320 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 | |
321 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
321 | doesn't do (obviously, since it doesn't know about ipython).""" | |
322 |
|
322 | |||
323 | def __init__(self,shell,name): |
|
323 | def __init__(self,shell,name): | |
324 | self.shell = shell |
|
324 | self.shell = shell | |
325 | self.name = name |
|
325 | self.name = name | |
326 |
|
326 | |||
327 | def __repr__(self): |
|
327 | def __repr__(self): | |
328 | return 'Type %s() to exit.' % self.name |
|
328 | return 'Type %s() to exit.' % self.name | |
329 | __str__ = __repr__ |
|
329 | __str__ = __repr__ | |
330 |
|
330 | |||
331 | def __call__(self): |
|
331 | def __call__(self): | |
332 | self.shell.exit() |
|
332 | self.shell.exit() | |
333 |
|
333 | |||
334 | class InputList(list): |
|
334 | class InputList(list): | |
335 | """Class to store user input. |
|
335 | """Class to store user input. | |
336 |
|
336 | |||
337 | It's basically a list, but slices return a string instead of a list, thus |
|
337 | It's basically a list, but slices return a string instead of a list, thus | |
338 | allowing things like (assuming 'In' is an instance): |
|
338 | allowing things like (assuming 'In' is an instance): | |
339 |
|
339 | |||
340 | exec In[4:7] |
|
340 | exec In[4:7] | |
341 |
|
341 | |||
342 | or |
|
342 | or | |
343 |
|
343 | |||
344 | exec In[5:9] + In[14] + In[21:25]""" |
|
344 | exec In[5:9] + In[14] + In[21:25]""" | |
345 |
|
345 | |||
346 | def __getslice__(self,i,j): |
|
346 | def __getslice__(self,i,j): | |
347 | return ''.join(list.__getslice__(self,i,j)) |
|
347 | return ''.join(list.__getslice__(self,i,j)) | |
348 |
|
348 | |||
349 | class SyntaxTB(ultraTB.ListTB): |
|
349 | class SyntaxTB(ultraTB.ListTB): | |
350 | """Extension which holds some state: the last exception value""" |
|
350 | """Extension which holds some state: the last exception value""" | |
351 |
|
351 | |||
352 | def __init__(self,color_scheme = 'NoColor'): |
|
352 | def __init__(self,color_scheme = 'NoColor'): | |
353 | ultraTB.ListTB.__init__(self,color_scheme) |
|
353 | ultraTB.ListTB.__init__(self,color_scheme) | |
354 | self.last_syntax_error = None |
|
354 | self.last_syntax_error = None | |
355 |
|
355 | |||
356 | def __call__(self, etype, value, elist): |
|
356 | def __call__(self, etype, value, elist): | |
357 | self.last_syntax_error = value |
|
357 | self.last_syntax_error = value | |
358 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
358 | ultraTB.ListTB.__call__(self,etype,value,elist) | |
359 |
|
359 | |||
360 | def clear_err_state(self): |
|
360 | def clear_err_state(self): | |
361 | """Return the current error state and clear it""" |
|
361 | """Return the current error state and clear it""" | |
362 | e = self.last_syntax_error |
|
362 | e = self.last_syntax_error | |
363 | self.last_syntax_error = None |
|
363 | self.last_syntax_error = None | |
364 | return e |
|
364 | return e | |
365 |
|
365 | |||
366 | #**************************************************************************** |
|
366 | #**************************************************************************** | |
367 | # Main IPython class |
|
367 | # Main IPython class | |
368 |
|
368 | |||
369 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
369 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |
370 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
370 | # until a full rewrite is made. I've cleaned all cross-class uses of | |
371 | # attributes and methods, but too much user code out there relies on the |
|
371 | # attributes and methods, but too much user code out there relies on the | |
372 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
372 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |
373 | # |
|
373 | # | |
374 | # But at least now, all the pieces have been separated and we could, in |
|
374 | # But at least now, all the pieces have been separated and we could, in | |
375 | # principle, stop using the mixin. This will ease the transition to the |
|
375 | # principle, stop using the mixin. This will ease the transition to the | |
376 | # chainsaw branch. |
|
376 | # chainsaw branch. | |
377 |
|
377 | |||
378 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
378 | # For reference, the following is the list of 'self.foo' uses in the Magic | |
379 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
379 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |
380 | # class, to prevent clashes. |
|
380 | # class, to prevent clashes. | |
381 |
|
381 | |||
382 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
382 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |
383 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
383 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |
384 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
384 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |
385 | # 'self.value'] |
|
385 | # 'self.value'] | |
386 |
|
386 | |||
387 | class InteractiveShell(object,Magic): |
|
387 | class InteractiveShell(object,Magic): | |
388 | """An enhanced console for Python.""" |
|
388 | """An enhanced console for Python.""" | |
389 |
|
389 | |||
390 | # class attribute to indicate whether the class supports threads or not. |
|
390 | # class attribute to indicate whether the class supports threads or not. | |
391 | # Subclasses with thread support should override this as needed. |
|
391 | # Subclasses with thread support should override this as needed. | |
392 | isthreaded = False |
|
392 | isthreaded = False | |
393 |
|
393 | |||
394 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
394 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
395 | user_ns=None,user_global_ns=None,banner2='', |
|
395 | user_ns=None,user_global_ns=None,banner2='', | |
396 | custom_exceptions=((),None),embedded=False): |
|
396 | custom_exceptions=((),None),embedded=False): | |
397 |
|
397 | |||
398 | # log system |
|
398 | # log system | |
399 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
399 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
400 |
|
400 | |||
401 | # Job manager (for jobs run as background threads) |
|
401 | # Job manager (for jobs run as background threads) | |
402 | self.jobs = BackgroundJobManager() |
|
402 | self.jobs = BackgroundJobManager() | |
403 |
|
403 | |||
404 | # Store the actual shell's name |
|
404 | # Store the actual shell's name | |
405 | self.name = name |
|
405 | self.name = name | |
406 | self.more = False |
|
406 | self.more = False | |
407 |
|
407 | |||
408 | # We need to know whether the instance is meant for embedding, since |
|
408 | # We need to know whether the instance is meant for embedding, since | |
409 | # global/local namespaces need to be handled differently in that case |
|
409 | # global/local namespaces need to be handled differently in that case | |
410 | self.embedded = embedded |
|
410 | self.embedded = embedded | |
411 | if embedded: |
|
411 | if embedded: | |
412 | # Control variable so users can, from within the embedded instance, |
|
412 | # Control variable so users can, from within the embedded instance, | |
413 | # permanently deactivate it. |
|
413 | # permanently deactivate it. | |
414 | self.embedded_active = True |
|
414 | self.embedded_active = True | |
415 |
|
415 | |||
416 | # command compiler |
|
416 | # command compiler | |
417 | self.compile = codeop.CommandCompiler() |
|
417 | self.compile = codeop.CommandCompiler() | |
418 |
|
418 | |||
419 | # User input buffer |
|
419 | # User input buffer | |
420 | self.buffer = [] |
|
420 | self.buffer = [] | |
421 |
|
421 | |||
422 | # Default name given in compilation of code |
|
422 | # Default name given in compilation of code | |
423 | self.filename = '<ipython console>' |
|
423 | self.filename = '<ipython console>' | |
424 |
|
424 | |||
425 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
425 | # Install our own quitter instead of the builtins. For python2.3-2.4, | |
426 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
426 | # this brings in behavior like 2.5, and for 2.5 it's identical. | |
427 | __builtin__.exit = Quitter(self,'exit') |
|
427 | __builtin__.exit = Quitter(self,'exit') | |
428 | __builtin__.quit = Quitter(self,'quit') |
|
428 | __builtin__.quit = Quitter(self,'quit') | |
429 |
|
429 | |||
430 | # Make an empty namespace, which extension writers can rely on both |
|
430 | # Make an empty namespace, which extension writers can rely on both | |
431 | # existing and NEVER being used by ipython itself. This gives them a |
|
431 | # existing and NEVER being used by ipython itself. This gives them a | |
432 | # convenient location for storing additional information and state |
|
432 | # convenient location for storing additional information and state | |
433 | # their extensions may require, without fear of collisions with other |
|
433 | # their extensions may require, without fear of collisions with other | |
434 | # ipython names that may develop later. |
|
434 | # ipython names that may develop later. | |
435 | self.meta = Struct() |
|
435 | self.meta = Struct() | |
436 |
|
436 | |||
437 | # Create the namespace where the user will operate. user_ns is |
|
437 | # Create the namespace where the user will operate. user_ns is | |
438 | # normally the only one used, and it is passed to the exec calls as |
|
438 | # normally the only one used, and it is passed to the exec calls as | |
439 | # the locals argument. But we do carry a user_global_ns namespace |
|
439 | # the locals argument. But we do carry a user_global_ns namespace | |
440 | # given as the exec 'globals' argument, This is useful in embedding |
|
440 | # given as the exec 'globals' argument, This is useful in embedding | |
441 | # situations where the ipython shell opens in a context where the |
|
441 | # situations where the ipython shell opens in a context where the | |
442 | # distinction between locals and globals is meaningful. For |
|
442 | # distinction between locals and globals is meaningful. For | |
443 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
443 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
444 |
|
444 | |||
445 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
445 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
446 | # level as a dict instead of a module. This is a manual fix, but I |
|
446 | # level as a dict instead of a module. This is a manual fix, but I | |
447 | # should really track down where the problem is coming from. Alex |
|
447 | # should really track down where the problem is coming from. Alex | |
448 | # Schmolck reported this problem first. |
|
448 | # Schmolck reported this problem first. | |
449 |
|
449 | |||
450 | # A useful post by Alex Martelli on this topic: |
|
450 | # A useful post by Alex Martelli on this topic: | |
451 | # Re: inconsistent value from __builtins__ |
|
451 | # Re: inconsistent value from __builtins__ | |
452 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
452 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
453 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
453 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
454 | # Gruppen: comp.lang.python |
|
454 | # Gruppen: comp.lang.python | |
455 |
|
455 | |||
456 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
456 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
457 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
457 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
458 | # > <type 'dict'> |
|
458 | # > <type 'dict'> | |
459 | # > >>> print type(__builtins__) |
|
459 | # > >>> print type(__builtins__) | |
460 | # > <type 'module'> |
|
460 | # > <type 'module'> | |
461 | # > Is this difference in return value intentional? |
|
461 | # > Is this difference in return value intentional? | |
462 |
|
462 | |||
463 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
463 | # Well, it's documented that '__builtins__' can be either a dictionary | |
464 | # or a module, and it's been that way for a long time. Whether it's |
|
464 | # or a module, and it's been that way for a long time. Whether it's | |
465 | # intentional (or sensible), I don't know. In any case, the idea is |
|
465 | # intentional (or sensible), I don't know. In any case, the idea is | |
466 | # that if you need to access the built-in namespace directly, you |
|
466 | # that if you need to access the built-in namespace directly, you | |
467 | # should start with "import __builtin__" (note, no 's') which will |
|
467 | # should start with "import __builtin__" (note, no 's') which will | |
468 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
468 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
469 |
|
469 | |||
470 | # These routines return properly built dicts as needed by the rest of |
|
470 | # These routines return properly built dicts as needed by the rest of | |
471 | # the code, and can also be used by extension writers to generate |
|
471 | # the code, and can also be used by extension writers to generate | |
472 | # properly initialized namespaces. |
|
472 | # properly initialized namespaces. | |
473 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, |
|
473 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, | |
474 | user_global_ns) |
|
474 | user_global_ns) | |
475 |
|
475 | |||
476 | # Assign namespaces |
|
476 | # Assign namespaces | |
477 | # This is the namespace where all normal user variables live |
|
477 | # This is the namespace where all normal user variables live | |
478 | self.user_ns = user_ns |
|
478 | self.user_ns = user_ns | |
479 | self.user_global_ns = user_global_ns |
|
479 | self.user_global_ns = user_global_ns | |
480 |
|
480 | |||
481 | # An auxiliary namespace that checks what parts of the user_ns were |
|
481 | # An auxiliary namespace that checks what parts of the user_ns were | |
482 | # loaded at startup, so we can list later only variables defined in |
|
482 | # loaded at startup, so we can list later only variables defined in | |
483 | # actual interactive use. Since it is always a subset of user_ns, it |
|
483 | # actual interactive use. Since it is always a subset of user_ns, it | |
484 | # doesn't need to be seaparately tracked in the ns_table |
|
484 | # doesn't need to be seaparately tracked in the ns_table | |
485 | self.user_config_ns = {} |
|
485 | self.user_config_ns = {} | |
486 |
|
486 | |||
487 | # A namespace to keep track of internal data structures to prevent |
|
487 | # A namespace to keep track of internal data structures to prevent | |
488 | # them from cluttering user-visible stuff. Will be updated later |
|
488 | # them from cluttering user-visible stuff. Will be updated later | |
489 | self.internal_ns = {} |
|
489 | self.internal_ns = {} | |
490 |
|
490 | |||
491 | # Namespace of system aliases. Each entry in the alias |
|
491 | # Namespace of system aliases. Each entry in the alias | |
492 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
492 | # table must be a 2-tuple of the form (N,name), where N is the number | |
493 | # of positional arguments of the alias. |
|
493 | # of positional arguments of the alias. | |
494 | self.alias_table = {} |
|
494 | self.alias_table = {} | |
495 |
|
495 | |||
496 | # Now that FakeModule produces a real module, we've run into a nasty |
|
496 | # Now that FakeModule produces a real module, we've run into a nasty | |
497 | # problem: after script execution (via %run), the module where the user |
|
497 | # problem: after script execution (via %run), the module where the user | |
498 | # code ran is deleted. Now that this object is a true module (needed |
|
498 | # code ran is deleted. Now that this object is a true module (needed | |
499 | # so docetst and other tools work correctly), the Python module |
|
499 | # so docetst and other tools work correctly), the Python module | |
500 | # teardown mechanism runs over it, and sets to None every variable |
|
500 | # teardown mechanism runs over it, and sets to None every variable | |
501 | # present in that module. Top-level references to objects from the |
|
501 | # present in that module. Top-level references to objects from the | |
502 | # script survive, because the user_ns is updated with them. However, |
|
502 | # script survive, because the user_ns is updated with them. However, | |
503 | # calling functions defined in the script that use other things from |
|
503 | # calling functions defined in the script that use other things from | |
504 | # the script will fail, because the function's closure had references |
|
504 | # the script will fail, because the function's closure had references | |
505 | # to the original objects, which are now all None. So we must protect |
|
505 | # to the original objects, which are now all None. So we must protect | |
506 | # these modules from deletion by keeping a cache. |
|
506 | # these modules from deletion by keeping a cache. | |
507 | # |
|
507 | # | |
508 | # To avoid keeping stale modules around (we only need the one from the |
|
508 | # To avoid keeping stale modules around (we only need the one from the | |
509 | # last run), we use a dict keyed with the full path to the script, so |
|
509 | # last run), we use a dict keyed with the full path to the script, so | |
510 | # only the last version of the module is held in the cache. Note, |
|
510 | # only the last version of the module is held in the cache. Note, | |
511 | # however, that we must cache the module *namespace contents* (their |
|
511 | # however, that we must cache the module *namespace contents* (their | |
512 | # __dict__). Because if we try to cache the actual modules, old ones |
|
512 | # __dict__). Because if we try to cache the actual modules, old ones | |
513 | # (uncached) could be destroyed while still holding references (such as |
|
513 | # (uncached) could be destroyed while still holding references (such as | |
514 | # those held by GUI objects that tend to be long-lived)> |
|
514 | # those held by GUI objects that tend to be long-lived)> | |
515 | # |
|
515 | # | |
516 | # The %reset command will flush this cache. See the cache_main_mod() |
|
516 | # The %reset command will flush this cache. See the cache_main_mod() | |
517 | # and clear_main_mod_cache() methods for details on use. |
|
517 | # and clear_main_mod_cache() methods for details on use. | |
518 |
|
518 | |||
519 | # This is the cache used for 'main' namespaces |
|
519 | # This is the cache used for 'main' namespaces | |
520 | self._main_ns_cache = {} |
|
520 | self._main_ns_cache = {} | |
521 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
521 | # And this is the single instance of FakeModule whose __dict__ we keep | |
522 | # copying and clearing for reuse on each %run |
|
522 | # copying and clearing for reuse on each %run | |
523 | self._user_main_module = FakeModule() |
|
523 | self._user_main_module = FakeModule() | |
524 |
|
524 | |||
525 | # A table holding all the namespaces IPython deals with, so that |
|
525 | # A table holding all the namespaces IPython deals with, so that | |
526 | # introspection facilities can search easily. |
|
526 | # introspection facilities can search easily. | |
527 | self.ns_table = {'user':user_ns, |
|
527 | self.ns_table = {'user':user_ns, | |
528 | 'user_global':user_global_ns, |
|
528 | 'user_global':user_global_ns, | |
529 | 'alias':self.alias_table, |
|
529 | 'alias':self.alias_table, | |
530 | 'internal':self.internal_ns, |
|
530 | 'internal':self.internal_ns, | |
531 | 'builtin':__builtin__.__dict__ |
|
531 | 'builtin':__builtin__.__dict__ | |
532 | } |
|
532 | } | |
533 |
|
533 | |||
534 | # Similarly, track all namespaces where references can be held and that |
|
534 | # Similarly, track all namespaces where references can be held and that | |
535 | # we can safely clear (so it can NOT include builtin). This one can be |
|
535 | # we can safely clear (so it can NOT include builtin). This one can be | |
536 | # a simple list. |
|
536 | # a simple list. | |
537 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
537 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |
538 | self.alias_table, self.internal_ns, |
|
538 | self.alias_table, self.internal_ns, | |
539 | self._main_ns_cache ] |
|
539 | self._main_ns_cache ] | |
540 |
|
540 | |||
541 | # We need to insert into sys.modules something that looks like a |
|
541 | # We need to insert into sys.modules something that looks like a | |
542 | # module but which accesses the IPython namespace, for shelve and |
|
542 | # module but which accesses the IPython namespace, for shelve and | |
543 | # pickle to work interactively. Normally they rely on getting |
|
543 | # pickle to work interactively. Normally they rely on getting | |
544 | # everything out of __main__, but for embedding purposes each IPython |
|
544 | # everything out of __main__, but for embedding purposes each IPython | |
545 | # instance has its own private namespace, so we can't go shoving |
|
545 | # instance has its own private namespace, so we can't go shoving | |
546 | # everything into __main__. |
|
546 | # everything into __main__. | |
547 |
|
547 | |||
548 | # note, however, that we should only do this for non-embedded |
|
548 | # note, however, that we should only do this for non-embedded | |
549 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
549 | # ipythons, which really mimic the __main__.__dict__ with their own | |
550 | # namespace. Embedded instances, on the other hand, should not do |
|
550 | # namespace. Embedded instances, on the other hand, should not do | |
551 | # this because they need to manage the user local/global namespaces |
|
551 | # this because they need to manage the user local/global namespaces | |
552 | # only, but they live within a 'normal' __main__ (meaning, they |
|
552 | # only, but they live within a 'normal' __main__ (meaning, they | |
553 | # shouldn't overtake the execution environment of the script they're |
|
553 | # shouldn't overtake the execution environment of the script they're | |
554 | # embedded in). |
|
554 | # embedded in). | |
555 |
|
555 | |||
556 | if not embedded: |
|
556 | if not embedded: | |
557 | try: |
|
557 | try: | |
558 | main_name = self.user_ns['__name__'] |
|
558 | main_name = self.user_ns['__name__'] | |
559 | except KeyError: |
|
559 | except KeyError: | |
560 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
560 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
561 | else: |
|
561 | else: | |
562 | #print "pickle hack in place" # dbg |
|
562 | #print "pickle hack in place" # dbg | |
563 | #print 'main_name:',main_name # dbg |
|
563 | #print 'main_name:',main_name # dbg | |
564 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
564 | sys.modules[main_name] = FakeModule(self.user_ns) | |
565 |
|
565 | |||
566 | # List of input with multi-line handling. |
|
566 | # List of input with multi-line handling. | |
567 | self.input_hist = InputList() |
|
567 | self.input_hist = InputList() | |
568 | # This one will hold the 'raw' input history, without any |
|
568 | # This one will hold the 'raw' input history, without any | |
569 | # pre-processing. This will allow users to retrieve the input just as |
|
569 | # pre-processing. This will allow users to retrieve the input just as | |
570 | # it was exactly typed in by the user, with %hist -r. |
|
570 | # it was exactly typed in by the user, with %hist -r. | |
571 | self.input_hist_raw = InputList() |
|
571 | self.input_hist_raw = InputList() | |
572 |
|
572 | |||
573 | # list of visited directories |
|
573 | # list of visited directories | |
574 | try: |
|
574 | try: | |
575 | self.dir_hist = [os.getcwd()] |
|
575 | self.dir_hist = [os.getcwd()] | |
576 | except OSError: |
|
576 | except OSError: | |
577 | self.dir_hist = [] |
|
577 | self.dir_hist = [] | |
578 |
|
578 | |||
579 | # dict of output history |
|
579 | # dict of output history | |
580 | self.output_hist = {} |
|
580 | self.output_hist = {} | |
581 |
|
581 | |||
582 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
582 | # Get system encoding at startup time. Certain terminals (like Emacs | |
583 | # under Win32 have it set to None, and we need to have a known valid |
|
583 | # under Win32 have it set to None, and we need to have a known valid | |
584 | # encoding to use in the raw_input() method |
|
584 | # encoding to use in the raw_input() method | |
585 | try: |
|
585 | try: | |
586 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
586 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
587 | except AttributeError: |
|
587 | except AttributeError: | |
588 | self.stdin_encoding = 'ascii' |
|
588 | self.stdin_encoding = 'ascii' | |
589 |
|
589 | |||
590 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
590 | # dict of things NOT to alias (keywords, builtins and some magics) | |
591 | no_alias = {} |
|
591 | no_alias = {} | |
592 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
592 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
593 | for key in keyword.kwlist + no_alias_magics: |
|
593 | for key in keyword.kwlist + no_alias_magics: | |
594 | no_alias[key] = 1 |
|
594 | no_alias[key] = 1 | |
595 | no_alias.update(__builtin__.__dict__) |
|
595 | no_alias.update(__builtin__.__dict__) | |
596 | self.no_alias = no_alias |
|
596 | self.no_alias = no_alias | |
597 |
|
597 | |||
598 | # Object variable to store code object waiting execution. This is |
|
598 | # Object variable to store code object waiting execution. This is | |
599 | # used mainly by the multithreaded shells, but it can come in handy in |
|
599 | # used mainly by the multithreaded shells, but it can come in handy in | |
600 | # other situations. No need to use a Queue here, since it's a single |
|
600 | # other situations. No need to use a Queue here, since it's a single | |
601 | # item which gets cleared once run. |
|
601 | # item which gets cleared once run. | |
602 | self.code_to_run = None |
|
602 | self.code_to_run = None | |
603 |
|
603 | |||
604 | # escapes for automatic behavior on the command line |
|
604 | # escapes for automatic behavior on the command line | |
605 | self.ESC_SHELL = '!' |
|
605 | self.ESC_SHELL = '!' | |
606 | self.ESC_SH_CAP = '!!' |
|
606 | self.ESC_SH_CAP = '!!' | |
607 | self.ESC_HELP = '?' |
|
607 | self.ESC_HELP = '?' | |
608 | self.ESC_MAGIC = '%' |
|
608 | self.ESC_MAGIC = '%' | |
609 | self.ESC_QUOTE = ',' |
|
609 | self.ESC_QUOTE = ',' | |
610 | self.ESC_QUOTE2 = ';' |
|
610 | self.ESC_QUOTE2 = ';' | |
611 | self.ESC_PAREN = '/' |
|
611 | self.ESC_PAREN = '/' | |
612 |
|
612 | |||
613 | # And their associated handlers |
|
613 | # And their associated handlers | |
614 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
614 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
615 | self.ESC_QUOTE : self.handle_auto, |
|
615 | self.ESC_QUOTE : self.handle_auto, | |
616 | self.ESC_QUOTE2 : self.handle_auto, |
|
616 | self.ESC_QUOTE2 : self.handle_auto, | |
617 | self.ESC_MAGIC : self.handle_magic, |
|
617 | self.ESC_MAGIC : self.handle_magic, | |
618 | self.ESC_HELP : self.handle_help, |
|
618 | self.ESC_HELP : self.handle_help, | |
619 | self.ESC_SHELL : self.handle_shell_escape, |
|
619 | self.ESC_SHELL : self.handle_shell_escape, | |
620 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
620 | self.ESC_SH_CAP : self.handle_shell_escape, | |
621 | } |
|
621 | } | |
622 |
|
622 | |||
623 | # class initializations |
|
623 | # class initializations | |
624 | Magic.__init__(self,self) |
|
624 | Magic.__init__(self,self) | |
625 |
|
625 | |||
626 | # Python source parser/formatter for syntax highlighting |
|
626 | # Python source parser/formatter for syntax highlighting | |
627 | pyformat = PyColorize.Parser().format |
|
627 | pyformat = PyColorize.Parser().format | |
628 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
628 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |
629 |
|
629 | |||
630 | # hooks holds pointers used for user-side customizations |
|
630 | # hooks holds pointers used for user-side customizations | |
631 | self.hooks = Struct() |
|
631 | self.hooks = Struct() | |
632 |
|
632 | |||
633 | self.strdispatchers = {} |
|
633 | self.strdispatchers = {} | |
634 |
|
634 | |||
635 | # Set all default hooks, defined in the IPython.hooks module. |
|
635 | # Set all default hooks, defined in the IPython.hooks module. | |
636 | hooks = IPython.hooks |
|
636 | hooks = IPython.hooks | |
637 | for hook_name in hooks.__all__: |
|
637 | for hook_name in hooks.__all__: | |
638 | # default hooks have priority 100, i.e. low; user hooks should have |
|
638 | # default hooks have priority 100, i.e. low; user hooks should have | |
639 | # 0-100 priority |
|
639 | # 0-100 priority | |
640 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
640 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
641 | #print "bound hook",hook_name |
|
641 | #print "bound hook",hook_name | |
642 |
|
642 | |||
643 | # Flag to mark unconditional exit |
|
643 | # Flag to mark unconditional exit | |
644 | self.exit_now = False |
|
644 | self.exit_now = False | |
645 |
|
645 | |||
646 | self.usage_min = """\ |
|
646 | self.usage_min = """\ | |
647 | An enhanced console for Python. |
|
647 | An enhanced console for Python. | |
648 | Some of its features are: |
|
648 | Some of its features are: | |
649 | - Readline support if the readline library is present. |
|
649 | - Readline support if the readline library is present. | |
650 | - Tab completion in the local namespace. |
|
650 | - Tab completion in the local namespace. | |
651 | - Logging of input, see command-line options. |
|
651 | - Logging of input, see command-line options. | |
652 | - System shell escape via ! , eg !ls. |
|
652 | - System shell escape via ! , eg !ls. | |
653 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
653 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
654 | - Keeps track of locally defined variables via %who, %whos. |
|
654 | - Keeps track of locally defined variables via %who, %whos. | |
655 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
655 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
656 | """ |
|
656 | """ | |
657 | if usage: self.usage = usage |
|
657 | if usage: self.usage = usage | |
658 | else: self.usage = self.usage_min |
|
658 | else: self.usage = self.usage_min | |
659 |
|
659 | |||
660 | # Storage |
|
660 | # Storage | |
661 | self.rc = rc # This will hold all configuration information |
|
661 | self.rc = rc # This will hold all configuration information | |
662 | self.pager = 'less' |
|
662 | self.pager = 'less' | |
663 | # temporary files used for various purposes. Deleted at exit. |
|
663 | # temporary files used for various purposes. Deleted at exit. | |
664 | self.tempfiles = [] |
|
664 | self.tempfiles = [] | |
665 |
|
665 | |||
666 | # Keep track of readline usage (later set by init_readline) |
|
666 | # Keep track of readline usage (later set by init_readline) | |
667 | self.has_readline = False |
|
667 | self.has_readline = False | |
668 |
|
668 | |||
669 | # template for logfile headers. It gets resolved at runtime by the |
|
669 | # template for logfile headers. It gets resolved at runtime by the | |
670 | # logstart method. |
|
670 | # logstart method. | |
671 | self.loghead_tpl = \ |
|
671 | self.loghead_tpl = \ | |
672 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
672 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
673 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
673 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW -* coding: %s *- | |
674 | #log# opts = %s |
|
674 | #log# opts = %s | |
675 | #log# args = %s |
|
675 | #log# args = %s | |
676 | #log# It is safe to make manual edits below here. |
|
676 | #log# It is safe to make manual edits below here. | |
677 | #log#----------------------------------------------------------------------- |
|
677 | #log#----------------------------------------------------------------------- | |
678 | """ |
|
678 | """ | |
679 | # for pushd/popd management |
|
679 | # for pushd/popd management | |
680 | try: |
|
680 | try: | |
681 | self.home_dir = get_home_dir() |
|
681 | self.home_dir = get_home_dir() | |
682 | except HomeDirError,msg: |
|
682 | except HomeDirError,msg: | |
683 | fatal(msg) |
|
683 | fatal(msg) | |
684 |
|
684 | |||
685 | self.dir_stack = [] |
|
685 | self.dir_stack = [] | |
686 |
|
686 | |||
687 | # Functions to call the underlying shell. |
|
687 | # Functions to call the underlying shell. | |
688 |
|
688 | |||
689 | # The first is similar to os.system, but it doesn't return a value, |
|
689 | # The first is similar to os.system, but it doesn't return a value, | |
690 | # and it allows interpolation of variables in the user's namespace. |
|
690 | # and it allows interpolation of variables in the user's namespace. | |
691 | self.system = lambda cmd: \ |
|
691 | self.system = lambda cmd: \ | |
692 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
692 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) | |
693 |
|
693 | |||
694 | # These are for getoutput and getoutputerror: |
|
694 | # These are for getoutput and getoutputerror: | |
695 | self.getoutput = lambda cmd: \ |
|
695 | self.getoutput = lambda cmd: \ | |
696 | getoutput(self.var_expand(cmd,depth=2), |
|
696 | getoutput(self.var_expand(cmd,depth=2), | |
697 | header=self.rc.system_header, |
|
697 | header=self.rc.system_header, | |
698 | verbose=self.rc.system_verbose) |
|
698 | verbose=self.rc.system_verbose) | |
699 |
|
699 | |||
700 | self.getoutputerror = lambda cmd: \ |
|
700 | self.getoutputerror = lambda cmd: \ | |
701 | getoutputerror(self.var_expand(cmd,depth=2), |
|
701 | getoutputerror(self.var_expand(cmd,depth=2), | |
702 | header=self.rc.system_header, |
|
702 | header=self.rc.system_header, | |
703 | verbose=self.rc.system_verbose) |
|
703 | verbose=self.rc.system_verbose) | |
704 |
|
704 | |||
705 |
|
705 | |||
706 | # keep track of where we started running (mainly for crash post-mortem) |
|
706 | # keep track of where we started running (mainly for crash post-mortem) | |
707 | self.starting_dir = os.getcwd() |
|
707 | self.starting_dir = os.getcwd() | |
708 |
|
708 | |||
709 | # Various switches which can be set |
|
709 | # Various switches which can be set | |
710 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
710 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
711 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
711 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
712 | self.banner2 = banner2 |
|
712 | self.banner2 = banner2 | |
713 |
|
713 | |||
714 | # TraceBack handlers: |
|
714 | # TraceBack handlers: | |
715 |
|
715 | |||
716 | # Syntax error handler. |
|
716 | # Syntax error handler. | |
717 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
717 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
718 |
|
718 | |||
719 | # The interactive one is initialized with an offset, meaning we always |
|
719 | # The interactive one is initialized with an offset, meaning we always | |
720 | # want to remove the topmost item in the traceback, which is our own |
|
720 | # want to remove the topmost item in the traceback, which is our own | |
721 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
721 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
722 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
722 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
723 | color_scheme='NoColor', |
|
723 | color_scheme='NoColor', | |
724 | tb_offset = 1) |
|
724 | tb_offset = 1) | |
725 |
|
725 | |||
726 | # IPython itself shouldn't crash. This will produce a detailed |
|
726 | # IPython itself shouldn't crash. This will produce a detailed | |
727 | # post-mortem if it does. But we only install the crash handler for |
|
727 | # post-mortem if it does. But we only install the crash handler for | |
728 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
728 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
729 | # and lose the crash handler. This is because exceptions in the main |
|
729 | # and lose the crash handler. This is because exceptions in the main | |
730 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
730 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
731 | # and there's no point in printing crash dumps for every user exception. |
|
731 | # and there's no point in printing crash dumps for every user exception. | |
732 | if self.isthreaded: |
|
732 | if self.isthreaded: | |
733 | ipCrashHandler = ultraTB.FormattedTB() |
|
733 | ipCrashHandler = ultraTB.FormattedTB() | |
734 | else: |
|
734 | else: | |
735 | from IPython import CrashHandler |
|
735 | from IPython import CrashHandler | |
736 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
736 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) | |
737 | self.set_crash_handler(ipCrashHandler) |
|
737 | self.set_crash_handler(ipCrashHandler) | |
738 |
|
738 | |||
739 | # and add any custom exception handlers the user may have specified |
|
739 | # and add any custom exception handlers the user may have specified | |
740 | self.set_custom_exc(*custom_exceptions) |
|
740 | self.set_custom_exc(*custom_exceptions) | |
741 |
|
741 | |||
742 | # indentation management |
|
742 | # indentation management | |
743 | self.autoindent = False |
|
743 | self.autoindent = False | |
744 | self.indent_current_nsp = 0 |
|
744 | self.indent_current_nsp = 0 | |
745 |
|
745 | |||
746 | # Make some aliases automatically |
|
746 | # Make some aliases automatically | |
747 | # Prepare list of shell aliases to auto-define |
|
747 | # Prepare list of shell aliases to auto-define | |
748 | if os.name == 'posix': |
|
748 | if os.name == 'posix': | |
749 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
749 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
750 | 'mv mv -i','rm rm -i','cp cp -i', |
|
750 | 'mv mv -i','rm rm -i','cp cp -i', | |
751 | 'cat cat','less less','clear clear', |
|
751 | 'cat cat','less less','clear clear', | |
752 | # a better ls |
|
752 | # a better ls | |
753 | 'ls ls -F', |
|
753 | 'ls ls -F', | |
754 | # long ls |
|
754 | # long ls | |
755 | 'll ls -lF') |
|
755 | 'll ls -lF') | |
756 | # Extra ls aliases with color, which need special treatment on BSD |
|
756 | # Extra ls aliases with color, which need special treatment on BSD | |
757 | # variants |
|
757 | # variants | |
758 | ls_extra = ( # color ls |
|
758 | ls_extra = ( # color ls | |
759 | 'lc ls -F -o --color', |
|
759 | 'lc ls -F -o --color', | |
760 | # ls normal files only |
|
760 | # ls normal files only | |
761 | 'lf ls -F -o --color %l | grep ^-', |
|
761 | 'lf ls -F -o --color %l | grep ^-', | |
762 | # ls symbolic links |
|
762 | # ls symbolic links | |
763 | 'lk ls -F -o --color %l | grep ^l', |
|
763 | 'lk ls -F -o --color %l | grep ^l', | |
764 | # directories or links to directories, |
|
764 | # directories or links to directories, | |
765 | 'ldir ls -F -o --color %l | grep /$', |
|
765 | 'ldir ls -F -o --color %l | grep /$', | |
766 | # things which are executable |
|
766 | # things which are executable | |
767 | 'lx ls -F -o --color %l | grep ^-..x', |
|
767 | 'lx ls -F -o --color %l | grep ^-..x', | |
768 | ) |
|
768 | ) | |
769 | # The BSDs don't ship GNU ls, so they don't understand the |
|
769 | # The BSDs don't ship GNU ls, so they don't understand the | |
770 | # --color switch out of the box |
|
770 | # --color switch out of the box | |
771 | if 'bsd' in sys.platform: |
|
771 | if 'bsd' in sys.platform: | |
772 | ls_extra = ( # ls normal files only |
|
772 | ls_extra = ( # ls normal files only | |
773 | 'lf ls -lF | grep ^-', |
|
773 | 'lf ls -lF | grep ^-', | |
774 | # ls symbolic links |
|
774 | # ls symbolic links | |
775 | 'lk ls -lF | grep ^l', |
|
775 | 'lk ls -lF | grep ^l', | |
776 | # directories or links to directories, |
|
776 | # directories or links to directories, | |
777 | 'ldir ls -lF | grep /$', |
|
777 | 'ldir ls -lF | grep /$', | |
778 | # things which are executable |
|
778 | # things which are executable | |
779 | 'lx ls -lF | grep ^-..x', |
|
779 | 'lx ls -lF | grep ^-..x', | |
780 | ) |
|
780 | ) | |
781 | auto_alias = auto_alias + ls_extra |
|
781 | auto_alias = auto_alias + ls_extra | |
782 | elif os.name in ['nt','dos']: |
|
782 | elif os.name in ['nt','dos']: | |
783 | auto_alias = ('ls dir /on', |
|
783 | auto_alias = ('ls dir /on', | |
784 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
784 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
785 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
785 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
786 | 'ren ren','cls cls','copy copy') |
|
786 | 'ren ren','cls cls','copy copy') | |
787 | else: |
|
787 | else: | |
788 | auto_alias = () |
|
788 | auto_alias = () | |
789 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
789 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |
790 |
|
790 | |||
791 | # Produce a public API instance |
|
791 | # Produce a public API instance | |
792 | self.api = IPython.ipapi.IPApi(self) |
|
792 | self.api = IPython.ipapi.IPApi(self) | |
793 |
|
793 | |||
794 | # Initialize all user-visible namespaces |
|
794 | # Initialize all user-visible namespaces | |
795 | self.init_namespaces() |
|
795 | self.init_namespaces() | |
796 |
|
796 | |||
797 | # Call the actual (public) initializer |
|
797 | # Call the actual (public) initializer | |
798 | self.init_auto_alias() |
|
798 | self.init_auto_alias() | |
799 |
|
799 | |||
800 | # track which builtins we add, so we can clean up later |
|
800 | # track which builtins we add, so we can clean up later | |
801 | self.builtins_added = {} |
|
801 | self.builtins_added = {} | |
802 | # This method will add the necessary builtins for operation, but |
|
802 | # This method will add the necessary builtins for operation, but | |
803 | # tracking what it did via the builtins_added dict. |
|
803 | # tracking what it did via the builtins_added dict. | |
804 |
|
804 | |||
805 | #TODO: remove this, redundant |
|
805 | #TODO: remove this, redundant | |
806 | self.add_builtins() |
|
806 | self.add_builtins() | |
807 | # end __init__ |
|
807 | # end __init__ | |
808 |
|
808 | |||
809 | def var_expand(self,cmd,depth=0): |
|
809 | def var_expand(self,cmd,depth=0): | |
810 | """Expand python variables in a string. |
|
810 | """Expand python variables in a string. | |
811 |
|
811 | |||
812 | The depth argument indicates how many frames above the caller should |
|
812 | The depth argument indicates how many frames above the caller should | |
813 | be walked to look for the local namespace where to expand variables. |
|
813 | be walked to look for the local namespace where to expand variables. | |
814 |
|
814 | |||
815 | The global namespace for expansion is always the user's interactive |
|
815 | The global namespace for expansion is always the user's interactive | |
816 | namespace. |
|
816 | namespace. | |
817 | """ |
|
817 | """ | |
818 |
|
818 | |||
819 | return str(ItplNS(cmd, |
|
819 | return str(ItplNS(cmd, | |
820 | self.user_ns, # globals |
|
820 | self.user_ns, # globals | |
821 | # Skip our own frame in searching for locals: |
|
821 | # Skip our own frame in searching for locals: | |
822 | sys._getframe(depth+1).f_locals # locals |
|
822 | sys._getframe(depth+1).f_locals # locals | |
823 | )) |
|
823 | )) | |
824 |
|
824 | |||
825 | def pre_config_initialization(self): |
|
825 | def pre_config_initialization(self): | |
826 | """Pre-configuration init method |
|
826 | """Pre-configuration init method | |
827 |
|
827 | |||
828 | This is called before the configuration files are processed to |
|
828 | This is called before the configuration files are processed to | |
829 | prepare the services the config files might need. |
|
829 | prepare the services the config files might need. | |
830 |
|
830 | |||
831 | self.rc already has reasonable default values at this point. |
|
831 | self.rc already has reasonable default values at this point. | |
832 | """ |
|
832 | """ | |
833 | rc = self.rc |
|
833 | rc = self.rc | |
834 | try: |
|
834 | try: | |
835 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
835 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") | |
836 | except exceptions.UnicodeDecodeError: |
|
836 | except exceptions.UnicodeDecodeError: | |
837 | print "Your ipythondir can't be decoded to unicode!" |
|
837 | print "Your ipythondir can't be decoded to unicode!" | |
838 | print "Please set HOME environment variable to something that" |
|
838 | print "Please set HOME environment variable to something that" | |
839 | print r"only has ASCII characters, e.g. c:\home" |
|
839 | print r"only has ASCII characters, e.g. c:\home" | |
840 | print "Now it is",rc.ipythondir |
|
840 | print "Now it is",rc.ipythondir | |
841 | sys.exit() |
|
841 | sys.exit() | |
842 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
842 | self.shadowhist = IPython.history.ShadowHist(self.db) | |
843 |
|
843 | |||
844 | def post_config_initialization(self): |
|
844 | def post_config_initialization(self): | |
845 | """Post configuration init method |
|
845 | """Post configuration init method | |
846 |
|
846 | |||
847 | This is called after the configuration files have been processed to |
|
847 | This is called after the configuration files have been processed to | |
848 | 'finalize' the initialization.""" |
|
848 | 'finalize' the initialization.""" | |
849 |
|
849 | |||
850 | rc = self.rc |
|
850 | rc = self.rc | |
851 |
|
851 | |||
852 | # Object inspector |
|
852 | # Object inspector | |
853 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
853 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
854 | PyColorize.ANSICodeColors, |
|
854 | PyColorize.ANSICodeColors, | |
855 | 'NoColor', |
|
855 | 'NoColor', | |
856 | rc.object_info_string_level) |
|
856 | rc.object_info_string_level) | |
857 |
|
857 | |||
858 | self.rl_next_input = None |
|
858 | self.rl_next_input = None | |
859 | self.rl_do_indent = False |
|
859 | self.rl_do_indent = False | |
860 | # Load readline proper |
|
860 | # Load readline proper | |
861 | if rc.readline: |
|
861 | if rc.readline: | |
862 | self.init_readline() |
|
862 | self.init_readline() | |
863 |
|
863 | |||
864 | # local shortcut, this is used a LOT |
|
864 | # local shortcut, this is used a LOT | |
865 | self.log = self.logger.log |
|
865 | self.log = self.logger.log | |
866 |
|
866 | |||
867 | # Initialize cache, set in/out prompts and printing system |
|
867 | # Initialize cache, set in/out prompts and printing system | |
868 | self.outputcache = CachedOutput(self, |
|
868 | self.outputcache = CachedOutput(self, | |
869 | rc.cache_size, |
|
869 | rc.cache_size, | |
870 | rc.pprint, |
|
870 | rc.pprint, | |
871 | input_sep = rc.separate_in, |
|
871 | input_sep = rc.separate_in, | |
872 | output_sep = rc.separate_out, |
|
872 | output_sep = rc.separate_out, | |
873 | output_sep2 = rc.separate_out2, |
|
873 | output_sep2 = rc.separate_out2, | |
874 | ps1 = rc.prompt_in1, |
|
874 | ps1 = rc.prompt_in1, | |
875 | ps2 = rc.prompt_in2, |
|
875 | ps2 = rc.prompt_in2, | |
876 | ps_out = rc.prompt_out, |
|
876 | ps_out = rc.prompt_out, | |
877 | pad_left = rc.prompts_pad_left) |
|
877 | pad_left = rc.prompts_pad_left) | |
878 |
|
878 | |||
879 | # user may have over-ridden the default print hook: |
|
879 | # user may have over-ridden the default print hook: | |
880 | try: |
|
880 | try: | |
881 | self.outputcache.__class__.display = self.hooks.display |
|
881 | self.outputcache.__class__.display = self.hooks.display | |
882 | except AttributeError: |
|
882 | except AttributeError: | |
883 | pass |
|
883 | pass | |
884 |
|
884 | |||
885 | # I don't like assigning globally to sys, because it means when |
|
885 | # I don't like assigning globally to sys, because it means when | |
886 | # embedding instances, each embedded instance overrides the previous |
|
886 | # embedding instances, each embedded instance overrides the previous | |
887 | # choice. But sys.displayhook seems to be called internally by exec, |
|
887 | # choice. But sys.displayhook seems to be called internally by exec, | |
888 | # so I don't see a way around it. We first save the original and then |
|
888 | # so I don't see a way around it. We first save the original and then | |
889 | # overwrite it. |
|
889 | # overwrite it. | |
890 | self.sys_displayhook = sys.displayhook |
|
890 | self.sys_displayhook = sys.displayhook | |
891 | sys.displayhook = self.outputcache |
|
891 | sys.displayhook = self.outputcache | |
892 |
|
892 | |||
893 | # Do a proper resetting of doctest, including the necessary displayhook |
|
893 | # Do a proper resetting of doctest, including the necessary displayhook | |
894 | # monkeypatching |
|
894 | # monkeypatching | |
895 | try: |
|
895 | try: | |
896 | doctest_reload() |
|
896 | doctest_reload() | |
897 | except ImportError: |
|
897 | except ImportError: | |
898 | warn("doctest module does not exist.") |
|
898 | warn("doctest module does not exist.") | |
899 |
|
899 | |||
900 | # Set user colors (don't do it in the constructor above so that it |
|
900 | # Set user colors (don't do it in the constructor above so that it | |
901 | # doesn't crash if colors option is invalid) |
|
901 | # doesn't crash if colors option is invalid) | |
902 | self.magic_colors(rc.colors) |
|
902 | self.magic_colors(rc.colors) | |
903 |
|
903 | |||
904 | # Set calling of pdb on exceptions |
|
904 | # Set calling of pdb on exceptions | |
905 | self.call_pdb = rc.pdb |
|
905 | self.call_pdb = rc.pdb | |
906 |
|
906 | |||
907 | # Load user aliases |
|
907 | # Load user aliases | |
908 | for alias in rc.alias: |
|
908 | for alias in rc.alias: | |
909 | self.magic_alias(alias) |
|
909 | self.magic_alias(alias) | |
910 |
|
910 | |||
911 | self.hooks.late_startup_hook() |
|
911 | self.hooks.late_startup_hook() | |
912 |
|
912 | |||
913 | for cmd in self.rc.autoexec: |
|
913 | for cmd in self.rc.autoexec: | |
914 | #print "autoexec>",cmd #dbg |
|
914 | #print "autoexec>",cmd #dbg | |
915 | self.api.runlines(cmd) |
|
915 | self.api.runlines(cmd) | |
916 |
|
916 | |||
917 | batchrun = False |
|
917 | batchrun = False | |
918 | for batchfile in [path(arg) for arg in self.rc.args |
|
918 | for batchfile in [path(arg) for arg in self.rc.args | |
919 | if arg.lower().endswith('.ipy')]: |
|
919 | if arg.lower().endswith('.ipy')]: | |
920 | if not batchfile.isfile(): |
|
920 | if not batchfile.isfile(): | |
921 | print "No such batch file:", batchfile |
|
921 | print "No such batch file:", batchfile | |
922 | continue |
|
922 | continue | |
923 | self.api.runlines(batchfile.text()) |
|
923 | self.api.runlines(batchfile.text()) | |
924 | batchrun = True |
|
924 | batchrun = True | |
925 | # without -i option, exit after running the batch file |
|
925 | # without -i option, exit after running the batch file | |
926 | if batchrun and not self.rc.interact: |
|
926 | if batchrun and not self.rc.interact: | |
927 | self.ask_exit() |
|
927 | self.ask_exit() | |
928 |
|
928 | |||
929 | def init_namespaces(self): |
|
929 | def init_namespaces(self): | |
930 | """Initialize all user-visible namespaces to their minimum defaults. |
|
930 | """Initialize all user-visible namespaces to their minimum defaults. | |
931 |
|
931 | |||
932 | Certain history lists are also initialized here, as they effectively |
|
932 | Certain history lists are also initialized here, as they effectively | |
933 | act as user namespaces. |
|
933 | act as user namespaces. | |
934 |
|
934 | |||
935 | Notes |
|
935 | Notes | |
936 | ----- |
|
936 | ----- | |
937 | All data structures here are only filled in, they are NOT reset by this |
|
937 | All data structures here are only filled in, they are NOT reset by this | |
938 | method. If they were not empty before, data will simply be added to |
|
938 | method. If they were not empty before, data will simply be added to | |
939 | therm. |
|
939 | therm. | |
940 | """ |
|
940 | """ | |
941 | # The user namespace MUST have a pointer to the shell itself. |
|
941 | # The user namespace MUST have a pointer to the shell itself. | |
942 | self.user_ns[self.name] = self |
|
942 | self.user_ns[self.name] = self | |
943 |
|
943 | |||
944 | # Store the public api instance |
|
944 | # Store the public api instance | |
945 | self.user_ns['_ip'] = self.api |
|
945 | self.user_ns['_ip'] = self.api | |
946 |
|
946 | |||
947 | # make global variables for user access to the histories |
|
947 | # make global variables for user access to the histories | |
948 | self.user_ns['_ih'] = self.input_hist |
|
948 | self.user_ns['_ih'] = self.input_hist | |
949 | self.user_ns['_oh'] = self.output_hist |
|
949 | self.user_ns['_oh'] = self.output_hist | |
950 | self.user_ns['_dh'] = self.dir_hist |
|
950 | self.user_ns['_dh'] = self.dir_hist | |
951 |
|
951 | |||
952 | # user aliases to input and output histories |
|
952 | # user aliases to input and output histories | |
953 | self.user_ns['In'] = self.input_hist |
|
953 | self.user_ns['In'] = self.input_hist | |
954 | self.user_ns['Out'] = self.output_hist |
|
954 | self.user_ns['Out'] = self.output_hist | |
955 |
|
955 | |||
956 | self.user_ns['_sh'] = IPython.shadowns |
|
956 | self.user_ns['_sh'] = IPython.shadowns | |
957 |
|
957 | |||
958 | # Fill the history zero entry, user counter starts at 1 |
|
958 | # Fill the history zero entry, user counter starts at 1 | |
959 | self.input_hist.append('\n') |
|
959 | self.input_hist.append('\n') | |
960 | self.input_hist_raw.append('\n') |
|
960 | self.input_hist_raw.append('\n') | |
961 |
|
961 | |||
962 | def add_builtins(self): |
|
962 | def add_builtins(self): | |
963 | """Store ipython references into the builtin namespace. |
|
963 | """Store ipython references into the builtin namespace. | |
964 |
|
964 | |||
965 | Some parts of ipython operate via builtins injected here, which hold a |
|
965 | Some parts of ipython operate via builtins injected here, which hold a | |
966 | reference to IPython itself.""" |
|
966 | reference to IPython itself.""" | |
967 |
|
967 | |||
968 | # TODO: deprecate all of these, they are unsafe |
|
968 | # TODO: deprecate all of these, they are unsafe | |
969 | builtins_new = dict(__IPYTHON__ = self, |
|
969 | builtins_new = dict(__IPYTHON__ = self, | |
970 | ip_set_hook = self.set_hook, |
|
970 | ip_set_hook = self.set_hook, | |
971 | jobs = self.jobs, |
|
971 | jobs = self.jobs, | |
972 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
972 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), | |
973 | ipalias = wrap_deprecated(self.ipalias), |
|
973 | ipalias = wrap_deprecated(self.ipalias), | |
974 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
974 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), | |
975 | #_ip = self.api |
|
975 | #_ip = self.api | |
976 | ) |
|
976 | ) | |
977 | for biname,bival in builtins_new.items(): |
|
977 | for biname,bival in builtins_new.items(): | |
978 | try: |
|
978 | try: | |
979 | # store the orignal value so we can restore it |
|
979 | # store the orignal value so we can restore it | |
980 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
980 | self.builtins_added[biname] = __builtin__.__dict__[biname] | |
981 | except KeyError: |
|
981 | except KeyError: | |
982 | # or mark that it wasn't defined, and we'll just delete it at |
|
982 | # or mark that it wasn't defined, and we'll just delete it at | |
983 | # cleanup |
|
983 | # cleanup | |
984 | self.builtins_added[biname] = Undefined |
|
984 | self.builtins_added[biname] = Undefined | |
985 | __builtin__.__dict__[biname] = bival |
|
985 | __builtin__.__dict__[biname] = bival | |
986 |
|
986 | |||
987 | # Keep in the builtins a flag for when IPython is active. We set it |
|
987 | # Keep in the builtins a flag for when IPython is active. We set it | |
988 | # with setdefault so that multiple nested IPythons don't clobber one |
|
988 | # with setdefault so that multiple nested IPythons don't clobber one | |
989 | # another. Each will increase its value by one upon being activated, |
|
989 | # another. Each will increase its value by one upon being activated, | |
990 | # which also gives us a way to determine the nesting level. |
|
990 | # which also gives us a way to determine the nesting level. | |
991 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
991 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
992 |
|
992 | |||
993 | def clean_builtins(self): |
|
993 | def clean_builtins(self): | |
994 | """Remove any builtins which might have been added by add_builtins, or |
|
994 | """Remove any builtins which might have been added by add_builtins, or | |
995 | restore overwritten ones to their previous values.""" |
|
995 | restore overwritten ones to their previous values.""" | |
996 | for biname,bival in self.builtins_added.items(): |
|
996 | for biname,bival in self.builtins_added.items(): | |
997 | if bival is Undefined: |
|
997 | if bival is Undefined: | |
998 | del __builtin__.__dict__[biname] |
|
998 | del __builtin__.__dict__[biname] | |
999 | else: |
|
999 | else: | |
1000 | __builtin__.__dict__[biname] = bival |
|
1000 | __builtin__.__dict__[biname] = bival | |
1001 | self.builtins_added.clear() |
|
1001 | self.builtins_added.clear() | |
1002 |
|
1002 | |||
1003 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
1003 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
1004 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
1004 | """set_hook(name,hook) -> sets an internal IPython hook. | |
1005 |
|
1005 | |||
1006 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
1006 | IPython exposes some of its internal API as user-modifiable hooks. By | |
1007 | adding your function to one of these hooks, you can modify IPython's |
|
1007 | adding your function to one of these hooks, you can modify IPython's | |
1008 | behavior to call at runtime your own routines.""" |
|
1008 | behavior to call at runtime your own routines.""" | |
1009 |
|
1009 | |||
1010 | # At some point in the future, this should validate the hook before it |
|
1010 | # At some point in the future, this should validate the hook before it | |
1011 | # accepts it. Probably at least check that the hook takes the number |
|
1011 | # accepts it. Probably at least check that the hook takes the number | |
1012 | # of args it's supposed to. |
|
1012 | # of args it's supposed to. | |
1013 |
|
1013 | |||
1014 | f = new.instancemethod(hook,self,self.__class__) |
|
1014 | f = new.instancemethod(hook,self,self.__class__) | |
1015 |
|
1015 | |||
1016 | # check if the hook is for strdispatcher first |
|
1016 | # check if the hook is for strdispatcher first | |
1017 | if str_key is not None: |
|
1017 | if str_key is not None: | |
1018 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1018 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
1019 | sdp.add_s(str_key, f, priority ) |
|
1019 | sdp.add_s(str_key, f, priority ) | |
1020 | self.strdispatchers[name] = sdp |
|
1020 | self.strdispatchers[name] = sdp | |
1021 | return |
|
1021 | return | |
1022 | if re_key is not None: |
|
1022 | if re_key is not None: | |
1023 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1023 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
1024 | sdp.add_re(re.compile(re_key), f, priority ) |
|
1024 | sdp.add_re(re.compile(re_key), f, priority ) | |
1025 | self.strdispatchers[name] = sdp |
|
1025 | self.strdispatchers[name] = sdp | |
1026 | return |
|
1026 | return | |
1027 |
|
1027 | |||
1028 | dp = getattr(self.hooks, name, None) |
|
1028 | dp = getattr(self.hooks, name, None) | |
1029 | if name not in IPython.hooks.__all__: |
|
1029 | if name not in IPython.hooks.__all__: | |
1030 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
1030 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) | |
1031 | if not dp: |
|
1031 | if not dp: | |
1032 | dp = IPython.hooks.CommandChainDispatcher() |
|
1032 | dp = IPython.hooks.CommandChainDispatcher() | |
1033 |
|
1033 | |||
1034 | try: |
|
1034 | try: | |
1035 | dp.add(f,priority) |
|
1035 | dp.add(f,priority) | |
1036 | except AttributeError: |
|
1036 | except AttributeError: | |
1037 | # it was not commandchain, plain old func - replace |
|
1037 | # it was not commandchain, plain old func - replace | |
1038 | dp = f |
|
1038 | dp = f | |
1039 |
|
1039 | |||
1040 | setattr(self.hooks,name, dp) |
|
1040 | setattr(self.hooks,name, dp) | |
1041 |
|
1041 | |||
1042 |
|
1042 | |||
1043 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
1043 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
1044 |
|
1044 | |||
1045 | def set_crash_handler(self,crashHandler): |
|
1045 | def set_crash_handler(self,crashHandler): | |
1046 | """Set the IPython crash handler. |
|
1046 | """Set the IPython crash handler. | |
1047 |
|
1047 | |||
1048 | This must be a callable with a signature suitable for use as |
|
1048 | This must be a callable with a signature suitable for use as | |
1049 | sys.excepthook.""" |
|
1049 | sys.excepthook.""" | |
1050 |
|
1050 | |||
1051 | # Install the given crash handler as the Python exception hook |
|
1051 | # Install the given crash handler as the Python exception hook | |
1052 | sys.excepthook = crashHandler |
|
1052 | sys.excepthook = crashHandler | |
1053 |
|
1053 | |||
1054 | # The instance will store a pointer to this, so that runtime code |
|
1054 | # The instance will store a pointer to this, so that runtime code | |
1055 | # (such as magics) can access it. This is because during the |
|
1055 | # (such as magics) can access it. This is because during the | |
1056 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1056 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
1057 | # frameworks). |
|
1057 | # frameworks). | |
1058 | self.sys_excepthook = sys.excepthook |
|
1058 | self.sys_excepthook = sys.excepthook | |
1059 |
|
1059 | |||
1060 |
|
1060 | |||
1061 | def set_custom_exc(self,exc_tuple,handler): |
|
1061 | def set_custom_exc(self,exc_tuple,handler): | |
1062 | """set_custom_exc(exc_tuple,handler) |
|
1062 | """set_custom_exc(exc_tuple,handler) | |
1063 |
|
1063 | |||
1064 | Set a custom exception handler, which will be called if any of the |
|
1064 | Set a custom exception handler, which will be called if any of the | |
1065 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1065 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1066 | runcode() method. |
|
1066 | runcode() method. | |
1067 |
|
1067 | |||
1068 | Inputs: |
|
1068 | Inputs: | |
1069 |
|
1069 | |||
1070 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1070 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1071 | handler for. It is very important that you use a tuple, and NOT A |
|
1071 | handler for. It is very important that you use a tuple, and NOT A | |
1072 | LIST here, because of the way Python's except statement works. If |
|
1072 | LIST here, because of the way Python's except statement works. If | |
1073 | you only want to trap a single exception, use a singleton tuple: |
|
1073 | you only want to trap a single exception, use a singleton tuple: | |
1074 |
|
1074 | |||
1075 | exc_tuple == (MyCustomException,) |
|
1075 | exc_tuple == (MyCustomException,) | |
1076 |
|
1076 | |||
1077 | - handler: this must be defined as a function with the following |
|
1077 | - handler: this must be defined as a function with the following | |
1078 | basic interface: def my_handler(self,etype,value,tb). |
|
1078 | basic interface: def my_handler(self,etype,value,tb). | |
1079 |
|
1079 | |||
1080 | This will be made into an instance method (via new.instancemethod) |
|
1080 | This will be made into an instance method (via new.instancemethod) | |
1081 | of IPython itself, and it will be called if any of the exceptions |
|
1081 | of IPython itself, and it will be called if any of the exceptions | |
1082 | listed in the exc_tuple are caught. If the handler is None, an |
|
1082 | listed in the exc_tuple are caught. If the handler is None, an | |
1083 | internal basic one is used, which just prints basic info. |
|
1083 | internal basic one is used, which just prints basic info. | |
1084 |
|
1084 | |||
1085 | WARNING: by putting in your own exception handler into IPython's main |
|
1085 | WARNING: by putting in your own exception handler into IPython's main | |
1086 | execution loop, you run a very good chance of nasty crashes. This |
|
1086 | execution loop, you run a very good chance of nasty crashes. This | |
1087 | facility should only be used if you really know what you are doing.""" |
|
1087 | facility should only be used if you really know what you are doing.""" | |
1088 |
|
1088 | |||
1089 | assert type(exc_tuple)==type(()) , \ |
|
1089 | assert type(exc_tuple)==type(()) , \ | |
1090 | "The custom exceptions must be given AS A TUPLE." |
|
1090 | "The custom exceptions must be given AS A TUPLE." | |
1091 |
|
1091 | |||
1092 | def dummy_handler(self,etype,value,tb): |
|
1092 | def dummy_handler(self,etype,value,tb): | |
1093 | print '*** Simple custom exception handler ***' |
|
1093 | print '*** Simple custom exception handler ***' | |
1094 | print 'Exception type :',etype |
|
1094 | print 'Exception type :',etype | |
1095 | print 'Exception value:',value |
|
1095 | print 'Exception value:',value | |
1096 | print 'Traceback :',tb |
|
1096 | print 'Traceback :',tb | |
1097 | print 'Source code :','\n'.join(self.buffer) |
|
1097 | print 'Source code :','\n'.join(self.buffer) | |
1098 |
|
1098 | |||
1099 | if handler is None: handler = dummy_handler |
|
1099 | if handler is None: handler = dummy_handler | |
1100 |
|
1100 | |||
1101 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1101 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1102 | self.custom_exceptions = exc_tuple |
|
1102 | self.custom_exceptions = exc_tuple | |
1103 |
|
1103 | |||
1104 | def set_custom_completer(self,completer,pos=0): |
|
1104 | def set_custom_completer(self,completer,pos=0): | |
1105 | """set_custom_completer(completer,pos=0) |
|
1105 | """set_custom_completer(completer,pos=0) | |
1106 |
|
1106 | |||
1107 | Adds a new custom completer function. |
|
1107 | Adds a new custom completer function. | |
1108 |
|
1108 | |||
1109 | The position argument (defaults to 0) is the index in the completers |
|
1109 | The position argument (defaults to 0) is the index in the completers | |
1110 | list where you want the completer to be inserted.""" |
|
1110 | list where you want the completer to be inserted.""" | |
1111 |
|
1111 | |||
1112 | newcomp = new.instancemethod(completer,self.Completer, |
|
1112 | newcomp = new.instancemethod(completer,self.Completer, | |
1113 | self.Completer.__class__) |
|
1113 | self.Completer.__class__) | |
1114 | self.Completer.matchers.insert(pos,newcomp) |
|
1114 | self.Completer.matchers.insert(pos,newcomp) | |
1115 |
|
1115 | |||
1116 | def set_completer(self): |
|
1116 | def set_completer(self): | |
1117 | """reset readline's completer to be our own.""" |
|
1117 | """reset readline's completer to be our own.""" | |
1118 | self.readline.set_completer(self.Completer.complete) |
|
1118 | self.readline.set_completer(self.Completer.complete) | |
1119 |
|
1119 | |||
1120 | def _get_call_pdb(self): |
|
1120 | def _get_call_pdb(self): | |
1121 | return self._call_pdb |
|
1121 | return self._call_pdb | |
1122 |
|
1122 | |||
1123 | def _set_call_pdb(self,val): |
|
1123 | def _set_call_pdb(self,val): | |
1124 |
|
1124 | |||
1125 | if val not in (0,1,False,True): |
|
1125 | if val not in (0,1,False,True): | |
1126 | raise ValueError,'new call_pdb value must be boolean' |
|
1126 | raise ValueError,'new call_pdb value must be boolean' | |
1127 |
|
1127 | |||
1128 | # store value in instance |
|
1128 | # store value in instance | |
1129 | self._call_pdb = val |
|
1129 | self._call_pdb = val | |
1130 |
|
1130 | |||
1131 | # notify the actual exception handlers |
|
1131 | # notify the actual exception handlers | |
1132 | self.InteractiveTB.call_pdb = val |
|
1132 | self.InteractiveTB.call_pdb = val | |
1133 | if self.isthreaded: |
|
1133 | if self.isthreaded: | |
1134 | try: |
|
1134 | try: | |
1135 | self.sys_excepthook.call_pdb = val |
|
1135 | self.sys_excepthook.call_pdb = val | |
1136 | except: |
|
1136 | except: | |
1137 | warn('Failed to activate pdb for threaded exception handler') |
|
1137 | warn('Failed to activate pdb for threaded exception handler') | |
1138 |
|
1138 | |||
1139 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1139 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
1140 | 'Control auto-activation of pdb at exceptions') |
|
1140 | 'Control auto-activation of pdb at exceptions') | |
1141 |
|
1141 | |||
1142 | # These special functions get installed in the builtin namespace, to |
|
1142 | # These special functions get installed in the builtin namespace, to | |
1143 | # provide programmatic (pure python) access to magics, aliases and system |
|
1143 | # provide programmatic (pure python) access to magics, aliases and system | |
1144 | # calls. This is important for logging, user scripting, and more. |
|
1144 | # calls. This is important for logging, user scripting, and more. | |
1145 |
|
1145 | |||
1146 | # We are basically exposing, via normal python functions, the three |
|
1146 | # We are basically exposing, via normal python functions, the three | |
1147 | # mechanisms in which ipython offers special call modes (magics for |
|
1147 | # mechanisms in which ipython offers special call modes (magics for | |
1148 | # internal control, aliases for direct system access via pre-selected |
|
1148 | # internal control, aliases for direct system access via pre-selected | |
1149 | # names, and !cmd for calling arbitrary system commands). |
|
1149 | # names, and !cmd for calling arbitrary system commands). | |
1150 |
|
1150 | |||
1151 | def ipmagic(self,arg_s): |
|
1151 | def ipmagic(self,arg_s): | |
1152 | """Call a magic function by name. |
|
1152 | """Call a magic function by name. | |
1153 |
|
1153 | |||
1154 | Input: a string containing the name of the magic function to call and any |
|
1154 | Input: a string containing the name of the magic function to call and any | |
1155 | additional arguments to be passed to the magic. |
|
1155 | additional arguments to be passed to the magic. | |
1156 |
|
1156 | |||
1157 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
1157 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
1158 | prompt: |
|
1158 | prompt: | |
1159 |
|
1159 | |||
1160 | In[1]: %name -opt foo bar |
|
1160 | In[1]: %name -opt foo bar | |
1161 |
|
1161 | |||
1162 | To call a magic without arguments, simply use ipmagic('name'). |
|
1162 | To call a magic without arguments, simply use ipmagic('name'). | |
1163 |
|
1163 | |||
1164 | This provides a proper Python function to call IPython's magics in any |
|
1164 | This provides a proper Python function to call IPython's magics in any | |
1165 | valid Python code you can type at the interpreter, including loops and |
|
1165 | valid Python code you can type at the interpreter, including loops and | |
1166 | compound statements. It is added by IPython to the Python builtin |
|
1166 | compound statements. It is added by IPython to the Python builtin | |
1167 | namespace upon initialization.""" |
|
1167 | namespace upon initialization.""" | |
1168 |
|
1168 | |||
1169 | args = arg_s.split(' ',1) |
|
1169 | args = arg_s.split(' ',1) | |
1170 | magic_name = args[0] |
|
1170 | magic_name = args[0] | |
1171 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
1171 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
1172 |
|
1172 | |||
1173 | try: |
|
1173 | try: | |
1174 | magic_args = args[1] |
|
1174 | magic_args = args[1] | |
1175 | except IndexError: |
|
1175 | except IndexError: | |
1176 | magic_args = '' |
|
1176 | magic_args = '' | |
1177 | fn = getattr(self,'magic_'+magic_name,None) |
|
1177 | fn = getattr(self,'magic_'+magic_name,None) | |
1178 | if fn is None: |
|
1178 | if fn is None: | |
1179 | error("Magic function `%s` not found." % magic_name) |
|
1179 | error("Magic function `%s` not found." % magic_name) | |
1180 | else: |
|
1180 | else: | |
1181 | magic_args = self.var_expand(magic_args,1) |
|
1181 | magic_args = self.var_expand(magic_args,1) | |
1182 | return fn(magic_args) |
|
1182 | return fn(magic_args) | |
1183 |
|
1183 | |||
1184 | def ipalias(self,arg_s): |
|
1184 | def ipalias(self,arg_s): | |
1185 | """Call an alias by name. |
|
1185 | """Call an alias by name. | |
1186 |
|
1186 | |||
1187 | Input: a string containing the name of the alias to call and any |
|
1187 | Input: a string containing the name of the alias to call and any | |
1188 | additional arguments to be passed to the magic. |
|
1188 | additional arguments to be passed to the magic. | |
1189 |
|
1189 | |||
1190 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
1190 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
1191 | prompt: |
|
1191 | prompt: | |
1192 |
|
1192 | |||
1193 | In[1]: name -opt foo bar |
|
1193 | In[1]: name -opt foo bar | |
1194 |
|
1194 | |||
1195 | To call an alias without arguments, simply use ipalias('name'). |
|
1195 | To call an alias without arguments, simply use ipalias('name'). | |
1196 |
|
1196 | |||
1197 | This provides a proper Python function to call IPython's aliases in any |
|
1197 | This provides a proper Python function to call IPython's aliases in any | |
1198 | valid Python code you can type at the interpreter, including loops and |
|
1198 | valid Python code you can type at the interpreter, including loops and | |
1199 | compound statements. It is added by IPython to the Python builtin |
|
1199 | compound statements. It is added by IPython to the Python builtin | |
1200 | namespace upon initialization.""" |
|
1200 | namespace upon initialization.""" | |
1201 |
|
1201 | |||
1202 | args = arg_s.split(' ',1) |
|
1202 | args = arg_s.split(' ',1) | |
1203 | alias_name = args[0] |
|
1203 | alias_name = args[0] | |
1204 | try: |
|
1204 | try: | |
1205 | alias_args = args[1] |
|
1205 | alias_args = args[1] | |
1206 | except IndexError: |
|
1206 | except IndexError: | |
1207 | alias_args = '' |
|
1207 | alias_args = '' | |
1208 | if alias_name in self.alias_table: |
|
1208 | if alias_name in self.alias_table: | |
1209 | self.call_alias(alias_name,alias_args) |
|
1209 | self.call_alias(alias_name,alias_args) | |
1210 | else: |
|
1210 | else: | |
1211 | error("Alias `%s` not found." % alias_name) |
|
1211 | error("Alias `%s` not found." % alias_name) | |
1212 |
|
1212 | |||
1213 | def ipsystem(self,arg_s): |
|
1213 | def ipsystem(self,arg_s): | |
1214 | """Make a system call, using IPython.""" |
|
1214 | """Make a system call, using IPython.""" | |
1215 |
|
1215 | |||
1216 | self.system(arg_s) |
|
1216 | self.system(arg_s) | |
1217 |
|
1217 | |||
1218 | def complete(self,text): |
|
1218 | def complete(self,text): | |
1219 | """Return a sorted list of all possible completions on text. |
|
1219 | """Return a sorted list of all possible completions on text. | |
1220 |
|
1220 | |||
1221 | Inputs: |
|
1221 | Inputs: | |
1222 |
|
1222 | |||
1223 | - text: a string of text to be completed on. |
|
1223 | - text: a string of text to be completed on. | |
1224 |
|
1224 | |||
1225 | This is a wrapper around the completion mechanism, similar to what |
|
1225 | This is a wrapper around the completion mechanism, similar to what | |
1226 | readline does at the command line when the TAB key is hit. By |
|
1226 | readline does at the command line when the TAB key is hit. By | |
1227 | exposing it as a method, it can be used by other non-readline |
|
1227 | exposing it as a method, it can be used by other non-readline | |
1228 | environments (such as GUIs) for text completion. |
|
1228 | environments (such as GUIs) for text completion. | |
1229 |
|
1229 | |||
1230 | Simple usage example: |
|
1230 | Simple usage example: | |
1231 |
|
1231 | |||
1232 | In [7]: x = 'hello' |
|
1232 | In [7]: x = 'hello' | |
1233 |
|
1233 | |||
1234 | In [8]: x |
|
1234 | In [8]: x | |
1235 | Out[8]: 'hello' |
|
1235 | Out[8]: 'hello' | |
1236 |
|
1236 | |||
1237 | In [9]: print x |
|
1237 | In [9]: print x | |
1238 | hello |
|
1238 | hello | |
1239 |
|
1239 | |||
1240 | In [10]: _ip.IP.complete('x.l') |
|
1240 | In [10]: _ip.IP.complete('x.l') | |
1241 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1241 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1242 | """ |
|
1242 | """ | |
1243 |
|
1243 | |||
1244 | complete = self.Completer.complete |
|
1244 | complete = self.Completer.complete | |
1245 | state = 0 |
|
1245 | state = 0 | |
1246 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1246 | # use a dict so we get unique keys, since ipyhton's multiple | |
1247 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1247 | # completers can return duplicates. When we make 2.4 a requirement, | |
1248 | # start using sets instead, which are faster. |
|
1248 | # start using sets instead, which are faster. | |
1249 | comps = {} |
|
1249 | comps = {} | |
1250 | while True: |
|
1250 | while True: | |
1251 | newcomp = complete(text,state,line_buffer=text) |
|
1251 | newcomp = complete(text,state,line_buffer=text) | |
1252 | if newcomp is None: |
|
1252 | if newcomp is None: | |
1253 | break |
|
1253 | break | |
1254 | comps[newcomp] = 1 |
|
1254 | comps[newcomp] = 1 | |
1255 | state += 1 |
|
1255 | state += 1 | |
1256 | outcomps = comps.keys() |
|
1256 | outcomps = comps.keys() | |
1257 | outcomps.sort() |
|
1257 | outcomps.sort() | |
1258 | #print "T:",text,"OC:",outcomps # dbg |
|
1258 | #print "T:",text,"OC:",outcomps # dbg | |
1259 | #print "vars:",self.user_ns.keys() |
|
1259 | #print "vars:",self.user_ns.keys() | |
1260 | return outcomps |
|
1260 | return outcomps | |
1261 |
|
1261 | |||
1262 | def set_completer_frame(self, frame=None): |
|
1262 | def set_completer_frame(self, frame=None): | |
1263 | if not self.has_readline: |
|
1263 | if not self.has_readline: | |
1264 | return |
|
1264 | return | |
1265 | if frame: |
|
1265 | if frame: | |
1266 | self.Completer.namespace = frame.f_locals |
|
1266 | self.Completer.namespace = frame.f_locals | |
1267 | self.Completer.global_namespace = frame.f_globals |
|
1267 | self.Completer.global_namespace = frame.f_globals | |
1268 | else: |
|
1268 | else: | |
1269 | self.Completer.namespace = self.user_ns |
|
1269 | self.Completer.namespace = self.user_ns | |
1270 | self.Completer.global_namespace = self.user_global_ns |
|
1270 | self.Completer.global_namespace = self.user_global_ns | |
1271 |
|
1271 | |||
1272 | def init_auto_alias(self): |
|
1272 | def init_auto_alias(self): | |
1273 | """Define some aliases automatically. |
|
1273 | """Define some aliases automatically. | |
1274 |
|
1274 | |||
1275 | These are ALL parameter-less aliases""" |
|
1275 | These are ALL parameter-less aliases""" | |
1276 |
|
1276 | |||
1277 | for alias,cmd in self.auto_alias: |
|
1277 | for alias,cmd in self.auto_alias: | |
1278 | self.getapi().defalias(alias,cmd) |
|
1278 | self.getapi().defalias(alias,cmd) | |
1279 |
|
1279 | |||
1280 |
|
1280 | |||
1281 | def alias_table_validate(self,verbose=0): |
|
1281 | def alias_table_validate(self,verbose=0): | |
1282 | """Update information about the alias table. |
|
1282 | """Update information about the alias table. | |
1283 |
|
1283 | |||
1284 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1284 | In particular, make sure no Python keywords/builtins are in it.""" | |
1285 |
|
1285 | |||
1286 | no_alias = self.no_alias |
|
1286 | no_alias = self.no_alias | |
1287 | for k in self.alias_table.keys(): |
|
1287 | for k in self.alias_table.keys(): | |
1288 | if k in no_alias: |
|
1288 | if k in no_alias: | |
1289 | del self.alias_table[k] |
|
1289 | del self.alias_table[k] | |
1290 | if verbose: |
|
1290 | if verbose: | |
1291 | print ("Deleting alias <%s>, it's a Python " |
|
1291 | print ("Deleting alias <%s>, it's a Python " | |
1292 | "keyword or builtin." % k) |
|
1292 | "keyword or builtin." % k) | |
1293 |
|
1293 | |||
1294 | def set_autoindent(self,value=None): |
|
1294 | def set_autoindent(self,value=None): | |
1295 | """Set the autoindent flag, checking for readline support. |
|
1295 | """Set the autoindent flag, checking for readline support. | |
1296 |
|
1296 | |||
1297 | If called with no arguments, it acts as a toggle.""" |
|
1297 | If called with no arguments, it acts as a toggle.""" | |
1298 |
|
1298 | |||
1299 | if not self.has_readline: |
|
1299 | if not self.has_readline: | |
1300 | if os.name == 'posix': |
|
1300 | if os.name == 'posix': | |
1301 | warn("The auto-indent feature requires the readline library") |
|
1301 | warn("The auto-indent feature requires the readline library") | |
1302 | self.autoindent = 0 |
|
1302 | self.autoindent = 0 | |
1303 | return |
|
1303 | return | |
1304 | if value is None: |
|
1304 | if value is None: | |
1305 | self.autoindent = not self.autoindent |
|
1305 | self.autoindent = not self.autoindent | |
1306 | else: |
|
1306 | else: | |
1307 | self.autoindent = value |
|
1307 | self.autoindent = value | |
1308 |
|
1308 | |||
1309 | def rc_set_toggle(self,rc_field,value=None): |
|
1309 | def rc_set_toggle(self,rc_field,value=None): | |
1310 | """Set or toggle a field in IPython's rc config. structure. |
|
1310 | """Set or toggle a field in IPython's rc config. structure. | |
1311 |
|
1311 | |||
1312 | If called with no arguments, it acts as a toggle. |
|
1312 | If called with no arguments, it acts as a toggle. | |
1313 |
|
1313 | |||
1314 | If called with a non-existent field, the resulting AttributeError |
|
1314 | If called with a non-existent field, the resulting AttributeError | |
1315 | exception will propagate out.""" |
|
1315 | exception will propagate out.""" | |
1316 |
|
1316 | |||
1317 | rc_val = getattr(self.rc,rc_field) |
|
1317 | rc_val = getattr(self.rc,rc_field) | |
1318 | if value is None: |
|
1318 | if value is None: | |
1319 | value = not rc_val |
|
1319 | value = not rc_val | |
1320 | setattr(self.rc,rc_field,value) |
|
1320 | setattr(self.rc,rc_field,value) | |
1321 |
|
1321 | |||
1322 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1322 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
1323 | """Install the user configuration directory. |
|
1323 | """Install the user configuration directory. | |
1324 |
|
1324 | |||
1325 | Notes |
|
1325 | Notes | |
1326 | ----- |
|
1326 | ----- | |
1327 | DEPRECATED: use the top-level user_setup() function instead. |
|
1327 | DEPRECATED: use the top-level user_setup() function instead. | |
1328 | """ |
|
1328 | """ | |
1329 | return user_setup(ipythondir,rc_suffix,mode) |
|
1329 | return user_setup(ipythondir,rc_suffix,mode) | |
1330 |
|
1330 | |||
1331 | def atexit_operations(self): |
|
1331 | def atexit_operations(self): | |
1332 | """This will be executed at the time of exit. |
|
1332 | """This will be executed at the time of exit. | |
1333 |
|
1333 | |||
1334 | Saving of persistent data should be performed here. """ |
|
1334 | Saving of persistent data should be performed here. """ | |
1335 |
|
1335 | |||
1336 | #print '*** IPython exit cleanup ***' # dbg |
|
1336 | #print '*** IPython exit cleanup ***' # dbg | |
1337 | # input history |
|
1337 | # input history | |
1338 | self.savehist() |
|
1338 | self.savehist() | |
1339 |
|
1339 | |||
1340 | # Cleanup all tempfiles left around |
|
1340 | # Cleanup all tempfiles left around | |
1341 | for tfile in self.tempfiles: |
|
1341 | for tfile in self.tempfiles: | |
1342 | try: |
|
1342 | try: | |
1343 | os.unlink(tfile) |
|
1343 | os.unlink(tfile) | |
1344 | except OSError: |
|
1344 | except OSError: | |
1345 | pass |
|
1345 | pass | |
1346 |
|
1346 | |||
1347 | # Clear all user namespaces to release all references cleanly. |
|
1347 | # Clear all user namespaces to release all references cleanly. | |
1348 | self.reset() |
|
1348 | self.reset() | |
1349 |
|
1349 | |||
1350 | # Run user hooks |
|
1350 | # Run user hooks | |
1351 | self.hooks.shutdown_hook() |
|
1351 | self.hooks.shutdown_hook() | |
1352 |
|
1352 | |||
1353 | def reset(self): |
|
1353 | def reset(self): | |
1354 | """Clear all internal namespaces. |
|
1354 | """Clear all internal namespaces. | |
1355 |
|
1355 | |||
1356 | Note that this is much more aggressive than %reset, since it clears |
|
1356 | Note that this is much more aggressive than %reset, since it clears | |
1357 | fully all namespaces, as well as all input/output lists. |
|
1357 | fully all namespaces, as well as all input/output lists. | |
1358 | """ |
|
1358 | """ | |
1359 | for ns in self.ns_refs_table: |
|
1359 | for ns in self.ns_refs_table: | |
1360 | ns.clear() |
|
1360 | ns.clear() | |
1361 |
|
1361 | |||
1362 | # Clear input and output histories |
|
1362 | # Clear input and output histories | |
1363 | self.input_hist[:] = [] |
|
1363 | self.input_hist[:] = [] | |
1364 | self.input_hist_raw[:] = [] |
|
1364 | self.input_hist_raw[:] = [] | |
1365 | self.output_hist.clear() |
|
1365 | self.output_hist.clear() | |
1366 | # Restore the user namespaces to minimal usability |
|
1366 | # Restore the user namespaces to minimal usability | |
1367 | self.init_namespaces() |
|
1367 | self.init_namespaces() | |
1368 |
|
1368 | |||
1369 | def savehist(self): |
|
1369 | def savehist(self): | |
1370 | """Save input history to a file (via readline library).""" |
|
1370 | """Save input history to a file (via readline library).""" | |
1371 |
|
1371 | |||
1372 | if not self.has_readline: |
|
1372 | if not self.has_readline: | |
1373 | return |
|
1373 | return | |
1374 |
|
1374 | |||
1375 | try: |
|
1375 | try: | |
1376 | self.readline.write_history_file(self.histfile) |
|
1376 | self.readline.write_history_file(self.histfile) | |
1377 | except: |
|
1377 | except: | |
1378 | print 'Unable to save IPython command history to file: ' + \ |
|
1378 | print 'Unable to save IPython command history to file: ' + \ | |
1379 | `self.histfile` |
|
1379 | `self.histfile` | |
1380 |
|
1380 | |||
1381 | def reloadhist(self): |
|
1381 | def reloadhist(self): | |
1382 | """Reload the input history from disk file.""" |
|
1382 | """Reload the input history from disk file.""" | |
1383 |
|
1383 | |||
1384 | if self.has_readline: |
|
1384 | if self.has_readline: | |
1385 | try: |
|
1385 | try: | |
1386 | self.readline.clear_history() |
|
1386 | self.readline.clear_history() | |
1387 | self.readline.read_history_file(self.shell.histfile) |
|
1387 | self.readline.read_history_file(self.shell.histfile) | |
1388 | except AttributeError: |
|
1388 | except AttributeError: | |
1389 | pass |
|
1389 | pass | |
1390 |
|
1390 | |||
1391 |
|
1391 | |||
1392 | def history_saving_wrapper(self, func): |
|
1392 | def history_saving_wrapper(self, func): | |
1393 | """ Wrap func for readline history saving |
|
1393 | """ Wrap func for readline history saving | |
1394 |
|
1394 | |||
1395 | Convert func into callable that saves & restores |
|
1395 | Convert func into callable that saves & restores | |
1396 | history around the call """ |
|
1396 | history around the call """ | |
1397 |
|
1397 | |||
1398 | if not self.has_readline: |
|
1398 | if not self.has_readline: | |
1399 | return func |
|
1399 | return func | |
1400 |
|
1400 | |||
1401 | def wrapper(): |
|
1401 | def wrapper(): | |
1402 | self.savehist() |
|
1402 | self.savehist() | |
1403 | try: |
|
1403 | try: | |
1404 | func() |
|
1404 | func() | |
1405 | finally: |
|
1405 | finally: | |
1406 | readline.read_history_file(self.histfile) |
|
1406 | readline.read_history_file(self.histfile) | |
1407 | return wrapper |
|
1407 | return wrapper | |
1408 |
|
1408 | |||
1409 | def pre_readline(self): |
|
1409 | def pre_readline(self): | |
1410 | """readline hook to be used at the start of each line. |
|
1410 | """readline hook to be used at the start of each line. | |
1411 |
|
1411 | |||
1412 | Currently it handles auto-indent only.""" |
|
1412 | Currently it handles auto-indent only.""" | |
1413 |
|
1413 | |||
1414 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1414 | #debugx('self.indent_current_nsp','pre_readline:') | |
1415 |
|
1415 | |||
1416 | if self.rl_do_indent: |
|
1416 | if self.rl_do_indent: | |
1417 | self.readline.insert_text(self.indent_current_str()) |
|
1417 | self.readline.insert_text(self.indent_current_str()) | |
1418 | if self.rl_next_input is not None: |
|
1418 | if self.rl_next_input is not None: | |
1419 | self.readline.insert_text(self.rl_next_input) |
|
1419 | self.readline.insert_text(self.rl_next_input) | |
1420 | self.rl_next_input = None |
|
1420 | self.rl_next_input = None | |
1421 |
|
1421 | |||
1422 | def init_readline(self): |
|
1422 | def init_readline(self): | |
1423 | """Command history completion/saving/reloading.""" |
|
1423 | """Command history completion/saving/reloading.""" | |
1424 |
|
1424 | |||
1425 |
|
1425 | |||
1426 | import IPython.rlineimpl as readline |
|
1426 | import IPython.rlineimpl as readline | |
1427 |
|
1427 | |||
1428 | if not readline.have_readline: |
|
1428 | if not readline.have_readline: | |
1429 | self.has_readline = 0 |
|
1429 | self.has_readline = 0 | |
1430 | self.readline = None |
|
1430 | self.readline = None | |
1431 | # no point in bugging windows users with this every time: |
|
1431 | # no point in bugging windows users with this every time: | |
1432 | warn('Readline services not available on this platform.') |
|
1432 | warn('Readline services not available on this platform.') | |
1433 | else: |
|
1433 | else: | |
1434 | sys.modules['readline'] = readline |
|
1434 | sys.modules['readline'] = readline | |
1435 | import atexit |
|
1435 | import atexit | |
1436 | from IPython.completer import IPCompleter |
|
1436 | from IPython.completer import IPCompleter | |
1437 | self.Completer = IPCompleter(self, |
|
1437 | self.Completer = IPCompleter(self, | |
1438 | self.user_ns, |
|
1438 | self.user_ns, | |
1439 | self.user_global_ns, |
|
1439 | self.user_global_ns, | |
1440 | self.rc.readline_omit__names, |
|
1440 | self.rc.readline_omit__names, | |
1441 | self.alias_table) |
|
1441 | self.alias_table) | |
1442 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1442 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1443 | self.strdispatchers['complete_command'] = sdisp |
|
1443 | self.strdispatchers['complete_command'] = sdisp | |
1444 | self.Completer.custom_completers = sdisp |
|
1444 | self.Completer.custom_completers = sdisp | |
1445 | # Platform-specific configuration |
|
1445 | # Platform-specific configuration | |
1446 | if os.name == 'nt': |
|
1446 | if os.name == 'nt': | |
1447 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1447 | self.readline_startup_hook = readline.set_pre_input_hook | |
1448 | else: |
|
1448 | else: | |
1449 | self.readline_startup_hook = readline.set_startup_hook |
|
1449 | self.readline_startup_hook = readline.set_startup_hook | |
1450 |
|
1450 | |||
1451 | # Load user's initrc file (readline config) |
|
1451 | # Load user's initrc file (readline config) | |
1452 | # Or if libedit is used, load editrc. |
|
1452 | # Or if libedit is used, load editrc. | |
1453 | inputrc_name = os.environ.get('INPUTRC') |
|
1453 | inputrc_name = os.environ.get('INPUTRC') | |
1454 | if inputrc_name is None: |
|
1454 | if inputrc_name is None: | |
1455 | home_dir = get_home_dir() |
|
1455 | home_dir = get_home_dir() | |
1456 | if home_dir is not None: |
|
1456 | if home_dir is not None: | |
1457 | inputrc_name = '.inputrc' |
|
1457 | inputrc_name = '.inputrc' | |
1458 | if readline.uses_libedit: |
|
1458 | if readline.uses_libedit: | |
1459 | inputrc_name = '.editrc' |
|
1459 | inputrc_name = '.editrc' | |
1460 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1460 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1461 | if os.path.isfile(inputrc_name): |
|
1461 | if os.path.isfile(inputrc_name): | |
1462 | try: |
|
1462 | try: | |
1463 | readline.read_init_file(inputrc_name) |
|
1463 | readline.read_init_file(inputrc_name) | |
1464 | except: |
|
1464 | except: | |
1465 | warn('Problems reading readline initialization file <%s>' |
|
1465 | warn('Problems reading readline initialization file <%s>' | |
1466 | % inputrc_name) |
|
1466 | % inputrc_name) | |
1467 |
|
1467 | |||
1468 | self.has_readline = 1 |
|
1468 | self.has_readline = 1 | |
1469 | self.readline = readline |
|
1469 | self.readline = readline | |
1470 | # save this in sys so embedded copies can restore it properly |
|
1470 | # save this in sys so embedded copies can restore it properly | |
1471 | sys.ipcompleter = self.Completer.complete |
|
1471 | sys.ipcompleter = self.Completer.complete | |
1472 | self.set_completer() |
|
1472 | self.set_completer() | |
1473 |
|
1473 | |||
1474 | # Configure readline according to user's prefs |
|
1474 | # Configure readline according to user's prefs | |
1475 | # This is only done if GNU readline is being used. If libedit |
|
1475 | # This is only done if GNU readline is being used. If libedit | |
1476 | # is being used (as on Leopard) the readline config is |
|
1476 | # is being used (as on Leopard) the readline config is | |
1477 | # not run as the syntax for libedit is different. |
|
1477 | # not run as the syntax for libedit is different. | |
1478 | if not readline.uses_libedit: |
|
1478 | if not readline.uses_libedit: | |
1479 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1479 | for rlcommand in self.rc.readline_parse_and_bind: | |
1480 | #print "loading rl:",rlcommand # dbg |
|
1480 | #print "loading rl:",rlcommand # dbg | |
1481 | readline.parse_and_bind(rlcommand) |
|
1481 | readline.parse_and_bind(rlcommand) | |
1482 |
|
1482 | |||
1483 | # Remove some chars from the delimiters list. If we encounter |
|
1483 | # Remove some chars from the delimiters list. If we encounter | |
1484 | # unicode chars, discard them. |
|
1484 | # unicode chars, discard them. | |
1485 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1485 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1486 | delims = delims.translate(string._idmap, |
|
1486 | delims = delims.translate(string._idmap, | |
1487 | self.rc.readline_remove_delims) |
|
1487 | self.rc.readline_remove_delims) | |
1488 | readline.set_completer_delims(delims) |
|
1488 | readline.set_completer_delims(delims) | |
1489 | # otherwise we end up with a monster history after a while: |
|
1489 | # otherwise we end up with a monster history after a while: | |
1490 | readline.set_history_length(1000) |
|
1490 | readline.set_history_length(1000) | |
1491 | try: |
|
1491 | try: | |
1492 | #print '*** Reading readline history' # dbg |
|
1492 | #print '*** Reading readline history' # dbg | |
1493 | readline.read_history_file(self.histfile) |
|
1493 | readline.read_history_file(self.histfile) | |
1494 | except IOError: |
|
1494 | except IOError: | |
1495 | pass # It doesn't exist yet. |
|
1495 | pass # It doesn't exist yet. | |
1496 |
|
1496 | |||
1497 | atexit.register(self.atexit_operations) |
|
1497 | atexit.register(self.atexit_operations) | |
1498 | del atexit |
|
1498 | del atexit | |
1499 |
|
1499 | |||
1500 | # Configure auto-indent for all platforms |
|
1500 | # Configure auto-indent for all platforms | |
1501 | self.set_autoindent(self.rc.autoindent) |
|
1501 | self.set_autoindent(self.rc.autoindent) | |
1502 |
|
1502 | |||
1503 | def ask_yes_no(self,prompt,default=True): |
|
1503 | def ask_yes_no(self,prompt,default=True): | |
1504 | if self.rc.quiet: |
|
1504 | if self.rc.quiet: | |
1505 | return True |
|
1505 | return True | |
1506 | return ask_yes_no(prompt,default) |
|
1506 | return ask_yes_no(prompt,default) | |
1507 |
|
1507 | |||
1508 | def new_main_mod(self,ns=None): |
|
1508 | def new_main_mod(self,ns=None): | |
1509 | """Return a new 'main' module object for user code execution. |
|
1509 | """Return a new 'main' module object for user code execution. | |
1510 | """ |
|
1510 | """ | |
1511 | main_mod = self._user_main_module |
|
1511 | main_mod = self._user_main_module | |
1512 | init_fakemod_dict(main_mod,ns) |
|
1512 | init_fakemod_dict(main_mod,ns) | |
1513 | return main_mod |
|
1513 | return main_mod | |
1514 |
|
1514 | |||
1515 | def cache_main_mod(self,ns,fname): |
|
1515 | def cache_main_mod(self,ns,fname): | |
1516 | """Cache a main module's namespace. |
|
1516 | """Cache a main module's namespace. | |
1517 |
|
1517 | |||
1518 | When scripts are executed via %run, we must keep a reference to the |
|
1518 | When scripts are executed via %run, we must keep a reference to the | |
1519 | namespace of their __main__ module (a FakeModule instance) around so |
|
1519 | namespace of their __main__ module (a FakeModule instance) around so | |
1520 | that Python doesn't clear it, rendering objects defined therein |
|
1520 | that Python doesn't clear it, rendering objects defined therein | |
1521 | useless. |
|
1521 | useless. | |
1522 |
|
1522 | |||
1523 | This method keeps said reference in a private dict, keyed by the |
|
1523 | This method keeps said reference in a private dict, keyed by the | |
1524 | absolute path of the module object (which corresponds to the script |
|
1524 | absolute path of the module object (which corresponds to the script | |
1525 | path). This way, for multiple executions of the same script we only |
|
1525 | path). This way, for multiple executions of the same script we only | |
1526 | keep one copy of the namespace (the last one), thus preventing memory |
|
1526 | keep one copy of the namespace (the last one), thus preventing memory | |
1527 | leaks from old references while allowing the objects from the last |
|
1527 | leaks from old references while allowing the objects from the last | |
1528 | execution to be accessible. |
|
1528 | execution to be accessible. | |
1529 |
|
1529 | |||
1530 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
1530 | Note: we can not allow the actual FakeModule instances to be deleted, | |
1531 | because of how Python tears down modules (it hard-sets all their |
|
1531 | because of how Python tears down modules (it hard-sets all their | |
1532 | references to None without regard for reference counts). This method |
|
1532 | references to None without regard for reference counts). This method | |
1533 | must therefore make a *copy* of the given namespace, to allow the |
|
1533 | must therefore make a *copy* of the given namespace, to allow the | |
1534 | original module's __dict__ to be cleared and reused. |
|
1534 | original module's __dict__ to be cleared and reused. | |
1535 |
|
1535 | |||
1536 |
|
1536 | |||
1537 | Parameters |
|
1537 | Parameters | |
1538 | ---------- |
|
1538 | ---------- | |
1539 | ns : a namespace (a dict, typically) |
|
1539 | ns : a namespace (a dict, typically) | |
1540 |
|
1540 | |||
1541 | fname : str |
|
1541 | fname : str | |
1542 | Filename associated with the namespace. |
|
1542 | Filename associated with the namespace. | |
1543 |
|
1543 | |||
1544 | Examples |
|
1544 | Examples | |
1545 | -------- |
|
1545 | -------- | |
1546 |
|
1546 | |||
1547 | In [10]: import IPython |
|
1547 | In [10]: import IPython | |
1548 |
|
1548 | |||
1549 | In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1549 | In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) | |
1550 |
|
1550 | |||
1551 | In [12]: IPython.__file__ in _ip.IP._main_ns_cache |
|
1551 | In [12]: IPython.__file__ in _ip.IP._main_ns_cache | |
1552 | Out[12]: True |
|
1552 | Out[12]: True | |
1553 | """ |
|
1553 | """ | |
1554 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
1554 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
1555 |
|
1555 | |||
1556 | def clear_main_mod_cache(self): |
|
1556 | def clear_main_mod_cache(self): | |
1557 | """Clear the cache of main modules. |
|
1557 | """Clear the cache of main modules. | |
1558 |
|
1558 | |||
1559 | Mainly for use by utilities like %reset. |
|
1559 | Mainly for use by utilities like %reset. | |
1560 |
|
1560 | |||
1561 | Examples |
|
1561 | Examples | |
1562 | -------- |
|
1562 | -------- | |
1563 |
|
1563 | |||
1564 | In [15]: import IPython |
|
1564 | In [15]: import IPython | |
1565 |
|
1565 | |||
1566 | In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
1566 | In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__) | |
1567 |
|
1567 | |||
1568 | In [17]: len(_ip.IP._main_ns_cache) > 0 |
|
1568 | In [17]: len(_ip.IP._main_ns_cache) > 0 | |
1569 | Out[17]: True |
|
1569 | Out[17]: True | |
1570 |
|
1570 | |||
1571 | In [18]: _ip.IP.clear_main_mod_cache() |
|
1571 | In [18]: _ip.IP.clear_main_mod_cache() | |
1572 |
|
1572 | |||
1573 | In [19]: len(_ip.IP._main_ns_cache) == 0 |
|
1573 | In [19]: len(_ip.IP._main_ns_cache) == 0 | |
1574 | Out[19]: True |
|
1574 | Out[19]: True | |
1575 | """ |
|
1575 | """ | |
1576 | self._main_ns_cache.clear() |
|
1576 | self._main_ns_cache.clear() | |
1577 |
|
1577 | |||
1578 | def _should_recompile(self,e): |
|
1578 | def _should_recompile(self,e): | |
1579 | """Utility routine for edit_syntax_error""" |
|
1579 | """Utility routine for edit_syntax_error""" | |
1580 |
|
1580 | |||
1581 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1581 | if e.filename in ('<ipython console>','<input>','<string>', | |
1582 | '<console>','<BackgroundJob compilation>', |
|
1582 | '<console>','<BackgroundJob compilation>', | |
1583 | None): |
|
1583 | None): | |
1584 |
|
1584 | |||
1585 | return False |
|
1585 | return False | |
1586 | try: |
|
1586 | try: | |
1587 | if (self.rc.autoedit_syntax and |
|
1587 | if (self.rc.autoedit_syntax and | |
1588 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1588 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1589 | '[Y/n] ','y')): |
|
1589 | '[Y/n] ','y')): | |
1590 | return False |
|
1590 | return False | |
1591 | except EOFError: |
|
1591 | except EOFError: | |
1592 | return False |
|
1592 | return False | |
1593 |
|
1593 | |||
1594 | def int0(x): |
|
1594 | def int0(x): | |
1595 | try: |
|
1595 | try: | |
1596 | return int(x) |
|
1596 | return int(x) | |
1597 | except TypeError: |
|
1597 | except TypeError: | |
1598 | return 0 |
|
1598 | return 0 | |
1599 | # always pass integer line and offset values to editor hook |
|
1599 | # always pass integer line and offset values to editor hook | |
1600 | try: |
|
1600 | try: | |
1601 | self.hooks.fix_error_editor(e.filename, |
|
1601 | self.hooks.fix_error_editor(e.filename, | |
1602 | int0(e.lineno),int0(e.offset),e.msg) |
|
1602 | int0(e.lineno),int0(e.offset),e.msg) | |
1603 | except IPython.ipapi.TryNext: |
|
1603 | except IPython.ipapi.TryNext: | |
1604 | warn('Could not open editor') |
|
1604 | warn('Could not open editor') | |
1605 | return False |
|
1605 | return False | |
1606 | return True |
|
1606 | return True | |
1607 |
|
1607 | |||
1608 | def edit_syntax_error(self): |
|
1608 | def edit_syntax_error(self): | |
1609 | """The bottom half of the syntax error handler called in the main loop. |
|
1609 | """The bottom half of the syntax error handler called in the main loop. | |
1610 |
|
1610 | |||
1611 | Loop until syntax error is fixed or user cancels. |
|
1611 | Loop until syntax error is fixed or user cancels. | |
1612 | """ |
|
1612 | """ | |
1613 |
|
1613 | |||
1614 | while self.SyntaxTB.last_syntax_error: |
|
1614 | while self.SyntaxTB.last_syntax_error: | |
1615 | # copy and clear last_syntax_error |
|
1615 | # copy and clear last_syntax_error | |
1616 | err = self.SyntaxTB.clear_err_state() |
|
1616 | err = self.SyntaxTB.clear_err_state() | |
1617 | if not self._should_recompile(err): |
|
1617 | if not self._should_recompile(err): | |
1618 | return |
|
1618 | return | |
1619 | try: |
|
1619 | try: | |
1620 | # may set last_syntax_error again if a SyntaxError is raised |
|
1620 | # may set last_syntax_error again if a SyntaxError is raised | |
1621 | self.safe_execfile(err.filename,self.user_ns) |
|
1621 | self.safe_execfile(err.filename,self.user_ns) | |
1622 | except: |
|
1622 | except: | |
1623 | self.showtraceback() |
|
1623 | self.showtraceback() | |
1624 | else: |
|
1624 | else: | |
1625 | try: |
|
1625 | try: | |
1626 | f = file(err.filename) |
|
1626 | f = file(err.filename) | |
1627 | try: |
|
1627 | try: | |
1628 | sys.displayhook(f.read()) |
|
1628 | sys.displayhook(f.read()) | |
1629 | finally: |
|
1629 | finally: | |
1630 | f.close() |
|
1630 | f.close() | |
1631 | except: |
|
1631 | except: | |
1632 | self.showtraceback() |
|
1632 | self.showtraceback() | |
1633 |
|
1633 | |||
1634 | def showsyntaxerror(self, filename=None): |
|
1634 | def showsyntaxerror(self, filename=None): | |
1635 | """Display the syntax error that just occurred. |
|
1635 | """Display the syntax error that just occurred. | |
1636 |
|
1636 | |||
1637 | This doesn't display a stack trace because there isn't one. |
|
1637 | This doesn't display a stack trace because there isn't one. | |
1638 |
|
1638 | |||
1639 | If a filename is given, it is stuffed in the exception instead |
|
1639 | If a filename is given, it is stuffed in the exception instead | |
1640 | of what was there before (because Python's parser always uses |
|
1640 | of what was there before (because Python's parser always uses | |
1641 | "<string>" when reading from a string). |
|
1641 | "<string>" when reading from a string). | |
1642 | """ |
|
1642 | """ | |
1643 | etype, value, last_traceback = sys.exc_info() |
|
1643 | etype, value, last_traceback = sys.exc_info() | |
1644 |
|
1644 | |||
1645 | # See note about these variables in showtraceback() below |
|
1645 | # See note about these variables in showtraceback() below | |
1646 | sys.last_type = etype |
|
1646 | sys.last_type = etype | |
1647 | sys.last_value = value |
|
1647 | sys.last_value = value | |
1648 | sys.last_traceback = last_traceback |
|
1648 | sys.last_traceback = last_traceback | |
1649 |
|
1649 | |||
1650 | if filename and etype is SyntaxError: |
|
1650 | if filename and etype is SyntaxError: | |
1651 | # Work hard to stuff the correct filename in the exception |
|
1651 | # Work hard to stuff the correct filename in the exception | |
1652 | try: |
|
1652 | try: | |
1653 | msg, (dummy_filename, lineno, offset, line) = value |
|
1653 | msg, (dummy_filename, lineno, offset, line) = value | |
1654 | except: |
|
1654 | except: | |
1655 | # Not the format we expect; leave it alone |
|
1655 | # Not the format we expect; leave it alone | |
1656 | pass |
|
1656 | pass | |
1657 | else: |
|
1657 | else: | |
1658 | # Stuff in the right filename |
|
1658 | # Stuff in the right filename | |
1659 | try: |
|
1659 | try: | |
1660 | # Assume SyntaxError is a class exception |
|
1660 | # Assume SyntaxError is a class exception | |
1661 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1661 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1662 | except: |
|
1662 | except: | |
1663 | # If that failed, assume SyntaxError is a string |
|
1663 | # If that failed, assume SyntaxError is a string | |
1664 | value = msg, (filename, lineno, offset, line) |
|
1664 | value = msg, (filename, lineno, offset, line) | |
1665 | self.SyntaxTB(etype,value,[]) |
|
1665 | self.SyntaxTB(etype,value,[]) | |
1666 |
|
1666 | |||
1667 | def debugger(self,force=False): |
|
1667 | def debugger(self,force=False): | |
1668 | """Call the pydb/pdb debugger. |
|
1668 | """Call the pydb/pdb debugger. | |
1669 |
|
1669 | |||
1670 | Keywords: |
|
1670 | Keywords: | |
1671 |
|
1671 | |||
1672 | - force(False): by default, this routine checks the instance call_pdb |
|
1672 | - force(False): by default, this routine checks the instance call_pdb | |
1673 | flag and does not actually invoke the debugger if the flag is false. |
|
1673 | flag and does not actually invoke the debugger if the flag is false. | |
1674 | The 'force' option forces the debugger to activate even if the flag |
|
1674 | The 'force' option forces the debugger to activate even if the flag | |
1675 | is false. |
|
1675 | is false. | |
1676 | """ |
|
1676 | """ | |
1677 |
|
1677 | |||
1678 | if not (force or self.call_pdb): |
|
1678 | if not (force or self.call_pdb): | |
1679 | return |
|
1679 | return | |
1680 |
|
1680 | |||
1681 | if not hasattr(sys,'last_traceback'): |
|
1681 | if not hasattr(sys,'last_traceback'): | |
1682 | error('No traceback has been produced, nothing to debug.') |
|
1682 | error('No traceback has been produced, nothing to debug.') | |
1683 | return |
|
1683 | return | |
1684 |
|
1684 | |||
1685 | # use pydb if available |
|
1685 | # use pydb if available | |
1686 | if Debugger.has_pydb: |
|
1686 | if Debugger.has_pydb: | |
1687 | from pydb import pm |
|
1687 | from pydb import pm | |
1688 | else: |
|
1688 | else: | |
1689 | # fallback to our internal debugger |
|
1689 | # fallback to our internal debugger | |
1690 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1690 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
1691 | self.history_saving_wrapper(pm)() |
|
1691 | self.history_saving_wrapper(pm)() | |
1692 |
|
1692 | |||
1693 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1693 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1694 | """Display the exception that just occurred. |
|
1694 | """Display the exception that just occurred. | |
1695 |
|
1695 | |||
1696 | If nothing is known about the exception, this is the method which |
|
1696 | If nothing is known about the exception, this is the method which | |
1697 | should be used throughout the code for presenting user tracebacks, |
|
1697 | should be used throughout the code for presenting user tracebacks, | |
1698 | rather than directly invoking the InteractiveTB object. |
|
1698 | rather than directly invoking the InteractiveTB object. | |
1699 |
|
1699 | |||
1700 | A specific showsyntaxerror() also exists, but this method can take |
|
1700 | A specific showsyntaxerror() also exists, but this method can take | |
1701 | care of calling it if needed, so unless you are explicitly catching a |
|
1701 | care of calling it if needed, so unless you are explicitly catching a | |
1702 | SyntaxError exception, don't try to analyze the stack manually and |
|
1702 | SyntaxError exception, don't try to analyze the stack manually and | |
1703 | simply call this method.""" |
|
1703 | simply call this method.""" | |
1704 |
|
1704 | |||
1705 |
|
1705 | |||
1706 | # Though this won't be called by syntax errors in the input line, |
|
1706 | # Though this won't be called by syntax errors in the input line, | |
1707 | # there may be SyntaxError cases whith imported code. |
|
1707 | # there may be SyntaxError cases whith imported code. | |
1708 |
|
1708 | |||
1709 | try: |
|
1709 | try: | |
1710 | if exc_tuple is None: |
|
1710 | if exc_tuple is None: | |
1711 | etype, value, tb = sys.exc_info() |
|
1711 | etype, value, tb = sys.exc_info() | |
1712 | else: |
|
1712 | else: | |
1713 | etype, value, tb = exc_tuple |
|
1713 | etype, value, tb = exc_tuple | |
1714 |
|
1714 | |||
1715 | if etype is SyntaxError: |
|
1715 | if etype is SyntaxError: | |
1716 | self.showsyntaxerror(filename) |
|
1716 | self.showsyntaxerror(filename) | |
1717 | elif etype is IPython.ipapi.UsageError: |
|
1717 | elif etype is IPython.ipapi.UsageError: | |
1718 | print "UsageError:", value |
|
1718 | print "UsageError:", value | |
1719 | else: |
|
1719 | else: | |
1720 | # WARNING: these variables are somewhat deprecated and not |
|
1720 | # WARNING: these variables are somewhat deprecated and not | |
1721 | # necessarily safe to use in a threaded environment, but tools |
|
1721 | # necessarily safe to use in a threaded environment, but tools | |
1722 | # like pdb depend on their existence, so let's set them. If we |
|
1722 | # like pdb depend on their existence, so let's set them. If we | |
1723 | # find problems in the field, we'll need to revisit their use. |
|
1723 | # find problems in the field, we'll need to revisit their use. | |
1724 | sys.last_type = etype |
|
1724 | sys.last_type = etype | |
1725 | sys.last_value = value |
|
1725 | sys.last_value = value | |
1726 | sys.last_traceback = tb |
|
1726 | sys.last_traceback = tb | |
1727 |
|
1727 | |||
1728 | if etype in self.custom_exceptions: |
|
1728 | if etype in self.custom_exceptions: | |
1729 | self.CustomTB(etype,value,tb) |
|
1729 | self.CustomTB(etype,value,tb) | |
1730 | else: |
|
1730 | else: | |
1731 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1731 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1732 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1732 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1733 | # pdb mucks up readline, fix it back |
|
1733 | # pdb mucks up readline, fix it back | |
1734 | self.set_completer() |
|
1734 | self.set_completer() | |
1735 | except KeyboardInterrupt: |
|
1735 | except KeyboardInterrupt: | |
1736 | self.write("\nKeyboardInterrupt\n") |
|
1736 | self.write("\nKeyboardInterrupt\n") | |
1737 |
|
1737 | |||
1738 | def mainloop(self,banner=None): |
|
1738 | def mainloop(self,banner=None): | |
1739 | """Creates the local namespace and starts the mainloop. |
|
1739 | """Creates the local namespace and starts the mainloop. | |
1740 |
|
1740 | |||
1741 | If an optional banner argument is given, it will override the |
|
1741 | If an optional banner argument is given, it will override the | |
1742 | internally created default banner.""" |
|
1742 | internally created default banner.""" | |
1743 |
|
1743 | |||
1744 | if self.rc.c: # Emulate Python's -c option |
|
1744 | if self.rc.c: # Emulate Python's -c option | |
1745 | self.exec_init_cmd() |
|
1745 | self.exec_init_cmd() | |
1746 | if banner is None: |
|
1746 | if banner is None: | |
1747 | if not self.rc.banner: |
|
1747 | if not self.rc.banner: | |
1748 | banner = '' |
|
1748 | banner = '' | |
1749 | # banner is string? Use it directly! |
|
1749 | # banner is string? Use it directly! | |
1750 | elif isinstance(self.rc.banner,basestring): |
|
1750 | elif isinstance(self.rc.banner,basestring): | |
1751 | banner = self.rc.banner |
|
1751 | banner = self.rc.banner | |
1752 | else: |
|
1752 | else: | |
1753 | banner = self.BANNER+self.banner2 |
|
1753 | banner = self.BANNER+self.banner2 | |
1754 |
|
1754 | |||
1755 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1755 | # if you run stuff with -c <cmd>, raw hist is not updated | |
1756 | # ensure that it's in sync |
|
1756 | # ensure that it's in sync | |
1757 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1757 | if len(self.input_hist) != len (self.input_hist_raw): | |
1758 | self.input_hist_raw = InputList(self.input_hist) |
|
1758 | self.input_hist_raw = InputList(self.input_hist) | |
1759 |
|
1759 | |||
1760 | while 1: |
|
1760 | while 1: | |
1761 | try: |
|
1761 | try: | |
1762 | self.interact(banner) |
|
1762 | self.interact(banner) | |
1763 | #self.interact_with_readline() |
|
1763 | #self.interact_with_readline() | |
1764 |
|
1764 | |||
1765 | # XXX for testing of a readline-decoupled repl loop, call |
|
1765 | # XXX for testing of a readline-decoupled repl loop, call | |
1766 | # interact_with_readline above |
|
1766 | # interact_with_readline above | |
1767 |
|
1767 | |||
1768 | break |
|
1768 | break | |
1769 | except KeyboardInterrupt: |
|
1769 | except KeyboardInterrupt: | |
1770 | # this should not be necessary, but KeyboardInterrupt |
|
1770 | # this should not be necessary, but KeyboardInterrupt | |
1771 | # handling seems rather unpredictable... |
|
1771 | # handling seems rather unpredictable... | |
1772 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1772 | self.write("\nKeyboardInterrupt in interact()\n") | |
1773 |
|
1773 | |||
1774 | def exec_init_cmd(self): |
|
1774 | def exec_init_cmd(self): | |
1775 | """Execute a command given at the command line. |
|
1775 | """Execute a command given at the command line. | |
1776 |
|
1776 | |||
1777 | This emulates Python's -c option.""" |
|
1777 | This emulates Python's -c option.""" | |
1778 |
|
1778 | |||
1779 | #sys.argv = ['-c'] |
|
1779 | #sys.argv = ['-c'] | |
1780 | self.push(self.prefilter(self.rc.c, False)) |
|
1780 | self.push(self.prefilter(self.rc.c, False)) | |
1781 | if not self.rc.interact: |
|
1781 | if not self.rc.interact: | |
1782 | self.ask_exit() |
|
1782 | self.ask_exit() | |
1783 |
|
1783 | |||
1784 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1784 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1785 | """Embeds IPython into a running python program. |
|
1785 | """Embeds IPython into a running python program. | |
1786 |
|
1786 | |||
1787 | Input: |
|
1787 | Input: | |
1788 |
|
1788 | |||
1789 | - header: An optional header message can be specified. |
|
1789 | - header: An optional header message can be specified. | |
1790 |
|
1790 | |||
1791 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1791 | - local_ns, global_ns: working namespaces. If given as None, the | |
1792 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1792 | IPython-initialized one is updated with __main__.__dict__, so that | |
1793 | program variables become visible but user-specific configuration |
|
1793 | program variables become visible but user-specific configuration | |
1794 | remains possible. |
|
1794 | remains possible. | |
1795 |
|
1795 | |||
1796 | - stack_depth: specifies how many levels in the stack to go to |
|
1796 | - stack_depth: specifies how many levels in the stack to go to | |
1797 | looking for namespaces (when local_ns and global_ns are None). This |
|
1797 | looking for namespaces (when local_ns and global_ns are None). This | |
1798 | allows an intermediate caller to make sure that this function gets |
|
1798 | allows an intermediate caller to make sure that this function gets | |
1799 | the namespace from the intended level in the stack. By default (0) |
|
1799 | the namespace from the intended level in the stack. By default (0) | |
1800 | it will get its locals and globals from the immediate caller. |
|
1800 | it will get its locals and globals from the immediate caller. | |
1801 |
|
1801 | |||
1802 | Warning: it's possible to use this in a program which is being run by |
|
1802 | Warning: it's possible to use this in a program which is being run by | |
1803 | IPython itself (via %run), but some funny things will happen (a few |
|
1803 | IPython itself (via %run), but some funny things will happen (a few | |
1804 | globals get overwritten). In the future this will be cleaned up, as |
|
1804 | globals get overwritten). In the future this will be cleaned up, as | |
1805 | there is no fundamental reason why it can't work perfectly.""" |
|
1805 | there is no fundamental reason why it can't work perfectly.""" | |
1806 |
|
1806 | |||
1807 | # Get locals and globals from caller |
|
1807 | # Get locals and globals from caller | |
1808 | if local_ns is None or global_ns is None: |
|
1808 | if local_ns is None or global_ns is None: | |
1809 | call_frame = sys._getframe(stack_depth).f_back |
|
1809 | call_frame = sys._getframe(stack_depth).f_back | |
1810 |
|
1810 | |||
1811 | if local_ns is None: |
|
1811 | if local_ns is None: | |
1812 | local_ns = call_frame.f_locals |
|
1812 | local_ns = call_frame.f_locals | |
1813 | if global_ns is None: |
|
1813 | if global_ns is None: | |
1814 | global_ns = call_frame.f_globals |
|
1814 | global_ns = call_frame.f_globals | |
1815 |
|
1815 | |||
1816 | # Update namespaces and fire up interpreter |
|
1816 | # Update namespaces and fire up interpreter | |
1817 |
|
1817 | |||
1818 | # The global one is easy, we can just throw it in |
|
1818 | # The global one is easy, we can just throw it in | |
1819 | self.user_global_ns = global_ns |
|
1819 | self.user_global_ns = global_ns | |
1820 |
|
1820 | |||
1821 | # but the user/local one is tricky: ipython needs it to store internal |
|
1821 | # but the user/local one is tricky: ipython needs it to store internal | |
1822 | # data, but we also need the locals. We'll copy locals in the user |
|
1822 | # data, but we also need the locals. We'll copy locals in the user | |
1823 | # one, but will track what got copied so we can delete them at exit. |
|
1823 | # one, but will track what got copied so we can delete them at exit. | |
1824 | # This is so that a later embedded call doesn't see locals from a |
|
1824 | # This is so that a later embedded call doesn't see locals from a | |
1825 | # previous call (which most likely existed in a separate scope). |
|
1825 | # previous call (which most likely existed in a separate scope). | |
1826 | local_varnames = local_ns.keys() |
|
1826 | local_varnames = local_ns.keys() | |
1827 | self.user_ns.update(local_ns) |
|
1827 | self.user_ns.update(local_ns) | |
1828 | #self.user_ns['local_ns'] = local_ns # dbg |
|
1828 | #self.user_ns['local_ns'] = local_ns # dbg | |
1829 |
|
1829 | |||
1830 | # Patch for global embedding to make sure that things don't overwrite |
|
1830 | # Patch for global embedding to make sure that things don't overwrite | |
1831 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1831 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1832 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1832 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1833 | if local_ns is None and global_ns is None: |
|
1833 | if local_ns is None and global_ns is None: | |
1834 | self.user_global_ns.update(__main__.__dict__) |
|
1834 | self.user_global_ns.update(__main__.__dict__) | |
1835 |
|
1835 | |||
1836 | # make sure the tab-completer has the correct frame information, so it |
|
1836 | # make sure the tab-completer has the correct frame information, so it | |
1837 | # actually completes using the frame's locals/globals |
|
1837 | # actually completes using the frame's locals/globals | |
1838 | self.set_completer_frame() |
|
1838 | self.set_completer_frame() | |
1839 |
|
1839 | |||
1840 | # before activating the interactive mode, we need to make sure that |
|
1840 | # before activating the interactive mode, we need to make sure that | |
1841 | # all names in the builtin namespace needed by ipython point to |
|
1841 | # all names in the builtin namespace needed by ipython point to | |
1842 | # ourselves, and not to other instances. |
|
1842 | # ourselves, and not to other instances. | |
1843 | self.add_builtins() |
|
1843 | self.add_builtins() | |
1844 |
|
1844 | |||
1845 | self.interact(header) |
|
1845 | self.interact(header) | |
1846 |
|
1846 | |||
1847 | # now, purge out the user namespace from anything we might have added |
|
1847 | # now, purge out the user namespace from anything we might have added | |
1848 | # from the caller's local namespace |
|
1848 | # from the caller's local namespace | |
1849 | delvar = self.user_ns.pop |
|
1849 | delvar = self.user_ns.pop | |
1850 | for var in local_varnames: |
|
1850 | for var in local_varnames: | |
1851 | delvar(var,None) |
|
1851 | delvar(var,None) | |
1852 | # and clean builtins we may have overridden |
|
1852 | # and clean builtins we may have overridden | |
1853 | self.clean_builtins() |
|
1853 | self.clean_builtins() | |
1854 |
|
1854 | |||
1855 | def interact_prompt(self): |
|
1855 | def interact_prompt(self): | |
1856 | """ Print the prompt (in read-eval-print loop) |
|
1856 | """ Print the prompt (in read-eval-print loop) | |
1857 |
|
1857 | |||
1858 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1858 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1859 | used in standard IPython flow. |
|
1859 | used in standard IPython flow. | |
1860 | """ |
|
1860 | """ | |
1861 | if self.more: |
|
1861 | if self.more: | |
1862 | try: |
|
1862 | try: | |
1863 | prompt = self.hooks.generate_prompt(True) |
|
1863 | prompt = self.hooks.generate_prompt(True) | |
1864 | except: |
|
1864 | except: | |
1865 | self.showtraceback() |
|
1865 | self.showtraceback() | |
1866 | if self.autoindent: |
|
1866 | if self.autoindent: | |
1867 | self.rl_do_indent = True |
|
1867 | self.rl_do_indent = True | |
1868 |
|
1868 | |||
1869 | else: |
|
1869 | else: | |
1870 | try: |
|
1870 | try: | |
1871 | prompt = self.hooks.generate_prompt(False) |
|
1871 | prompt = self.hooks.generate_prompt(False) | |
1872 | except: |
|
1872 | except: | |
1873 | self.showtraceback() |
|
1873 | self.showtraceback() | |
1874 | self.write(prompt) |
|
1874 | self.write(prompt) | |
1875 |
|
1875 | |||
1876 | def interact_handle_input(self,line): |
|
1876 | def interact_handle_input(self,line): | |
1877 | """ Handle the input line (in read-eval-print loop) |
|
1877 | """ Handle the input line (in read-eval-print loop) | |
1878 |
|
1878 | |||
1879 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1879 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1880 | used in standard IPython flow. |
|
1880 | used in standard IPython flow. | |
1881 | """ |
|
1881 | """ | |
1882 | if line.lstrip() == line: |
|
1882 | if line.lstrip() == line: | |
1883 | self.shadowhist.add(line.strip()) |
|
1883 | self.shadowhist.add(line.strip()) | |
1884 | lineout = self.prefilter(line,self.more) |
|
1884 | lineout = self.prefilter(line,self.more) | |
1885 |
|
1885 | |||
1886 | if line.strip(): |
|
1886 | if line.strip(): | |
1887 | if self.more: |
|
1887 | if self.more: | |
1888 | self.input_hist_raw[-1] += '%s\n' % line |
|
1888 | self.input_hist_raw[-1] += '%s\n' % line | |
1889 | else: |
|
1889 | else: | |
1890 | self.input_hist_raw.append('%s\n' % line) |
|
1890 | self.input_hist_raw.append('%s\n' % line) | |
1891 |
|
1891 | |||
1892 |
|
1892 | |||
1893 | self.more = self.push(lineout) |
|
1893 | self.more = self.push(lineout) | |
1894 | if (self.SyntaxTB.last_syntax_error and |
|
1894 | if (self.SyntaxTB.last_syntax_error and | |
1895 | self.rc.autoedit_syntax): |
|
1895 | self.rc.autoedit_syntax): | |
1896 | self.edit_syntax_error() |
|
1896 | self.edit_syntax_error() | |
1897 |
|
1897 | |||
1898 | def interact_with_readline(self): |
|
1898 | def interact_with_readline(self): | |
1899 | """ Demo of using interact_handle_input, interact_prompt |
|
1899 | """ Demo of using interact_handle_input, interact_prompt | |
1900 |
|
1900 | |||
1901 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1901 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1902 | it should work like this. |
|
1902 | it should work like this. | |
1903 | """ |
|
1903 | """ | |
1904 | self.readline_startup_hook(self.pre_readline) |
|
1904 | self.readline_startup_hook(self.pre_readline) | |
1905 | while not self.exit_now: |
|
1905 | while not self.exit_now: | |
1906 | self.interact_prompt() |
|
1906 | self.interact_prompt() | |
1907 | if self.more: |
|
1907 | if self.more: | |
1908 | self.rl_do_indent = True |
|
1908 | self.rl_do_indent = True | |
1909 | else: |
|
1909 | else: | |
1910 | self.rl_do_indent = False |
|
1910 | self.rl_do_indent = False | |
1911 | line = raw_input_original().decode(self.stdin_encoding) |
|
1911 | line = raw_input_original().decode(self.stdin_encoding) | |
1912 | self.interact_handle_input(line) |
|
1912 | self.interact_handle_input(line) | |
1913 |
|
1913 | |||
1914 |
|
1914 | |||
1915 | def interact(self, banner=None): |
|
1915 | def interact(self, banner=None): | |
1916 | """Closely emulate the interactive Python console. |
|
1916 | """Closely emulate the interactive Python console. | |
1917 |
|
1917 | |||
1918 | The optional banner argument specify the banner to print |
|
1918 | The optional banner argument specify the banner to print | |
1919 | before the first interaction; by default it prints a banner |
|
1919 | before the first interaction; by default it prints a banner | |
1920 | similar to the one printed by the real Python interpreter, |
|
1920 | similar to the one printed by the real Python interpreter, | |
1921 | followed by the current class name in parentheses (so as not |
|
1921 | followed by the current class name in parentheses (so as not | |
1922 | to confuse this with the real interpreter -- since it's so |
|
1922 | to confuse this with the real interpreter -- since it's so | |
1923 | close!). |
|
1923 | close!). | |
1924 |
|
1924 | |||
1925 | """ |
|
1925 | """ | |
1926 |
|
1926 | |||
1927 | if self.exit_now: |
|
1927 | if self.exit_now: | |
1928 | # batch run -> do not interact |
|
1928 | # batch run -> do not interact | |
1929 | return |
|
1929 | return | |
1930 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1930 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1931 | if banner is None: |
|
1931 | if banner is None: | |
1932 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1932 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1933 | (sys.version, sys.platform, cprt, |
|
1933 | (sys.version, sys.platform, cprt, | |
1934 | self.__class__.__name__)) |
|
1934 | self.__class__.__name__)) | |
1935 | else: |
|
1935 | else: | |
1936 | self.write(banner) |
|
1936 | self.write(banner) | |
1937 |
|
1937 | |||
1938 | more = 0 |
|
1938 | more = 0 | |
1939 |
|
1939 | |||
1940 | # Mark activity in the builtins |
|
1940 | # Mark activity in the builtins | |
1941 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1941 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1942 |
|
1942 | |||
1943 | if self.has_readline: |
|
1943 | if self.has_readline: | |
1944 | self.readline_startup_hook(self.pre_readline) |
|
1944 | self.readline_startup_hook(self.pre_readline) | |
1945 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1945 | # exit_now is set by a call to %Exit or %Quit, through the | |
1946 | # ask_exit callback. |
|
1946 | # ask_exit callback. | |
1947 |
|
1947 | |||
1948 | while not self.exit_now: |
|
1948 | while not self.exit_now: | |
1949 | self.hooks.pre_prompt_hook() |
|
1949 | self.hooks.pre_prompt_hook() | |
1950 | if more: |
|
1950 | if more: | |
1951 | try: |
|
1951 | try: | |
1952 | prompt = self.hooks.generate_prompt(True) |
|
1952 | prompt = self.hooks.generate_prompt(True) | |
1953 | except: |
|
1953 | except: | |
1954 | self.showtraceback() |
|
1954 | self.showtraceback() | |
1955 | if self.autoindent: |
|
1955 | if self.autoindent: | |
1956 | self.rl_do_indent = True |
|
1956 | self.rl_do_indent = True | |
1957 |
|
1957 | |||
1958 | else: |
|
1958 | else: | |
1959 | try: |
|
1959 | try: | |
1960 | prompt = self.hooks.generate_prompt(False) |
|
1960 | prompt = self.hooks.generate_prompt(False) | |
1961 | except: |
|
1961 | except: | |
1962 | self.showtraceback() |
|
1962 | self.showtraceback() | |
1963 | try: |
|
1963 | try: | |
1964 | line = self.raw_input(prompt,more) |
|
1964 | line = self.raw_input(prompt,more) | |
1965 | if self.exit_now: |
|
1965 | if self.exit_now: | |
1966 | # quick exit on sys.std[in|out] close |
|
1966 | # quick exit on sys.std[in|out] close | |
1967 | break |
|
1967 | break | |
1968 | if self.autoindent: |
|
1968 | if self.autoindent: | |
1969 | self.rl_do_indent = False |
|
1969 | self.rl_do_indent = False | |
1970 |
|
1970 | |||
1971 | except KeyboardInterrupt: |
|
1971 | except KeyboardInterrupt: | |
1972 | #double-guard against keyboardinterrupts during kbdint handling |
|
1972 | #double-guard against keyboardinterrupts during kbdint handling | |
1973 | try: |
|
1973 | try: | |
1974 | self.write('\nKeyboardInterrupt\n') |
|
1974 | self.write('\nKeyboardInterrupt\n') | |
1975 | self.resetbuffer() |
|
1975 | self.resetbuffer() | |
1976 | # keep cache in sync with the prompt counter: |
|
1976 | # keep cache in sync with the prompt counter: | |
1977 | self.outputcache.prompt_count -= 1 |
|
1977 | self.outputcache.prompt_count -= 1 | |
1978 |
|
1978 | |||
1979 | if self.autoindent: |
|
1979 | if self.autoindent: | |
1980 | self.indent_current_nsp = 0 |
|
1980 | self.indent_current_nsp = 0 | |
1981 | more = 0 |
|
1981 | more = 0 | |
1982 | except KeyboardInterrupt: |
|
1982 | except KeyboardInterrupt: | |
1983 | pass |
|
1983 | pass | |
1984 | except EOFError: |
|
1984 | except EOFError: | |
1985 | if self.autoindent: |
|
1985 | if self.autoindent: | |
1986 | self.rl_do_indent = False |
|
1986 | self.rl_do_indent = False | |
1987 | if self.has_readline: |
|
1987 | if self.has_readline: | |
1988 | self.readline_startup_hook(None) |
|
1988 | self.readline_startup_hook(None) | |
1989 | self.write('\n') |
|
1989 | self.write('\n') | |
1990 | self.exit() |
|
1990 | self.exit() | |
1991 | except bdb.BdbQuit: |
|
1991 | except bdb.BdbQuit: | |
1992 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1992 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1993 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1993 | 'Because of how pdb handles the stack, it is impossible\n' | |
1994 | 'for IPython to properly format this particular exception.\n' |
|
1994 | 'for IPython to properly format this particular exception.\n' | |
1995 | 'IPython will resume normal operation.') |
|
1995 | 'IPython will resume normal operation.') | |
1996 | except: |
|
1996 | except: | |
1997 | # exceptions here are VERY RARE, but they can be triggered |
|
1997 | # exceptions here are VERY RARE, but they can be triggered | |
1998 | # asynchronously by signal handlers, for example. |
|
1998 | # asynchronously by signal handlers, for example. | |
1999 | self.showtraceback() |
|
1999 | self.showtraceback() | |
2000 | else: |
|
2000 | else: | |
2001 | more = self.push(line) |
|
2001 | more = self.push(line) | |
2002 | if (self.SyntaxTB.last_syntax_error and |
|
2002 | if (self.SyntaxTB.last_syntax_error and | |
2003 | self.rc.autoedit_syntax): |
|
2003 | self.rc.autoedit_syntax): | |
2004 | self.edit_syntax_error() |
|
2004 | self.edit_syntax_error() | |
2005 |
|
2005 | |||
2006 | # We are off again... |
|
2006 | # We are off again... | |
2007 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
2007 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
2008 |
|
2008 | |||
2009 | def excepthook(self, etype, value, tb): |
|
2009 | def excepthook(self, etype, value, tb): | |
2010 | """One more defense for GUI apps that call sys.excepthook. |
|
2010 | """One more defense for GUI apps that call sys.excepthook. | |
2011 |
|
2011 | |||
2012 | GUI frameworks like wxPython trap exceptions and call |
|
2012 | GUI frameworks like wxPython trap exceptions and call | |
2013 | sys.excepthook themselves. I guess this is a feature that |
|
2013 | sys.excepthook themselves. I guess this is a feature that | |
2014 | enables them to keep running after exceptions that would |
|
2014 | enables them to keep running after exceptions that would | |
2015 | otherwise kill their mainloop. This is a bother for IPython |
|
2015 | otherwise kill their mainloop. This is a bother for IPython | |
2016 | which excepts to catch all of the program exceptions with a try: |
|
2016 | which excepts to catch all of the program exceptions with a try: | |
2017 | except: statement. |
|
2017 | except: statement. | |
2018 |
|
2018 | |||
2019 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
2019 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
2020 | any app directly invokes sys.excepthook, it will look to the user like |
|
2020 | any app directly invokes sys.excepthook, it will look to the user like | |
2021 | IPython crashed. In order to work around this, we can disable the |
|
2021 | IPython crashed. In order to work around this, we can disable the | |
2022 | CrashHandler and replace it with this excepthook instead, which prints a |
|
2022 | CrashHandler and replace it with this excepthook instead, which prints a | |
2023 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
2023 | regular traceback using our InteractiveTB. In this fashion, apps which | |
2024 | call sys.excepthook will generate a regular-looking exception from |
|
2024 | call sys.excepthook will generate a regular-looking exception from | |
2025 | IPython, and the CrashHandler will only be triggered by real IPython |
|
2025 | IPython, and the CrashHandler will only be triggered by real IPython | |
2026 | crashes. |
|
2026 | crashes. | |
2027 |
|
2027 | |||
2028 | This hook should be used sparingly, only in places which are not likely |
|
2028 | This hook should be used sparingly, only in places which are not likely | |
2029 | to be true IPython errors. |
|
2029 | to be true IPython errors. | |
2030 | """ |
|
2030 | """ | |
2031 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
2031 | self.showtraceback((etype,value,tb),tb_offset=0) | |
2032 |
|
2032 | |||
2033 | def expand_aliases(self,fn,rest): |
|
2033 | def expand_aliases(self,fn,rest): | |
2034 | """ Expand multiple levels of aliases: |
|
2034 | """ Expand multiple levels of aliases: | |
2035 |
|
2035 | |||
2036 | if: |
|
2036 | if: | |
2037 |
|
2037 | |||
2038 | alias foo bar /tmp |
|
2038 | alias foo bar /tmp | |
2039 | alias baz foo |
|
2039 | alias baz foo | |
2040 |
|
2040 | |||
2041 | then: |
|
2041 | then: | |
2042 |
|
2042 | |||
2043 | baz huhhahhei -> bar /tmp huhhahhei |
|
2043 | baz huhhahhei -> bar /tmp huhhahhei | |
2044 |
|
2044 | |||
2045 | """ |
|
2045 | """ | |
2046 | line = fn + " " + rest |
|
2046 | line = fn + " " + rest | |
2047 |
|
2047 | |||
2048 | done = set() |
|
2048 | done = set() | |
2049 | while 1: |
|
2049 | while 1: | |
2050 | pre,fn,rest = prefilter.splitUserInput(line, |
|
2050 | pre,fn,rest = prefilter.splitUserInput(line, | |
2051 | prefilter.shell_line_split) |
|
2051 | prefilter.shell_line_split) | |
2052 | if fn in self.alias_table: |
|
2052 | if fn in self.alias_table: | |
2053 | if fn in done: |
|
2053 | if fn in done: | |
2054 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
2054 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
2055 | return "" |
|
2055 | return "" | |
2056 | done.add(fn) |
|
2056 | done.add(fn) | |
2057 |
|
2057 | |||
2058 | l2 = self.transform_alias(fn,rest) |
|
2058 | l2 = self.transform_alias(fn,rest) | |
2059 | # dir -> dir |
|
2059 | # dir -> dir | |
2060 | # print "alias",line, "->",l2 #dbg |
|
2060 | # print "alias",line, "->",l2 #dbg | |
2061 | if l2 == line: |
|
2061 | if l2 == line: | |
2062 | break |
|
2062 | break | |
2063 | # ls -> ls -F should not recurse forever |
|
2063 | # ls -> ls -F should not recurse forever | |
2064 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
2064 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
2065 | line = l2 |
|
2065 | line = l2 | |
2066 | break |
|
2066 | break | |
2067 |
|
2067 | |||
2068 | line=l2 |
|
2068 | line=l2 | |
2069 |
|
2069 | |||
2070 |
|
2070 | |||
2071 | # print "al expand to",line #dbg |
|
2071 | # print "al expand to",line #dbg | |
2072 | else: |
|
2072 | else: | |
2073 | break |
|
2073 | break | |
2074 |
|
2074 | |||
2075 | return line |
|
2075 | return line | |
2076 |
|
2076 | |||
2077 | def transform_alias(self, alias,rest=''): |
|
2077 | def transform_alias(self, alias,rest=''): | |
2078 | """ Transform alias to system command string. |
|
2078 | """ Transform alias to system command string. | |
2079 | """ |
|
2079 | """ | |
2080 | trg = self.alias_table[alias] |
|
2080 | trg = self.alias_table[alias] | |
2081 |
|
2081 | |||
2082 | nargs,cmd = trg |
|
2082 | nargs,cmd = trg | |
2083 | # print trg #dbg |
|
2083 | # print trg #dbg | |
2084 | if ' ' in cmd and os.path.isfile(cmd): |
|
2084 | if ' ' in cmd and os.path.isfile(cmd): | |
2085 | cmd = '"%s"' % cmd |
|
2085 | cmd = '"%s"' % cmd | |
2086 |
|
2086 | |||
2087 | # Expand the %l special to be the user's input line |
|
2087 | # Expand the %l special to be the user's input line | |
2088 | if cmd.find('%l') >= 0: |
|
2088 | if cmd.find('%l') >= 0: | |
2089 | cmd = cmd.replace('%l',rest) |
|
2089 | cmd = cmd.replace('%l',rest) | |
2090 | rest = '' |
|
2090 | rest = '' | |
2091 | if nargs==0: |
|
2091 | if nargs==0: | |
2092 | # Simple, argument-less aliases |
|
2092 | # Simple, argument-less aliases | |
2093 | cmd = '%s %s' % (cmd,rest) |
|
2093 | cmd = '%s %s' % (cmd,rest) | |
2094 | else: |
|
2094 | else: | |
2095 | # Handle aliases with positional arguments |
|
2095 | # Handle aliases with positional arguments | |
2096 | args = rest.split(None,nargs) |
|
2096 | args = rest.split(None,nargs) | |
2097 | if len(args)< nargs: |
|
2097 | if len(args)< nargs: | |
2098 | error('Alias <%s> requires %s arguments, %s given.' % |
|
2098 | error('Alias <%s> requires %s arguments, %s given.' % | |
2099 | (alias,nargs,len(args))) |
|
2099 | (alias,nargs,len(args))) | |
2100 | return None |
|
2100 | return None | |
2101 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
2101 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
2102 | # Now call the macro, evaluating in the user's namespace |
|
2102 | # Now call the macro, evaluating in the user's namespace | |
2103 | #print 'new command: <%r>' % cmd # dbg |
|
2103 | #print 'new command: <%r>' % cmd # dbg | |
2104 | return cmd |
|
2104 | return cmd | |
2105 |
|
2105 | |||
2106 | def call_alias(self,alias,rest=''): |
|
2106 | def call_alias(self,alias,rest=''): | |
2107 | """Call an alias given its name and the rest of the line. |
|
2107 | """Call an alias given its name and the rest of the line. | |
2108 |
|
2108 | |||
2109 | This is only used to provide backwards compatibility for users of |
|
2109 | This is only used to provide backwards compatibility for users of | |
2110 | ipalias(), use of which is not recommended for anymore.""" |
|
2110 | ipalias(), use of which is not recommended for anymore.""" | |
2111 |
|
2111 | |||
2112 | # Now call the macro, evaluating in the user's namespace |
|
2112 | # Now call the macro, evaluating in the user's namespace | |
2113 | cmd = self.transform_alias(alias, rest) |
|
2113 | cmd = self.transform_alias(alias, rest) | |
2114 | try: |
|
2114 | try: | |
2115 | self.system(cmd) |
|
2115 | self.system(cmd) | |
2116 | except: |
|
2116 | except: | |
2117 | self.showtraceback() |
|
2117 | self.showtraceback() | |
2118 |
|
2118 | |||
2119 | def indent_current_str(self): |
|
2119 | def indent_current_str(self): | |
2120 | """return the current level of indentation as a string""" |
|
2120 | """return the current level of indentation as a string""" | |
2121 | return self.indent_current_nsp * ' ' |
|
2121 | return self.indent_current_nsp * ' ' | |
2122 |
|
2122 | |||
2123 | def autoindent_update(self,line): |
|
2123 | def autoindent_update(self,line): | |
2124 | """Keep track of the indent level.""" |
|
2124 | """Keep track of the indent level.""" | |
2125 |
|
2125 | |||
2126 | #debugx('line') |
|
2126 | #debugx('line') | |
2127 | #debugx('self.indent_current_nsp') |
|
2127 | #debugx('self.indent_current_nsp') | |
2128 | if self.autoindent: |
|
2128 | if self.autoindent: | |
2129 | if line: |
|
2129 | if line: | |
2130 | inisp = num_ini_spaces(line) |
|
2130 | inisp = num_ini_spaces(line) | |
2131 | if inisp < self.indent_current_nsp: |
|
2131 | if inisp < self.indent_current_nsp: | |
2132 | self.indent_current_nsp = inisp |
|
2132 | self.indent_current_nsp = inisp | |
2133 |
|
2133 | |||
2134 | if line[-1] == ':': |
|
2134 | if line[-1] == ':': | |
2135 | self.indent_current_nsp += 4 |
|
2135 | self.indent_current_nsp += 4 | |
2136 | elif dedent_re.match(line): |
|
2136 | elif dedent_re.match(line): | |
2137 | self.indent_current_nsp -= 4 |
|
2137 | self.indent_current_nsp -= 4 | |
2138 | else: |
|
2138 | else: | |
2139 | self.indent_current_nsp = 0 |
|
2139 | self.indent_current_nsp = 0 | |
2140 |
|
2140 | |||
2141 | def runlines(self,lines): |
|
2141 | def runlines(self,lines): | |
2142 | """Run a string of one or more lines of source. |
|
2142 | """Run a string of one or more lines of source. | |
2143 |
|
2143 | |||
2144 | This method is capable of running a string containing multiple source |
|
2144 | This method is capable of running a string containing multiple source | |
2145 | lines, as if they had been entered at the IPython prompt. Since it |
|
2145 | lines, as if they had been entered at the IPython prompt. Since it | |
2146 | exposes IPython's processing machinery, the given strings can contain |
|
2146 | exposes IPython's processing machinery, the given strings can contain | |
2147 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
2147 | magic calls (%magic), special shell access (!cmd), etc.""" | |
2148 |
|
2148 | |||
2149 | # We must start with a clean buffer, in case this is run from an |
|
2149 | # We must start with a clean buffer, in case this is run from an | |
2150 | # interactive IPython session (via a magic, for example). |
|
2150 | # interactive IPython session (via a magic, for example). | |
2151 | self.resetbuffer() |
|
2151 | self.resetbuffer() | |
2152 | lines = lines.split('\n') |
|
2152 | lines = lines.split('\n') | |
2153 | more = 0 |
|
2153 | more = 0 | |
2154 |
|
2154 | |||
2155 | for line in lines: |
|
2155 | for line in lines: | |
2156 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2156 | # skip blank lines so we don't mess up the prompt counter, but do | |
2157 | # NOT skip even a blank line if we are in a code block (more is |
|
2157 | # NOT skip even a blank line if we are in a code block (more is | |
2158 | # true) |
|
2158 | # true) | |
2159 |
|
2159 | |||
2160 | if line or more: |
|
2160 | if line or more: | |
2161 | # push to raw history, so hist line numbers stay in sync |
|
2161 | # push to raw history, so hist line numbers stay in sync | |
2162 | self.input_hist_raw.append("# " + line + "\n") |
|
2162 | self.input_hist_raw.append("# " + line + "\n") | |
2163 | more = self.push(self.prefilter(line,more)) |
|
2163 | more = self.push(self.prefilter(line,more)) | |
2164 | # IPython's runsource returns None if there was an error |
|
2164 | # IPython's runsource returns None if there was an error | |
2165 | # compiling the code. This allows us to stop processing right |
|
2165 | # compiling the code. This allows us to stop processing right | |
2166 | # away, so the user gets the error message at the right place. |
|
2166 | # away, so the user gets the error message at the right place. | |
2167 | if more is None: |
|
2167 | if more is None: | |
2168 | break |
|
2168 | break | |
2169 | else: |
|
2169 | else: | |
2170 | self.input_hist_raw.append("\n") |
|
2170 | self.input_hist_raw.append("\n") | |
2171 | # final newline in case the input didn't have it, so that the code |
|
2171 | # final newline in case the input didn't have it, so that the code | |
2172 | # actually does get executed |
|
2172 | # actually does get executed | |
2173 | if more: |
|
2173 | if more: | |
2174 | self.push('\n') |
|
2174 | self.push('\n') | |
2175 |
|
2175 | |||
2176 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2176 | def runsource(self, source, filename='<input>', symbol='single'): | |
2177 | """Compile and run some source in the interpreter. |
|
2177 | """Compile and run some source in the interpreter. | |
2178 |
|
2178 | |||
2179 | Arguments are as for compile_command(). |
|
2179 | Arguments are as for compile_command(). | |
2180 |
|
2180 | |||
2181 | One several things can happen: |
|
2181 | One several things can happen: | |
2182 |
|
2182 | |||
2183 | 1) The input is incorrect; compile_command() raised an |
|
2183 | 1) The input is incorrect; compile_command() raised an | |
2184 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2184 | exception (SyntaxError or OverflowError). A syntax traceback | |
2185 | will be printed by calling the showsyntaxerror() method. |
|
2185 | will be printed by calling the showsyntaxerror() method. | |
2186 |
|
2186 | |||
2187 | 2) The input is incomplete, and more input is required; |
|
2187 | 2) The input is incomplete, and more input is required; | |
2188 | compile_command() returned None. Nothing happens. |
|
2188 | compile_command() returned None. Nothing happens. | |
2189 |
|
2189 | |||
2190 | 3) The input is complete; compile_command() returned a code |
|
2190 | 3) The input is complete; compile_command() returned a code | |
2191 | object. The code is executed by calling self.runcode() (which |
|
2191 | object. The code is executed by calling self.runcode() (which | |
2192 | also handles run-time exceptions, except for SystemExit). |
|
2192 | also handles run-time exceptions, except for SystemExit). | |
2193 |
|
2193 | |||
2194 | The return value is: |
|
2194 | The return value is: | |
2195 |
|
2195 | |||
2196 | - True in case 2 |
|
2196 | - True in case 2 | |
2197 |
|
2197 | |||
2198 | - False in the other cases, unless an exception is raised, where |
|
2198 | - False in the other cases, unless an exception is raised, where | |
2199 | None is returned instead. This can be used by external callers to |
|
2199 | None is returned instead. This can be used by external callers to | |
2200 | know whether to continue feeding input or not. |
|
2200 | know whether to continue feeding input or not. | |
2201 |
|
2201 | |||
2202 | The return value can be used to decide whether to use sys.ps1 or |
|
2202 | The return value can be used to decide whether to use sys.ps1 or | |
2203 | sys.ps2 to prompt the next line.""" |
|
2203 | sys.ps2 to prompt the next line.""" | |
2204 |
|
2204 | |||
2205 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2205 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2206 | # this allows execution of indented pasted code. It is tempting |
|
2206 | # this allows execution of indented pasted code. It is tempting | |
2207 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2207 | # to add '\n' at the end of source to run commands like ' a=1' | |
2208 | # directly, but this fails for more complicated scenarios |
|
2208 | # directly, but this fails for more complicated scenarios | |
2209 | source=source.encode(self.stdin_encoding) |
|
2209 | source=source.encode(self.stdin_encoding) | |
2210 | if source[:1] in [' ', '\t']: |
|
2210 | if source[:1] in [' ', '\t']: | |
2211 | source = 'if 1:\n%s' % source |
|
2211 | source = 'if 1:\n%s' % source | |
2212 |
|
2212 | |||
2213 | try: |
|
2213 | try: | |
2214 | code = self.compile(source,filename,symbol) |
|
2214 | code = self.compile(source,filename,symbol) | |
2215 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2215 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2216 | # Case 1 |
|
2216 | # Case 1 | |
2217 | self.showsyntaxerror(filename) |
|
2217 | self.showsyntaxerror(filename) | |
2218 | return None |
|
2218 | return None | |
2219 |
|
2219 | |||
2220 | if code is None: |
|
2220 | if code is None: | |
2221 | # Case 2 |
|
2221 | # Case 2 | |
2222 | return True |
|
2222 | return True | |
2223 |
|
2223 | |||
2224 | # Case 3 |
|
2224 | # Case 3 | |
2225 | # We store the code object so that threaded shells and |
|
2225 | # We store the code object so that threaded shells and | |
2226 | # custom exception handlers can access all this info if needed. |
|
2226 | # custom exception handlers can access all this info if needed. | |
2227 | # The source corresponding to this can be obtained from the |
|
2227 | # The source corresponding to this can be obtained from the | |
2228 | # buffer attribute as '\n'.join(self.buffer). |
|
2228 | # buffer attribute as '\n'.join(self.buffer). | |
2229 | self.code_to_run = code |
|
2229 | self.code_to_run = code | |
2230 | # now actually execute the code object |
|
2230 | # now actually execute the code object | |
2231 | if self.runcode(code) == 0: |
|
2231 | if self.runcode(code) == 0: | |
2232 | return False |
|
2232 | return False | |
2233 | else: |
|
2233 | else: | |
2234 | return None |
|
2234 | return None | |
2235 |
|
2235 | |||
2236 | def runcode(self,code_obj): |
|
2236 | def runcode(self,code_obj): | |
2237 | """Execute a code object. |
|
2237 | """Execute a code object. | |
2238 |
|
2238 | |||
2239 | When an exception occurs, self.showtraceback() is called to display a |
|
2239 | When an exception occurs, self.showtraceback() is called to display a | |
2240 | traceback. |
|
2240 | traceback. | |
2241 |
|
2241 | |||
2242 | Return value: a flag indicating whether the code to be run completed |
|
2242 | Return value: a flag indicating whether the code to be run completed | |
2243 | successfully: |
|
2243 | successfully: | |
2244 |
|
2244 | |||
2245 | - 0: successful execution. |
|
2245 | - 0: successful execution. | |
2246 | - 1: an error occurred. |
|
2246 | - 1: an error occurred. | |
2247 | """ |
|
2247 | """ | |
2248 |
|
2248 | |||
2249 | # Set our own excepthook in case the user code tries to call it |
|
2249 | # Set our own excepthook in case the user code tries to call it | |
2250 | # directly, so that the IPython crash handler doesn't get triggered |
|
2250 | # directly, so that the IPython crash handler doesn't get triggered | |
2251 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2251 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2252 |
|
2252 | |||
2253 | # we save the original sys.excepthook in the instance, in case config |
|
2253 | # we save the original sys.excepthook in the instance, in case config | |
2254 | # code (such as magics) needs access to it. |
|
2254 | # code (such as magics) needs access to it. | |
2255 | self.sys_excepthook = old_excepthook |
|
2255 | self.sys_excepthook = old_excepthook | |
2256 | outflag = 1 # happens in more places, so it's easier as default |
|
2256 | outflag = 1 # happens in more places, so it's easier as default | |
2257 | try: |
|
2257 | try: | |
2258 | try: |
|
2258 | try: | |
2259 | self.hooks.pre_runcode_hook() |
|
2259 | self.hooks.pre_runcode_hook() | |
2260 | exec code_obj in self.user_global_ns, self.user_ns |
|
2260 | exec code_obj in self.user_global_ns, self.user_ns | |
2261 | finally: |
|
2261 | finally: | |
2262 | # Reset our crash handler in place |
|
2262 | # Reset our crash handler in place | |
2263 | sys.excepthook = old_excepthook |
|
2263 | sys.excepthook = old_excepthook | |
2264 | except SystemExit: |
|
2264 | except SystemExit: | |
2265 | self.resetbuffer() |
|
2265 | self.resetbuffer() | |
2266 | self.showtraceback() |
|
2266 | self.showtraceback() | |
2267 | warn("Type %exit or %quit to exit IPython " |
|
2267 | warn("Type %exit or %quit to exit IPython " | |
2268 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2268 | "(%Exit or %Quit do so unconditionally).",level=1) | |
2269 | except self.custom_exceptions: |
|
2269 | except self.custom_exceptions: | |
2270 | etype,value,tb = sys.exc_info() |
|
2270 | etype,value,tb = sys.exc_info() | |
2271 | self.CustomTB(etype,value,tb) |
|
2271 | self.CustomTB(etype,value,tb) | |
2272 | except: |
|
2272 | except: | |
2273 | self.showtraceback() |
|
2273 | self.showtraceback() | |
2274 | else: |
|
2274 | else: | |
2275 | outflag = 0 |
|
2275 | outflag = 0 | |
2276 | if softspace(sys.stdout, 0): |
|
2276 | if softspace(sys.stdout, 0): | |
2277 |
|
2277 | |||
2278 | # Flush out code object which has been run (and source) |
|
2278 | # Flush out code object which has been run (and source) | |
2279 | self.code_to_run = None |
|
2279 | self.code_to_run = None | |
2280 | return outflag |
|
2280 | return outflag | |
2281 |
|
2281 | |||
2282 | def push(self, line): |
|
2282 | def push(self, line): | |
2283 | """Push a line to the interpreter. |
|
2283 | """Push a line to the interpreter. | |
2284 |
|
2284 | |||
2285 | The line should not have a trailing newline; it may have |
|
2285 | The line should not have a trailing newline; it may have | |
2286 | internal newlines. The line is appended to a buffer and the |
|
2286 | internal newlines. The line is appended to a buffer and the | |
2287 | interpreter's runsource() method is called with the |
|
2287 | interpreter's runsource() method is called with the | |
2288 | concatenated contents of the buffer as source. If this |
|
2288 | concatenated contents of the buffer as source. If this | |
2289 | indicates that the command was executed or invalid, the buffer |
|
2289 | indicates that the command was executed or invalid, the buffer | |
2290 | is reset; otherwise, the command is incomplete, and the buffer |
|
2290 | is reset; otherwise, the command is incomplete, and the buffer | |
2291 | is left as it was after the line was appended. The return |
|
2291 | is left as it was after the line was appended. The return | |
2292 | value is 1 if more input is required, 0 if the line was dealt |
|
2292 | value is 1 if more input is required, 0 if the line was dealt | |
2293 | with in some way (this is the same as runsource()). |
|
2293 | with in some way (this is the same as runsource()). | |
2294 | """ |
|
2294 | """ | |
2295 |
|
2295 | |||
2296 | # autoindent management should be done here, and not in the |
|
2296 | # autoindent management should be done here, and not in the | |
2297 | # interactive loop, since that one is only seen by keyboard input. We |
|
2297 | # interactive loop, since that one is only seen by keyboard input. We | |
2298 | # need this done correctly even for code run via runlines (which uses |
|
2298 | # need this done correctly even for code run via runlines (which uses | |
2299 | # push). |
|
2299 | # push). | |
2300 |
|
2300 | |||
2301 | #print 'push line: <%s>' % line # dbg |
|
2301 | #print 'push line: <%s>' % line # dbg | |
2302 | for subline in line.splitlines(): |
|
2302 | for subline in line.splitlines(): | |
2303 | self.autoindent_update(subline) |
|
2303 | self.autoindent_update(subline) | |
2304 | self.buffer.append(line) |
|
2304 | self.buffer.append(line) | |
2305 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2305 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2306 | if not more: |
|
2306 | if not more: | |
2307 | self.resetbuffer() |
|
2307 | self.resetbuffer() | |
2308 | return more |
|
2308 | return more | |
2309 |
|
2309 | |||
2310 | def split_user_input(self, line): |
|
2310 | def split_user_input(self, line): | |
2311 | # This is really a hold-over to support ipapi and some extensions |
|
2311 | # This is really a hold-over to support ipapi and some extensions | |
2312 | return prefilter.splitUserInput(line) |
|
2312 | return prefilter.splitUserInput(line) | |
2313 |
|
2313 | |||
2314 | def resetbuffer(self): |
|
2314 | def resetbuffer(self): | |
2315 | """Reset the input buffer.""" |
|
2315 | """Reset the input buffer.""" | |
2316 | self.buffer[:] = [] |
|
2316 | self.buffer[:] = [] | |
2317 |
|
2317 | |||
2318 | def raw_input(self,prompt='',continue_prompt=False): |
|
2318 | def raw_input(self,prompt='',continue_prompt=False): | |
2319 | """Write a prompt and read a line. |
|
2319 | """Write a prompt and read a line. | |
2320 |
|
2320 | |||
2321 | The returned line does not include the trailing newline. |
|
2321 | The returned line does not include the trailing newline. | |
2322 | When the user enters the EOF key sequence, EOFError is raised. |
|
2322 | When the user enters the EOF key sequence, EOFError is raised. | |
2323 |
|
2323 | |||
2324 | Optional inputs: |
|
2324 | Optional inputs: | |
2325 |
|
2325 | |||
2326 | - prompt(''): a string to be printed to prompt the user. |
|
2326 | - prompt(''): a string to be printed to prompt the user. | |
2327 |
|
2327 | |||
2328 | - continue_prompt(False): whether this line is the first one or a |
|
2328 | - continue_prompt(False): whether this line is the first one or a | |
2329 | continuation in a sequence of inputs. |
|
2329 | continuation in a sequence of inputs. | |
2330 | """ |
|
2330 | """ | |
2331 |
|
2331 | |||
2332 | # Code run by the user may have modified the readline completer state. |
|
2332 | # Code run by the user may have modified the readline completer state. | |
2333 | # We must ensure that our completer is back in place. |
|
2333 | # We must ensure that our completer is back in place. | |
2334 | if self.has_readline: |
|
2334 | if self.has_readline: | |
2335 | self.set_completer() |
|
2335 | self.set_completer() | |
2336 |
|
2336 | |||
2337 | try: |
|
2337 | try: | |
2338 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2338 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2339 | except ValueError: |
|
2339 | except ValueError: | |
2340 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2340 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2341 | " or sys.stdout.close()!\nExiting IPython!") |
|
2341 | " or sys.stdout.close()!\nExiting IPython!") | |
2342 | self.ask_exit() |
|
2342 | self.ask_exit() | |
2343 | return "" |
|
2343 | return "" | |
2344 |
|
2344 | |||
2345 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2345 | # Try to be reasonably smart about not re-indenting pasted input more | |
2346 | # than necessary. We do this by trimming out the auto-indent initial |
|
2346 | # than necessary. We do this by trimming out the auto-indent initial | |
2347 | # spaces, if the user's actual input started itself with whitespace. |
|
2347 | # spaces, if the user's actual input started itself with whitespace. | |
2348 | #debugx('self.buffer[-1]') |
|
2348 | #debugx('self.buffer[-1]') | |
2349 |
|
2349 | |||
2350 | if self.autoindent: |
|
2350 | if self.autoindent: | |
2351 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2351 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2352 | line = line[self.indent_current_nsp:] |
|
2352 | line = line[self.indent_current_nsp:] | |
2353 | self.indent_current_nsp = 0 |
|
2353 | self.indent_current_nsp = 0 | |
2354 |
|
2354 | |||
2355 | # store the unfiltered input before the user has any chance to modify |
|
2355 | # store the unfiltered input before the user has any chance to modify | |
2356 | # it. |
|
2356 | # it. | |
2357 | if line.strip(): |
|
2357 | if line.strip(): | |
2358 | if continue_prompt: |
|
2358 | if continue_prompt: | |
2359 | self.input_hist_raw[-1] += '%s\n' % line |
|
2359 | self.input_hist_raw[-1] += '%s\n' % line | |
2360 | if self.has_readline: # and some config option is set? |
|
2360 | if self.has_readline: # and some config option is set? | |
2361 | try: |
|
2361 | try: | |
2362 | histlen = self.readline.get_current_history_length() |
|
2362 | histlen = self.readline.get_current_history_length() | |
2363 | if histlen > 1: |
|
2363 | if histlen > 1: | |
2364 | newhist = self.input_hist_raw[-1].rstrip() |
|
2364 | newhist = self.input_hist_raw[-1].rstrip() | |
2365 | self.readline.remove_history_item(histlen-1) |
|
2365 | self.readline.remove_history_item(histlen-1) | |
2366 | self.readline.replace_history_item(histlen-2, |
|
2366 | self.readline.replace_history_item(histlen-2, | |
2367 | newhist.encode(self.stdin_encoding)) |
|
2367 | newhist.encode(self.stdin_encoding)) | |
2368 | except AttributeError: |
|
2368 | except AttributeError: | |
2369 | pass # re{move,place}_history_item are new in 2.4. |
|
2369 | pass # re{move,place}_history_item are new in 2.4. | |
2370 | else: |
|
2370 | else: | |
2371 | self.input_hist_raw.append('%s\n' % line) |
|
2371 | self.input_hist_raw.append('%s\n' % line) | |
2372 | # only entries starting at first column go to shadow history |
|
2372 | # only entries starting at first column go to shadow history | |
2373 | if line.lstrip() == line: |
|
2373 | if line.lstrip() == line: | |
2374 | self.shadowhist.add(line.strip()) |
|
2374 | self.shadowhist.add(line.strip()) | |
2375 | elif not continue_prompt: |
|
2375 | elif not continue_prompt: | |
2376 | self.input_hist_raw.append('\n') |
|
2376 | self.input_hist_raw.append('\n') | |
2377 | try: |
|
2377 | try: | |
2378 | lineout = self.prefilter(line,continue_prompt) |
|
2378 | lineout = self.prefilter(line,continue_prompt) | |
2379 | except: |
|
2379 | except: | |
2380 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2380 | # blanket except, in case a user-defined prefilter crashes, so it | |
2381 | # can't take all of ipython with it. |
|
2381 | # can't take all of ipython with it. | |
2382 | self.showtraceback() |
|
2382 | self.showtraceback() | |
2383 | return '' |
|
2383 | return '' | |
2384 | else: |
|
2384 | else: | |
2385 | return lineout |
|
2385 | return lineout | |
2386 |
|
2386 | |||
2387 | def _prefilter(self, line, continue_prompt): |
|
2387 | def _prefilter(self, line, continue_prompt): | |
2388 | """Calls different preprocessors, depending on the form of line.""" |
|
2388 | """Calls different preprocessors, depending on the form of line.""" | |
2389 |
|
2389 | |||
2390 | # All handlers *must* return a value, even if it's blank (''). |
|
2390 | # All handlers *must* return a value, even if it's blank (''). | |
2391 |
|
2391 | |||
2392 | # Lines are NOT logged here. Handlers should process the line as |
|
2392 | # Lines are NOT logged here. Handlers should process the line as | |
2393 | # needed, update the cache AND log it (so that the input cache array |
|
2393 | # needed, update the cache AND log it (so that the input cache array | |
2394 | # stays synced). |
|
2394 | # stays synced). | |
2395 |
|
2395 | |||
2396 | #..................................................................... |
|
2396 | #..................................................................... | |
2397 | # Code begins |
|
2397 | # Code begins | |
2398 |
|
2398 | |||
2399 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2399 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
2400 |
|
2400 | |||
2401 | # save the line away in case we crash, so the post-mortem handler can |
|
2401 | # save the line away in case we crash, so the post-mortem handler can | |
2402 | # record it |
|
2402 | # record it | |
2403 | self._last_input_line = line |
|
2403 | self._last_input_line = line | |
2404 |
|
2404 | |||
2405 | #print '***line: <%s>' % line # dbg |
|
2405 | #print '***line: <%s>' % line # dbg | |
2406 |
|
2406 | |||
2407 | if not line: |
|
2407 | if not line: | |
2408 | # Return immediately on purely empty lines, so that if the user |
|
2408 | # Return immediately on purely empty lines, so that if the user | |
2409 | # previously typed some whitespace that started a continuation |
|
2409 | # previously typed some whitespace that started a continuation | |
2410 | # prompt, he can break out of that loop with just an empty line. |
|
2410 | # prompt, he can break out of that loop with just an empty line. | |
2411 | # This is how the default python prompt works. |
|
2411 | # This is how the default python prompt works. | |
2412 |
|
2412 | |||
2413 | # Only return if the accumulated input buffer was just whitespace! |
|
2413 | # Only return if the accumulated input buffer was just whitespace! | |
2414 | if ''.join(self.buffer).isspace(): |
|
2414 | if ''.join(self.buffer).isspace(): | |
2415 | self.buffer[:] = [] |
|
2415 | self.buffer[:] = [] | |
2416 | return '' |
|
2416 | return '' | |
2417 |
|
2417 | |||
2418 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2418 | line_info = prefilter.LineInfo(line, continue_prompt) | |
2419 |
|
2419 | |||
2420 | # the input history needs to track even empty lines |
|
2420 | # the input history needs to track even empty lines | |
2421 | stripped = line.strip() |
|
2421 | stripped = line.strip() | |
2422 |
|
2422 | |||
2423 | if not stripped: |
|
2423 | if not stripped: | |
2424 | if not continue_prompt: |
|
2424 | if not continue_prompt: | |
2425 | self.outputcache.prompt_count -= 1 |
|
2425 | self.outputcache.prompt_count -= 1 | |
2426 | return self.handle_normal(line_info) |
|
2426 | return self.handle_normal(line_info) | |
2427 |
|
2427 | |||
2428 | # print '***cont',continue_prompt # dbg |
|
2428 | # print '***cont',continue_prompt # dbg | |
2429 | # special handlers are only allowed for single line statements |
|
2429 | # special handlers are only allowed for single line statements | |
2430 | if continue_prompt and not self.rc.multi_line_specials: |
|
2430 | if continue_prompt and not self.rc.multi_line_specials: | |
2431 | return self.handle_normal(line_info) |
|
2431 | return self.handle_normal(line_info) | |
2432 |
|
2432 | |||
2433 |
|
2433 | |||
2434 | # See whether any pre-existing handler can take care of it |
|
2434 | # See whether any pre-existing handler can take care of it | |
2435 | rewritten = self.hooks.input_prefilter(stripped) |
|
2435 | rewritten = self.hooks.input_prefilter(stripped) | |
2436 | if rewritten != stripped: # ok, some prefilter did something |
|
2436 | if rewritten != stripped: # ok, some prefilter did something | |
2437 | rewritten = line_info.pre + rewritten # add indentation |
|
2437 | rewritten = line_info.pre + rewritten # add indentation | |
2438 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2438 | return self.handle_normal(prefilter.LineInfo(rewritten, | |
2439 | continue_prompt)) |
|
2439 | continue_prompt)) | |
2440 |
|
2440 | |||
2441 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2441 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2442 |
|
2442 | |||
2443 | return prefilter.prefilter(line_info, self) |
|
2443 | return prefilter.prefilter(line_info, self) | |
2444 |
|
2444 | |||
2445 |
|
2445 | |||
2446 | def _prefilter_dumb(self, line, continue_prompt): |
|
2446 | def _prefilter_dumb(self, line, continue_prompt): | |
2447 | """simple prefilter function, for debugging""" |
|
2447 | """simple prefilter function, for debugging""" | |
2448 | return self.handle_normal(line,continue_prompt) |
|
2448 | return self.handle_normal(line,continue_prompt) | |
2449 |
|
2449 | |||
2450 |
|
2450 | |||
2451 | def multiline_prefilter(self, line, continue_prompt): |
|
2451 | def multiline_prefilter(self, line, continue_prompt): | |
2452 | """ Run _prefilter for each line of input |
|
2452 | """ Run _prefilter for each line of input | |
2453 |
|
2453 | |||
2454 | Covers cases where there are multiple lines in the user entry, |
|
2454 | Covers cases where there are multiple lines in the user entry, | |
2455 | which is the case when the user goes back to a multiline history |
|
2455 | which is the case when the user goes back to a multiline history | |
2456 | entry and presses enter. |
|
2456 | entry and presses enter. | |
2457 |
|
2457 | |||
2458 | """ |
|
2458 | """ | |
2459 | out = [] |
|
2459 | out = [] | |
2460 | for l in line.rstrip('\n').split('\n'): |
|
2460 | for l in line.rstrip('\n').split('\n'): | |
2461 | out.append(self._prefilter(l, continue_prompt)) |
|
2461 | out.append(self._prefilter(l, continue_prompt)) | |
2462 | return '\n'.join(out) |
|
2462 | return '\n'.join(out) | |
2463 |
|
2463 | |||
2464 | # Set the default prefilter() function (this can be user-overridden) |
|
2464 | # Set the default prefilter() function (this can be user-overridden) | |
2465 | prefilter = multiline_prefilter |
|
2465 | prefilter = multiline_prefilter | |
2466 |
|
2466 | |||
2467 | def handle_normal(self,line_info): |
|
2467 | def handle_normal(self,line_info): | |
2468 | """Handle normal input lines. Use as a template for handlers.""" |
|
2468 | """Handle normal input lines. Use as a template for handlers.""" | |
2469 |
|
2469 | |||
2470 | # With autoindent on, we need some way to exit the input loop, and I |
|
2470 | # With autoindent on, we need some way to exit the input loop, and I | |
2471 | # don't want to force the user to have to backspace all the way to |
|
2471 | # don't want to force the user to have to backspace all the way to | |
2472 | # clear the line. The rule will be in this case, that either two |
|
2472 | # clear the line. The rule will be in this case, that either two | |
2473 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2473 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2474 | # of a size different to the indent level, will exit the input loop. |
|
2474 | # of a size different to the indent level, will exit the input loop. | |
2475 | line = line_info.line |
|
2475 | line = line_info.line | |
2476 | continue_prompt = line_info.continue_prompt |
|
2476 | continue_prompt = line_info.continue_prompt | |
2477 |
|
2477 | |||
2478 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2478 | if (continue_prompt and self.autoindent and line.isspace() and | |
2479 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2479 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2480 | (self.buffer[-1]).isspace() )): |
|
2480 | (self.buffer[-1]).isspace() )): | |
2481 | line = '' |
|
2481 | line = '' | |
2482 |
|
2482 | |||
2483 | self.log(line,line,continue_prompt) |
|
2483 | self.log(line,line,continue_prompt) | |
2484 | return line |
|
2484 | return line | |
2485 |
|
2485 | |||
2486 | def handle_alias(self,line_info): |
|
2486 | def handle_alias(self,line_info): | |
2487 | """Handle alias input lines. """ |
|
2487 | """Handle alias input lines. """ | |
2488 | tgt = self.alias_table[line_info.iFun] |
|
2488 | tgt = self.alias_table[line_info.iFun] | |
2489 | # print "=>",tgt #dbg |
|
2489 | # print "=>",tgt #dbg | |
2490 | if callable(tgt): |
|
2490 | if callable(tgt): | |
2491 | if '$' in line_info.line: |
|
2491 | if '$' in line_info.line: | |
2492 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2492 | call_meth = '(_ip, _ip.itpl(%s))' | |
2493 | else: |
|
2493 | else: | |
2494 | call_meth = '(_ip,%s)' |
|
2494 | call_meth = '(_ip,%s)' | |
2495 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2495 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, | |
2496 | line_info.iFun, |
|
2496 | line_info.iFun, | |
2497 | make_quoted_expr(line_info.line)) |
|
2497 | make_quoted_expr(line_info.line)) | |
2498 | else: |
|
2498 | else: | |
2499 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2499 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) | |
2500 |
|
2500 | |||
2501 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2501 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2502 | # aliases won't work in indented sections. |
|
2502 | # aliases won't work in indented sections. | |
2503 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2503 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2504 | make_quoted_expr( transformed )) |
|
2504 | make_quoted_expr( transformed )) | |
2505 |
|
2505 | |||
2506 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2506 | self.log(line_info.line,line_out,line_info.continue_prompt) | |
2507 | #print 'line out:',line_out # dbg |
|
2507 | #print 'line out:',line_out # dbg | |
2508 | return line_out |
|
2508 | return line_out | |
2509 |
|
2509 | |||
2510 | def handle_shell_escape(self, line_info): |
|
2510 | def handle_shell_escape(self, line_info): | |
2511 | """Execute the line in a shell, empty return value""" |
|
2511 | """Execute the line in a shell, empty return value""" | |
2512 | #print 'line in :', `line` # dbg |
|
2512 | #print 'line in :', `line` # dbg | |
2513 | line = line_info.line |
|
2513 | line = line_info.line | |
2514 | if line.lstrip().startswith('!!'): |
|
2514 | if line.lstrip().startswith('!!'): | |
2515 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2515 | # rewrite LineInfo's line, iFun and theRest to properly hold the | |
2516 | # call to %sx and the actual command to be executed, so |
|
2516 | # call to %sx and the actual command to be executed, so | |
2517 | # handle_magic can work correctly. Note that this works even if |
|
2517 | # handle_magic can work correctly. Note that this works even if | |
2518 | # the line is indented, so it handles multi_line_specials |
|
2518 | # the line is indented, so it handles multi_line_specials | |
2519 | # properly. |
|
2519 | # properly. | |
2520 | new_rest = line.lstrip()[2:] |
|
2520 | new_rest = line.lstrip()[2:] | |
2521 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2521 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) | |
2522 | line_info.iFun = 'sx' |
|
2522 | line_info.iFun = 'sx' | |
2523 | line_info.theRest = new_rest |
|
2523 | line_info.theRest = new_rest | |
2524 | return self.handle_magic(line_info) |
|
2524 | return self.handle_magic(line_info) | |
2525 | else: |
|
2525 | else: | |
2526 | cmd = line.lstrip().lstrip('!') |
|
2526 | cmd = line.lstrip().lstrip('!') | |
2527 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2527 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2528 | make_quoted_expr(cmd)) |
|
2528 | make_quoted_expr(cmd)) | |
2529 | # update cache/log and return |
|
2529 | # update cache/log and return | |
2530 | self.log(line,line_out,line_info.continue_prompt) |
|
2530 | self.log(line,line_out,line_info.continue_prompt) | |
2531 | return line_out |
|
2531 | return line_out | |
2532 |
|
2532 | |||
2533 | def handle_magic(self, line_info): |
|
2533 | def handle_magic(self, line_info): | |
2534 | """Execute magic functions.""" |
|
2534 | """Execute magic functions.""" | |
2535 | iFun = line_info.iFun |
|
2535 | iFun = line_info.iFun | |
2536 | theRest = line_info.theRest |
|
2536 | theRest = line_info.theRest | |
2537 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2537 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, | |
2538 | make_quoted_expr(iFun + " " + theRest)) |
|
2538 | make_quoted_expr(iFun + " " + theRest)) | |
2539 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2539 | self.log(line_info.line,cmd,line_info.continue_prompt) | |
2540 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2540 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2541 | return cmd |
|
2541 | return cmd | |
2542 |
|
2542 | |||
2543 | def handle_auto(self, line_info): |
|
2543 | def handle_auto(self, line_info): | |
2544 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2544 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2545 |
|
2545 | |||
2546 | line = line_info.line |
|
2546 | line = line_info.line | |
2547 | iFun = line_info.iFun |
|
2547 | iFun = line_info.iFun | |
2548 | theRest = line_info.theRest |
|
2548 | theRest = line_info.theRest | |
2549 | pre = line_info.pre |
|
2549 | pre = line_info.pre | |
2550 | continue_prompt = line_info.continue_prompt |
|
2550 | continue_prompt = line_info.continue_prompt | |
2551 | obj = line_info.ofind(self)['obj'] |
|
2551 | obj = line_info.ofind(self)['obj'] | |
2552 |
|
2552 | |||
2553 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2553 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2554 |
|
2554 | |||
2555 | # This should only be active for single-line input! |
|
2555 | # This should only be active for single-line input! | |
2556 | if continue_prompt: |
|
2556 | if continue_prompt: | |
2557 | self.log(line,line,continue_prompt) |
|
2557 | self.log(line,line,continue_prompt) | |
2558 | return line |
|
2558 | return line | |
2559 |
|
2559 | |||
2560 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
2560 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) | |
2561 | auto_rewrite = True |
|
2561 | auto_rewrite = True | |
2562 |
|
2562 | |||
2563 | if pre == self.ESC_QUOTE: |
|
2563 | if pre == self.ESC_QUOTE: | |
2564 | # Auto-quote splitting on whitespace |
|
2564 | # Auto-quote splitting on whitespace | |
2565 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2565 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2566 | elif pre == self.ESC_QUOTE2: |
|
2566 | elif pre == self.ESC_QUOTE2: | |
2567 | # Auto-quote whole string |
|
2567 | # Auto-quote whole string | |
2568 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2568 | newcmd = '%s("%s")' % (iFun,theRest) | |
2569 | elif pre == self.ESC_PAREN: |
|
2569 | elif pre == self.ESC_PAREN: | |
2570 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2570 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2571 | else: |
|
2571 | else: | |
2572 | # Auto-paren. |
|
2572 | # Auto-paren. | |
2573 | # We only apply it to argument-less calls if the autocall |
|
2573 | # We only apply it to argument-less calls if the autocall | |
2574 | # parameter is set to 2. We only need to check that autocall is < |
|
2574 | # parameter is set to 2. We only need to check that autocall is < | |
2575 | # 2, since this function isn't called unless it's at least 1. |
|
2575 | # 2, since this function isn't called unless it's at least 1. | |
2576 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
2576 | if not theRest and (self.rc.autocall < 2) and not force_auto: | |
2577 | newcmd = '%s %s' % (iFun,theRest) |
|
2577 | newcmd = '%s %s' % (iFun,theRest) | |
2578 | auto_rewrite = False |
|
2578 | auto_rewrite = False | |
2579 | else: |
|
2579 | else: | |
2580 | if not force_auto and theRest.startswith('['): |
|
2580 | if not force_auto and theRest.startswith('['): | |
2581 | if hasattr(obj,'__getitem__'): |
|
2581 | if hasattr(obj,'__getitem__'): | |
2582 | # Don't autocall in this case: item access for an object |
|
2582 | # Don't autocall in this case: item access for an object | |
2583 | # which is BOTH callable and implements __getitem__. |
|
2583 | # which is BOTH callable and implements __getitem__. | |
2584 | newcmd = '%s %s' % (iFun,theRest) |
|
2584 | newcmd = '%s %s' % (iFun,theRest) | |
2585 | auto_rewrite = False |
|
2585 | auto_rewrite = False | |
2586 | else: |
|
2586 | else: | |
2587 | # if the object doesn't support [] access, go ahead and |
|
2587 | # if the object doesn't support [] access, go ahead and | |
2588 | # autocall |
|
2588 | # autocall | |
2589 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2589 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2590 | elif theRest.endswith(';'): |
|
2590 | elif theRest.endswith(';'): | |
2591 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2591 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2592 | else: |
|
2592 | else: | |
2593 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2593 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2594 |
|
2594 | |||
2595 | if auto_rewrite: |
|
2595 | if auto_rewrite: | |
2596 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2596 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd | |
2597 |
|
2597 | |||
2598 | try: |
|
2598 | try: | |
2599 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2599 | # plain ascii works better w/ pyreadline, on some machines, so | |
2600 | # we use it and only print uncolored rewrite if we have unicode |
|
2600 | # we use it and only print uncolored rewrite if we have unicode | |
2601 | rw = str(rw) |
|
2601 | rw = str(rw) | |
2602 | print >>Term.cout, rw |
|
2602 | print >>Term.cout, rw | |
2603 | except UnicodeEncodeError: |
|
2603 | except UnicodeEncodeError: | |
2604 | print "-------------->" + newcmd |
|
2604 | print "-------------->" + newcmd | |
2605 |
|
2605 | |||
2606 | # log what is now valid Python, not the actual user input (without the |
|
2606 | # log what is now valid Python, not the actual user input (without the | |
2607 | # final newline) |
|
2607 | # final newline) | |
2608 | self.log(line,newcmd,continue_prompt) |
|
2608 | self.log(line,newcmd,continue_prompt) | |
2609 | return newcmd |
|
2609 | return newcmd | |
2610 |
|
2610 | |||
2611 | def handle_help(self, line_info): |
|
2611 | def handle_help(self, line_info): | |
2612 | """Try to get some help for the object. |
|
2612 | """Try to get some help for the object. | |
2613 |
|
2613 | |||
2614 | obj? or ?obj -> basic information. |
|
2614 | obj? or ?obj -> basic information. | |
2615 | obj?? or ??obj -> more details. |
|
2615 | obj?? or ??obj -> more details. | |
2616 | """ |
|
2616 | """ | |
2617 |
|
2617 | |||
2618 | line = line_info.line |
|
2618 | line = line_info.line | |
2619 | # We need to make sure that we don't process lines which would be |
|
2619 | # We need to make sure that we don't process lines which would be | |
2620 | # otherwise valid python, such as "x=1 # what?" |
|
2620 | # otherwise valid python, such as "x=1 # what?" | |
2621 | try: |
|
2621 | try: | |
2622 | codeop.compile_command(line) |
|
2622 | codeop.compile_command(line) | |
2623 | except SyntaxError: |
|
2623 | except SyntaxError: | |
2624 | # We should only handle as help stuff which is NOT valid syntax |
|
2624 | # We should only handle as help stuff which is NOT valid syntax | |
2625 | if line[0]==self.ESC_HELP: |
|
2625 | if line[0]==self.ESC_HELP: | |
2626 | line = line[1:] |
|
2626 | line = line[1:] | |
2627 | elif line[-1]==self.ESC_HELP: |
|
2627 | elif line[-1]==self.ESC_HELP: | |
2628 | line = line[:-1] |
|
2628 | line = line[:-1] | |
2629 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2629 | self.log(line,'#?'+line,line_info.continue_prompt) | |
2630 | if line: |
|
2630 | if line: | |
2631 | #print 'line:<%r>' % line # dbg |
|
2631 | #print 'line:<%r>' % line # dbg | |
2632 | self.magic_pinfo(line) |
|
2632 | self.magic_pinfo(line) | |
2633 | else: |
|
2633 | else: | |
2634 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2634 | page(self.usage,screen_lines=self.rc.screen_length) | |
2635 | return '' # Empty string is needed here! |
|
2635 | return '' # Empty string is needed here! | |
2636 | except: |
|
2636 | except: | |
2637 | # Pass any other exceptions through to the normal handler |
|
2637 | # Pass any other exceptions through to the normal handler | |
2638 | return self.handle_normal(line_info) |
|
2638 | return self.handle_normal(line_info) | |
2639 | else: |
|
2639 | else: | |
2640 | # If the code compiles ok, we should handle it normally |
|
2640 | # If the code compiles ok, we should handle it normally | |
2641 | return self.handle_normal(line_info) |
|
2641 | return self.handle_normal(line_info) | |
2642 |
|
2642 | |||
2643 | def getapi(self): |
|
2643 | def getapi(self): | |
2644 | """ Get an IPApi object for this shell instance |
|
2644 | """ Get an IPApi object for this shell instance | |
2645 |
|
2645 | |||
2646 | Getting an IPApi object is always preferable to accessing the shell |
|
2646 | Getting an IPApi object is always preferable to accessing the shell | |
2647 | directly, but this holds true especially for extensions. |
|
2647 | directly, but this holds true especially for extensions. | |
2648 |
|
2648 | |||
2649 | It should always be possible to implement an extension with IPApi |
|
2649 | It should always be possible to implement an extension with IPApi | |
2650 | alone. If not, contact maintainer to request an addition. |
|
2650 | alone. If not, contact maintainer to request an addition. | |
2651 |
|
2651 | |||
2652 | """ |
|
2652 | """ | |
2653 | return self.api |
|
2653 | return self.api | |
2654 |
|
2654 | |||
2655 | def handle_emacs(self, line_info): |
|
2655 | def handle_emacs(self, line_info): | |
2656 | """Handle input lines marked by python-mode.""" |
|
2656 | """Handle input lines marked by python-mode.""" | |
2657 |
|
2657 | |||
2658 | # Currently, nothing is done. Later more functionality can be added |
|
2658 | # Currently, nothing is done. Later more functionality can be added | |
2659 | # here if needed. |
|
2659 | # here if needed. | |
2660 |
|
2660 | |||
2661 | # The input cache shouldn't be updated |
|
2661 | # The input cache shouldn't be updated | |
2662 | return line_info.line |
|
2662 | return line_info.line | |
2663 |
|
2663 | |||
2664 |
|
2664 | |||
2665 | def mktempfile(self,data=None): |
|
2665 | def mktempfile(self,data=None): | |
2666 | """Make a new tempfile and return its filename. |
|
2666 | """Make a new tempfile and return its filename. | |
2667 |
|
2667 | |||
2668 | This makes a call to tempfile.mktemp, but it registers the created |
|
2668 | This makes a call to tempfile.mktemp, but it registers the created | |
2669 | filename internally so ipython cleans it up at exit time. |
|
2669 | filename internally so ipython cleans it up at exit time. | |
2670 |
|
2670 | |||
2671 | Optional inputs: |
|
2671 | Optional inputs: | |
2672 |
|
2672 | |||
2673 | - data(None): if data is given, it gets written out to the temp file |
|
2673 | - data(None): if data is given, it gets written out to the temp file | |
2674 | immediately, and the file is closed again.""" |
|
2674 | immediately, and the file is closed again.""" | |
2675 |
|
2675 | |||
2676 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2676 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2677 | self.tempfiles.append(filename) |
|
2677 | self.tempfiles.append(filename) | |
2678 |
|
2678 | |||
2679 | if data: |
|
2679 | if data: | |
2680 | tmp_file = open(filename,'w') |
|
2680 | tmp_file = open(filename,'w') | |
2681 | tmp_file.write(data) |
|
2681 | tmp_file.write(data) | |
2682 | tmp_file.close() |
|
2682 | tmp_file.close() | |
2683 | return filename |
|
2683 | return filename | |
2684 |
|
2684 | |||
2685 | def write(self,data): |
|
2685 | def write(self,data): | |
2686 | """Write a string to the default output""" |
|
2686 | """Write a string to the default output""" | |
2687 | Term.cout.write(data) |
|
2687 | Term.cout.write(data) | |
2688 |
|
2688 | |||
2689 | def write_err(self,data): |
|
2689 | def write_err(self,data): | |
2690 | """Write a string to the default error output""" |
|
2690 | """Write a string to the default error output""" | |
2691 | Term.cerr.write(data) |
|
2691 | Term.cerr.write(data) | |
2692 |
|
2692 | |||
2693 | def ask_exit(self): |
|
2693 | def ask_exit(self): | |
2694 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2694 | """ Call for exiting. Can be overiden and used as a callback. """ | |
2695 | self.exit_now = True |
|
2695 | self.exit_now = True | |
2696 |
|
2696 | |||
2697 | def exit(self): |
|
2697 | def exit(self): | |
2698 | """Handle interactive exit. |
|
2698 | """Handle interactive exit. | |
2699 |
|
2699 | |||
2700 | This method calls the ask_exit callback.""" |
|
2700 | This method calls the ask_exit callback.""" | |
2701 |
|
2701 | |||
2702 | if self.rc.confirm_exit: |
|
2702 | if self.rc.confirm_exit: | |
2703 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2703 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2704 | self.ask_exit() |
|
2704 | self.ask_exit() | |
2705 | else: |
|
2705 | else: | |
2706 | self.ask_exit() |
|
2706 | self.ask_exit() | |
2707 |
|
2707 | |||
2708 | def safe_execfile(self,fname,*where,**kw): |
|
2708 | def safe_execfile(self,fname,*where,**kw): | |
2709 | """A safe version of the builtin execfile(). |
|
2709 | """A safe version of the builtin execfile(). | |
2710 |
|
2710 | |||
2711 | This version will never throw an exception, and knows how to handle |
|
2711 | This version will never throw an exception, and knows how to handle | |
2712 | ipython logs as well. |
|
2712 | ipython logs as well. | |
2713 |
|
2713 | |||
2714 | :Parameters: |
|
2714 | :Parameters: | |
2715 | fname : string |
|
2715 | fname : string | |
2716 | Name of the file to be executed. |
|
2716 | Name of the file to be executed. | |
2717 |
|
2717 | |||
2718 | where : tuple |
|
2718 | where : tuple | |
2719 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2719 | One or two namespaces, passed to execfile() as (globals,locals). | |
2720 | If only one is given, it is passed as both. |
|
2720 | If only one is given, it is passed as both. | |
2721 |
|
2721 | |||
2722 | :Keywords: |
|
2722 | :Keywords: | |
2723 | islog : boolean (False) |
|
2723 | islog : boolean (False) | |
2724 |
|
2724 | |||
2725 | quiet : boolean (True) |
|
2725 | quiet : boolean (True) | |
2726 |
|
2726 | |||
2727 | exit_ignore : boolean (False) |
|
2727 | exit_ignore : boolean (False) | |
2728 | """ |
|
2728 | """ | |
2729 |
|
2729 | |||
2730 | def syspath_cleanup(): |
|
2730 | def syspath_cleanup(): | |
2731 | """Internal cleanup routine for sys.path.""" |
|
2731 | """Internal cleanup routine for sys.path.""" | |
2732 | if add_dname: |
|
2732 | if add_dname: | |
2733 | try: |
|
2733 | try: | |
2734 | sys.path.remove(dname) |
|
2734 | sys.path.remove(dname) | |
2735 | except ValueError: |
|
2735 | except ValueError: | |
2736 | # For some reason the user has already removed it, ignore. |
|
2736 | # For some reason the user has already removed it, ignore. | |
2737 | pass |
|
2737 | pass | |
2738 |
|
2738 | |||
2739 | fname = os.path.expanduser(fname) |
|
2739 | fname = os.path.expanduser(fname) | |
2740 |
|
2740 | |||
2741 | # Find things also in current directory. This is needed to mimic the |
|
2741 | # Find things also in current directory. This is needed to mimic the | |
2742 | # behavior of running a script from the system command line, where |
|
2742 | # behavior of running a script from the system command line, where | |
2743 | # Python inserts the script's directory into sys.path |
|
2743 | # Python inserts the script's directory into sys.path | |
2744 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2744 | dname = os.path.dirname(os.path.abspath(fname)) | |
2745 | add_dname = False |
|
2745 | add_dname = False | |
2746 | if dname not in sys.path: |
|
2746 | if dname not in sys.path: | |
2747 | sys.path.insert(0,dname) |
|
2747 | sys.path.insert(0,dname) | |
2748 | add_dname = True |
|
2748 | add_dname = True | |
2749 |
|
2749 | |||
2750 | try: |
|
2750 | try: | |
2751 | xfile = open(fname) |
|
2751 | xfile = open(fname) | |
2752 | except: |
|
2752 | except: | |
2753 | print >> Term.cerr, \ |
|
2753 | print >> Term.cerr, \ | |
2754 | 'Could not open file <%s> for safe execution.' % fname |
|
2754 | 'Could not open file <%s> for safe execution.' % fname | |
2755 | syspath_cleanup() |
|
2755 | syspath_cleanup() | |
2756 | return None |
|
2756 | return None | |
2757 |
|
2757 | |||
2758 | kw.setdefault('islog',0) |
|
2758 | kw.setdefault('islog',0) | |
2759 | kw.setdefault('quiet',1) |
|
2759 | kw.setdefault('quiet',1) | |
2760 | kw.setdefault('exit_ignore',0) |
|
2760 | kw.setdefault('exit_ignore',0) | |
2761 |
|
2761 | |||
2762 | first = xfile.readline() |
|
2762 | first = xfile.readline() | |
2763 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2763 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2764 | xfile.close() |
|
2764 | xfile.close() | |
2765 | # line by line execution |
|
2765 | # line by line execution | |
2766 | if first.startswith(loghead) or kw['islog']: |
|
2766 | if first.startswith(loghead) or kw['islog']: | |
2767 | print 'Loading log file <%s> one line at a time...' % fname |
|
2767 | print 'Loading log file <%s> one line at a time...' % fname | |
2768 | if kw['quiet']: |
|
2768 | if kw['quiet']: | |
2769 | stdout_save = sys.stdout |
|
2769 | stdout_save = sys.stdout | |
2770 | sys.stdout = StringIO.StringIO() |
|
2770 | sys.stdout = StringIO.StringIO() | |
2771 | try: |
|
2771 | try: | |
2772 | globs,locs = where[0:2] |
|
2772 | globs,locs = where[0:2] | |
2773 | except: |
|
2773 | except: | |
2774 | try: |
|
2774 | try: | |
2775 | globs = locs = where[0] |
|
2775 | globs = locs = where[0] | |
2776 | except: |
|
2776 | except: | |
2777 | globs = locs = globals() |
|
2777 | globs = locs = globals() | |
2778 | badblocks = [] |
|
2778 | badblocks = [] | |
2779 |
|
2779 | |||
2780 | # we also need to identify indented blocks of code when replaying |
|
2780 | # we also need to identify indented blocks of code when replaying | |
2781 | # logs and put them together before passing them to an exec |
|
2781 | # logs and put them together before passing them to an exec | |
2782 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2782 | # statement. This takes a bit of regexp and look-ahead work in the | |
2783 | # file. It's easiest if we swallow the whole thing in memory |
|
2783 | # file. It's easiest if we swallow the whole thing in memory | |
2784 | # first, and manually walk through the lines list moving the |
|
2784 | # first, and manually walk through the lines list moving the | |
2785 | # counter ourselves. |
|
2785 | # counter ourselves. | |
2786 | indent_re = re.compile('\s+\S') |
|
2786 | indent_re = re.compile('\s+\S') | |
2787 | xfile = open(fname) |
|
2787 | xfile = open(fname) | |
2788 | filelines = xfile.readlines() |
|
2788 | filelines = xfile.readlines() | |
2789 | xfile.close() |
|
2789 | xfile.close() | |
2790 | nlines = len(filelines) |
|
2790 | nlines = len(filelines) | |
2791 | lnum = 0 |
|
2791 | lnum = 0 | |
2792 | while lnum < nlines: |
|
2792 | while lnum < nlines: | |
2793 | line = filelines[lnum] |
|
2793 | line = filelines[lnum] | |
2794 | lnum += 1 |
|
2794 | lnum += 1 | |
2795 | # don't re-insert logger status info into cache |
|
2795 | # don't re-insert logger status info into cache | |
2796 | if line.startswith('#log#'): |
|
2796 | if line.startswith('#log#'): | |
2797 | continue |
|
2797 | continue | |
2798 | else: |
|
2798 | else: | |
2799 | # build a block of code (maybe a single line) for execution |
|
2799 | # build a block of code (maybe a single line) for execution | |
2800 | block = line |
|
2800 | block = line | |
2801 | try: |
|
2801 | try: | |
2802 | next = filelines[lnum] # lnum has already incremented |
|
2802 | next = filelines[lnum] # lnum has already incremented | |
2803 | except: |
|
2803 | except: | |
2804 | next = None |
|
2804 | next = None | |
2805 | while next and indent_re.match(next): |
|
2805 | while next and indent_re.match(next): | |
2806 | block += next |
|
2806 | block += next | |
2807 | lnum += 1 |
|
2807 | lnum += 1 | |
2808 | try: |
|
2808 | try: | |
2809 | next = filelines[lnum] |
|
2809 | next = filelines[lnum] | |
2810 | except: |
|
2810 | except: | |
2811 | next = None |
|
2811 | next = None | |
2812 | # now execute the block of one or more lines |
|
2812 | # now execute the block of one or more lines | |
2813 | try: |
|
2813 | try: | |
2814 | exec block in globs,locs |
|
2814 | exec block in globs,locs | |
2815 | except SystemExit: |
|
2815 | except SystemExit: | |
2816 | pass |
|
2816 | pass | |
2817 | except: |
|
2817 | except: | |
2818 | badblocks.append(block.rstrip()) |
|
2818 | badblocks.append(block.rstrip()) | |
2819 | if kw['quiet']: # restore stdout |
|
2819 | if kw['quiet']: # restore stdout | |
2820 | sys.stdout.close() |
|
2820 | sys.stdout.close() | |
2821 | sys.stdout = stdout_save |
|
2821 | sys.stdout = stdout_save | |
2822 | print 'Finished replaying log file <%s>' % fname |
|
2822 | print 'Finished replaying log file <%s>' % fname | |
2823 | if badblocks: |
|
2823 | if badblocks: | |
2824 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2824 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2825 | '<%s> reported errors:' % fname) |
|
2825 | '<%s> reported errors:' % fname) | |
2826 |
|
2826 | |||
2827 | for badline in badblocks: |
|
2827 | for badline in badblocks: | |
2828 | print >> sys.stderr, badline |
|
2828 | print >> sys.stderr, badline | |
2829 | else: # regular file execution |
|
2829 | else: # regular file execution | |
2830 | try: |
|
2830 | try: | |
2831 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2831 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
2832 | # Work around a bug in Python for Windows. The bug was |
|
2832 | # Work around a bug in Python for Windows. The bug was | |
2833 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2833 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |
2834 | # SVN Python as of March/07. For details, see: |
|
2834 | # SVN Python as of March/07. For details, see: | |
2835 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2835 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |
2836 | try: |
|
2836 | try: | |
2837 | globs,locs = where[0:2] |
|
2837 | globs,locs = where[0:2] | |
2838 | except: |
|
2838 | except: | |
2839 | try: |
|
2839 | try: | |
2840 | globs = locs = where[0] |
|
2840 | globs = locs = where[0] | |
2841 | except: |
|
2841 | except: | |
2842 | globs = locs = globals() |
|
2842 | globs = locs = globals() | |
2843 | exec file(fname) in globs,locs |
|
2843 | exec file(fname) in globs,locs | |
2844 | else: |
|
2844 | else: | |
2845 | execfile(fname,*where) |
|
2845 | execfile(fname,*where) | |
2846 | except SyntaxError: |
|
2846 | except SyntaxError: | |
2847 | self.showsyntaxerror() |
|
2847 | self.showsyntaxerror() | |
2848 | warn('Failure executing file: <%s>' % fname) |
|
2848 | warn('Failure executing file: <%s>' % fname) | |
2849 | except SystemExit,status: |
|
2849 | except SystemExit,status: | |
2850 | # Code that correctly sets the exit status flag to success (0) |
|
2850 | # Code that correctly sets the exit status flag to success (0) | |
2851 | # shouldn't be bothered with a traceback. Note that a plain |
|
2851 | # shouldn't be bothered with a traceback. Note that a plain | |
2852 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2852 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |
2853 | # will still get a traceback. Note that the structure of the |
|
2853 | # will still get a traceback. Note that the structure of the | |
2854 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2854 | # SystemExit exception changed between Python 2.4 and 2.5, so | |
2855 | # the checks must be done in a version-dependent way. |
|
2855 | # the checks must be done in a version-dependent way. | |
2856 | show = False |
|
2856 | show = False | |
2857 |
|
2857 | |||
2858 | if sys.version_info[:2] > (2,5): |
|
2858 | if sys.version_info[:2] > (2,5): | |
2859 | if status.message!=0 and not kw['exit_ignore']: |
|
2859 | if status.message!=0 and not kw['exit_ignore']: | |
2860 | show = True |
|
2860 | show = True | |
2861 | else: |
|
2861 | else: | |
2862 | if status.code and not kw['exit_ignore']: |
|
2862 | if status.code and not kw['exit_ignore']: | |
2863 | show = True |
|
2863 | show = True | |
2864 | if show: |
|
2864 | if show: | |
2865 | self.showtraceback() |
|
2865 | self.showtraceback() | |
2866 | warn('Failure executing file: <%s>' % fname) |
|
2866 | warn('Failure executing file: <%s>' % fname) | |
2867 | except: |
|
2867 | except: | |
2868 | self.showtraceback() |
|
2868 | self.showtraceback() | |
2869 | warn('Failure executing file: <%s>' % fname) |
|
2869 | warn('Failure executing file: <%s>' % fname) | |
2870 |
|
2870 | |||
2871 | syspath_cleanup() |
|
2871 | syspath_cleanup() | |
2872 |
|
2872 | |||
2873 | #************************* end of file <iplib.py> ***************************** |
|
2873 | #************************* end of file <iplib.py> ***************************** |
General Comments 0
You need to be logged in to leave comments.
Login now