Show More
@@ -1,2836 +1,2839 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | Requires Python 2.4 or newer. |
|
5 | Requires Python 2.4 or newer. | |
6 |
|
6 | |||
7 | This file contains all the classes and helper functions specific to IPython. |
|
7 | This file contains all the classes and helper functions specific to IPython. | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
11 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | # |
|
16 | # | |
17 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
17 | # Note: this code originally subclassed code.InteractiveConsole from the | |
18 | # Python standard library. Over time, all of that class has been copied |
|
18 | # Python standard library. Over time, all of that class has been copied | |
19 | # verbatim here for modifications which could not be accomplished by |
|
19 | # verbatim here for modifications which could not be accomplished by | |
20 | # subclassing. At this point, there are no dependencies at all on the code |
|
20 | # subclassing. At this point, there are no dependencies at all on the code | |
21 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
21 | # module anymore (it is not even imported). The Python License (sec. 2) | |
22 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
22 | # allows for this, but it's always nice to acknowledge credit where credit is | |
23 | # due. |
|
23 | # due. | |
24 | #***************************************************************************** |
|
24 | #***************************************************************************** | |
25 |
|
25 | |||
26 | #**************************************************************************** |
|
26 | #**************************************************************************** | |
27 | # Modules and globals |
|
27 | # Modules and globals | |
28 |
|
28 | |||
29 | # Python standard modules |
|
29 | # Python standard modules | |
30 | import __main__ |
|
30 | import __main__ | |
31 | import __builtin__ |
|
31 | import __builtin__ | |
32 | import StringIO |
|
32 | import StringIO | |
33 | import bdb |
|
33 | import bdb | |
34 | import cPickle as pickle |
|
34 | import cPickle as pickle | |
35 | import codeop |
|
35 | import codeop | |
36 | import exceptions |
|
36 | import exceptions | |
37 | import glob |
|
37 | import glob | |
38 | import inspect |
|
38 | import inspect | |
39 | import keyword |
|
39 | import keyword | |
40 | import new |
|
40 | import new | |
41 | import os |
|
41 | import os | |
42 | import pydoc |
|
42 | import pydoc | |
43 | import re |
|
43 | import re | |
44 | import shutil |
|
44 | import shutil | |
45 | import string |
|
45 | import string | |
46 | import sys |
|
46 | import sys | |
47 | import tempfile |
|
47 | import tempfile | |
48 | import traceback |
|
48 | import traceback | |
49 | import types |
|
49 | import types | |
50 | from pprint import pprint, pformat |
|
50 | from pprint import pprint, pformat | |
51 |
|
51 | |||
52 | # IPython's own modules |
|
52 | # IPython's own modules | |
53 | #import IPython |
|
53 | #import IPython | |
54 | from IPython import Debugger,OInspect,PyColorize,ultraTB |
|
54 | from IPython import Debugger,OInspect,PyColorize,ultraTB | |
55 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
55 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names | |
56 | from IPython.Extensions import pickleshare |
|
56 | from IPython.Extensions import pickleshare | |
57 | from IPython.FakeModule import FakeModule |
|
57 | from IPython.FakeModule import FakeModule | |
58 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
58 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
59 | from IPython.Logger import Logger |
|
59 | from IPython.Logger import Logger | |
60 | from IPython.Magic import Magic |
|
60 | from IPython.Magic import Magic | |
61 | from IPython.Prompts import CachedOutput |
|
61 | from IPython.Prompts import CachedOutput | |
62 | from IPython.ipstruct import Struct |
|
62 | from IPython.ipstruct import Struct | |
63 | from IPython.background_jobs import BackgroundJobManager |
|
63 | from IPython.background_jobs import BackgroundJobManager | |
64 | from IPython.usage import cmd_line_usage,interactive_usage |
|
64 | from IPython.usage import cmd_line_usage,interactive_usage | |
65 | from IPython.genutils import * |
|
65 | from IPython.genutils import * | |
66 | from IPython.strdispatch import StrDispatch |
|
66 | from IPython.strdispatch import StrDispatch | |
67 | import IPython.ipapi |
|
67 | import IPython.ipapi | |
68 | import IPython.history |
|
68 | import IPython.history | |
69 | import IPython.prefilter as prefilter |
|
69 | import IPython.prefilter as prefilter | |
70 | import IPython.shadowns |
|
70 | import IPython.shadowns | |
71 | # Globals |
|
71 | # Globals | |
72 |
|
72 | |||
73 | # store the builtin raw_input globally, and use this always, in case user code |
|
73 | # store the builtin raw_input globally, and use this always, in case user code | |
74 | # overwrites it (like wx.py.PyShell does) |
|
74 | # overwrites it (like wx.py.PyShell does) | |
75 | raw_input_original = raw_input |
|
75 | raw_input_original = raw_input | |
76 |
|
76 | |||
77 | # compiled regexps for autoindent management |
|
77 | # compiled regexps for autoindent management | |
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
79 |
|
79 | |||
80 |
|
80 | |||
81 | #**************************************************************************** |
|
81 | #**************************************************************************** | |
82 | # Some utility function definitions |
|
82 | # Some utility function definitions | |
83 |
|
83 | |||
84 | ini_spaces_re = re.compile(r'^(\s+)') |
|
84 | ini_spaces_re = re.compile(r'^(\s+)') | |
85 |
|
85 | |||
86 | def num_ini_spaces(strng): |
|
86 | def num_ini_spaces(strng): | |
87 | """Return the number of initial spaces in a string""" |
|
87 | """Return the number of initial spaces in a string""" | |
88 |
|
88 | |||
89 | ini_spaces = ini_spaces_re.match(strng) |
|
89 | ini_spaces = ini_spaces_re.match(strng) | |
90 | if ini_spaces: |
|
90 | if ini_spaces: | |
91 | return ini_spaces.end() |
|
91 | return ini_spaces.end() | |
92 | else: |
|
92 | else: | |
93 | return 0 |
|
93 | return 0 | |
94 |
|
94 | |||
95 | def softspace(file, newvalue): |
|
95 | def softspace(file, newvalue): | |
96 | """Copied from code.py, to remove the dependency""" |
|
96 | """Copied from code.py, to remove the dependency""" | |
97 |
|
97 | |||
98 | oldvalue = 0 |
|
98 | oldvalue = 0 | |
99 | try: |
|
99 | try: | |
100 | oldvalue = file.softspace |
|
100 | oldvalue = file.softspace | |
101 | except AttributeError: |
|
101 | except AttributeError: | |
102 | pass |
|
102 | pass | |
103 | try: |
|
103 | try: | |
104 | file.softspace = newvalue |
|
104 | file.softspace = newvalue | |
105 | except (AttributeError, TypeError): |
|
105 | except (AttributeError, TypeError): | |
106 | # "attribute-less object" or "read-only attributes" |
|
106 | # "attribute-less object" or "read-only attributes" | |
107 | pass |
|
107 | pass | |
108 | return oldvalue |
|
108 | return oldvalue | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | 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 | if mode == 'install' and os.path.isdir(ipythondir): |
|
156 | if mode == 'install' and os.path.isdir(ipythondir): | |
157 | return |
|
157 | return | |
158 |
|
158 | |||
159 | cwd = os.getcwd() # remember where we started |
|
159 | cwd = os.getcwd() # remember where we started | |
160 | glb = glob.glob |
|
160 | glb = glob.glob | |
161 |
|
161 | |||
162 | printf('*'*70) |
|
162 | printf('*'*70) | |
163 | if mode == 'install': |
|
163 | if mode == 'install': | |
164 | printf( |
|
164 | printf( | |
165 | """Welcome to IPython. I will try to create a personal configuration directory |
|
165 | """Welcome to IPython. I will try to create a personal configuration directory | |
166 | where you can customize many aspects of IPython's functionality in:\n""") |
|
166 | where you can customize many aspects of IPython's functionality in:\n""") | |
167 | else: |
|
167 | else: | |
168 | printf('I am going to upgrade your configuration in:') |
|
168 | printf('I am going to upgrade your configuration in:') | |
169 |
|
169 | |||
170 | printf(ipythondir) |
|
170 | printf(ipythondir) | |
171 |
|
171 | |||
172 | rcdirend = os.path.join('IPython','UserConfig') |
|
172 | rcdirend = os.path.join('IPython','UserConfig') | |
173 | cfg = lambda d: os.path.join(d,rcdirend) |
|
173 | cfg = lambda d: os.path.join(d,rcdirend) | |
174 | try: |
|
174 | try: | |
175 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
175 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
176 | printf("Initializing from configuration: %s" % rcdir) |
|
176 | printf("Initializing from configuration: %s" % rcdir) | |
177 | except IndexError: |
|
177 | except IndexError: | |
178 | warning = """ |
|
178 | warning = """ | |
179 | Installation error. IPython's directory was not found. |
|
179 | Installation error. IPython's directory was not found. | |
180 |
|
180 | |||
181 | Check the following: |
|
181 | Check the following: | |
182 |
|
182 | |||
183 | The ipython/IPython directory should be in a directory belonging to your |
|
183 | The ipython/IPython directory should be in a directory belonging to your | |
184 | PYTHONPATH environment variable (that is, it should be in a directory |
|
184 | PYTHONPATH environment variable (that is, it should be in a directory | |
185 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
185 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
186 |
|
186 | |||
187 | IPython will create a minimal default configuration for you. |
|
187 | IPython will create a minimal default configuration for you. | |
188 |
|
188 | |||
189 | """ |
|
189 | """ | |
190 | warn(warning) |
|
190 | warn(warning) | |
191 | wait() |
|
191 | wait() | |
192 |
|
192 | |||
193 | if sys.platform =='win32': |
|
193 | if sys.platform =='win32': | |
194 | inif = 'ipythonrc.ini' |
|
194 | inif = 'ipythonrc.ini' | |
195 | else: |
|
195 | else: | |
196 | inif = 'ipythonrc' |
|
196 | inif = 'ipythonrc' | |
197 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', |
|
197 | minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', | |
198 | inif : '# intentionally left blank' } |
|
198 | inif : '# intentionally left blank' } | |
199 | os.makedirs(ipythondir, mode = 0777) |
|
199 | os.makedirs(ipythondir, mode = 0777) | |
200 | for f, cont in minimal_setup.items(): |
|
200 | for f, cont in minimal_setup.items(): | |
201 | # In 2.5, this can be more cleanly done using 'with' |
|
201 | # In 2.5, this can be more cleanly done using 'with' | |
202 | fobj = file(ipythondir + '/' + f,'w') |
|
202 | fobj = file(ipythondir + '/' + f,'w') | |
203 | fobj.write(cont) |
|
203 | fobj.write(cont) | |
204 | fobj.close() |
|
204 | fobj.close() | |
205 |
|
205 | |||
206 | return |
|
206 | return | |
207 |
|
207 | |||
208 | if mode == 'install': |
|
208 | if mode == 'install': | |
209 | try: |
|
209 | try: | |
210 | shutil.copytree(rcdir,ipythondir) |
|
210 | shutil.copytree(rcdir,ipythondir) | |
211 | os.chdir(ipythondir) |
|
211 | os.chdir(ipythondir) | |
212 | rc_files = glb("ipythonrc*") |
|
212 | rc_files = glb("ipythonrc*") | |
213 | for rc_file in rc_files: |
|
213 | for rc_file in rc_files: | |
214 | os.rename(rc_file,rc_file+rc_suffix) |
|
214 | os.rename(rc_file,rc_file+rc_suffix) | |
215 | except: |
|
215 | except: | |
216 | warning = """ |
|
216 | warning = """ | |
217 |
|
217 | |||
218 | There was a problem with the installation: |
|
218 | There was a problem with the installation: | |
219 | %s |
|
219 | %s | |
220 | Try to correct it or contact the developers if you think it's a bug. |
|
220 | Try to correct it or contact the developers if you think it's a bug. | |
221 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
221 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
222 | warn(warning) |
|
222 | warn(warning) | |
223 | wait() |
|
223 | wait() | |
224 | return |
|
224 | return | |
225 |
|
225 | |||
226 | elif mode == 'upgrade': |
|
226 | elif mode == 'upgrade': | |
227 | try: |
|
227 | try: | |
228 | os.chdir(ipythondir) |
|
228 | os.chdir(ipythondir) | |
229 | except: |
|
229 | except: | |
230 | printf(""" |
|
230 | printf(""" | |
231 | Can not upgrade: changing to directory %s failed. Details: |
|
231 | Can not upgrade: changing to directory %s failed. Details: | |
232 | %s |
|
232 | %s | |
233 | """ % (ipythondir,sys.exc_info()[1]) ) |
|
233 | """ % (ipythondir,sys.exc_info()[1]) ) | |
234 | wait() |
|
234 | wait() | |
235 | return |
|
235 | return | |
236 | else: |
|
236 | else: | |
237 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
237 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
238 | for new_full_path in sources: |
|
238 | for new_full_path in sources: | |
239 | new_filename = os.path.basename(new_full_path) |
|
239 | new_filename = os.path.basename(new_full_path) | |
240 | if new_filename.startswith('ipythonrc'): |
|
240 | if new_filename.startswith('ipythonrc'): | |
241 | new_filename = new_filename + rc_suffix |
|
241 | new_filename = new_filename + rc_suffix | |
242 | # The config directory should only contain files, skip any |
|
242 | # The config directory should only contain files, skip any | |
243 | # directories which may be there (like CVS) |
|
243 | # directories which may be there (like CVS) | |
244 | if os.path.isdir(new_full_path): |
|
244 | if os.path.isdir(new_full_path): | |
245 | continue |
|
245 | continue | |
246 | if os.path.exists(new_filename): |
|
246 | if os.path.exists(new_filename): | |
247 | old_file = new_filename+'.old' |
|
247 | old_file = new_filename+'.old' | |
248 | if os.path.exists(old_file): |
|
248 | if os.path.exists(old_file): | |
249 | os.remove(old_file) |
|
249 | os.remove(old_file) | |
250 | os.rename(new_filename,old_file) |
|
250 | os.rename(new_filename,old_file) | |
251 | shutil.copy(new_full_path,new_filename) |
|
251 | shutil.copy(new_full_path,new_filename) | |
252 | else: |
|
252 | else: | |
253 | raise ValueError('unrecognized mode for install: %r' % mode) |
|
253 | raise ValueError('unrecognized mode for install: %r' % mode) | |
254 |
|
254 | |||
255 | # Fix line-endings to those native to each platform in the config |
|
255 | # Fix line-endings to those native to each platform in the config | |
256 | # directory. |
|
256 | # directory. | |
257 | try: |
|
257 | try: | |
258 | os.chdir(ipythondir) |
|
258 | os.chdir(ipythondir) | |
259 | except: |
|
259 | except: | |
260 | printf(""" |
|
260 | printf(""" | |
261 | Problem: changing to directory %s failed. |
|
261 | Problem: changing to directory %s failed. | |
262 | Details: |
|
262 | Details: | |
263 | %s |
|
263 | %s | |
264 |
|
264 | |||
265 | Some configuration files may have incorrect line endings. This should not |
|
265 | Some configuration files may have incorrect line endings. This should not | |
266 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) ) |
|
266 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) ) | |
267 | wait() |
|
267 | wait() | |
268 | else: |
|
268 | else: | |
269 | for fname in glb('ipythonrc*'): |
|
269 | for fname in glb('ipythonrc*'): | |
270 | try: |
|
270 | try: | |
271 | native_line_ends(fname,backup=0) |
|
271 | native_line_ends(fname,backup=0) | |
272 | except IOError: |
|
272 | except IOError: | |
273 | pass |
|
273 | pass | |
274 |
|
274 | |||
275 | if mode == 'install': |
|
275 | if mode == 'install': | |
276 | printf(""" |
|
276 | printf(""" | |
277 | Successful installation! |
|
277 | Successful installation! | |
278 |
|
278 | |||
279 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
279 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
280 | IPython manual (there are both HTML and PDF versions supplied with the |
|
280 | IPython manual (there are both HTML and PDF versions supplied with the | |
281 | distribution) to make sure that your system environment is properly configured |
|
281 | distribution) to make sure that your system environment is properly configured | |
282 | to take advantage of IPython's features. |
|
282 | to take advantage of IPython's features. | |
283 |
|
283 | |||
284 | Important note: the configuration system has changed! The old system is |
|
284 | Important note: the configuration system has changed! The old system is | |
285 | still in place, but its setting may be partly overridden by the settings in |
|
285 | still in place, but its setting may be partly overridden by the settings in | |
286 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file |
|
286 | "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file | |
287 | if some of the new settings bother you. |
|
287 | if some of the new settings bother you. | |
288 |
|
288 | |||
289 | """) |
|
289 | """) | |
290 | else: |
|
290 | else: | |
291 | printf(""" |
|
291 | printf(""" | |
292 | Successful upgrade! |
|
292 | Successful upgrade! | |
293 |
|
293 | |||
294 | All files in your directory: |
|
294 | All files in your directory: | |
295 | %(ipythondir)s |
|
295 | %(ipythondir)s | |
296 | which would have been overwritten by the upgrade were backed up with a .old |
|
296 | which would have been overwritten by the upgrade were backed up with a .old | |
297 | extension. If you had made particular customizations in those files you may |
|
297 | extension. If you had made particular customizations in those files you may | |
298 | want to merge them back into the new files.""" % locals() ) |
|
298 | want to merge them back into the new files.""" % locals() ) | |
299 | wait() |
|
299 | wait() | |
300 | os.chdir(cwd) |
|
300 | os.chdir(cwd) | |
301 |
|
301 | |||
302 | #**************************************************************************** |
|
302 | #**************************************************************************** | |
303 | # Local use exceptions |
|
303 | # Local use exceptions | |
304 | class SpaceInInput(exceptions.Exception): pass |
|
304 | class SpaceInInput(exceptions.Exception): pass | |
305 |
|
305 | |||
306 |
|
306 | |||
307 | #**************************************************************************** |
|
307 | #**************************************************************************** | |
308 | # Local use classes |
|
308 | # Local use classes | |
309 | class Bunch: pass |
|
309 | class Bunch: pass | |
310 |
|
310 | |||
311 | class Undefined: pass |
|
311 | class Undefined: pass | |
312 |
|
312 | |||
313 | class Quitter(object): |
|
313 | class Quitter(object): | |
314 | """Simple class to handle exit, similar to Python 2.5's. |
|
314 | """Simple class to handle exit, similar to Python 2.5's. | |
315 |
|
315 | |||
316 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 |
|
316 | It handles exiting in an ipython-safe manner, which the one in Python 2.5 | |
317 | doesn't do (obviously, since it doesn't know about ipython).""" |
|
317 | doesn't do (obviously, since it doesn't know about ipython).""" | |
318 |
|
318 | |||
319 | def __init__(self,shell,name): |
|
319 | def __init__(self,shell,name): | |
320 | self.shell = shell |
|
320 | self.shell = shell | |
321 | self.name = name |
|
321 | self.name = name | |
322 |
|
322 | |||
323 | def __repr__(self): |
|
323 | def __repr__(self): | |
324 | return 'Type %s() to exit.' % self.name |
|
324 | return 'Type %s() to exit.' % self.name | |
325 | __str__ = __repr__ |
|
325 | __str__ = __repr__ | |
326 |
|
326 | |||
327 | def __call__(self): |
|
327 | def __call__(self): | |
328 | self.shell.exit() |
|
328 | self.shell.exit() | |
329 |
|
329 | |||
330 | class InputList(list): |
|
330 | class InputList(list): | |
331 | """Class to store user input. |
|
331 | """Class to store user input. | |
332 |
|
332 | |||
333 | It's basically a list, but slices return a string instead of a list, thus |
|
333 | It's basically a list, but slices return a string instead of a list, thus | |
334 | allowing things like (assuming 'In' is an instance): |
|
334 | allowing things like (assuming 'In' is an instance): | |
335 |
|
335 | |||
336 | exec In[4:7] |
|
336 | exec In[4:7] | |
337 |
|
337 | |||
338 | or |
|
338 | or | |
339 |
|
339 | |||
340 | exec In[5:9] + In[14] + In[21:25]""" |
|
340 | exec In[5:9] + In[14] + In[21:25]""" | |
341 |
|
341 | |||
342 | def __getslice__(self,i,j): |
|
342 | def __getslice__(self,i,j): | |
343 | return ''.join(list.__getslice__(self,i,j)) |
|
343 | return ''.join(list.__getslice__(self,i,j)) | |
344 |
|
344 | |||
345 | class SyntaxTB(ultraTB.ListTB): |
|
345 | class SyntaxTB(ultraTB.ListTB): | |
346 | """Extension which holds some state: the last exception value""" |
|
346 | """Extension which holds some state: the last exception value""" | |
347 |
|
347 | |||
348 | def __init__(self,color_scheme = 'NoColor'): |
|
348 | def __init__(self,color_scheme = 'NoColor'): | |
349 | ultraTB.ListTB.__init__(self,color_scheme) |
|
349 | ultraTB.ListTB.__init__(self,color_scheme) | |
350 | self.last_syntax_error = None |
|
350 | self.last_syntax_error = None | |
351 |
|
351 | |||
352 | def __call__(self, etype, value, elist): |
|
352 | def __call__(self, etype, value, elist): | |
353 | self.last_syntax_error = value |
|
353 | self.last_syntax_error = value | |
354 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
354 | ultraTB.ListTB.__call__(self,etype,value,elist) | |
355 |
|
355 | |||
356 | def clear_err_state(self): |
|
356 | def clear_err_state(self): | |
357 | """Return the current error state and clear it""" |
|
357 | """Return the current error state and clear it""" | |
358 | e = self.last_syntax_error |
|
358 | e = self.last_syntax_error | |
359 | self.last_syntax_error = None |
|
359 | self.last_syntax_error = None | |
360 | return e |
|
360 | return e | |
361 |
|
361 | |||
362 | #**************************************************************************** |
|
362 | #**************************************************************************** | |
363 | # Main IPython class |
|
363 | # Main IPython class | |
364 |
|
364 | |||
365 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
365 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |
366 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
366 | # until a full rewrite is made. I've cleaned all cross-class uses of | |
367 | # attributes and methods, but too much user code out there relies on the |
|
367 | # attributes and methods, but too much user code out there relies on the | |
368 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
368 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |
369 | # |
|
369 | # | |
370 | # But at least now, all the pieces have been separated and we could, in |
|
370 | # But at least now, all the pieces have been separated and we could, in | |
371 | # principle, stop using the mixin. This will ease the transition to the |
|
371 | # principle, stop using the mixin. This will ease the transition to the | |
372 | # chainsaw branch. |
|
372 | # chainsaw branch. | |
373 |
|
373 | |||
374 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
374 | # For reference, the following is the list of 'self.foo' uses in the Magic | |
375 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
375 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |
376 | # class, to prevent clashes. |
|
376 | # class, to prevent clashes. | |
377 |
|
377 | |||
378 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
378 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |
379 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
379 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |
380 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
380 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |
381 | # 'self.value'] |
|
381 | # 'self.value'] | |
382 |
|
382 | |||
383 | class InteractiveShell(object,Magic): |
|
383 | class InteractiveShell(object,Magic): | |
384 | """An enhanced console for Python.""" |
|
384 | """An enhanced console for Python.""" | |
385 |
|
385 | |||
386 | # class attribute to indicate whether the class supports threads or not. |
|
386 | # class attribute to indicate whether the class supports threads or not. | |
387 | # Subclasses with thread support should override this as needed. |
|
387 | # Subclasses with thread support should override this as needed. | |
388 | isthreaded = False |
|
388 | isthreaded = False | |
389 |
|
389 | |||
390 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
390 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
391 | user_ns=None,user_global_ns=None,banner2='', |
|
391 | user_ns=None,user_global_ns=None,banner2='', | |
392 | custom_exceptions=((),None),embedded=False): |
|
392 | custom_exceptions=((),None),embedded=False): | |
393 |
|
393 | |||
394 | # log system |
|
394 | # log system | |
395 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
395 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
396 |
|
396 | |||
397 | # Job manager (for jobs run as background threads) |
|
397 | # Job manager (for jobs run as background threads) | |
398 | self.jobs = BackgroundJobManager() |
|
398 | self.jobs = BackgroundJobManager() | |
399 |
|
399 | |||
400 | # Store the actual shell's name |
|
400 | # Store the actual shell's name | |
401 | self.name = name |
|
401 | self.name = name | |
402 | self.more = False |
|
402 | self.more = False | |
403 |
|
403 | |||
404 | # We need to know whether the instance is meant for embedding, since |
|
404 | # We need to know whether the instance is meant for embedding, since | |
405 | # global/local namespaces need to be handled differently in that case |
|
405 | # global/local namespaces need to be handled differently in that case | |
406 | self.embedded = embedded |
|
406 | self.embedded = embedded | |
407 | if embedded: |
|
407 | if embedded: | |
408 | # Control variable so users can, from within the embedded instance, |
|
408 | # Control variable so users can, from within the embedded instance, | |
409 | # permanently deactivate it. |
|
409 | # permanently deactivate it. | |
410 | self.embedded_active = True |
|
410 | self.embedded_active = True | |
411 |
|
411 | |||
412 | # command compiler |
|
412 | # command compiler | |
413 | self.compile = codeop.CommandCompiler() |
|
413 | self.compile = codeop.CommandCompiler() | |
414 |
|
414 | |||
415 | # User input buffer |
|
415 | # User input buffer | |
416 | self.buffer = [] |
|
416 | self.buffer = [] | |
417 |
|
417 | |||
418 | # Default name given in compilation of code |
|
418 | # Default name given in compilation of code | |
419 | self.filename = '<ipython console>' |
|
419 | self.filename = '<ipython console>' | |
420 |
|
420 | |||
421 | # Install our own quitter instead of the builtins. For python2.3-2.4, |
|
421 | # Install our own quitter instead of the builtins. For python2.3-2.4, | |
422 | # this brings in behavior like 2.5, and for 2.5 it's identical. |
|
422 | # this brings in behavior like 2.5, and for 2.5 it's identical. | |
423 | __builtin__.exit = Quitter(self,'exit') |
|
423 | __builtin__.exit = Quitter(self,'exit') | |
424 | __builtin__.quit = Quitter(self,'quit') |
|
424 | __builtin__.quit = Quitter(self,'quit') | |
425 |
|
425 | |||
426 | # Make an empty namespace, which extension writers can rely on both |
|
426 | # Make an empty namespace, which extension writers can rely on both | |
427 | # existing and NEVER being used by ipython itself. This gives them a |
|
427 | # existing and NEVER being used by ipython itself. This gives them a | |
428 | # convenient location for storing additional information and state |
|
428 | # convenient location for storing additional information and state | |
429 | # their extensions may require, without fear of collisions with other |
|
429 | # their extensions may require, without fear of collisions with other | |
430 | # ipython names that may develop later. |
|
430 | # ipython names that may develop later. | |
431 | self.meta = Struct() |
|
431 | self.meta = Struct() | |
432 |
|
432 | |||
433 | # Create the namespace where the user will operate. user_ns is |
|
433 | # Create the namespace where the user will operate. user_ns is | |
434 | # normally the only one used, and it is passed to the exec calls as |
|
434 | # normally the only one used, and it is passed to the exec calls as | |
435 | # the locals argument. But we do carry a user_global_ns namespace |
|
435 | # the locals argument. But we do carry a user_global_ns namespace | |
436 | # given as the exec 'globals' argument, This is useful in embedding |
|
436 | # given as the exec 'globals' argument, This is useful in embedding | |
437 | # situations where the ipython shell opens in a context where the |
|
437 | # situations where the ipython shell opens in a context where the | |
438 | # distinction between locals and globals is meaningful. For |
|
438 | # distinction between locals and globals is meaningful. For | |
439 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
439 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
440 |
|
440 | |||
441 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
441 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
442 | # level as a dict instead of a module. This is a manual fix, but I |
|
442 | # level as a dict instead of a module. This is a manual fix, but I | |
443 | # should really track down where the problem is coming from. Alex |
|
443 | # should really track down where the problem is coming from. Alex | |
444 | # Schmolck reported this problem first. |
|
444 | # Schmolck reported this problem first. | |
445 |
|
445 | |||
446 | # A useful post by Alex Martelli on this topic: |
|
446 | # A useful post by Alex Martelli on this topic: | |
447 | # Re: inconsistent value from __builtins__ |
|
447 | # Re: inconsistent value from __builtins__ | |
448 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
448 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
449 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
449 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
450 | # Gruppen: comp.lang.python |
|
450 | # Gruppen: comp.lang.python | |
451 |
|
451 | |||
452 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
452 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
453 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
453 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
454 | # > <type 'dict'> |
|
454 | # > <type 'dict'> | |
455 | # > >>> print type(__builtins__) |
|
455 | # > >>> print type(__builtins__) | |
456 | # > <type 'module'> |
|
456 | # > <type 'module'> | |
457 | # > Is this difference in return value intentional? |
|
457 | # > Is this difference in return value intentional? | |
458 |
|
458 | |||
459 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
459 | # Well, it's documented that '__builtins__' can be either a dictionary | |
460 | # or a module, and it's been that way for a long time. Whether it's |
|
460 | # or a module, and it's been that way for a long time. Whether it's | |
461 | # intentional (or sensible), I don't know. In any case, the idea is |
|
461 | # intentional (or sensible), I don't know. In any case, the idea is | |
462 | # that if you need to access the built-in namespace directly, you |
|
462 | # that if you need to access the built-in namespace directly, you | |
463 | # should start with "import __builtin__" (note, no 's') which will |
|
463 | # should start with "import __builtin__" (note, no 's') which will | |
464 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
464 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
465 |
|
465 | |||
466 | # These routines return properly built dicts as needed by the rest of |
|
466 | # These routines return properly built dicts as needed by the rest of | |
467 | # the code, and can also be used by extension writers to generate |
|
467 | # the code, and can also be used by extension writers to generate | |
468 | # properly initialized namespaces. |
|
468 | # properly initialized namespaces. | |
469 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, |
|
469 | user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns, | |
470 | user_global_ns) |
|
470 | user_global_ns) | |
471 |
|
471 | |||
472 | # Assign namespaces |
|
472 | # Assign namespaces | |
473 | # This is the namespace where all normal user variables live |
|
473 | # This is the namespace where all normal user variables live | |
474 | self.user_ns = user_ns |
|
474 | self.user_ns = user_ns | |
475 | self.user_global_ns = user_global_ns |
|
475 | self.user_global_ns = user_global_ns | |
476 |
|
476 | |||
477 | # An auxiliary namespace that checks what parts of the user_ns were |
|
477 | # An auxiliary namespace that checks what parts of the user_ns were | |
478 | # loaded at startup, so we can list later only variables defined in |
|
478 | # loaded at startup, so we can list later only variables defined in | |
479 | # actual interactive use. Since it is always a subset of user_ns, it |
|
479 | # actual interactive use. Since it is always a subset of user_ns, it | |
480 | # doesn't need to be seaparately tracked in the ns_table |
|
480 | # doesn't need to be seaparately tracked in the ns_table | |
481 | self.user_config_ns = {} |
|
481 | self.user_config_ns = {} | |
482 |
|
482 | |||
483 | # A namespace to keep track of internal data structures to prevent |
|
483 | # A namespace to keep track of internal data structures to prevent | |
484 | # them from cluttering user-visible stuff. Will be updated later |
|
484 | # them from cluttering user-visible stuff. Will be updated later | |
485 | self.internal_ns = {} |
|
485 | self.internal_ns = {} | |
486 |
|
486 | |||
487 | # Namespace of system aliases. Each entry in the alias |
|
487 | # Namespace of system aliases. Each entry in the alias | |
488 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
488 | # table must be a 2-tuple of the form (N,name), where N is the number | |
489 | # of positional arguments of the alias. |
|
489 | # of positional arguments of the alias. | |
490 | self.alias_table = {} |
|
490 | self.alias_table = {} | |
491 |
|
491 | |||
492 | # Now that FakeModule produces a real module, we've run into a nasty |
|
492 | # Now that FakeModule produces a real module, we've run into a nasty | |
493 | # problem: after script execution (via %run), the module where the user |
|
493 | # problem: after script execution (via %run), the module where the user | |
494 | # code ran is deleted. Now that this object is a true module (needed |
|
494 | # code ran is deleted. Now that this object is a true module (needed | |
495 | # so docetst and other tools work correctly), the Python module |
|
495 | # so docetst and other tools work correctly), the Python module | |
496 | # teardown mechanism runs over it, and sets to None every variable |
|
496 | # teardown mechanism runs over it, and sets to None every variable | |
497 | # present in that module. Top-level references to objects from the |
|
497 | # present in that module. Top-level references to objects from the | |
498 | # script survive, because the user_ns is updated with them. However, |
|
498 | # script survive, because the user_ns is updated with them. However, | |
499 | # calling functions defined in the script that use other things from |
|
499 | # calling functions defined in the script that use other things from | |
500 | # the script will fail, because the function's closure had references |
|
500 | # the script will fail, because the function's closure had references | |
501 | # to the original objects, which are now all None. So we must protect |
|
501 | # to the original objects, which are now all None. So we must protect | |
502 | # these modules from deletion by keeping a cache. To avoid keeping |
|
502 | # these modules from deletion by keeping a cache. To avoid keeping | |
503 | # stale modules around (we only need the one from the last run), we use |
|
503 | # stale modules around (we only need the one from the last run), we use | |
504 | # a dict keyed with the full path to the script, so only the last |
|
504 | # a dict keyed with the full path to the script, so only the last | |
505 | # version of the module is held in the cache. The %reset command will |
|
505 | # version of the module is held in the cache. The %reset command will | |
506 | # flush this cache. See the cache_main_mod() and clear_main_mod_cache() |
|
506 | # flush this cache. See the cache_main_mod() and clear_main_mod_cache() | |
507 | # methods for details on use. |
|
507 | # methods for details on use. | |
508 | self._user_main_modules = {} |
|
508 | self._user_main_modules = {} | |
509 |
|
509 | |||
510 | # A table holding all the namespaces IPython deals with, so that |
|
510 | # A table holding all the namespaces IPython deals with, so that | |
511 | # introspection facilities can search easily. |
|
511 | # introspection facilities can search easily. | |
512 | self.ns_table = {'user':user_ns, |
|
512 | self.ns_table = {'user':user_ns, | |
513 | 'user_global':user_global_ns, |
|
513 | 'user_global':user_global_ns, | |
514 | 'alias':self.alias_table, |
|
514 | 'alias':self.alias_table, | |
515 | 'internal':self.internal_ns, |
|
515 | 'internal':self.internal_ns, | |
516 | 'builtin':__builtin__.__dict__ |
|
516 | 'builtin':__builtin__.__dict__ | |
517 | } |
|
517 | } | |
518 |
|
518 | |||
519 | # Similarly, track all namespaces where references can be held and that |
|
519 | # Similarly, track all namespaces where references can be held and that | |
520 | # we can safely clear (so it can NOT include builtin). This one can be |
|
520 | # we can safely clear (so it can NOT include builtin). This one can be | |
521 | # a simple list. |
|
521 | # a simple list. | |
522 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
522 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |
523 | self.alias_table, self.internal_ns, |
|
523 | self.alias_table, self.internal_ns, | |
524 | self._user_main_modules ] |
|
524 | self._user_main_modules ] | |
525 |
|
525 | |||
526 | # We need to insert into sys.modules something that looks like a |
|
526 | # We need to insert into sys.modules something that looks like a | |
527 | # module but which accesses the IPython namespace, for shelve and |
|
527 | # module but which accesses the IPython namespace, for shelve and | |
528 | # pickle to work interactively. Normally they rely on getting |
|
528 | # pickle to work interactively. Normally they rely on getting | |
529 | # everything out of __main__, but for embedding purposes each IPython |
|
529 | # everything out of __main__, but for embedding purposes each IPython | |
530 | # instance has its own private namespace, so we can't go shoving |
|
530 | # instance has its own private namespace, so we can't go shoving | |
531 | # everything into __main__. |
|
531 | # everything into __main__. | |
532 |
|
532 | |||
533 | # note, however, that we should only do this for non-embedded |
|
533 | # note, however, that we should only do this for non-embedded | |
534 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
534 | # ipythons, which really mimic the __main__.__dict__ with their own | |
535 | # namespace. Embedded instances, on the other hand, should not do |
|
535 | # namespace. Embedded instances, on the other hand, should not do | |
536 | # this because they need to manage the user local/global namespaces |
|
536 | # this because they need to manage the user local/global namespaces | |
537 | # only, but they live within a 'normal' __main__ (meaning, they |
|
537 | # only, but they live within a 'normal' __main__ (meaning, they | |
538 | # shouldn't overtake the execution environment of the script they're |
|
538 | # shouldn't overtake the execution environment of the script they're | |
539 | # embedded in). |
|
539 | # embedded in). | |
540 |
|
540 | |||
541 | if not embedded: |
|
541 | if not embedded: | |
542 | try: |
|
542 | try: | |
543 | main_name = self.user_ns['__name__'] |
|
543 | main_name = self.user_ns['__name__'] | |
544 | except KeyError: |
|
544 | except KeyError: | |
545 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
545 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
546 | else: |
|
546 | else: | |
547 | #print "pickle hack in place" # dbg |
|
547 | #print "pickle hack in place" # dbg | |
548 | #print 'main_name:',main_name # dbg |
|
548 | #print 'main_name:',main_name # dbg | |
549 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
549 | sys.modules[main_name] = FakeModule(self.user_ns) | |
550 |
|
550 | |||
551 | # List of input with multi-line handling. |
|
551 | # List of input with multi-line handling. | |
552 | self.input_hist = InputList() |
|
552 | self.input_hist = InputList() | |
553 | # This one will hold the 'raw' input history, without any |
|
553 | # This one will hold the 'raw' input history, without any | |
554 | # pre-processing. This will allow users to retrieve the input just as |
|
554 | # pre-processing. This will allow users to retrieve the input just as | |
555 | # it was exactly typed in by the user, with %hist -r. |
|
555 | # it was exactly typed in by the user, with %hist -r. | |
556 | self.input_hist_raw = InputList() |
|
556 | self.input_hist_raw = InputList() | |
557 |
|
557 | |||
558 | # list of visited directories |
|
558 | # list of visited directories | |
559 | try: |
|
559 | try: | |
560 | self.dir_hist = [os.getcwd()] |
|
560 | self.dir_hist = [os.getcwd()] | |
561 | except OSError: |
|
561 | except OSError: | |
562 | self.dir_hist = [] |
|
562 | self.dir_hist = [] | |
563 |
|
563 | |||
564 | # dict of output history |
|
564 | # dict of output history | |
565 | self.output_hist = {} |
|
565 | self.output_hist = {} | |
566 |
|
566 | |||
567 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
567 | # Get system encoding at startup time. Certain terminals (like Emacs | |
568 | # under Win32 have it set to None, and we need to have a known valid |
|
568 | # under Win32 have it set to None, and we need to have a known valid | |
569 | # encoding to use in the raw_input() method |
|
569 | # encoding to use in the raw_input() method | |
570 | try: |
|
570 | try: | |
571 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
571 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
572 | except AttributeError: |
|
572 | except AttributeError: | |
573 | self.stdin_encoding = 'ascii' |
|
573 | self.stdin_encoding = 'ascii' | |
574 |
|
574 | |||
575 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
575 | # dict of things NOT to alias (keywords, builtins and some magics) | |
576 | no_alias = {} |
|
576 | no_alias = {} | |
577 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
577 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
578 | for key in keyword.kwlist + no_alias_magics: |
|
578 | for key in keyword.kwlist + no_alias_magics: | |
579 | no_alias[key] = 1 |
|
579 | no_alias[key] = 1 | |
580 | no_alias.update(__builtin__.__dict__) |
|
580 | no_alias.update(__builtin__.__dict__) | |
581 | self.no_alias = no_alias |
|
581 | self.no_alias = no_alias | |
582 |
|
582 | |||
583 | # Object variable to store code object waiting execution. This is |
|
583 | # Object variable to store code object waiting execution. This is | |
584 | # used mainly by the multithreaded shells, but it can come in handy in |
|
584 | # used mainly by the multithreaded shells, but it can come in handy in | |
585 | # other situations. No need to use a Queue here, since it's a single |
|
585 | # other situations. No need to use a Queue here, since it's a single | |
586 | # item which gets cleared once run. |
|
586 | # item which gets cleared once run. | |
587 | self.code_to_run = None |
|
587 | self.code_to_run = None | |
588 |
|
588 | |||
589 | # escapes for automatic behavior on the command line |
|
589 | # escapes for automatic behavior on the command line | |
590 | self.ESC_SHELL = '!' |
|
590 | self.ESC_SHELL = '!' | |
591 | self.ESC_SH_CAP = '!!' |
|
591 | self.ESC_SH_CAP = '!!' | |
592 | self.ESC_HELP = '?' |
|
592 | self.ESC_HELP = '?' | |
593 | self.ESC_MAGIC = '%' |
|
593 | self.ESC_MAGIC = '%' | |
594 | self.ESC_QUOTE = ',' |
|
594 | self.ESC_QUOTE = ',' | |
595 | self.ESC_QUOTE2 = ';' |
|
595 | self.ESC_QUOTE2 = ';' | |
596 | self.ESC_PAREN = '/' |
|
596 | self.ESC_PAREN = '/' | |
597 |
|
597 | |||
598 | # And their associated handlers |
|
598 | # And their associated handlers | |
599 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
599 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
600 | self.ESC_QUOTE : self.handle_auto, |
|
600 | self.ESC_QUOTE : self.handle_auto, | |
601 | self.ESC_QUOTE2 : self.handle_auto, |
|
601 | self.ESC_QUOTE2 : self.handle_auto, | |
602 | self.ESC_MAGIC : self.handle_magic, |
|
602 | self.ESC_MAGIC : self.handle_magic, | |
603 | self.ESC_HELP : self.handle_help, |
|
603 | self.ESC_HELP : self.handle_help, | |
604 | self.ESC_SHELL : self.handle_shell_escape, |
|
604 | self.ESC_SHELL : self.handle_shell_escape, | |
605 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
605 | self.ESC_SH_CAP : self.handle_shell_escape, | |
606 | } |
|
606 | } | |
607 |
|
607 | |||
608 | # class initializations |
|
608 | # class initializations | |
609 | Magic.__init__(self,self) |
|
609 | Magic.__init__(self,self) | |
610 |
|
610 | |||
611 | # Python source parser/formatter for syntax highlighting |
|
611 | # Python source parser/formatter for syntax highlighting | |
612 | pyformat = PyColorize.Parser().format |
|
612 | pyformat = PyColorize.Parser().format | |
613 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
613 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |
614 |
|
614 | |||
615 | # hooks holds pointers used for user-side customizations |
|
615 | # hooks holds pointers used for user-side customizations | |
616 | self.hooks = Struct() |
|
616 | self.hooks = Struct() | |
617 |
|
617 | |||
618 | self.strdispatchers = {} |
|
618 | self.strdispatchers = {} | |
619 |
|
619 | |||
620 | # Set all default hooks, defined in the IPython.hooks module. |
|
620 | # Set all default hooks, defined in the IPython.hooks module. | |
621 | hooks = IPython.hooks |
|
621 | hooks = IPython.hooks | |
622 | for hook_name in hooks.__all__: |
|
622 | for hook_name in hooks.__all__: | |
623 | # default hooks have priority 100, i.e. low; user hooks should have |
|
623 | # default hooks have priority 100, i.e. low; user hooks should have | |
624 | # 0-100 priority |
|
624 | # 0-100 priority | |
625 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
625 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
626 | #print "bound hook",hook_name |
|
626 | #print "bound hook",hook_name | |
627 |
|
627 | |||
628 | # Flag to mark unconditional exit |
|
628 | # Flag to mark unconditional exit | |
629 | self.exit_now = False |
|
629 | self.exit_now = False | |
630 |
|
630 | |||
631 | self.usage_min = """\ |
|
631 | self.usage_min = """\ | |
632 | An enhanced console for Python. |
|
632 | An enhanced console for Python. | |
633 | Some of its features are: |
|
633 | Some of its features are: | |
634 | - Readline support if the readline library is present. |
|
634 | - Readline support if the readline library is present. | |
635 | - Tab completion in the local namespace. |
|
635 | - Tab completion in the local namespace. | |
636 | - Logging of input, see command-line options. |
|
636 | - Logging of input, see command-line options. | |
637 | - System shell escape via ! , eg !ls. |
|
637 | - System shell escape via ! , eg !ls. | |
638 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
638 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
639 | - Keeps track of locally defined variables via %who, %whos. |
|
639 | - Keeps track of locally defined variables via %who, %whos. | |
640 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
640 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
641 | """ |
|
641 | """ | |
642 | if usage: self.usage = usage |
|
642 | if usage: self.usage = usage | |
643 | else: self.usage = self.usage_min |
|
643 | else: self.usage = self.usage_min | |
644 |
|
644 | |||
645 | # Storage |
|
645 | # Storage | |
646 | self.rc = rc # This will hold all configuration information |
|
646 | self.rc = rc # This will hold all configuration information | |
647 | self.pager = 'less' |
|
647 | self.pager = 'less' | |
648 | # temporary files used for various purposes. Deleted at exit. |
|
648 | # temporary files used for various purposes. Deleted at exit. | |
649 | self.tempfiles = [] |
|
649 | self.tempfiles = [] | |
650 |
|
650 | |||
651 | # Keep track of readline usage (later set by init_readline) |
|
651 | # Keep track of readline usage (later set by init_readline) | |
652 | self.has_readline = False |
|
652 | self.has_readline = False | |
653 |
|
653 | |||
654 | # template for logfile headers. It gets resolved at runtime by the |
|
654 | # template for logfile headers. It gets resolved at runtime by the | |
655 | # logstart method. |
|
655 | # logstart method. | |
656 | self.loghead_tpl = \ |
|
656 | self.loghead_tpl = \ | |
657 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
657 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
658 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
658 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
659 | #log# opts = %s |
|
659 | #log# opts = %s | |
660 | #log# args = %s |
|
660 | #log# args = %s | |
661 | #log# It is safe to make manual edits below here. |
|
661 | #log# It is safe to make manual edits below here. | |
662 | #log#----------------------------------------------------------------------- |
|
662 | #log#----------------------------------------------------------------------- | |
663 | """ |
|
663 | """ | |
664 | # for pushd/popd management |
|
664 | # for pushd/popd management | |
665 | try: |
|
665 | try: | |
666 | self.home_dir = get_home_dir() |
|
666 | self.home_dir = get_home_dir() | |
667 | except HomeDirError,msg: |
|
667 | except HomeDirError,msg: | |
668 | fatal(msg) |
|
668 | fatal(msg) | |
669 |
|
669 | |||
670 | self.dir_stack = [] |
|
670 | self.dir_stack = [] | |
671 |
|
671 | |||
672 | # Functions to call the underlying shell. |
|
672 | # Functions to call the underlying shell. | |
673 |
|
673 | |||
674 | # The first is similar to os.system, but it doesn't return a value, |
|
674 | # The first is similar to os.system, but it doesn't return a value, | |
675 | # and it allows interpolation of variables in the user's namespace. |
|
675 | # and it allows interpolation of variables in the user's namespace. | |
676 | self.system = lambda cmd: \ |
|
676 | self.system = lambda cmd: \ | |
677 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) |
|
677 | self.hooks.shell_hook(self.var_expand(cmd,depth=2)) | |
678 |
|
678 | |||
679 | # These are for getoutput and getoutputerror: |
|
679 | # These are for getoutput and getoutputerror: | |
680 | self.getoutput = lambda cmd: \ |
|
680 | self.getoutput = lambda cmd: \ | |
681 | getoutput(self.var_expand(cmd,depth=2), |
|
681 | getoutput(self.var_expand(cmd,depth=2), | |
682 | header=self.rc.system_header, |
|
682 | header=self.rc.system_header, | |
683 | verbose=self.rc.system_verbose) |
|
683 | verbose=self.rc.system_verbose) | |
684 |
|
684 | |||
685 | self.getoutputerror = lambda cmd: \ |
|
685 | self.getoutputerror = lambda cmd: \ | |
686 | getoutputerror(self.var_expand(cmd,depth=2), |
|
686 | getoutputerror(self.var_expand(cmd,depth=2), | |
687 | header=self.rc.system_header, |
|
687 | header=self.rc.system_header, | |
688 | verbose=self.rc.system_verbose) |
|
688 | verbose=self.rc.system_verbose) | |
689 |
|
689 | |||
690 |
|
690 | |||
691 | # keep track of where we started running (mainly for crash post-mortem) |
|
691 | # keep track of where we started running (mainly for crash post-mortem) | |
692 | self.starting_dir = os.getcwd() |
|
692 | self.starting_dir = os.getcwd() | |
693 |
|
693 | |||
694 | # Various switches which can be set |
|
694 | # Various switches which can be set | |
695 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
695 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
696 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
696 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
697 | self.banner2 = banner2 |
|
697 | self.banner2 = banner2 | |
698 |
|
698 | |||
699 | # TraceBack handlers: |
|
699 | # TraceBack handlers: | |
700 |
|
700 | |||
701 | # Syntax error handler. |
|
701 | # Syntax error handler. | |
702 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
702 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
703 |
|
703 | |||
704 | # The interactive one is initialized with an offset, meaning we always |
|
704 | # The interactive one is initialized with an offset, meaning we always | |
705 | # want to remove the topmost item in the traceback, which is our own |
|
705 | # want to remove the topmost item in the traceback, which is our own | |
706 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
706 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
707 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
707 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
708 | color_scheme='NoColor', |
|
708 | color_scheme='NoColor', | |
709 | tb_offset = 1) |
|
709 | tb_offset = 1) | |
710 |
|
710 | |||
711 | # IPython itself shouldn't crash. This will produce a detailed |
|
711 | # IPython itself shouldn't crash. This will produce a detailed | |
712 | # post-mortem if it does. But we only install the crash handler for |
|
712 | # post-mortem if it does. But we only install the crash handler for | |
713 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
713 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
714 | # and lose the crash handler. This is because exceptions in the main |
|
714 | # and lose the crash handler. This is because exceptions in the main | |
715 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
715 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
716 | # and there's no point in printing crash dumps for every user exception. |
|
716 | # and there's no point in printing crash dumps for every user exception. | |
717 | if self.isthreaded: |
|
717 | if self.isthreaded: | |
718 | ipCrashHandler = ultraTB.FormattedTB() |
|
718 | ipCrashHandler = ultraTB.FormattedTB() | |
719 | else: |
|
719 | else: | |
720 | from IPython import CrashHandler |
|
720 | from IPython import CrashHandler | |
721 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) |
|
721 | ipCrashHandler = CrashHandler.IPythonCrashHandler(self) | |
722 | self.set_crash_handler(ipCrashHandler) |
|
722 | self.set_crash_handler(ipCrashHandler) | |
723 |
|
723 | |||
724 | # and add any custom exception handlers the user may have specified |
|
724 | # and add any custom exception handlers the user may have specified | |
725 | self.set_custom_exc(*custom_exceptions) |
|
725 | self.set_custom_exc(*custom_exceptions) | |
726 |
|
726 | |||
727 | # indentation management |
|
727 | # indentation management | |
728 | self.autoindent = False |
|
728 | self.autoindent = False | |
729 | self.indent_current_nsp = 0 |
|
729 | self.indent_current_nsp = 0 | |
730 |
|
730 | |||
731 | # Make some aliases automatically |
|
731 | # Make some aliases automatically | |
732 | # Prepare list of shell aliases to auto-define |
|
732 | # Prepare list of shell aliases to auto-define | |
733 | if os.name == 'posix': |
|
733 | if os.name == 'posix': | |
734 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
734 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
735 | 'mv mv -i','rm rm -i','cp cp -i', |
|
735 | 'mv mv -i','rm rm -i','cp cp -i', | |
736 | 'cat cat','less less','clear clear', |
|
736 | 'cat cat','less less','clear clear', | |
737 | # a better ls |
|
737 | # a better ls | |
738 | 'ls ls -F', |
|
738 | 'ls ls -F', | |
739 | # long ls |
|
739 | # long ls | |
740 | 'll ls -lF') |
|
740 | 'll ls -lF') | |
741 | # Extra ls aliases with color, which need special treatment on BSD |
|
741 | # Extra ls aliases with color, which need special treatment on BSD | |
742 | # variants |
|
742 | # variants | |
743 | ls_extra = ( # color ls |
|
743 | ls_extra = ( # color ls | |
744 | 'lc ls -F -o --color', |
|
744 | 'lc ls -F -o --color', | |
745 | # ls normal files only |
|
745 | # ls normal files only | |
746 | 'lf ls -F -o --color %l | grep ^-', |
|
746 | 'lf ls -F -o --color %l | grep ^-', | |
747 | # ls symbolic links |
|
747 | # ls symbolic links | |
748 | 'lk ls -F -o --color %l | grep ^l', |
|
748 | 'lk ls -F -o --color %l | grep ^l', | |
749 | # directories or links to directories, |
|
749 | # directories or links to directories, | |
750 | 'ldir ls -F -o --color %l | grep /$', |
|
750 | 'ldir ls -F -o --color %l | grep /$', | |
751 | # things which are executable |
|
751 | # things which are executable | |
752 | 'lx ls -F -o --color %l | grep ^-..x', |
|
752 | 'lx ls -F -o --color %l | grep ^-..x', | |
753 | ) |
|
753 | ) | |
754 | # The BSDs don't ship GNU ls, so they don't understand the |
|
754 | # The BSDs don't ship GNU ls, so they don't understand the | |
755 | # --color switch out of the box |
|
755 | # --color switch out of the box | |
756 | if 'bsd' in sys.platform: |
|
756 | if 'bsd' in sys.platform: | |
757 | ls_extra = ( # ls normal files only |
|
757 | ls_extra = ( # ls normal files only | |
758 | 'lf ls -lF | grep ^-', |
|
758 | 'lf ls -lF | grep ^-', | |
759 | # ls symbolic links |
|
759 | # ls symbolic links | |
760 | 'lk ls -lF | grep ^l', |
|
760 | 'lk ls -lF | grep ^l', | |
761 | # directories or links to directories, |
|
761 | # directories or links to directories, | |
762 | 'ldir ls -lF | grep /$', |
|
762 | 'ldir ls -lF | grep /$', | |
763 | # things which are executable |
|
763 | # things which are executable | |
764 | 'lx ls -lF | grep ^-..x', |
|
764 | 'lx ls -lF | grep ^-..x', | |
765 | ) |
|
765 | ) | |
766 | auto_alias = auto_alias + ls_extra |
|
766 | auto_alias = auto_alias + ls_extra | |
767 | elif os.name in ['nt','dos']: |
|
767 | elif os.name in ['nt','dos']: | |
768 | auto_alias = ('ls dir /on', |
|
768 | auto_alias = ('ls dir /on', | |
769 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
769 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
770 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
770 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
771 | 'ren ren','cls cls','copy copy') |
|
771 | 'ren ren','cls cls','copy copy') | |
772 | else: |
|
772 | else: | |
773 | auto_alias = () |
|
773 | auto_alias = () | |
774 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
774 | self.auto_alias = [s.split(None,1) for s in auto_alias] | |
775 |
|
775 | |||
776 | # Produce a public API instance |
|
776 | # Produce a public API instance | |
777 | self.api = IPython.ipapi.IPApi(self) |
|
777 | self.api = IPython.ipapi.IPApi(self) | |
778 |
|
778 | |||
779 | # Initialize all user-visible namespaces |
|
779 | # Initialize all user-visible namespaces | |
780 | self.init_namespaces() |
|
780 | self.init_namespaces() | |
781 |
|
781 | |||
782 | # Call the actual (public) initializer |
|
782 | # Call the actual (public) initializer | |
783 | self.init_auto_alias() |
|
783 | self.init_auto_alias() | |
784 |
|
784 | |||
785 | # track which builtins we add, so we can clean up later |
|
785 | # track which builtins we add, so we can clean up later | |
786 | self.builtins_added = {} |
|
786 | self.builtins_added = {} | |
787 | # This method will add the necessary builtins for operation, but |
|
787 | # This method will add the necessary builtins for operation, but | |
788 | # tracking what it did via the builtins_added dict. |
|
788 | # tracking what it did via the builtins_added dict. | |
789 |
|
789 | |||
790 | #TODO: remove this, redundant |
|
790 | #TODO: remove this, redundant | |
791 | self.add_builtins() |
|
791 | self.add_builtins() | |
792 | # end __init__ |
|
792 | # end __init__ | |
793 |
|
793 | |||
794 | def var_expand(self,cmd,depth=0): |
|
794 | def var_expand(self,cmd,depth=0): | |
795 | """Expand python variables in a string. |
|
795 | """Expand python variables in a string. | |
796 |
|
796 | |||
797 | The depth argument indicates how many frames above the caller should |
|
797 | The depth argument indicates how many frames above the caller should | |
798 | be walked to look for the local namespace where to expand variables. |
|
798 | be walked to look for the local namespace where to expand variables. | |
799 |
|
799 | |||
800 | The global namespace for expansion is always the user's interactive |
|
800 | The global namespace for expansion is always the user's interactive | |
801 | namespace. |
|
801 | namespace. | |
802 | """ |
|
802 | """ | |
803 |
|
803 | |||
804 | return str(ItplNS(cmd, |
|
804 | return str(ItplNS(cmd, | |
805 | self.user_ns, # globals |
|
805 | self.user_ns, # globals | |
806 | # Skip our own frame in searching for locals: |
|
806 | # Skip our own frame in searching for locals: | |
807 | sys._getframe(depth+1).f_locals # locals |
|
807 | sys._getframe(depth+1).f_locals # locals | |
808 | )) |
|
808 | )) | |
809 |
|
809 | |||
810 | def pre_config_initialization(self): |
|
810 | def pre_config_initialization(self): | |
811 | """Pre-configuration init method |
|
811 | """Pre-configuration init method | |
812 |
|
812 | |||
813 | This is called before the configuration files are processed to |
|
813 | This is called before the configuration files are processed to | |
814 | prepare the services the config files might need. |
|
814 | prepare the services the config files might need. | |
815 |
|
815 | |||
816 | self.rc already has reasonable default values at this point. |
|
816 | self.rc already has reasonable default values at this point. | |
817 | """ |
|
817 | """ | |
818 | rc = self.rc |
|
818 | rc = self.rc | |
819 | try: |
|
819 | try: | |
820 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") |
|
820 | self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db") | |
821 | except exceptions.UnicodeDecodeError: |
|
821 | except exceptions.UnicodeDecodeError: | |
822 | print "Your ipythondir can't be decoded to unicode!" |
|
822 | print "Your ipythondir can't be decoded to unicode!" | |
823 | print "Please set HOME environment variable to something that" |
|
823 | print "Please set HOME environment variable to something that" | |
824 | print r"only has ASCII characters, e.g. c:\home" |
|
824 | print r"only has ASCII characters, e.g. c:\home" | |
825 | print "Now it is",rc.ipythondir |
|
825 | print "Now it is",rc.ipythondir | |
826 | sys.exit() |
|
826 | sys.exit() | |
827 | self.shadowhist = IPython.history.ShadowHist(self.db) |
|
827 | self.shadowhist = IPython.history.ShadowHist(self.db) | |
828 |
|
828 | |||
829 | def post_config_initialization(self): |
|
829 | def post_config_initialization(self): | |
830 | """Post configuration init method |
|
830 | """Post configuration init method | |
831 |
|
831 | |||
832 | This is called after the configuration files have been processed to |
|
832 | This is called after the configuration files have been processed to | |
833 | 'finalize' the initialization.""" |
|
833 | 'finalize' the initialization.""" | |
834 |
|
834 | |||
835 | rc = self.rc |
|
835 | rc = self.rc | |
836 |
|
836 | |||
837 | # Object inspector |
|
837 | # Object inspector | |
838 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
838 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
839 | PyColorize.ANSICodeColors, |
|
839 | PyColorize.ANSICodeColors, | |
840 | 'NoColor', |
|
840 | 'NoColor', | |
841 | rc.object_info_string_level) |
|
841 | rc.object_info_string_level) | |
842 |
|
842 | |||
843 | self.rl_next_input = None |
|
843 | self.rl_next_input = None | |
844 | self.rl_do_indent = False |
|
844 | self.rl_do_indent = False | |
845 | # Load readline proper |
|
845 | # Load readline proper | |
846 | if rc.readline: |
|
846 | if rc.readline: | |
847 | self.init_readline() |
|
847 | self.init_readline() | |
848 |
|
848 | |||
849 | # local shortcut, this is used a LOT |
|
849 | # local shortcut, this is used a LOT | |
850 | self.log = self.logger.log |
|
850 | self.log = self.logger.log | |
851 |
|
851 | |||
852 | # Initialize cache, set in/out prompts and printing system |
|
852 | # Initialize cache, set in/out prompts and printing system | |
853 | self.outputcache = CachedOutput(self, |
|
853 | self.outputcache = CachedOutput(self, | |
854 | rc.cache_size, |
|
854 | rc.cache_size, | |
855 | rc.pprint, |
|
855 | rc.pprint, | |
856 | input_sep = rc.separate_in, |
|
856 | input_sep = rc.separate_in, | |
857 | output_sep = rc.separate_out, |
|
857 | output_sep = rc.separate_out, | |
858 | output_sep2 = rc.separate_out2, |
|
858 | output_sep2 = rc.separate_out2, | |
859 | ps1 = rc.prompt_in1, |
|
859 | ps1 = rc.prompt_in1, | |
860 | ps2 = rc.prompt_in2, |
|
860 | ps2 = rc.prompt_in2, | |
861 | ps_out = rc.prompt_out, |
|
861 | ps_out = rc.prompt_out, | |
862 | pad_left = rc.prompts_pad_left) |
|
862 | pad_left = rc.prompts_pad_left) | |
863 |
|
863 | |||
864 | # user may have over-ridden the default print hook: |
|
864 | # user may have over-ridden the default print hook: | |
865 | try: |
|
865 | try: | |
866 | self.outputcache.__class__.display = self.hooks.display |
|
866 | self.outputcache.__class__.display = self.hooks.display | |
867 | except AttributeError: |
|
867 | except AttributeError: | |
868 | pass |
|
868 | pass | |
869 |
|
869 | |||
870 | # I don't like assigning globally to sys, because it means when |
|
870 | # I don't like assigning globally to sys, because it means when | |
871 | # embedding instances, each embedded instance overrides the previous |
|
871 | # embedding instances, each embedded instance overrides the previous | |
872 | # choice. But sys.displayhook seems to be called internally by exec, |
|
872 | # choice. But sys.displayhook seems to be called internally by exec, | |
873 | # so I don't see a way around it. We first save the original and then |
|
873 | # so I don't see a way around it. We first save the original and then | |
874 | # overwrite it. |
|
874 | # overwrite it. | |
875 | self.sys_displayhook = sys.displayhook |
|
875 | self.sys_displayhook = sys.displayhook | |
876 | sys.displayhook = self.outputcache |
|
876 | sys.displayhook = self.outputcache | |
877 |
|
877 | |||
878 | # Do a proper resetting of doctest, including the necessary displayhook |
|
878 | # Do a proper resetting of doctest, including the necessary displayhook | |
879 | # monkeypatching |
|
879 | # monkeypatching | |
880 | try: |
|
880 | try: | |
881 | doctest_reload() |
|
881 | doctest_reload() | |
882 | except ImportError: |
|
882 | except ImportError: | |
883 | warn("doctest module does not exist.") |
|
883 | warn("doctest module does not exist.") | |
884 |
|
884 | |||
885 | # Set user colors (don't do it in the constructor above so that it |
|
885 | # Set user colors (don't do it in the constructor above so that it | |
886 | # doesn't crash if colors option is invalid) |
|
886 | # doesn't crash if colors option is invalid) | |
887 | self.magic_colors(rc.colors) |
|
887 | self.magic_colors(rc.colors) | |
888 |
|
888 | |||
889 | # Set calling of pdb on exceptions |
|
889 | # Set calling of pdb on exceptions | |
890 | self.call_pdb = rc.pdb |
|
890 | self.call_pdb = rc.pdb | |
891 |
|
891 | |||
892 | # Load user aliases |
|
892 | # Load user aliases | |
893 | for alias in rc.alias: |
|
893 | for alias in rc.alias: | |
894 | self.magic_alias(alias) |
|
894 | self.magic_alias(alias) | |
895 |
|
895 | |||
896 | self.hooks.late_startup_hook() |
|
896 | self.hooks.late_startup_hook() | |
897 |
|
897 | |||
898 | for cmd in self.rc.autoexec: |
|
898 | for cmd in self.rc.autoexec: | |
899 | #print "autoexec>",cmd #dbg |
|
899 | #print "autoexec>",cmd #dbg | |
900 | self.api.runlines(cmd) |
|
900 | self.api.runlines(cmd) | |
901 |
|
901 | |||
902 | batchrun = False |
|
902 | batchrun = False | |
903 | for batchfile in [path(arg) for arg in self.rc.args |
|
903 | for batchfile in [path(arg) for arg in self.rc.args | |
904 | if arg.lower().endswith('.ipy')]: |
|
904 | if arg.lower().endswith('.ipy')]: | |
905 | if not batchfile.isfile(): |
|
905 | if not batchfile.isfile(): | |
906 | print "No such batch file:", batchfile |
|
906 | print "No such batch file:", batchfile | |
907 | continue |
|
907 | continue | |
908 | self.api.runlines(batchfile.text()) |
|
908 | self.api.runlines(batchfile.text()) | |
909 | batchrun = True |
|
909 | batchrun = True | |
910 | # without -i option, exit after running the batch file |
|
910 | # without -i option, exit after running the batch file | |
911 | if batchrun and not self.rc.interact: |
|
911 | if batchrun and not self.rc.interact: | |
912 | self.ask_exit() |
|
912 | self.ask_exit() | |
913 |
|
913 | |||
914 | def init_namespaces(self): |
|
914 | def init_namespaces(self): | |
915 | """Initialize all user-visible namespaces to their minimum defaults. |
|
915 | """Initialize all user-visible namespaces to their minimum defaults. | |
916 |
|
916 | |||
917 | Certain history lists are also initialized here, as they effectively |
|
917 | Certain history lists are also initialized here, as they effectively | |
918 | act as user namespaces. |
|
918 | act as user namespaces. | |
919 |
|
919 | |||
920 | Note |
|
920 | Note | |
921 | ---- |
|
921 | ---- | |
922 | All data structures here are only filled in, they are NOT reset by this |
|
922 | All data structures here are only filled in, they are NOT reset by this | |
923 | method. If they were not empty before, data will simply be added to |
|
923 | method. If they were not empty before, data will simply be added to | |
924 | therm. |
|
924 | therm. | |
925 | """ |
|
925 | """ | |
926 | # The user namespace MUST have a pointer to the shell itself. |
|
926 | # The user namespace MUST have a pointer to the shell itself. | |
927 | self.user_ns[self.name] = self |
|
927 | self.user_ns[self.name] = self | |
928 |
|
928 | |||
929 | # Store the public api instance |
|
929 | # Store the public api instance | |
930 | self.user_ns['_ip'] = self.api |
|
930 | self.user_ns['_ip'] = self.api | |
931 |
|
931 | |||
932 | # make global variables for user access to the histories |
|
932 | # make global variables for user access to the histories | |
933 | self.user_ns['_ih'] = self.input_hist |
|
933 | self.user_ns['_ih'] = self.input_hist | |
934 | self.user_ns['_oh'] = self.output_hist |
|
934 | self.user_ns['_oh'] = self.output_hist | |
935 | self.user_ns['_dh'] = self.dir_hist |
|
935 | self.user_ns['_dh'] = self.dir_hist | |
936 |
|
936 | |||
937 | # user aliases to input and output histories |
|
937 | # user aliases to input and output histories | |
938 | self.user_ns['In'] = self.input_hist |
|
938 | self.user_ns['In'] = self.input_hist | |
939 | self.user_ns['Out'] = self.output_hist |
|
939 | self.user_ns['Out'] = self.output_hist | |
940 |
|
940 | |||
941 | self.user_ns['_sh'] = IPython.shadowns |
|
941 | self.user_ns['_sh'] = IPython.shadowns | |
942 |
|
942 | |||
943 | # Fill the history zero entry, user counter starts at 1 |
|
943 | # Fill the history zero entry, user counter starts at 1 | |
944 | self.input_hist.append('\n') |
|
944 | self.input_hist.append('\n') | |
945 | self.input_hist_raw.append('\n') |
|
945 | self.input_hist_raw.append('\n') | |
946 |
|
946 | |||
947 | def add_builtins(self): |
|
947 | def add_builtins(self): | |
948 | """Store ipython references into the builtin namespace. |
|
948 | """Store ipython references into the builtin namespace. | |
949 |
|
949 | |||
950 | Some parts of ipython operate via builtins injected here, which hold a |
|
950 | Some parts of ipython operate via builtins injected here, which hold a | |
951 | reference to IPython itself.""" |
|
951 | reference to IPython itself.""" | |
952 |
|
952 | |||
953 | # TODO: deprecate all of these, they are unsafe |
|
953 | # TODO: deprecate all of these, they are unsafe | |
954 | builtins_new = dict(__IPYTHON__ = self, |
|
954 | builtins_new = dict(__IPYTHON__ = self, | |
955 | ip_set_hook = self.set_hook, |
|
955 | ip_set_hook = self.set_hook, | |
956 | jobs = self.jobs, |
|
956 | jobs = self.jobs, | |
957 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), |
|
957 | ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'), | |
958 | ipalias = wrap_deprecated(self.ipalias), |
|
958 | ipalias = wrap_deprecated(self.ipalias), | |
959 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), |
|
959 | ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'), | |
960 | #_ip = self.api |
|
960 | #_ip = self.api | |
961 | ) |
|
961 | ) | |
962 | for biname,bival in builtins_new.items(): |
|
962 | for biname,bival in builtins_new.items(): | |
963 | try: |
|
963 | try: | |
964 | # store the orignal value so we can restore it |
|
964 | # store the orignal value so we can restore it | |
965 | self.builtins_added[biname] = __builtin__.__dict__[biname] |
|
965 | self.builtins_added[biname] = __builtin__.__dict__[biname] | |
966 | except KeyError: |
|
966 | except KeyError: | |
967 | # or mark that it wasn't defined, and we'll just delete it at |
|
967 | # or mark that it wasn't defined, and we'll just delete it at | |
968 | # cleanup |
|
968 | # cleanup | |
969 | self.builtins_added[biname] = Undefined |
|
969 | self.builtins_added[biname] = Undefined | |
970 | __builtin__.__dict__[biname] = bival |
|
970 | __builtin__.__dict__[biname] = bival | |
971 |
|
971 | |||
972 | # Keep in the builtins a flag for when IPython is active. We set it |
|
972 | # Keep in the builtins a flag for when IPython is active. We set it | |
973 | # with setdefault so that multiple nested IPythons don't clobber one |
|
973 | # with setdefault so that multiple nested IPythons don't clobber one | |
974 | # another. Each will increase its value by one upon being activated, |
|
974 | # another. Each will increase its value by one upon being activated, | |
975 | # which also gives us a way to determine the nesting level. |
|
975 | # which also gives us a way to determine the nesting level. | |
976 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
976 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
977 |
|
977 | |||
978 | def clean_builtins(self): |
|
978 | def clean_builtins(self): | |
979 | """Remove any builtins which might have been added by add_builtins, or |
|
979 | """Remove any builtins which might have been added by add_builtins, or | |
980 | restore overwritten ones to their previous values.""" |
|
980 | restore overwritten ones to their previous values.""" | |
981 | for biname,bival in self.builtins_added.items(): |
|
981 | for biname,bival in self.builtins_added.items(): | |
982 | if bival is Undefined: |
|
982 | if bival is Undefined: | |
983 | del __builtin__.__dict__[biname] |
|
983 | del __builtin__.__dict__[biname] | |
984 | else: |
|
984 | else: | |
985 | __builtin__.__dict__[biname] = bival |
|
985 | __builtin__.__dict__[biname] = bival | |
986 | self.builtins_added.clear() |
|
986 | self.builtins_added.clear() | |
987 |
|
987 | |||
988 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
988 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
989 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
989 | """set_hook(name,hook) -> sets an internal IPython hook. | |
990 |
|
990 | |||
991 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
991 | IPython exposes some of its internal API as user-modifiable hooks. By | |
992 | adding your function to one of these hooks, you can modify IPython's |
|
992 | adding your function to one of these hooks, you can modify IPython's | |
993 | behavior to call at runtime your own routines.""" |
|
993 | behavior to call at runtime your own routines.""" | |
994 |
|
994 | |||
995 | # At some point in the future, this should validate the hook before it |
|
995 | # At some point in the future, this should validate the hook before it | |
996 | # accepts it. Probably at least check that the hook takes the number |
|
996 | # accepts it. Probably at least check that the hook takes the number | |
997 | # of args it's supposed to. |
|
997 | # of args it's supposed to. | |
998 |
|
998 | |||
999 | f = new.instancemethod(hook,self,self.__class__) |
|
999 | f = new.instancemethod(hook,self,self.__class__) | |
1000 |
|
1000 | |||
1001 | # check if the hook is for strdispatcher first |
|
1001 | # check if the hook is for strdispatcher first | |
1002 | if str_key is not None: |
|
1002 | if str_key is not None: | |
1003 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1003 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
1004 | sdp.add_s(str_key, f, priority ) |
|
1004 | sdp.add_s(str_key, f, priority ) | |
1005 | self.strdispatchers[name] = sdp |
|
1005 | self.strdispatchers[name] = sdp | |
1006 | return |
|
1006 | return | |
1007 | if re_key is not None: |
|
1007 | if re_key is not None: | |
1008 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
1008 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
1009 | sdp.add_re(re.compile(re_key), f, priority ) |
|
1009 | sdp.add_re(re.compile(re_key), f, priority ) | |
1010 | self.strdispatchers[name] = sdp |
|
1010 | self.strdispatchers[name] = sdp | |
1011 | return |
|
1011 | return | |
1012 |
|
1012 | |||
1013 | dp = getattr(self.hooks, name, None) |
|
1013 | dp = getattr(self.hooks, name, None) | |
1014 | if name not in IPython.hooks.__all__: |
|
1014 | if name not in IPython.hooks.__all__: | |
1015 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) |
|
1015 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ ) | |
1016 | if not dp: |
|
1016 | if not dp: | |
1017 | dp = IPython.hooks.CommandChainDispatcher() |
|
1017 | dp = IPython.hooks.CommandChainDispatcher() | |
1018 |
|
1018 | |||
1019 | try: |
|
1019 | try: | |
1020 | dp.add(f,priority) |
|
1020 | dp.add(f,priority) | |
1021 | except AttributeError: |
|
1021 | except AttributeError: | |
1022 | # it was not commandchain, plain old func - replace |
|
1022 | # it was not commandchain, plain old func - replace | |
1023 | dp = f |
|
1023 | dp = f | |
1024 |
|
1024 | |||
1025 | setattr(self.hooks,name, dp) |
|
1025 | setattr(self.hooks,name, dp) | |
1026 |
|
1026 | |||
1027 |
|
1027 | |||
1028 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
1028 | #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
1029 |
|
1029 | |||
1030 | def set_crash_handler(self,crashHandler): |
|
1030 | def set_crash_handler(self,crashHandler): | |
1031 | """Set the IPython crash handler. |
|
1031 | """Set the IPython crash handler. | |
1032 |
|
1032 | |||
1033 | This must be a callable with a signature suitable for use as |
|
1033 | This must be a callable with a signature suitable for use as | |
1034 | sys.excepthook.""" |
|
1034 | sys.excepthook.""" | |
1035 |
|
1035 | |||
1036 | # Install the given crash handler as the Python exception hook |
|
1036 | # Install the given crash handler as the Python exception hook | |
1037 | sys.excepthook = crashHandler |
|
1037 | sys.excepthook = crashHandler | |
1038 |
|
1038 | |||
1039 | # The instance will store a pointer to this, so that runtime code |
|
1039 | # The instance will store a pointer to this, so that runtime code | |
1040 | # (such as magics) can access it. This is because during the |
|
1040 | # (such as magics) can access it. This is because during the | |
1041 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1041 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
1042 | # frameworks). |
|
1042 | # frameworks). | |
1043 | self.sys_excepthook = sys.excepthook |
|
1043 | self.sys_excepthook = sys.excepthook | |
1044 |
|
1044 | |||
1045 |
|
1045 | |||
1046 | def set_custom_exc(self,exc_tuple,handler): |
|
1046 | def set_custom_exc(self,exc_tuple,handler): | |
1047 | """set_custom_exc(exc_tuple,handler) |
|
1047 | """set_custom_exc(exc_tuple,handler) | |
1048 |
|
1048 | |||
1049 | Set a custom exception handler, which will be called if any of the |
|
1049 | Set a custom exception handler, which will be called if any of the | |
1050 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1050 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1051 | runcode() method. |
|
1051 | runcode() method. | |
1052 |
|
1052 | |||
1053 | Inputs: |
|
1053 | Inputs: | |
1054 |
|
1054 | |||
1055 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1055 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1056 | handler for. It is very important that you use a tuple, and NOT A |
|
1056 | handler for. It is very important that you use a tuple, and NOT A | |
1057 | LIST here, because of the way Python's except statement works. If |
|
1057 | LIST here, because of the way Python's except statement works. If | |
1058 | you only want to trap a single exception, use a singleton tuple: |
|
1058 | you only want to trap a single exception, use a singleton tuple: | |
1059 |
|
1059 | |||
1060 | exc_tuple == (MyCustomException,) |
|
1060 | exc_tuple == (MyCustomException,) | |
1061 |
|
1061 | |||
1062 | - handler: this must be defined as a function with the following |
|
1062 | - handler: this must be defined as a function with the following | |
1063 | basic interface: def my_handler(self,etype,value,tb). |
|
1063 | basic interface: def my_handler(self,etype,value,tb). | |
1064 |
|
1064 | |||
1065 | This will be made into an instance method (via new.instancemethod) |
|
1065 | This will be made into an instance method (via new.instancemethod) | |
1066 | of IPython itself, and it will be called if any of the exceptions |
|
1066 | of IPython itself, and it will be called if any of the exceptions | |
1067 | listed in the exc_tuple are caught. If the handler is None, an |
|
1067 | listed in the exc_tuple are caught. If the handler is None, an | |
1068 | internal basic one is used, which just prints basic info. |
|
1068 | internal basic one is used, which just prints basic info. | |
1069 |
|
1069 | |||
1070 | WARNING: by putting in your own exception handler into IPython's main |
|
1070 | WARNING: by putting in your own exception handler into IPython's main | |
1071 | execution loop, you run a very good chance of nasty crashes. This |
|
1071 | execution loop, you run a very good chance of nasty crashes. This | |
1072 | facility should only be used if you really know what you are doing.""" |
|
1072 | facility should only be used if you really know what you are doing.""" | |
1073 |
|
1073 | |||
1074 | assert type(exc_tuple)==type(()) , \ |
|
1074 | assert type(exc_tuple)==type(()) , \ | |
1075 | "The custom exceptions must be given AS A TUPLE." |
|
1075 | "The custom exceptions must be given AS A TUPLE." | |
1076 |
|
1076 | |||
1077 | def dummy_handler(self,etype,value,tb): |
|
1077 | def dummy_handler(self,etype,value,tb): | |
1078 | print '*** Simple custom exception handler ***' |
|
1078 | print '*** Simple custom exception handler ***' | |
1079 | print 'Exception type :',etype |
|
1079 | print 'Exception type :',etype | |
1080 | print 'Exception value:',value |
|
1080 | print 'Exception value:',value | |
1081 | print 'Traceback :',tb |
|
1081 | print 'Traceback :',tb | |
1082 | print 'Source code :','\n'.join(self.buffer) |
|
1082 | print 'Source code :','\n'.join(self.buffer) | |
1083 |
|
1083 | |||
1084 | if handler is None: handler = dummy_handler |
|
1084 | if handler is None: handler = dummy_handler | |
1085 |
|
1085 | |||
1086 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1086 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1087 | self.custom_exceptions = exc_tuple |
|
1087 | self.custom_exceptions = exc_tuple | |
1088 |
|
1088 | |||
1089 | def set_custom_completer(self,completer,pos=0): |
|
1089 | def set_custom_completer(self,completer,pos=0): | |
1090 | """set_custom_completer(completer,pos=0) |
|
1090 | """set_custom_completer(completer,pos=0) | |
1091 |
|
1091 | |||
1092 | Adds a new custom completer function. |
|
1092 | Adds a new custom completer function. | |
1093 |
|
1093 | |||
1094 | The position argument (defaults to 0) is the index in the completers |
|
1094 | The position argument (defaults to 0) is the index in the completers | |
1095 | list where you want the completer to be inserted.""" |
|
1095 | list where you want the completer to be inserted.""" | |
1096 |
|
1096 | |||
1097 | newcomp = new.instancemethod(completer,self.Completer, |
|
1097 | newcomp = new.instancemethod(completer,self.Completer, | |
1098 | self.Completer.__class__) |
|
1098 | self.Completer.__class__) | |
1099 | self.Completer.matchers.insert(pos,newcomp) |
|
1099 | self.Completer.matchers.insert(pos,newcomp) | |
1100 |
|
1100 | |||
1101 | def set_completer(self): |
|
1101 | def set_completer(self): | |
1102 | """reset readline's completer to be our own.""" |
|
1102 | """reset readline's completer to be our own.""" | |
1103 | self.readline.set_completer(self.Completer.complete) |
|
1103 | self.readline.set_completer(self.Completer.complete) | |
1104 |
|
1104 | |||
1105 | def _get_call_pdb(self): |
|
1105 | def _get_call_pdb(self): | |
1106 | return self._call_pdb |
|
1106 | return self._call_pdb | |
1107 |
|
1107 | |||
1108 | def _set_call_pdb(self,val): |
|
1108 | def _set_call_pdb(self,val): | |
1109 |
|
1109 | |||
1110 | if val not in (0,1,False,True): |
|
1110 | if val not in (0,1,False,True): | |
1111 | raise ValueError,'new call_pdb value must be boolean' |
|
1111 | raise ValueError,'new call_pdb value must be boolean' | |
1112 |
|
1112 | |||
1113 | # store value in instance |
|
1113 | # store value in instance | |
1114 | self._call_pdb = val |
|
1114 | self._call_pdb = val | |
1115 |
|
1115 | |||
1116 | # notify the actual exception handlers |
|
1116 | # notify the actual exception handlers | |
1117 | self.InteractiveTB.call_pdb = val |
|
1117 | self.InteractiveTB.call_pdb = val | |
1118 | if self.isthreaded: |
|
1118 | if self.isthreaded: | |
1119 | try: |
|
1119 | try: | |
1120 | self.sys_excepthook.call_pdb = val |
|
1120 | self.sys_excepthook.call_pdb = val | |
1121 | except: |
|
1121 | except: | |
1122 | warn('Failed to activate pdb for threaded exception handler') |
|
1122 | warn('Failed to activate pdb for threaded exception handler') | |
1123 |
|
1123 | |||
1124 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1124 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
1125 | 'Control auto-activation of pdb at exceptions') |
|
1125 | 'Control auto-activation of pdb at exceptions') | |
1126 |
|
1126 | |||
1127 | # These special functions get installed in the builtin namespace, to |
|
1127 | # These special functions get installed in the builtin namespace, to | |
1128 | # provide programmatic (pure python) access to magics, aliases and system |
|
1128 | # provide programmatic (pure python) access to magics, aliases and system | |
1129 | # calls. This is important for logging, user scripting, and more. |
|
1129 | # calls. This is important for logging, user scripting, and more. | |
1130 |
|
1130 | |||
1131 | # We are basically exposing, via normal python functions, the three |
|
1131 | # We are basically exposing, via normal python functions, the three | |
1132 | # mechanisms in which ipython offers special call modes (magics for |
|
1132 | # mechanisms in which ipython offers special call modes (magics for | |
1133 | # internal control, aliases for direct system access via pre-selected |
|
1133 | # internal control, aliases for direct system access via pre-selected | |
1134 | # names, and !cmd for calling arbitrary system commands). |
|
1134 | # names, and !cmd for calling arbitrary system commands). | |
1135 |
|
1135 | |||
1136 | def ipmagic(self,arg_s): |
|
1136 | def ipmagic(self,arg_s): | |
1137 | """Call a magic function by name. |
|
1137 | """Call a magic function by name. | |
1138 |
|
1138 | |||
1139 | Input: a string containing the name of the magic function to call and any |
|
1139 | Input: a string containing the name of the magic function to call and any | |
1140 | additional arguments to be passed to the magic. |
|
1140 | additional arguments to be passed to the magic. | |
1141 |
|
1141 | |||
1142 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
1142 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
1143 | prompt: |
|
1143 | prompt: | |
1144 |
|
1144 | |||
1145 | In[1]: %name -opt foo bar |
|
1145 | In[1]: %name -opt foo bar | |
1146 |
|
1146 | |||
1147 | To call a magic without arguments, simply use ipmagic('name'). |
|
1147 | To call a magic without arguments, simply use ipmagic('name'). | |
1148 |
|
1148 | |||
1149 | This provides a proper Python function to call IPython's magics in any |
|
1149 | This provides a proper Python function to call IPython's magics in any | |
1150 | valid Python code you can type at the interpreter, including loops and |
|
1150 | valid Python code you can type at the interpreter, including loops and | |
1151 | compound statements. It is added by IPython to the Python builtin |
|
1151 | compound statements. It is added by IPython to the Python builtin | |
1152 | namespace upon initialization.""" |
|
1152 | namespace upon initialization.""" | |
1153 |
|
1153 | |||
1154 | args = arg_s.split(' ',1) |
|
1154 | args = arg_s.split(' ',1) | |
1155 | magic_name = args[0] |
|
1155 | magic_name = args[0] | |
1156 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
1156 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
1157 |
|
1157 | |||
1158 | try: |
|
1158 | try: | |
1159 | magic_args = args[1] |
|
1159 | magic_args = args[1] | |
1160 | except IndexError: |
|
1160 | except IndexError: | |
1161 | magic_args = '' |
|
1161 | magic_args = '' | |
1162 | fn = getattr(self,'magic_'+magic_name,None) |
|
1162 | fn = getattr(self,'magic_'+magic_name,None) | |
1163 | if fn is None: |
|
1163 | if fn is None: | |
1164 | error("Magic function `%s` not found." % magic_name) |
|
1164 | error("Magic function `%s` not found." % magic_name) | |
1165 | else: |
|
1165 | else: | |
1166 | magic_args = self.var_expand(magic_args,1) |
|
1166 | magic_args = self.var_expand(magic_args,1) | |
1167 | return fn(magic_args) |
|
1167 | return fn(magic_args) | |
1168 |
|
1168 | |||
1169 | def ipalias(self,arg_s): |
|
1169 | def ipalias(self,arg_s): | |
1170 | """Call an alias by name. |
|
1170 | """Call an alias by name. | |
1171 |
|
1171 | |||
1172 | Input: a string containing the name of the alias to call and any |
|
1172 | Input: a string containing the name of the alias to call and any | |
1173 | additional arguments to be passed to the magic. |
|
1173 | additional arguments to be passed to the magic. | |
1174 |
|
1174 | |||
1175 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
1175 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
1176 | prompt: |
|
1176 | prompt: | |
1177 |
|
1177 | |||
1178 | In[1]: name -opt foo bar |
|
1178 | In[1]: name -opt foo bar | |
1179 |
|
1179 | |||
1180 | To call an alias without arguments, simply use ipalias('name'). |
|
1180 | To call an alias without arguments, simply use ipalias('name'). | |
1181 |
|
1181 | |||
1182 | This provides a proper Python function to call IPython's aliases in any |
|
1182 | This provides a proper Python function to call IPython's aliases in any | |
1183 | valid Python code you can type at the interpreter, including loops and |
|
1183 | valid Python code you can type at the interpreter, including loops and | |
1184 | compound statements. It is added by IPython to the Python builtin |
|
1184 | compound statements. It is added by IPython to the Python builtin | |
1185 | namespace upon initialization.""" |
|
1185 | namespace upon initialization.""" | |
1186 |
|
1186 | |||
1187 | args = arg_s.split(' ',1) |
|
1187 | args = arg_s.split(' ',1) | |
1188 | alias_name = args[0] |
|
1188 | alias_name = args[0] | |
1189 | try: |
|
1189 | try: | |
1190 | alias_args = args[1] |
|
1190 | alias_args = args[1] | |
1191 | except IndexError: |
|
1191 | except IndexError: | |
1192 | alias_args = '' |
|
1192 | alias_args = '' | |
1193 | if alias_name in self.alias_table: |
|
1193 | if alias_name in self.alias_table: | |
1194 | self.call_alias(alias_name,alias_args) |
|
1194 | self.call_alias(alias_name,alias_args) | |
1195 | else: |
|
1195 | else: | |
1196 | error("Alias `%s` not found." % alias_name) |
|
1196 | error("Alias `%s` not found." % alias_name) | |
1197 |
|
1197 | |||
1198 | def ipsystem(self,arg_s): |
|
1198 | def ipsystem(self,arg_s): | |
1199 | """Make a system call, using IPython.""" |
|
1199 | """Make a system call, using IPython.""" | |
1200 |
|
1200 | |||
1201 | self.system(arg_s) |
|
1201 | self.system(arg_s) | |
1202 |
|
1202 | |||
1203 | def complete(self,text): |
|
1203 | def complete(self,text): | |
1204 | """Return a sorted list of all possible completions on text. |
|
1204 | """Return a sorted list of all possible completions on text. | |
1205 |
|
1205 | |||
1206 | Inputs: |
|
1206 | Inputs: | |
1207 |
|
1207 | |||
1208 | - text: a string of text to be completed on. |
|
1208 | - text: a string of text to be completed on. | |
1209 |
|
1209 | |||
1210 | This is a wrapper around the completion mechanism, similar to what |
|
1210 | This is a wrapper around the completion mechanism, similar to what | |
1211 | readline does at the command line when the TAB key is hit. By |
|
1211 | readline does at the command line when the TAB key is hit. By | |
1212 | exposing it as a method, it can be used by other non-readline |
|
1212 | exposing it as a method, it can be used by other non-readline | |
1213 | environments (such as GUIs) for text completion. |
|
1213 | environments (such as GUIs) for text completion. | |
1214 |
|
1214 | |||
1215 | Simple usage example: |
|
1215 | Simple usage example: | |
1216 |
|
1216 | |||
1217 | In [7]: x = 'hello' |
|
1217 | In [7]: x = 'hello' | |
1218 |
|
1218 | |||
1219 | In [8]: x |
|
1219 | In [8]: x | |
1220 | Out[8]: 'hello' |
|
1220 | Out[8]: 'hello' | |
1221 |
|
1221 | |||
1222 | In [9]: print x |
|
1222 | In [9]: print x | |
1223 | hello |
|
1223 | hello | |
1224 |
|
1224 | |||
1225 | In [10]: _ip.IP.complete('x.l') |
|
1225 | In [10]: _ip.IP.complete('x.l') | |
1226 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1226 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1227 | """ |
|
1227 | """ | |
1228 |
|
1228 | |||
1229 | complete = self.Completer.complete |
|
1229 | complete = self.Completer.complete | |
1230 | state = 0 |
|
1230 | state = 0 | |
1231 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1231 | # use a dict so we get unique keys, since ipyhton's multiple | |
1232 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1232 | # completers can return duplicates. When we make 2.4 a requirement, | |
1233 | # start using sets instead, which are faster. |
|
1233 | # start using sets instead, which are faster. | |
1234 | comps = {} |
|
1234 | comps = {} | |
1235 | while True: |
|
1235 | while True: | |
1236 | newcomp = complete(text,state,line_buffer=text) |
|
1236 | newcomp = complete(text,state,line_buffer=text) | |
1237 | if newcomp is None: |
|
1237 | if newcomp is None: | |
1238 | break |
|
1238 | break | |
1239 | comps[newcomp] = 1 |
|
1239 | comps[newcomp] = 1 | |
1240 | state += 1 |
|
1240 | state += 1 | |
1241 | outcomps = comps.keys() |
|
1241 | outcomps = comps.keys() | |
1242 | outcomps.sort() |
|
1242 | outcomps.sort() | |
1243 | #print "T:",text,"OC:",outcomps # dbg |
|
1243 | #print "T:",text,"OC:",outcomps # dbg | |
1244 | #print "vars:",self.user_ns.keys() |
|
1244 | #print "vars:",self.user_ns.keys() | |
1245 | return outcomps |
|
1245 | return outcomps | |
1246 |
|
1246 | |||
1247 | def set_completer_frame(self, frame=None): |
|
1247 | def set_completer_frame(self, frame=None): | |
1248 | if frame: |
|
1248 | if frame: | |
1249 | self.Completer.namespace = frame.f_locals |
|
1249 | self.Completer.namespace = frame.f_locals | |
1250 | self.Completer.global_namespace = frame.f_globals |
|
1250 | self.Completer.global_namespace = frame.f_globals | |
1251 | else: |
|
1251 | else: | |
1252 | self.Completer.namespace = self.user_ns |
|
1252 | self.Completer.namespace = self.user_ns | |
1253 | self.Completer.global_namespace = self.user_global_ns |
|
1253 | self.Completer.global_namespace = self.user_global_ns | |
1254 |
|
1254 | |||
1255 | def init_auto_alias(self): |
|
1255 | def init_auto_alias(self): | |
1256 | """Define some aliases automatically. |
|
1256 | """Define some aliases automatically. | |
1257 |
|
1257 | |||
1258 | These are ALL parameter-less aliases""" |
|
1258 | These are ALL parameter-less aliases""" | |
1259 |
|
1259 | |||
1260 | for alias,cmd in self.auto_alias: |
|
1260 | for alias,cmd in self.auto_alias: | |
1261 | self.getapi().defalias(alias,cmd) |
|
1261 | self.getapi().defalias(alias,cmd) | |
1262 |
|
1262 | |||
1263 |
|
1263 | |||
1264 | def alias_table_validate(self,verbose=0): |
|
1264 | def alias_table_validate(self,verbose=0): | |
1265 | """Update information about the alias table. |
|
1265 | """Update information about the alias table. | |
1266 |
|
1266 | |||
1267 | In particular, make sure no Python keywords/builtins are in it.""" |
|
1267 | In particular, make sure no Python keywords/builtins are in it.""" | |
1268 |
|
1268 | |||
1269 | no_alias = self.no_alias |
|
1269 | no_alias = self.no_alias | |
1270 | for k in self.alias_table.keys(): |
|
1270 | for k in self.alias_table.keys(): | |
1271 | if k in no_alias: |
|
1271 | if k in no_alias: | |
1272 | del self.alias_table[k] |
|
1272 | del self.alias_table[k] | |
1273 | if verbose: |
|
1273 | if verbose: | |
1274 | print ("Deleting alias <%s>, it's a Python " |
|
1274 | print ("Deleting alias <%s>, it's a Python " | |
1275 | "keyword or builtin." % k) |
|
1275 | "keyword or builtin." % k) | |
1276 |
|
1276 | |||
1277 | def set_autoindent(self,value=None): |
|
1277 | def set_autoindent(self,value=None): | |
1278 | """Set the autoindent flag, checking for readline support. |
|
1278 | """Set the autoindent flag, checking for readline support. | |
1279 |
|
1279 | |||
1280 | If called with no arguments, it acts as a toggle.""" |
|
1280 | If called with no arguments, it acts as a toggle.""" | |
1281 |
|
1281 | |||
1282 | if not self.has_readline: |
|
1282 | if not self.has_readline: | |
1283 | if os.name == 'posix': |
|
1283 | if os.name == 'posix': | |
1284 | warn("The auto-indent feature requires the readline library") |
|
1284 | warn("The auto-indent feature requires the readline library") | |
1285 | self.autoindent = 0 |
|
1285 | self.autoindent = 0 | |
1286 | return |
|
1286 | return | |
1287 | if value is None: |
|
1287 | if value is None: | |
1288 | self.autoindent = not self.autoindent |
|
1288 | self.autoindent = not self.autoindent | |
1289 | else: |
|
1289 | else: | |
1290 | self.autoindent = value |
|
1290 | self.autoindent = value | |
1291 |
|
1291 | |||
1292 | def rc_set_toggle(self,rc_field,value=None): |
|
1292 | def rc_set_toggle(self,rc_field,value=None): | |
1293 | """Set or toggle a field in IPython's rc config. structure. |
|
1293 | """Set or toggle a field in IPython's rc config. structure. | |
1294 |
|
1294 | |||
1295 | If called with no arguments, it acts as a toggle. |
|
1295 | If called with no arguments, it acts as a toggle. | |
1296 |
|
1296 | |||
1297 | If called with a non-existent field, the resulting AttributeError |
|
1297 | If called with a non-existent field, the resulting AttributeError | |
1298 | exception will propagate out.""" |
|
1298 | exception will propagate out.""" | |
1299 |
|
1299 | |||
1300 | rc_val = getattr(self.rc,rc_field) |
|
1300 | rc_val = getattr(self.rc,rc_field) | |
1301 | if value is None: |
|
1301 | if value is None: | |
1302 | value = not rc_val |
|
1302 | value = not rc_val | |
1303 | setattr(self.rc,rc_field,value) |
|
1303 | setattr(self.rc,rc_field,value) | |
1304 |
|
1304 | |||
1305 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
1305 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
1306 | """Install the user configuration directory. |
|
1306 | """Install the user configuration directory. | |
1307 |
|
1307 | |||
1308 | Note |
|
1308 | Note | |
1309 | ---- |
|
1309 | ---- | |
1310 | DEPRECATED: use the top-level user_setup() function instead. |
|
1310 | DEPRECATED: use the top-level user_setup() function instead. | |
1311 | """ |
|
1311 | """ | |
1312 | return user_setup(ipythondir,rc_suffix,mode) |
|
1312 | return user_setup(ipythondir,rc_suffix,mode) | |
1313 |
|
1313 | |||
1314 | def atexit_operations(self): |
|
1314 | def atexit_operations(self): | |
1315 | """This will be executed at the time of exit. |
|
1315 | """This will be executed at the time of exit. | |
1316 |
|
1316 | |||
1317 | Saving of persistent data should be performed here. """ |
|
1317 | Saving of persistent data should be performed here. """ | |
1318 |
|
1318 | |||
1319 | #print '*** IPython exit cleanup ***' # dbg |
|
1319 | #print '*** IPython exit cleanup ***' # dbg | |
1320 | # input history |
|
1320 | # input history | |
1321 | self.savehist() |
|
1321 | self.savehist() | |
1322 |
|
1322 | |||
1323 | # Cleanup all tempfiles left around |
|
1323 | # Cleanup all tempfiles left around | |
1324 | for tfile in self.tempfiles: |
|
1324 | for tfile in self.tempfiles: | |
1325 | try: |
|
1325 | try: | |
1326 | os.unlink(tfile) |
|
1326 | os.unlink(tfile) | |
1327 | except OSError: |
|
1327 | except OSError: | |
1328 | pass |
|
1328 | pass | |
1329 |
|
1329 | |||
1330 | # Clear all user namespaces to release all references cleanly. |
|
1330 | # Clear all user namespaces to release all references cleanly. | |
1331 | self.reset() |
|
1331 | self.reset() | |
1332 |
|
1332 | |||
1333 | # Run user hooks |
|
1333 | # Run user hooks | |
1334 | self.hooks.shutdown_hook() |
|
1334 | self.hooks.shutdown_hook() | |
1335 |
|
1335 | |||
1336 | def reset(self): |
|
1336 | def reset(self): | |
1337 | """Clear all internal namespaces. |
|
1337 | """Clear all internal namespaces. | |
1338 |
|
1338 | |||
1339 | Note that this is much more aggressive than %reset, since it clears |
|
1339 | Note that this is much more aggressive than %reset, since it clears | |
1340 | fully all namespaces, as well as all input/output lists. |
|
1340 | fully all namespaces, as well as all input/output lists. | |
1341 | """ |
|
1341 | """ | |
1342 | for ns in self.ns_refs_table: |
|
1342 | for ns in self.ns_refs_table: | |
1343 | ns.clear() |
|
1343 | ns.clear() | |
1344 |
|
1344 | |||
1345 | # Clear input and output histories |
|
1345 | # Clear input and output histories | |
1346 | self.input_hist[:] = [] |
|
1346 | self.input_hist[:] = [] | |
1347 | self.input_hist_raw[:] = [] |
|
1347 | self.input_hist_raw[:] = [] | |
1348 | self.output_hist.clear() |
|
1348 | self.output_hist.clear() | |
1349 | # Restore the user namespaces to minimal usability |
|
1349 | # Restore the user namespaces to minimal usability | |
1350 | self.init_namespaces() |
|
1350 | self.init_namespaces() | |
1351 |
|
1351 | |||
1352 | def savehist(self): |
|
1352 | def savehist(self): | |
1353 | """Save input history to a file (via readline library).""" |
|
1353 | """Save input history to a file (via readline library).""" | |
1354 |
|
1354 | |||
1355 | if not self.has_readline: |
|
1355 | if not self.has_readline: | |
1356 | return |
|
1356 | return | |
1357 |
|
1357 | |||
1358 | try: |
|
1358 | try: | |
1359 | self.readline.write_history_file(self.histfile) |
|
1359 | self.readline.write_history_file(self.histfile) | |
1360 | except: |
|
1360 | except: | |
1361 | print 'Unable to save IPython command history to file: ' + \ |
|
1361 | print 'Unable to save IPython command history to file: ' + \ | |
1362 | `self.histfile` |
|
1362 | `self.histfile` | |
1363 |
|
1363 | |||
1364 | def reloadhist(self): |
|
1364 | def reloadhist(self): | |
1365 | """Reload the input history from disk file.""" |
|
1365 | """Reload the input history from disk file.""" | |
1366 |
|
1366 | |||
1367 | if self.has_readline: |
|
1367 | if self.has_readline: | |
1368 | try: |
|
1368 | try: | |
1369 | self.readline.clear_history() |
|
1369 | self.readline.clear_history() | |
1370 | self.readline.read_history_file(self.shell.histfile) |
|
1370 | self.readline.read_history_file(self.shell.histfile) | |
1371 | except AttributeError: |
|
1371 | except AttributeError: | |
1372 | pass |
|
1372 | pass | |
1373 |
|
1373 | |||
1374 |
|
1374 | |||
1375 | def history_saving_wrapper(self, func): |
|
1375 | def history_saving_wrapper(self, func): | |
1376 | """ Wrap func for readline history saving |
|
1376 | """ Wrap func for readline history saving | |
1377 |
|
1377 | |||
1378 | Convert func into callable that saves & restores |
|
1378 | Convert func into callable that saves & restores | |
1379 | history around the call """ |
|
1379 | history around the call """ | |
1380 |
|
1380 | |||
1381 | if not self.has_readline: |
|
1381 | if not self.has_readline: | |
1382 | return func |
|
1382 | return func | |
1383 |
|
1383 | |||
1384 | def wrapper(): |
|
1384 | def wrapper(): | |
1385 | self.savehist() |
|
1385 | self.savehist() | |
1386 | try: |
|
1386 | try: | |
1387 | func() |
|
1387 | func() | |
1388 | finally: |
|
1388 | finally: | |
1389 | readline.read_history_file(self.histfile) |
|
1389 | readline.read_history_file(self.histfile) | |
1390 | return wrapper |
|
1390 | return wrapper | |
1391 |
|
1391 | |||
1392 | def pre_readline(self): |
|
1392 | def pre_readline(self): | |
1393 | """readline hook to be used at the start of each line. |
|
1393 | """readline hook to be used at the start of each line. | |
1394 |
|
1394 | |||
1395 | Currently it handles auto-indent only.""" |
|
1395 | Currently it handles auto-indent only.""" | |
1396 |
|
1396 | |||
1397 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1397 | #debugx('self.indent_current_nsp','pre_readline:') | |
1398 |
|
1398 | |||
1399 | if self.rl_do_indent: |
|
1399 | if self.rl_do_indent: | |
1400 | self.readline.insert_text(self.indent_current_str()) |
|
1400 | self.readline.insert_text(self.indent_current_str()) | |
1401 | if self.rl_next_input is not None: |
|
1401 | if self.rl_next_input is not None: | |
1402 | self.readline.insert_text(self.rl_next_input) |
|
1402 | self.readline.insert_text(self.rl_next_input) | |
1403 | self.rl_next_input = None |
|
1403 | self.rl_next_input = None | |
1404 |
|
1404 | |||
1405 | def init_readline(self): |
|
1405 | def init_readline(self): | |
1406 | """Command history completion/saving/reloading.""" |
|
1406 | """Command history completion/saving/reloading.""" | |
1407 |
|
1407 | |||
1408 |
|
1408 | |||
1409 | import IPython.rlineimpl as readline |
|
1409 | import IPython.rlineimpl as readline | |
1410 |
|
1410 | |||
1411 | if not readline.have_readline: |
|
1411 | if not readline.have_readline: | |
1412 | self.has_readline = 0 |
|
1412 | self.has_readline = 0 | |
1413 | self.readline = None |
|
1413 | self.readline = None | |
1414 | # no point in bugging windows users with this every time: |
|
1414 | # no point in bugging windows users with this every time: | |
1415 | warn('Readline services not available on this platform.') |
|
1415 | warn('Readline services not available on this platform.') | |
1416 | else: |
|
1416 | else: | |
1417 | sys.modules['readline'] = readline |
|
1417 | sys.modules['readline'] = readline | |
1418 | import atexit |
|
1418 | import atexit | |
1419 | from IPython.completer import IPCompleter |
|
1419 | from IPython.completer import IPCompleter | |
1420 | self.Completer = IPCompleter(self, |
|
1420 | self.Completer = IPCompleter(self, | |
1421 | self.user_ns, |
|
1421 | self.user_ns, | |
1422 | self.user_global_ns, |
|
1422 | self.user_global_ns, | |
1423 | self.rc.readline_omit__names, |
|
1423 | self.rc.readline_omit__names, | |
1424 | self.alias_table) |
|
1424 | self.alias_table) | |
1425 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1425 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1426 | self.strdispatchers['complete_command'] = sdisp |
|
1426 | self.strdispatchers['complete_command'] = sdisp | |
1427 | self.Completer.custom_completers = sdisp |
|
1427 | self.Completer.custom_completers = sdisp | |
1428 | # Platform-specific configuration |
|
1428 | # Platform-specific configuration | |
1429 | if os.name == 'nt': |
|
1429 | if os.name == 'nt': | |
1430 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1430 | self.readline_startup_hook = readline.set_pre_input_hook | |
1431 | else: |
|
1431 | else: | |
1432 | self.readline_startup_hook = readline.set_startup_hook |
|
1432 | self.readline_startup_hook = readline.set_startup_hook | |
1433 |
|
1433 | |||
1434 | # Load user's initrc file (readline config) |
|
1434 | # Load user's initrc file (readline config) | |
1435 | # Or if libedit is used, load editrc. |
|
1435 | # Or if libedit is used, load editrc. | |
1436 | inputrc_name = os.environ.get('INPUTRC') |
|
1436 | inputrc_name = os.environ.get('INPUTRC') | |
1437 | if inputrc_name is None: |
|
1437 | if inputrc_name is None: | |
1438 | home_dir = get_home_dir() |
|
1438 | home_dir = get_home_dir() | |
1439 | if home_dir is not None: |
|
1439 | if home_dir is not None: | |
1440 | inputrc_name = '.inputrc' |
|
1440 | inputrc_name = '.inputrc' | |
1441 | if readline.uses_libedit: |
|
1441 | if readline.uses_libedit: | |
1442 | inputrc_name = '.editrc' |
|
1442 | inputrc_name = '.editrc' | |
1443 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1443 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1444 | if os.path.isfile(inputrc_name): |
|
1444 | if os.path.isfile(inputrc_name): | |
1445 | try: |
|
1445 | try: | |
1446 | readline.read_init_file(inputrc_name) |
|
1446 | readline.read_init_file(inputrc_name) | |
1447 | except: |
|
1447 | except: | |
1448 | warn('Problems reading readline initialization file <%s>' |
|
1448 | warn('Problems reading readline initialization file <%s>' | |
1449 | % inputrc_name) |
|
1449 | % inputrc_name) | |
1450 |
|
1450 | |||
1451 | self.has_readline = 1 |
|
1451 | self.has_readline = 1 | |
1452 | self.readline = readline |
|
1452 | self.readline = readline | |
1453 | # save this in sys so embedded copies can restore it properly |
|
1453 | # save this in sys so embedded copies can restore it properly | |
1454 | sys.ipcompleter = self.Completer.complete |
|
1454 | sys.ipcompleter = self.Completer.complete | |
1455 | self.set_completer() |
|
1455 | self.set_completer() | |
1456 |
|
1456 | |||
1457 | # Configure readline according to user's prefs |
|
1457 | # Configure readline according to user's prefs | |
1458 | # This is only done if GNU readline is being used. If libedit |
|
1458 | # This is only done if GNU readline is being used. If libedit | |
1459 | # is being used (as on Leopard) the readline config is |
|
1459 | # is being used (as on Leopard) the readline config is | |
1460 | # not run as the syntax for libedit is different. |
|
1460 | # not run as the syntax for libedit is different. | |
1461 | if not readline.uses_libedit: |
|
1461 | if not readline.uses_libedit: | |
1462 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1462 | for rlcommand in self.rc.readline_parse_and_bind: | |
1463 | #print "loading rl:",rlcommand # dbg |
|
1463 | #print "loading rl:",rlcommand # dbg | |
1464 | readline.parse_and_bind(rlcommand) |
|
1464 | readline.parse_and_bind(rlcommand) | |
1465 |
|
1465 | |||
1466 | # remove some chars from the delimiters list |
|
1466 | # remove some chars from the delimiters list | |
1467 | delims = readline.get_completer_delims() |
|
1467 | delims = readline.get_completer_delims() | |
1468 | delims = delims.translate(string._idmap, |
|
1468 | delims = delims.translate(string._idmap, | |
1469 | self.rc.readline_remove_delims) |
|
1469 | self.rc.readline_remove_delims) | |
1470 | readline.set_completer_delims(delims) |
|
1470 | readline.set_completer_delims(delims) | |
1471 | # otherwise we end up with a monster history after a while: |
|
1471 | # otherwise we end up with a monster history after a while: | |
1472 | readline.set_history_length(1000) |
|
1472 | readline.set_history_length(1000) | |
1473 | try: |
|
1473 | try: | |
1474 | #print '*** Reading readline history' # dbg |
|
1474 | #print '*** Reading readline history' # dbg | |
1475 | readline.read_history_file(self.histfile) |
|
1475 | readline.read_history_file(self.histfile) | |
1476 | except IOError: |
|
1476 | except IOError: | |
1477 | pass # It doesn't exist yet. |
|
1477 | pass # It doesn't exist yet. | |
1478 |
|
1478 | |||
1479 | atexit.register(self.atexit_operations) |
|
1479 | atexit.register(self.atexit_operations) | |
1480 | del atexit |
|
1480 | del atexit | |
1481 |
|
1481 | |||
1482 | # Configure auto-indent for all platforms |
|
1482 | # Configure auto-indent for all platforms | |
1483 | self.set_autoindent(self.rc.autoindent) |
|
1483 | self.set_autoindent(self.rc.autoindent) | |
1484 |
|
1484 | |||
1485 | def ask_yes_no(self,prompt,default=True): |
|
1485 | def ask_yes_no(self,prompt,default=True): | |
1486 | if self.rc.quiet: |
|
1486 | if self.rc.quiet: | |
1487 | return True |
|
1487 | return True | |
1488 | return ask_yes_no(prompt,default) |
|
1488 | return ask_yes_no(prompt,default) | |
1489 |
|
1489 | |||
1490 | def cache_main_mod(self,mod): |
|
1490 | def cache_main_mod(self,mod,fname=None): | |
1491 | """Cache a main module. |
|
1491 | """Cache a main module. | |
1492 |
|
1492 | |||
1493 | When scripts are executed via %run, we must keep a reference to their |
|
1493 | When scripts are executed via %run, we must keep a reference to their | |
1494 | __main__ module (a FakeModule instance) around so that Python doesn't |
|
1494 | __main__ module (a FakeModule instance) around so that Python doesn't | |
1495 | clear it, rendering objects defined therein useless. |
|
1495 | clear it, rendering objects defined therein useless. | |
1496 |
|
1496 | |||
1497 | This method keeps said reference in a private dict, keyed by the |
|
1497 | This method keeps said reference in a private dict, keyed by the | |
1498 | absolute path of the module object (which corresponds to the script |
|
1498 | absolute path of the module object (which corresponds to the script | |
1499 | path). This way, for multiple executions of the same script we only |
|
1499 | path). This way, for multiple executions of the same script we only | |
1500 | keep one copy of __main__ (the last one), thus preventing memory leaks |
|
1500 | keep one copy of __main__ (the last one), thus preventing memory leaks | |
1501 | from old references while allowing the objects from the last execution |
|
1501 | from old references while allowing the objects from the last execution | |
1502 | to be accessible. |
|
1502 | to be accessible. | |
1503 |
|
1503 | |||
1504 | Parameters |
|
1504 | Parameters | |
1505 | ---------- |
|
1505 | ---------- | |
1506 | mod : a module object |
|
1506 | mod : a module object | |
1507 |
|
1507 | |||
1508 | Examples |
|
1508 | Examples | |
1509 | -------- |
|
1509 | -------- | |
1510 |
|
1510 | |||
1511 | In [10]: import IPython |
|
1511 | In [10]: import IPython | |
1512 |
|
1512 | |||
1513 | In [11]: _ip.IP.cache_main_mod(IPython) |
|
1513 | In [11]: _ip.IP.cache_main_mod(IPython) | |
1514 |
|
1514 | |||
1515 | In [12]: IPython.__file__ in _ip.IP._user_main_modules |
|
1515 | In [12]: IPython.__file__ in _ip.IP._user_main_modules | |
1516 | Out[12]: True |
|
1516 | Out[12]: True | |
1517 | """ |
|
1517 | """ | |
1518 | self._user_main_modules[os.path.abspath(mod.__file__) ] = mod |
|
1518 | if fname is None: | |
|
1519 | fname = mod.__file__ | |||
|
1520 | #print >> sys.stderr, 'CFNAME :', os.path.abspath(fname) # dbg | |||
|
1521 | self._user_main_modules[os.path.abspath(fname)] = mod | |||
1519 |
|
1522 | |||
1520 | def clear_main_mod_cache(self): |
|
1523 | def clear_main_mod_cache(self): | |
1521 | """Clear the cache of main modules. |
|
1524 | """Clear the cache of main modules. | |
1522 |
|
1525 | |||
1523 | Mainly for use by utilities like %reset. |
|
1526 | Mainly for use by utilities like %reset. | |
1524 |
|
1527 | |||
1525 | Examples |
|
1528 | Examples | |
1526 | -------- |
|
1529 | -------- | |
1527 |
|
1530 | |||
1528 | In [15]: import IPython |
|
1531 | In [15]: import IPython | |
1529 |
|
1532 | |||
1530 | In [16]: _ip.IP.cache_main_mod(IPython) |
|
1533 | In [16]: _ip.IP.cache_main_mod(IPython) | |
1531 |
|
1534 | |||
1532 | In [17]: len(_ip.IP._user_main_modules) > 0 |
|
1535 | In [17]: len(_ip.IP._user_main_modules) > 0 | |
1533 | Out[17]: True |
|
1536 | Out[17]: True | |
1534 |
|
1537 | |||
1535 | In [18]: _ip.IP.clear_main_mod_cache() |
|
1538 | In [18]: _ip.IP.clear_main_mod_cache() | |
1536 |
|
1539 | |||
1537 | In [19]: len(_ip.IP._user_main_modules) == 0 |
|
1540 | In [19]: len(_ip.IP._user_main_modules) == 0 | |
1538 | Out[19]: True |
|
1541 | Out[19]: True | |
1539 | """ |
|
1542 | """ | |
1540 | self._user_main_modules.clear() |
|
1543 | self._user_main_modules.clear() | |
1541 |
|
1544 | |||
1542 | def _should_recompile(self,e): |
|
1545 | def _should_recompile(self,e): | |
1543 | """Utility routine for edit_syntax_error""" |
|
1546 | """Utility routine for edit_syntax_error""" | |
1544 |
|
1547 | |||
1545 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1548 | if e.filename in ('<ipython console>','<input>','<string>', | |
1546 | '<console>','<BackgroundJob compilation>', |
|
1549 | '<console>','<BackgroundJob compilation>', | |
1547 | None): |
|
1550 | None): | |
1548 |
|
1551 | |||
1549 | return False |
|
1552 | return False | |
1550 | try: |
|
1553 | try: | |
1551 | if (self.rc.autoedit_syntax and |
|
1554 | if (self.rc.autoedit_syntax and | |
1552 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1555 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1553 | '[Y/n] ','y')): |
|
1556 | '[Y/n] ','y')): | |
1554 | return False |
|
1557 | return False | |
1555 | except EOFError: |
|
1558 | except EOFError: | |
1556 | return False |
|
1559 | return False | |
1557 |
|
1560 | |||
1558 | def int0(x): |
|
1561 | def int0(x): | |
1559 | try: |
|
1562 | try: | |
1560 | return int(x) |
|
1563 | return int(x) | |
1561 | except TypeError: |
|
1564 | except TypeError: | |
1562 | return 0 |
|
1565 | return 0 | |
1563 | # always pass integer line and offset values to editor hook |
|
1566 | # always pass integer line and offset values to editor hook | |
1564 | try: |
|
1567 | try: | |
1565 | self.hooks.fix_error_editor(e.filename, |
|
1568 | self.hooks.fix_error_editor(e.filename, | |
1566 | int0(e.lineno),int0(e.offset),e.msg) |
|
1569 | int0(e.lineno),int0(e.offset),e.msg) | |
1567 | except IPython.ipapi.TryNext: |
|
1570 | except IPython.ipapi.TryNext: | |
1568 | warn('Could not open editor') |
|
1571 | warn('Could not open editor') | |
1569 | return False |
|
1572 | return False | |
1570 | return True |
|
1573 | return True | |
1571 |
|
1574 | |||
1572 | def edit_syntax_error(self): |
|
1575 | def edit_syntax_error(self): | |
1573 | """The bottom half of the syntax error handler called in the main loop. |
|
1576 | """The bottom half of the syntax error handler called in the main loop. | |
1574 |
|
1577 | |||
1575 | Loop until syntax error is fixed or user cancels. |
|
1578 | Loop until syntax error is fixed or user cancels. | |
1576 | """ |
|
1579 | """ | |
1577 |
|
1580 | |||
1578 | while self.SyntaxTB.last_syntax_error: |
|
1581 | while self.SyntaxTB.last_syntax_error: | |
1579 | # copy and clear last_syntax_error |
|
1582 | # copy and clear last_syntax_error | |
1580 | err = self.SyntaxTB.clear_err_state() |
|
1583 | err = self.SyntaxTB.clear_err_state() | |
1581 | if not self._should_recompile(err): |
|
1584 | if not self._should_recompile(err): | |
1582 | return |
|
1585 | return | |
1583 | try: |
|
1586 | try: | |
1584 | # may set last_syntax_error again if a SyntaxError is raised |
|
1587 | # may set last_syntax_error again if a SyntaxError is raised | |
1585 | self.safe_execfile(err.filename,self.user_ns) |
|
1588 | self.safe_execfile(err.filename,self.user_ns) | |
1586 | except: |
|
1589 | except: | |
1587 | self.showtraceback() |
|
1590 | self.showtraceback() | |
1588 | else: |
|
1591 | else: | |
1589 | try: |
|
1592 | try: | |
1590 | f = file(err.filename) |
|
1593 | f = file(err.filename) | |
1591 | try: |
|
1594 | try: | |
1592 | sys.displayhook(f.read()) |
|
1595 | sys.displayhook(f.read()) | |
1593 | finally: |
|
1596 | finally: | |
1594 | f.close() |
|
1597 | f.close() | |
1595 | except: |
|
1598 | except: | |
1596 | self.showtraceback() |
|
1599 | self.showtraceback() | |
1597 |
|
1600 | |||
1598 | def showsyntaxerror(self, filename=None): |
|
1601 | def showsyntaxerror(self, filename=None): | |
1599 | """Display the syntax error that just occurred. |
|
1602 | """Display the syntax error that just occurred. | |
1600 |
|
1603 | |||
1601 | This doesn't display a stack trace because there isn't one. |
|
1604 | This doesn't display a stack trace because there isn't one. | |
1602 |
|
1605 | |||
1603 | If a filename is given, it is stuffed in the exception instead |
|
1606 | If a filename is given, it is stuffed in the exception instead | |
1604 | of what was there before (because Python's parser always uses |
|
1607 | of what was there before (because Python's parser always uses | |
1605 | "<string>" when reading from a string). |
|
1608 | "<string>" when reading from a string). | |
1606 | """ |
|
1609 | """ | |
1607 | etype, value, last_traceback = sys.exc_info() |
|
1610 | etype, value, last_traceback = sys.exc_info() | |
1608 |
|
1611 | |||
1609 | # See note about these variables in showtraceback() below |
|
1612 | # See note about these variables in showtraceback() below | |
1610 | sys.last_type = etype |
|
1613 | sys.last_type = etype | |
1611 | sys.last_value = value |
|
1614 | sys.last_value = value | |
1612 | sys.last_traceback = last_traceback |
|
1615 | sys.last_traceback = last_traceback | |
1613 |
|
1616 | |||
1614 | if filename and etype is SyntaxError: |
|
1617 | if filename and etype is SyntaxError: | |
1615 | # Work hard to stuff the correct filename in the exception |
|
1618 | # Work hard to stuff the correct filename in the exception | |
1616 | try: |
|
1619 | try: | |
1617 | msg, (dummy_filename, lineno, offset, line) = value |
|
1620 | msg, (dummy_filename, lineno, offset, line) = value | |
1618 | except: |
|
1621 | except: | |
1619 | # Not the format we expect; leave it alone |
|
1622 | # Not the format we expect; leave it alone | |
1620 | pass |
|
1623 | pass | |
1621 | else: |
|
1624 | else: | |
1622 | # Stuff in the right filename |
|
1625 | # Stuff in the right filename | |
1623 | try: |
|
1626 | try: | |
1624 | # Assume SyntaxError is a class exception |
|
1627 | # Assume SyntaxError is a class exception | |
1625 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1628 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1626 | except: |
|
1629 | except: | |
1627 | # If that failed, assume SyntaxError is a string |
|
1630 | # If that failed, assume SyntaxError is a string | |
1628 | value = msg, (filename, lineno, offset, line) |
|
1631 | value = msg, (filename, lineno, offset, line) | |
1629 | self.SyntaxTB(etype,value,[]) |
|
1632 | self.SyntaxTB(etype,value,[]) | |
1630 |
|
1633 | |||
1631 | def debugger(self,force=False): |
|
1634 | def debugger(self,force=False): | |
1632 | """Call the pydb/pdb debugger. |
|
1635 | """Call the pydb/pdb debugger. | |
1633 |
|
1636 | |||
1634 | Keywords: |
|
1637 | Keywords: | |
1635 |
|
1638 | |||
1636 | - force(False): by default, this routine checks the instance call_pdb |
|
1639 | - force(False): by default, this routine checks the instance call_pdb | |
1637 | flag and does not actually invoke the debugger if the flag is false. |
|
1640 | flag and does not actually invoke the debugger if the flag is false. | |
1638 | The 'force' option forces the debugger to activate even if the flag |
|
1641 | The 'force' option forces the debugger to activate even if the flag | |
1639 | is false. |
|
1642 | is false. | |
1640 | """ |
|
1643 | """ | |
1641 |
|
1644 | |||
1642 | if not (force or self.call_pdb): |
|
1645 | if not (force or self.call_pdb): | |
1643 | return |
|
1646 | return | |
1644 |
|
1647 | |||
1645 | if not hasattr(sys,'last_traceback'): |
|
1648 | if not hasattr(sys,'last_traceback'): | |
1646 | error('No traceback has been produced, nothing to debug.') |
|
1649 | error('No traceback has been produced, nothing to debug.') | |
1647 | return |
|
1650 | return | |
1648 |
|
1651 | |||
1649 | # use pydb if available |
|
1652 | # use pydb if available | |
1650 | if Debugger.has_pydb: |
|
1653 | if Debugger.has_pydb: | |
1651 | from pydb import pm |
|
1654 | from pydb import pm | |
1652 | else: |
|
1655 | else: | |
1653 | # fallback to our internal debugger |
|
1656 | # fallback to our internal debugger | |
1654 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
1657 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
1655 | self.history_saving_wrapper(pm)() |
|
1658 | self.history_saving_wrapper(pm)() | |
1656 |
|
1659 | |||
1657 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1660 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1658 | """Display the exception that just occurred. |
|
1661 | """Display the exception that just occurred. | |
1659 |
|
1662 | |||
1660 | If nothing is known about the exception, this is the method which |
|
1663 | If nothing is known about the exception, this is the method which | |
1661 | should be used throughout the code for presenting user tracebacks, |
|
1664 | should be used throughout the code for presenting user tracebacks, | |
1662 | rather than directly invoking the InteractiveTB object. |
|
1665 | rather than directly invoking the InteractiveTB object. | |
1663 |
|
1666 | |||
1664 | A specific showsyntaxerror() also exists, but this method can take |
|
1667 | A specific showsyntaxerror() also exists, but this method can take | |
1665 | care of calling it if needed, so unless you are explicitly catching a |
|
1668 | care of calling it if needed, so unless you are explicitly catching a | |
1666 | SyntaxError exception, don't try to analyze the stack manually and |
|
1669 | SyntaxError exception, don't try to analyze the stack manually and | |
1667 | simply call this method.""" |
|
1670 | simply call this method.""" | |
1668 |
|
1671 | |||
1669 |
|
1672 | |||
1670 | # Though this won't be called by syntax errors in the input line, |
|
1673 | # Though this won't be called by syntax errors in the input line, | |
1671 | # there may be SyntaxError cases whith imported code. |
|
1674 | # there may be SyntaxError cases whith imported code. | |
1672 |
|
1675 | |||
1673 | try: |
|
1676 | try: | |
1674 | if exc_tuple is None: |
|
1677 | if exc_tuple is None: | |
1675 | etype, value, tb = sys.exc_info() |
|
1678 | etype, value, tb = sys.exc_info() | |
1676 | else: |
|
1679 | else: | |
1677 | etype, value, tb = exc_tuple |
|
1680 | etype, value, tb = exc_tuple | |
1678 |
|
1681 | |||
1679 | if etype is SyntaxError: |
|
1682 | if etype is SyntaxError: | |
1680 | self.showsyntaxerror(filename) |
|
1683 | self.showsyntaxerror(filename) | |
1681 | elif etype is IPython.ipapi.UsageError: |
|
1684 | elif etype is IPython.ipapi.UsageError: | |
1682 | print "UsageError:", value |
|
1685 | print "UsageError:", value | |
1683 | else: |
|
1686 | else: | |
1684 | # WARNING: these variables are somewhat deprecated and not |
|
1687 | # WARNING: these variables are somewhat deprecated and not | |
1685 | # necessarily safe to use in a threaded environment, but tools |
|
1688 | # necessarily safe to use in a threaded environment, but tools | |
1686 | # like pdb depend on their existence, so let's set them. If we |
|
1689 | # like pdb depend on their existence, so let's set them. If we | |
1687 | # find problems in the field, we'll need to revisit their use. |
|
1690 | # find problems in the field, we'll need to revisit their use. | |
1688 | sys.last_type = etype |
|
1691 | sys.last_type = etype | |
1689 | sys.last_value = value |
|
1692 | sys.last_value = value | |
1690 | sys.last_traceback = tb |
|
1693 | sys.last_traceback = tb | |
1691 |
|
1694 | |||
1692 | if etype in self.custom_exceptions: |
|
1695 | if etype in self.custom_exceptions: | |
1693 | self.CustomTB(etype,value,tb) |
|
1696 | self.CustomTB(etype,value,tb) | |
1694 | else: |
|
1697 | else: | |
1695 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1698 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1696 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1699 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1697 | # pdb mucks up readline, fix it back |
|
1700 | # pdb mucks up readline, fix it back | |
1698 | self.set_completer() |
|
1701 | self.set_completer() | |
1699 | except KeyboardInterrupt: |
|
1702 | except KeyboardInterrupt: | |
1700 | self.write("\nKeyboardInterrupt\n") |
|
1703 | self.write("\nKeyboardInterrupt\n") | |
1701 |
|
1704 | |||
1702 | def mainloop(self,banner=None): |
|
1705 | def mainloop(self,banner=None): | |
1703 | """Creates the local namespace and starts the mainloop. |
|
1706 | """Creates the local namespace and starts the mainloop. | |
1704 |
|
1707 | |||
1705 | If an optional banner argument is given, it will override the |
|
1708 | If an optional banner argument is given, it will override the | |
1706 | internally created default banner.""" |
|
1709 | internally created default banner.""" | |
1707 |
|
1710 | |||
1708 | if self.rc.c: # Emulate Python's -c option |
|
1711 | if self.rc.c: # Emulate Python's -c option | |
1709 | self.exec_init_cmd() |
|
1712 | self.exec_init_cmd() | |
1710 | if banner is None: |
|
1713 | if banner is None: | |
1711 | if not self.rc.banner: |
|
1714 | if not self.rc.banner: | |
1712 | banner = '' |
|
1715 | banner = '' | |
1713 | # banner is string? Use it directly! |
|
1716 | # banner is string? Use it directly! | |
1714 | elif isinstance(self.rc.banner,basestring): |
|
1717 | elif isinstance(self.rc.banner,basestring): | |
1715 | banner = self.rc.banner |
|
1718 | banner = self.rc.banner | |
1716 | else: |
|
1719 | else: | |
1717 | banner = self.BANNER+self.banner2 |
|
1720 | banner = self.BANNER+self.banner2 | |
1718 |
|
1721 | |||
1719 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1722 | # if you run stuff with -c <cmd>, raw hist is not updated | |
1720 | # ensure that it's in sync |
|
1723 | # ensure that it's in sync | |
1721 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1724 | if len(self.input_hist) != len (self.input_hist_raw): | |
1722 | self.input_hist_raw = InputList(self.input_hist) |
|
1725 | self.input_hist_raw = InputList(self.input_hist) | |
1723 |
|
1726 | |||
1724 | while 1: |
|
1727 | while 1: | |
1725 | try: |
|
1728 | try: | |
1726 | self.interact(banner) |
|
1729 | self.interact(banner) | |
1727 | #self.interact_with_readline() |
|
1730 | #self.interact_with_readline() | |
1728 |
|
1731 | |||
1729 | # XXX for testing of a readline-decoupled repl loop, call |
|
1732 | # XXX for testing of a readline-decoupled repl loop, call | |
1730 | # interact_with_readline above |
|
1733 | # interact_with_readline above | |
1731 |
|
1734 | |||
1732 | break |
|
1735 | break | |
1733 | except KeyboardInterrupt: |
|
1736 | except KeyboardInterrupt: | |
1734 | # this should not be necessary, but KeyboardInterrupt |
|
1737 | # this should not be necessary, but KeyboardInterrupt | |
1735 | # handling seems rather unpredictable... |
|
1738 | # handling seems rather unpredictable... | |
1736 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1739 | self.write("\nKeyboardInterrupt in interact()\n") | |
1737 |
|
1740 | |||
1738 | def exec_init_cmd(self): |
|
1741 | def exec_init_cmd(self): | |
1739 | """Execute a command given at the command line. |
|
1742 | """Execute a command given at the command line. | |
1740 |
|
1743 | |||
1741 | This emulates Python's -c option.""" |
|
1744 | This emulates Python's -c option.""" | |
1742 |
|
1745 | |||
1743 | #sys.argv = ['-c'] |
|
1746 | #sys.argv = ['-c'] | |
1744 | self.push(self.prefilter(self.rc.c, False)) |
|
1747 | self.push(self.prefilter(self.rc.c, False)) | |
1745 | if not self.rc.interact: |
|
1748 | if not self.rc.interact: | |
1746 | self.ask_exit() |
|
1749 | self.ask_exit() | |
1747 |
|
1750 | |||
1748 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1751 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1749 | """Embeds IPython into a running python program. |
|
1752 | """Embeds IPython into a running python program. | |
1750 |
|
1753 | |||
1751 | Input: |
|
1754 | Input: | |
1752 |
|
1755 | |||
1753 | - header: An optional header message can be specified. |
|
1756 | - header: An optional header message can be specified. | |
1754 |
|
1757 | |||
1755 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1758 | - local_ns, global_ns: working namespaces. If given as None, the | |
1756 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1759 | IPython-initialized one is updated with __main__.__dict__, so that | |
1757 | program variables become visible but user-specific configuration |
|
1760 | program variables become visible but user-specific configuration | |
1758 | remains possible. |
|
1761 | remains possible. | |
1759 |
|
1762 | |||
1760 | - stack_depth: specifies how many levels in the stack to go to |
|
1763 | - stack_depth: specifies how many levels in the stack to go to | |
1761 | looking for namespaces (when local_ns and global_ns are None). This |
|
1764 | looking for namespaces (when local_ns and global_ns are None). This | |
1762 | allows an intermediate caller to make sure that this function gets |
|
1765 | allows an intermediate caller to make sure that this function gets | |
1763 | the namespace from the intended level in the stack. By default (0) |
|
1766 | the namespace from the intended level in the stack. By default (0) | |
1764 | it will get its locals and globals from the immediate caller. |
|
1767 | it will get its locals and globals from the immediate caller. | |
1765 |
|
1768 | |||
1766 | Warning: it's possible to use this in a program which is being run by |
|
1769 | Warning: it's possible to use this in a program which is being run by | |
1767 | IPython itself (via %run), but some funny things will happen (a few |
|
1770 | IPython itself (via %run), but some funny things will happen (a few | |
1768 | globals get overwritten). In the future this will be cleaned up, as |
|
1771 | globals get overwritten). In the future this will be cleaned up, as | |
1769 | there is no fundamental reason why it can't work perfectly.""" |
|
1772 | there is no fundamental reason why it can't work perfectly.""" | |
1770 |
|
1773 | |||
1771 | # Get locals and globals from caller |
|
1774 | # Get locals and globals from caller | |
1772 | if local_ns is None or global_ns is None: |
|
1775 | if local_ns is None or global_ns is None: | |
1773 | call_frame = sys._getframe(stack_depth).f_back |
|
1776 | call_frame = sys._getframe(stack_depth).f_back | |
1774 |
|
1777 | |||
1775 | if local_ns is None: |
|
1778 | if local_ns is None: | |
1776 | local_ns = call_frame.f_locals |
|
1779 | local_ns = call_frame.f_locals | |
1777 | if global_ns is None: |
|
1780 | if global_ns is None: | |
1778 | global_ns = call_frame.f_globals |
|
1781 | global_ns = call_frame.f_globals | |
1779 |
|
1782 | |||
1780 | # Update namespaces and fire up interpreter |
|
1783 | # Update namespaces and fire up interpreter | |
1781 |
|
1784 | |||
1782 | # The global one is easy, we can just throw it in |
|
1785 | # The global one is easy, we can just throw it in | |
1783 | self.user_global_ns = global_ns |
|
1786 | self.user_global_ns = global_ns | |
1784 |
|
1787 | |||
1785 | # but the user/local one is tricky: ipython needs it to store internal |
|
1788 | # but the user/local one is tricky: ipython needs it to store internal | |
1786 | # data, but we also need the locals. We'll copy locals in the user |
|
1789 | # data, but we also need the locals. We'll copy locals in the user | |
1787 | # one, but will track what got copied so we can delete them at exit. |
|
1790 | # one, but will track what got copied so we can delete them at exit. | |
1788 | # This is so that a later embedded call doesn't see locals from a |
|
1791 | # This is so that a later embedded call doesn't see locals from a | |
1789 | # previous call (which most likely existed in a separate scope). |
|
1792 | # previous call (which most likely existed in a separate scope). | |
1790 | local_varnames = local_ns.keys() |
|
1793 | local_varnames = local_ns.keys() | |
1791 | self.user_ns.update(local_ns) |
|
1794 | self.user_ns.update(local_ns) | |
1792 | #self.user_ns['local_ns'] = local_ns # dbg |
|
1795 | #self.user_ns['local_ns'] = local_ns # dbg | |
1793 |
|
1796 | |||
1794 | # Patch for global embedding to make sure that things don't overwrite |
|
1797 | # Patch for global embedding to make sure that things don't overwrite | |
1795 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1798 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1796 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1799 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1797 | if local_ns is None and global_ns is None: |
|
1800 | if local_ns is None and global_ns is None: | |
1798 | self.user_global_ns.update(__main__.__dict__) |
|
1801 | self.user_global_ns.update(__main__.__dict__) | |
1799 |
|
1802 | |||
1800 | # make sure the tab-completer has the correct frame information, so it |
|
1803 | # make sure the tab-completer has the correct frame information, so it | |
1801 | # actually completes using the frame's locals/globals |
|
1804 | # actually completes using the frame's locals/globals | |
1802 | self.set_completer_frame() |
|
1805 | self.set_completer_frame() | |
1803 |
|
1806 | |||
1804 | # before activating the interactive mode, we need to make sure that |
|
1807 | # before activating the interactive mode, we need to make sure that | |
1805 | # all names in the builtin namespace needed by ipython point to |
|
1808 | # all names in the builtin namespace needed by ipython point to | |
1806 | # ourselves, and not to other instances. |
|
1809 | # ourselves, and not to other instances. | |
1807 | self.add_builtins() |
|
1810 | self.add_builtins() | |
1808 |
|
1811 | |||
1809 | self.interact(header) |
|
1812 | self.interact(header) | |
1810 |
|
1813 | |||
1811 | # now, purge out the user namespace from anything we might have added |
|
1814 | # now, purge out the user namespace from anything we might have added | |
1812 | # from the caller's local namespace |
|
1815 | # from the caller's local namespace | |
1813 | delvar = self.user_ns.pop |
|
1816 | delvar = self.user_ns.pop | |
1814 | for var in local_varnames: |
|
1817 | for var in local_varnames: | |
1815 | delvar(var,None) |
|
1818 | delvar(var,None) | |
1816 | # and clean builtins we may have overridden |
|
1819 | # and clean builtins we may have overridden | |
1817 | self.clean_builtins() |
|
1820 | self.clean_builtins() | |
1818 |
|
1821 | |||
1819 | def interact_prompt(self): |
|
1822 | def interact_prompt(self): | |
1820 | """ Print the prompt (in read-eval-print loop) |
|
1823 | """ Print the prompt (in read-eval-print loop) | |
1821 |
|
1824 | |||
1822 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1825 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1823 | used in standard IPython flow. |
|
1826 | used in standard IPython flow. | |
1824 | """ |
|
1827 | """ | |
1825 | if self.more: |
|
1828 | if self.more: | |
1826 | try: |
|
1829 | try: | |
1827 | prompt = self.hooks.generate_prompt(True) |
|
1830 | prompt = self.hooks.generate_prompt(True) | |
1828 | except: |
|
1831 | except: | |
1829 | self.showtraceback() |
|
1832 | self.showtraceback() | |
1830 | if self.autoindent: |
|
1833 | if self.autoindent: | |
1831 | self.rl_do_indent = True |
|
1834 | self.rl_do_indent = True | |
1832 |
|
1835 | |||
1833 | else: |
|
1836 | else: | |
1834 | try: |
|
1837 | try: | |
1835 | prompt = self.hooks.generate_prompt(False) |
|
1838 | prompt = self.hooks.generate_prompt(False) | |
1836 | except: |
|
1839 | except: | |
1837 | self.showtraceback() |
|
1840 | self.showtraceback() | |
1838 | self.write(prompt) |
|
1841 | self.write(prompt) | |
1839 |
|
1842 | |||
1840 | def interact_handle_input(self,line): |
|
1843 | def interact_handle_input(self,line): | |
1841 | """ Handle the input line (in read-eval-print loop) |
|
1844 | """ Handle the input line (in read-eval-print loop) | |
1842 |
|
1845 | |||
1843 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1846 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1844 | used in standard IPython flow. |
|
1847 | used in standard IPython flow. | |
1845 | """ |
|
1848 | """ | |
1846 | if line.lstrip() == line: |
|
1849 | if line.lstrip() == line: | |
1847 | self.shadowhist.add(line.strip()) |
|
1850 | self.shadowhist.add(line.strip()) | |
1848 | lineout = self.prefilter(line,self.more) |
|
1851 | lineout = self.prefilter(line,self.more) | |
1849 |
|
1852 | |||
1850 | if line.strip(): |
|
1853 | if line.strip(): | |
1851 | if self.more: |
|
1854 | if self.more: | |
1852 | self.input_hist_raw[-1] += '%s\n' % line |
|
1855 | self.input_hist_raw[-1] += '%s\n' % line | |
1853 | else: |
|
1856 | else: | |
1854 | self.input_hist_raw.append('%s\n' % line) |
|
1857 | self.input_hist_raw.append('%s\n' % line) | |
1855 |
|
1858 | |||
1856 |
|
1859 | |||
1857 | self.more = self.push(lineout) |
|
1860 | self.more = self.push(lineout) | |
1858 | if (self.SyntaxTB.last_syntax_error and |
|
1861 | if (self.SyntaxTB.last_syntax_error and | |
1859 | self.rc.autoedit_syntax): |
|
1862 | self.rc.autoedit_syntax): | |
1860 | self.edit_syntax_error() |
|
1863 | self.edit_syntax_error() | |
1861 |
|
1864 | |||
1862 | def interact_with_readline(self): |
|
1865 | def interact_with_readline(self): | |
1863 | """ Demo of using interact_handle_input, interact_prompt |
|
1866 | """ Demo of using interact_handle_input, interact_prompt | |
1864 |
|
1867 | |||
1865 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1868 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1866 | it should work like this. |
|
1869 | it should work like this. | |
1867 | """ |
|
1870 | """ | |
1868 | self.readline_startup_hook(self.pre_readline) |
|
1871 | self.readline_startup_hook(self.pre_readline) | |
1869 | while not self.exit_now: |
|
1872 | while not self.exit_now: | |
1870 | self.interact_prompt() |
|
1873 | self.interact_prompt() | |
1871 | if self.more: |
|
1874 | if self.more: | |
1872 | self.rl_do_indent = True |
|
1875 | self.rl_do_indent = True | |
1873 | else: |
|
1876 | else: | |
1874 | self.rl_do_indent = False |
|
1877 | self.rl_do_indent = False | |
1875 | line = raw_input_original().decode(self.stdin_encoding) |
|
1878 | line = raw_input_original().decode(self.stdin_encoding) | |
1876 | self.interact_handle_input(line) |
|
1879 | self.interact_handle_input(line) | |
1877 |
|
1880 | |||
1878 |
|
1881 | |||
1879 | def interact(self, banner=None): |
|
1882 | def interact(self, banner=None): | |
1880 | """Closely emulate the interactive Python console. |
|
1883 | """Closely emulate the interactive Python console. | |
1881 |
|
1884 | |||
1882 | The optional banner argument specify the banner to print |
|
1885 | The optional banner argument specify the banner to print | |
1883 | before the first interaction; by default it prints a banner |
|
1886 | before the first interaction; by default it prints a banner | |
1884 | similar to the one printed by the real Python interpreter, |
|
1887 | similar to the one printed by the real Python interpreter, | |
1885 | followed by the current class name in parentheses (so as not |
|
1888 | followed by the current class name in parentheses (so as not | |
1886 | to confuse this with the real interpreter -- since it's so |
|
1889 | to confuse this with the real interpreter -- since it's so | |
1887 | close!). |
|
1890 | close!). | |
1888 |
|
1891 | |||
1889 | """ |
|
1892 | """ | |
1890 |
|
1893 | |||
1891 | if self.exit_now: |
|
1894 | if self.exit_now: | |
1892 | # batch run -> do not interact |
|
1895 | # batch run -> do not interact | |
1893 | return |
|
1896 | return | |
1894 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1897 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1895 | if banner is None: |
|
1898 | if banner is None: | |
1896 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1899 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1897 | (sys.version, sys.platform, cprt, |
|
1900 | (sys.version, sys.platform, cprt, | |
1898 | self.__class__.__name__)) |
|
1901 | self.__class__.__name__)) | |
1899 | else: |
|
1902 | else: | |
1900 | self.write(banner) |
|
1903 | self.write(banner) | |
1901 |
|
1904 | |||
1902 | more = 0 |
|
1905 | more = 0 | |
1903 |
|
1906 | |||
1904 | # Mark activity in the builtins |
|
1907 | # Mark activity in the builtins | |
1905 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1908 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1906 |
|
1909 | |||
1907 | if self.has_readline: |
|
1910 | if self.has_readline: | |
1908 | self.readline_startup_hook(self.pre_readline) |
|
1911 | self.readline_startup_hook(self.pre_readline) | |
1909 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1912 | # exit_now is set by a call to %Exit or %Quit, through the | |
1910 | # ask_exit callback. |
|
1913 | # ask_exit callback. | |
1911 |
|
1914 | |||
1912 | while not self.exit_now: |
|
1915 | while not self.exit_now: | |
1913 | self.hooks.pre_prompt_hook() |
|
1916 | self.hooks.pre_prompt_hook() | |
1914 | if more: |
|
1917 | if more: | |
1915 | try: |
|
1918 | try: | |
1916 | prompt = self.hooks.generate_prompt(True) |
|
1919 | prompt = self.hooks.generate_prompt(True) | |
1917 | except: |
|
1920 | except: | |
1918 | self.showtraceback() |
|
1921 | self.showtraceback() | |
1919 | if self.autoindent: |
|
1922 | if self.autoindent: | |
1920 | self.rl_do_indent = True |
|
1923 | self.rl_do_indent = True | |
1921 |
|
1924 | |||
1922 | else: |
|
1925 | else: | |
1923 | try: |
|
1926 | try: | |
1924 | prompt = self.hooks.generate_prompt(False) |
|
1927 | prompt = self.hooks.generate_prompt(False) | |
1925 | except: |
|
1928 | except: | |
1926 | self.showtraceback() |
|
1929 | self.showtraceback() | |
1927 | try: |
|
1930 | try: | |
1928 | line = self.raw_input(prompt,more) |
|
1931 | line = self.raw_input(prompt,more) | |
1929 | if self.exit_now: |
|
1932 | if self.exit_now: | |
1930 | # quick exit on sys.std[in|out] close |
|
1933 | # quick exit on sys.std[in|out] close | |
1931 | break |
|
1934 | break | |
1932 | if self.autoindent: |
|
1935 | if self.autoindent: | |
1933 | self.rl_do_indent = False |
|
1936 | self.rl_do_indent = False | |
1934 |
|
1937 | |||
1935 | except KeyboardInterrupt: |
|
1938 | except KeyboardInterrupt: | |
1936 | #double-guard against keyboardinterrupts during kbdint handling |
|
1939 | #double-guard against keyboardinterrupts during kbdint handling | |
1937 | try: |
|
1940 | try: | |
1938 | self.write('\nKeyboardInterrupt\n') |
|
1941 | self.write('\nKeyboardInterrupt\n') | |
1939 | self.resetbuffer() |
|
1942 | self.resetbuffer() | |
1940 | # keep cache in sync with the prompt counter: |
|
1943 | # keep cache in sync with the prompt counter: | |
1941 | self.outputcache.prompt_count -= 1 |
|
1944 | self.outputcache.prompt_count -= 1 | |
1942 |
|
1945 | |||
1943 | if self.autoindent: |
|
1946 | if self.autoindent: | |
1944 | self.indent_current_nsp = 0 |
|
1947 | self.indent_current_nsp = 0 | |
1945 | more = 0 |
|
1948 | more = 0 | |
1946 | except KeyboardInterrupt: |
|
1949 | except KeyboardInterrupt: | |
1947 | pass |
|
1950 | pass | |
1948 | except EOFError: |
|
1951 | except EOFError: | |
1949 | if self.autoindent: |
|
1952 | if self.autoindent: | |
1950 | self.rl_do_indent = False |
|
1953 | self.rl_do_indent = False | |
1951 | self.readline_startup_hook(None) |
|
1954 | self.readline_startup_hook(None) | |
1952 | self.write('\n') |
|
1955 | self.write('\n') | |
1953 | self.exit() |
|
1956 | self.exit() | |
1954 | except bdb.BdbQuit: |
|
1957 | except bdb.BdbQuit: | |
1955 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1958 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1956 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1959 | 'Because of how pdb handles the stack, it is impossible\n' | |
1957 | 'for IPython to properly format this particular exception.\n' |
|
1960 | 'for IPython to properly format this particular exception.\n' | |
1958 | 'IPython will resume normal operation.') |
|
1961 | 'IPython will resume normal operation.') | |
1959 | except: |
|
1962 | except: | |
1960 | # exceptions here are VERY RARE, but they can be triggered |
|
1963 | # exceptions here are VERY RARE, but they can be triggered | |
1961 | # asynchronously by signal handlers, for example. |
|
1964 | # asynchronously by signal handlers, for example. | |
1962 | self.showtraceback() |
|
1965 | self.showtraceback() | |
1963 | else: |
|
1966 | else: | |
1964 | more = self.push(line) |
|
1967 | more = self.push(line) | |
1965 | if (self.SyntaxTB.last_syntax_error and |
|
1968 | if (self.SyntaxTB.last_syntax_error and | |
1966 | self.rc.autoedit_syntax): |
|
1969 | self.rc.autoedit_syntax): | |
1967 | self.edit_syntax_error() |
|
1970 | self.edit_syntax_error() | |
1968 |
|
1971 | |||
1969 | # We are off again... |
|
1972 | # We are off again... | |
1970 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1973 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1971 |
|
1974 | |||
1972 | def excepthook(self, etype, value, tb): |
|
1975 | def excepthook(self, etype, value, tb): | |
1973 | """One more defense for GUI apps that call sys.excepthook. |
|
1976 | """One more defense for GUI apps that call sys.excepthook. | |
1974 |
|
1977 | |||
1975 | GUI frameworks like wxPython trap exceptions and call |
|
1978 | GUI frameworks like wxPython trap exceptions and call | |
1976 | sys.excepthook themselves. I guess this is a feature that |
|
1979 | sys.excepthook themselves. I guess this is a feature that | |
1977 | enables them to keep running after exceptions that would |
|
1980 | enables them to keep running after exceptions that would | |
1978 | otherwise kill their mainloop. This is a bother for IPython |
|
1981 | otherwise kill their mainloop. This is a bother for IPython | |
1979 | which excepts to catch all of the program exceptions with a try: |
|
1982 | which excepts to catch all of the program exceptions with a try: | |
1980 | except: statement. |
|
1983 | except: statement. | |
1981 |
|
1984 | |||
1982 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1985 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1983 | any app directly invokes sys.excepthook, it will look to the user like |
|
1986 | any app directly invokes sys.excepthook, it will look to the user like | |
1984 | IPython crashed. In order to work around this, we can disable the |
|
1987 | IPython crashed. In order to work around this, we can disable the | |
1985 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1988 | CrashHandler and replace it with this excepthook instead, which prints a | |
1986 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1989 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1987 | call sys.excepthook will generate a regular-looking exception from |
|
1990 | call sys.excepthook will generate a regular-looking exception from | |
1988 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1991 | IPython, and the CrashHandler will only be triggered by real IPython | |
1989 | crashes. |
|
1992 | crashes. | |
1990 |
|
1993 | |||
1991 | This hook should be used sparingly, only in places which are not likely |
|
1994 | This hook should be used sparingly, only in places which are not likely | |
1992 | to be true IPython errors. |
|
1995 | to be true IPython errors. | |
1993 | """ |
|
1996 | """ | |
1994 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1997 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1995 |
|
1998 | |||
1996 | def expand_aliases(self,fn,rest): |
|
1999 | def expand_aliases(self,fn,rest): | |
1997 | """ Expand multiple levels of aliases: |
|
2000 | """ Expand multiple levels of aliases: | |
1998 |
|
2001 | |||
1999 | if: |
|
2002 | if: | |
2000 |
|
2003 | |||
2001 | alias foo bar /tmp |
|
2004 | alias foo bar /tmp | |
2002 | alias baz foo |
|
2005 | alias baz foo | |
2003 |
|
2006 | |||
2004 | then: |
|
2007 | then: | |
2005 |
|
2008 | |||
2006 | baz huhhahhei -> bar /tmp huhhahhei |
|
2009 | baz huhhahhei -> bar /tmp huhhahhei | |
2007 |
|
2010 | |||
2008 | """ |
|
2011 | """ | |
2009 | line = fn + " " + rest |
|
2012 | line = fn + " " + rest | |
2010 |
|
2013 | |||
2011 | done = set() |
|
2014 | done = set() | |
2012 | while 1: |
|
2015 | while 1: | |
2013 | pre,fn,rest = prefilter.splitUserInput(line, |
|
2016 | pre,fn,rest = prefilter.splitUserInput(line, | |
2014 | prefilter.shell_line_split) |
|
2017 | prefilter.shell_line_split) | |
2015 | if fn in self.alias_table: |
|
2018 | if fn in self.alias_table: | |
2016 | if fn in done: |
|
2019 | if fn in done: | |
2017 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
2020 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
2018 | return "" |
|
2021 | return "" | |
2019 | done.add(fn) |
|
2022 | done.add(fn) | |
2020 |
|
2023 | |||
2021 | l2 = self.transform_alias(fn,rest) |
|
2024 | l2 = self.transform_alias(fn,rest) | |
2022 | # dir -> dir |
|
2025 | # dir -> dir | |
2023 | # print "alias",line, "->",l2 #dbg |
|
2026 | # print "alias",line, "->",l2 #dbg | |
2024 | if l2 == line: |
|
2027 | if l2 == line: | |
2025 | break |
|
2028 | break | |
2026 | # ls -> ls -F should not recurse forever |
|
2029 | # ls -> ls -F should not recurse forever | |
2027 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
2030 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
2028 | line = l2 |
|
2031 | line = l2 | |
2029 | break |
|
2032 | break | |
2030 |
|
2033 | |||
2031 | line=l2 |
|
2034 | line=l2 | |
2032 |
|
2035 | |||
2033 |
|
2036 | |||
2034 | # print "al expand to",line #dbg |
|
2037 | # print "al expand to",line #dbg | |
2035 | else: |
|
2038 | else: | |
2036 | break |
|
2039 | break | |
2037 |
|
2040 | |||
2038 | return line |
|
2041 | return line | |
2039 |
|
2042 | |||
2040 | def transform_alias(self, alias,rest=''): |
|
2043 | def transform_alias(self, alias,rest=''): | |
2041 | """ Transform alias to system command string. |
|
2044 | """ Transform alias to system command string. | |
2042 | """ |
|
2045 | """ | |
2043 | trg = self.alias_table[alias] |
|
2046 | trg = self.alias_table[alias] | |
2044 |
|
2047 | |||
2045 | nargs,cmd = trg |
|
2048 | nargs,cmd = trg | |
2046 | # print trg #dbg |
|
2049 | # print trg #dbg | |
2047 | if ' ' in cmd and os.path.isfile(cmd): |
|
2050 | if ' ' in cmd and os.path.isfile(cmd): | |
2048 | cmd = '"%s"' % cmd |
|
2051 | cmd = '"%s"' % cmd | |
2049 |
|
2052 | |||
2050 | # Expand the %l special to be the user's input line |
|
2053 | # Expand the %l special to be the user's input line | |
2051 | if cmd.find('%l') >= 0: |
|
2054 | if cmd.find('%l') >= 0: | |
2052 | cmd = cmd.replace('%l',rest) |
|
2055 | cmd = cmd.replace('%l',rest) | |
2053 | rest = '' |
|
2056 | rest = '' | |
2054 | if nargs==0: |
|
2057 | if nargs==0: | |
2055 | # Simple, argument-less aliases |
|
2058 | # Simple, argument-less aliases | |
2056 | cmd = '%s %s' % (cmd,rest) |
|
2059 | cmd = '%s %s' % (cmd,rest) | |
2057 | else: |
|
2060 | else: | |
2058 | # Handle aliases with positional arguments |
|
2061 | # Handle aliases with positional arguments | |
2059 | args = rest.split(None,nargs) |
|
2062 | args = rest.split(None,nargs) | |
2060 | if len(args)< nargs: |
|
2063 | if len(args)< nargs: | |
2061 | error('Alias <%s> requires %s arguments, %s given.' % |
|
2064 | error('Alias <%s> requires %s arguments, %s given.' % | |
2062 | (alias,nargs,len(args))) |
|
2065 | (alias,nargs,len(args))) | |
2063 | return None |
|
2066 | return None | |
2064 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
2067 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
2065 | # Now call the macro, evaluating in the user's namespace |
|
2068 | # Now call the macro, evaluating in the user's namespace | |
2066 | #print 'new command: <%r>' % cmd # dbg |
|
2069 | #print 'new command: <%r>' % cmd # dbg | |
2067 | return cmd |
|
2070 | return cmd | |
2068 |
|
2071 | |||
2069 | def call_alias(self,alias,rest=''): |
|
2072 | def call_alias(self,alias,rest=''): | |
2070 | """Call an alias given its name and the rest of the line. |
|
2073 | """Call an alias given its name and the rest of the line. | |
2071 |
|
2074 | |||
2072 | This is only used to provide backwards compatibility for users of |
|
2075 | This is only used to provide backwards compatibility for users of | |
2073 | ipalias(), use of which is not recommended for anymore.""" |
|
2076 | ipalias(), use of which is not recommended for anymore.""" | |
2074 |
|
2077 | |||
2075 | # Now call the macro, evaluating in the user's namespace |
|
2078 | # Now call the macro, evaluating in the user's namespace | |
2076 | cmd = self.transform_alias(alias, rest) |
|
2079 | cmd = self.transform_alias(alias, rest) | |
2077 | try: |
|
2080 | try: | |
2078 | self.system(cmd) |
|
2081 | self.system(cmd) | |
2079 | except: |
|
2082 | except: | |
2080 | self.showtraceback() |
|
2083 | self.showtraceback() | |
2081 |
|
2084 | |||
2082 | def indent_current_str(self): |
|
2085 | def indent_current_str(self): | |
2083 | """return the current level of indentation as a string""" |
|
2086 | """return the current level of indentation as a string""" | |
2084 | return self.indent_current_nsp * ' ' |
|
2087 | return self.indent_current_nsp * ' ' | |
2085 |
|
2088 | |||
2086 | def autoindent_update(self,line): |
|
2089 | def autoindent_update(self,line): | |
2087 | """Keep track of the indent level.""" |
|
2090 | """Keep track of the indent level.""" | |
2088 |
|
2091 | |||
2089 | #debugx('line') |
|
2092 | #debugx('line') | |
2090 | #debugx('self.indent_current_nsp') |
|
2093 | #debugx('self.indent_current_nsp') | |
2091 | if self.autoindent: |
|
2094 | if self.autoindent: | |
2092 | if line: |
|
2095 | if line: | |
2093 | inisp = num_ini_spaces(line) |
|
2096 | inisp = num_ini_spaces(line) | |
2094 | if inisp < self.indent_current_nsp: |
|
2097 | if inisp < self.indent_current_nsp: | |
2095 | self.indent_current_nsp = inisp |
|
2098 | self.indent_current_nsp = inisp | |
2096 |
|
2099 | |||
2097 | if line[-1] == ':': |
|
2100 | if line[-1] == ':': | |
2098 | self.indent_current_nsp += 4 |
|
2101 | self.indent_current_nsp += 4 | |
2099 | elif dedent_re.match(line): |
|
2102 | elif dedent_re.match(line): | |
2100 | self.indent_current_nsp -= 4 |
|
2103 | self.indent_current_nsp -= 4 | |
2101 | else: |
|
2104 | else: | |
2102 | self.indent_current_nsp = 0 |
|
2105 | self.indent_current_nsp = 0 | |
2103 |
|
2106 | |||
2104 | def runlines(self,lines): |
|
2107 | def runlines(self,lines): | |
2105 | """Run a string of one or more lines of source. |
|
2108 | """Run a string of one or more lines of source. | |
2106 |
|
2109 | |||
2107 | This method is capable of running a string containing multiple source |
|
2110 | This method is capable of running a string containing multiple source | |
2108 | lines, as if they had been entered at the IPython prompt. Since it |
|
2111 | lines, as if they had been entered at the IPython prompt. Since it | |
2109 | exposes IPython's processing machinery, the given strings can contain |
|
2112 | exposes IPython's processing machinery, the given strings can contain | |
2110 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
2113 | magic calls (%magic), special shell access (!cmd), etc.""" | |
2111 |
|
2114 | |||
2112 | # We must start with a clean buffer, in case this is run from an |
|
2115 | # We must start with a clean buffer, in case this is run from an | |
2113 | # interactive IPython session (via a magic, for example). |
|
2116 | # interactive IPython session (via a magic, for example). | |
2114 | self.resetbuffer() |
|
2117 | self.resetbuffer() | |
2115 | lines = lines.split('\n') |
|
2118 | lines = lines.split('\n') | |
2116 | more = 0 |
|
2119 | more = 0 | |
2117 |
|
2120 | |||
2118 | for line in lines: |
|
2121 | for line in lines: | |
2119 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2122 | # skip blank lines so we don't mess up the prompt counter, but do | |
2120 | # NOT skip even a blank line if we are in a code block (more is |
|
2123 | # NOT skip even a blank line if we are in a code block (more is | |
2121 | # true) |
|
2124 | # true) | |
2122 |
|
2125 | |||
2123 | if line or more: |
|
2126 | if line or more: | |
2124 | # push to raw history, so hist line numbers stay in sync |
|
2127 | # push to raw history, so hist line numbers stay in sync | |
2125 | self.input_hist_raw.append("# " + line + "\n") |
|
2128 | self.input_hist_raw.append("# " + line + "\n") | |
2126 | more = self.push(self.prefilter(line,more)) |
|
2129 | more = self.push(self.prefilter(line,more)) | |
2127 | # IPython's runsource returns None if there was an error |
|
2130 | # IPython's runsource returns None if there was an error | |
2128 | # compiling the code. This allows us to stop processing right |
|
2131 | # compiling the code. This allows us to stop processing right | |
2129 | # away, so the user gets the error message at the right place. |
|
2132 | # away, so the user gets the error message at the right place. | |
2130 | if more is None: |
|
2133 | if more is None: | |
2131 | break |
|
2134 | break | |
2132 | else: |
|
2135 | else: | |
2133 | self.input_hist_raw.append("\n") |
|
2136 | self.input_hist_raw.append("\n") | |
2134 | # final newline in case the input didn't have it, so that the code |
|
2137 | # final newline in case the input didn't have it, so that the code | |
2135 | # actually does get executed |
|
2138 | # actually does get executed | |
2136 | if more: |
|
2139 | if more: | |
2137 | self.push('\n') |
|
2140 | self.push('\n') | |
2138 |
|
2141 | |||
2139 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2142 | def runsource(self, source, filename='<input>', symbol='single'): | |
2140 | """Compile and run some source in the interpreter. |
|
2143 | """Compile and run some source in the interpreter. | |
2141 |
|
2144 | |||
2142 | Arguments are as for compile_command(). |
|
2145 | Arguments are as for compile_command(). | |
2143 |
|
2146 | |||
2144 | One several things can happen: |
|
2147 | One several things can happen: | |
2145 |
|
2148 | |||
2146 | 1) The input is incorrect; compile_command() raised an |
|
2149 | 1) The input is incorrect; compile_command() raised an | |
2147 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2150 | exception (SyntaxError or OverflowError). A syntax traceback | |
2148 | will be printed by calling the showsyntaxerror() method. |
|
2151 | will be printed by calling the showsyntaxerror() method. | |
2149 |
|
2152 | |||
2150 | 2) The input is incomplete, and more input is required; |
|
2153 | 2) The input is incomplete, and more input is required; | |
2151 | compile_command() returned None. Nothing happens. |
|
2154 | compile_command() returned None. Nothing happens. | |
2152 |
|
2155 | |||
2153 | 3) The input is complete; compile_command() returned a code |
|
2156 | 3) The input is complete; compile_command() returned a code | |
2154 | object. The code is executed by calling self.runcode() (which |
|
2157 | object. The code is executed by calling self.runcode() (which | |
2155 | also handles run-time exceptions, except for SystemExit). |
|
2158 | also handles run-time exceptions, except for SystemExit). | |
2156 |
|
2159 | |||
2157 | The return value is: |
|
2160 | The return value is: | |
2158 |
|
2161 | |||
2159 | - True in case 2 |
|
2162 | - True in case 2 | |
2160 |
|
2163 | |||
2161 | - False in the other cases, unless an exception is raised, where |
|
2164 | - False in the other cases, unless an exception is raised, where | |
2162 | None is returned instead. This can be used by external callers to |
|
2165 | None is returned instead. This can be used by external callers to | |
2163 | know whether to continue feeding input or not. |
|
2166 | know whether to continue feeding input or not. | |
2164 |
|
2167 | |||
2165 | The return value can be used to decide whether to use sys.ps1 or |
|
2168 | The return value can be used to decide whether to use sys.ps1 or | |
2166 | sys.ps2 to prompt the next line.""" |
|
2169 | sys.ps2 to prompt the next line.""" | |
2167 |
|
2170 | |||
2168 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2171 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2169 | # this allows execution of indented pasted code. It is tempting |
|
2172 | # this allows execution of indented pasted code. It is tempting | |
2170 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2173 | # to add '\n' at the end of source to run commands like ' a=1' | |
2171 | # directly, but this fails for more complicated scenarios |
|
2174 | # directly, but this fails for more complicated scenarios | |
2172 | source=source.encode(self.stdin_encoding) |
|
2175 | source=source.encode(self.stdin_encoding) | |
2173 | if source[:1] in [' ', '\t']: |
|
2176 | if source[:1] in [' ', '\t']: | |
2174 | source = 'if 1:\n%s' % source |
|
2177 | source = 'if 1:\n%s' % source | |
2175 |
|
2178 | |||
2176 | try: |
|
2179 | try: | |
2177 | code = self.compile(source,filename,symbol) |
|
2180 | code = self.compile(source,filename,symbol) | |
2178 | except (OverflowError, SyntaxError, ValueError, TypeError): |
|
2181 | except (OverflowError, SyntaxError, ValueError, TypeError): | |
2179 | # Case 1 |
|
2182 | # Case 1 | |
2180 | self.showsyntaxerror(filename) |
|
2183 | self.showsyntaxerror(filename) | |
2181 | return None |
|
2184 | return None | |
2182 |
|
2185 | |||
2183 | if code is None: |
|
2186 | if code is None: | |
2184 | # Case 2 |
|
2187 | # Case 2 | |
2185 | return True |
|
2188 | return True | |
2186 |
|
2189 | |||
2187 | # Case 3 |
|
2190 | # Case 3 | |
2188 | # We store the code object so that threaded shells and |
|
2191 | # We store the code object so that threaded shells and | |
2189 | # custom exception handlers can access all this info if needed. |
|
2192 | # custom exception handlers can access all this info if needed. | |
2190 | # The source corresponding to this can be obtained from the |
|
2193 | # The source corresponding to this can be obtained from the | |
2191 | # buffer attribute as '\n'.join(self.buffer). |
|
2194 | # buffer attribute as '\n'.join(self.buffer). | |
2192 | self.code_to_run = code |
|
2195 | self.code_to_run = code | |
2193 | # now actually execute the code object |
|
2196 | # now actually execute the code object | |
2194 | if self.runcode(code) == 0: |
|
2197 | if self.runcode(code) == 0: | |
2195 | return False |
|
2198 | return False | |
2196 | else: |
|
2199 | else: | |
2197 | return None |
|
2200 | return None | |
2198 |
|
2201 | |||
2199 | def runcode(self,code_obj): |
|
2202 | def runcode(self,code_obj): | |
2200 | """Execute a code object. |
|
2203 | """Execute a code object. | |
2201 |
|
2204 | |||
2202 | When an exception occurs, self.showtraceback() is called to display a |
|
2205 | When an exception occurs, self.showtraceback() is called to display a | |
2203 | traceback. |
|
2206 | traceback. | |
2204 |
|
2207 | |||
2205 | Return value: a flag indicating whether the code to be run completed |
|
2208 | Return value: a flag indicating whether the code to be run completed | |
2206 | successfully: |
|
2209 | successfully: | |
2207 |
|
2210 | |||
2208 | - 0: successful execution. |
|
2211 | - 0: successful execution. | |
2209 | - 1: an error occurred. |
|
2212 | - 1: an error occurred. | |
2210 | """ |
|
2213 | """ | |
2211 |
|
2214 | |||
2212 | # Set our own excepthook in case the user code tries to call it |
|
2215 | # Set our own excepthook in case the user code tries to call it | |
2213 | # directly, so that the IPython crash handler doesn't get triggered |
|
2216 | # directly, so that the IPython crash handler doesn't get triggered | |
2214 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2217 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2215 |
|
2218 | |||
2216 | # we save the original sys.excepthook in the instance, in case config |
|
2219 | # we save the original sys.excepthook in the instance, in case config | |
2217 | # code (such as magics) needs access to it. |
|
2220 | # code (such as magics) needs access to it. | |
2218 | self.sys_excepthook = old_excepthook |
|
2221 | self.sys_excepthook = old_excepthook | |
2219 | outflag = 1 # happens in more places, so it's easier as default |
|
2222 | outflag = 1 # happens in more places, so it's easier as default | |
2220 | try: |
|
2223 | try: | |
2221 | try: |
|
2224 | try: | |
2222 | self.hooks.pre_runcode_hook() |
|
2225 | self.hooks.pre_runcode_hook() | |
2223 | exec code_obj in self.user_global_ns, self.user_ns |
|
2226 | exec code_obj in self.user_global_ns, self.user_ns | |
2224 | finally: |
|
2227 | finally: | |
2225 | # Reset our crash handler in place |
|
2228 | # Reset our crash handler in place | |
2226 | sys.excepthook = old_excepthook |
|
2229 | sys.excepthook = old_excepthook | |
2227 | except SystemExit: |
|
2230 | except SystemExit: | |
2228 | self.resetbuffer() |
|
2231 | self.resetbuffer() | |
2229 | self.showtraceback() |
|
2232 | self.showtraceback() | |
2230 | warn("Type %exit or %quit to exit IPython " |
|
2233 | warn("Type %exit or %quit to exit IPython " | |
2231 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2234 | "(%Exit or %Quit do so unconditionally).",level=1) | |
2232 | except self.custom_exceptions: |
|
2235 | except self.custom_exceptions: | |
2233 | etype,value,tb = sys.exc_info() |
|
2236 | etype,value,tb = sys.exc_info() | |
2234 | self.CustomTB(etype,value,tb) |
|
2237 | self.CustomTB(etype,value,tb) | |
2235 | except: |
|
2238 | except: | |
2236 | self.showtraceback() |
|
2239 | self.showtraceback() | |
2237 | else: |
|
2240 | else: | |
2238 | outflag = 0 |
|
2241 | outflag = 0 | |
2239 | if softspace(sys.stdout, 0): |
|
2242 | if softspace(sys.stdout, 0): | |
2240 |
|
2243 | |||
2241 | # Flush out code object which has been run (and source) |
|
2244 | # Flush out code object which has been run (and source) | |
2242 | self.code_to_run = None |
|
2245 | self.code_to_run = None | |
2243 | return outflag |
|
2246 | return outflag | |
2244 |
|
2247 | |||
2245 | def push(self, line): |
|
2248 | def push(self, line): | |
2246 | """Push a line to the interpreter. |
|
2249 | """Push a line to the interpreter. | |
2247 |
|
2250 | |||
2248 | The line should not have a trailing newline; it may have |
|
2251 | The line should not have a trailing newline; it may have | |
2249 | internal newlines. The line is appended to a buffer and the |
|
2252 | internal newlines. The line is appended to a buffer and the | |
2250 | interpreter's runsource() method is called with the |
|
2253 | interpreter's runsource() method is called with the | |
2251 | concatenated contents of the buffer as source. If this |
|
2254 | concatenated contents of the buffer as source. If this | |
2252 | indicates that the command was executed or invalid, the buffer |
|
2255 | indicates that the command was executed or invalid, the buffer | |
2253 | is reset; otherwise, the command is incomplete, and the buffer |
|
2256 | is reset; otherwise, the command is incomplete, and the buffer | |
2254 | is left as it was after the line was appended. The return |
|
2257 | is left as it was after the line was appended. The return | |
2255 | value is 1 if more input is required, 0 if the line was dealt |
|
2258 | value is 1 if more input is required, 0 if the line was dealt | |
2256 | with in some way (this is the same as runsource()). |
|
2259 | with in some way (this is the same as runsource()). | |
2257 | """ |
|
2260 | """ | |
2258 |
|
2261 | |||
2259 | # autoindent management should be done here, and not in the |
|
2262 | # autoindent management should be done here, and not in the | |
2260 | # interactive loop, since that one is only seen by keyboard input. We |
|
2263 | # interactive loop, since that one is only seen by keyboard input. We | |
2261 | # need this done correctly even for code run via runlines (which uses |
|
2264 | # need this done correctly even for code run via runlines (which uses | |
2262 | # push). |
|
2265 | # push). | |
2263 |
|
2266 | |||
2264 | #print 'push line: <%s>' % line # dbg |
|
2267 | #print 'push line: <%s>' % line # dbg | |
2265 | for subline in line.splitlines(): |
|
2268 | for subline in line.splitlines(): | |
2266 | self.autoindent_update(subline) |
|
2269 | self.autoindent_update(subline) | |
2267 | self.buffer.append(line) |
|
2270 | self.buffer.append(line) | |
2268 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2271 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2269 | if not more: |
|
2272 | if not more: | |
2270 | self.resetbuffer() |
|
2273 | self.resetbuffer() | |
2271 | return more |
|
2274 | return more | |
2272 |
|
2275 | |||
2273 | def split_user_input(self, line): |
|
2276 | def split_user_input(self, line): | |
2274 | # This is really a hold-over to support ipapi and some extensions |
|
2277 | # This is really a hold-over to support ipapi and some extensions | |
2275 | return prefilter.splitUserInput(line) |
|
2278 | return prefilter.splitUserInput(line) | |
2276 |
|
2279 | |||
2277 | def resetbuffer(self): |
|
2280 | def resetbuffer(self): | |
2278 | """Reset the input buffer.""" |
|
2281 | """Reset the input buffer.""" | |
2279 | self.buffer[:] = [] |
|
2282 | self.buffer[:] = [] | |
2280 |
|
2283 | |||
2281 | def raw_input(self,prompt='',continue_prompt=False): |
|
2284 | def raw_input(self,prompt='',continue_prompt=False): | |
2282 | """Write a prompt and read a line. |
|
2285 | """Write a prompt and read a line. | |
2283 |
|
2286 | |||
2284 | The returned line does not include the trailing newline. |
|
2287 | The returned line does not include the trailing newline. | |
2285 | When the user enters the EOF key sequence, EOFError is raised. |
|
2288 | When the user enters the EOF key sequence, EOFError is raised. | |
2286 |
|
2289 | |||
2287 | Optional inputs: |
|
2290 | Optional inputs: | |
2288 |
|
2291 | |||
2289 | - prompt(''): a string to be printed to prompt the user. |
|
2292 | - prompt(''): a string to be printed to prompt the user. | |
2290 |
|
2293 | |||
2291 | - continue_prompt(False): whether this line is the first one or a |
|
2294 | - continue_prompt(False): whether this line is the first one or a | |
2292 | continuation in a sequence of inputs. |
|
2295 | continuation in a sequence of inputs. | |
2293 | """ |
|
2296 | """ | |
2294 |
|
2297 | |||
2295 | # Code run by the user may have modified the readline completer state. |
|
2298 | # Code run by the user may have modified the readline completer state. | |
2296 | # We must ensure that our completer is back in place. |
|
2299 | # We must ensure that our completer is back in place. | |
2297 | if self.has_readline: |
|
2300 | if self.has_readline: | |
2298 | self.set_completer() |
|
2301 | self.set_completer() | |
2299 |
|
2302 | |||
2300 | try: |
|
2303 | try: | |
2301 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2304 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2302 | except ValueError: |
|
2305 | except ValueError: | |
2303 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2306 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2304 | " or sys.stdout.close()!\nExiting IPython!") |
|
2307 | " or sys.stdout.close()!\nExiting IPython!") | |
2305 | self.ask_exit() |
|
2308 | self.ask_exit() | |
2306 | return "" |
|
2309 | return "" | |
2307 |
|
2310 | |||
2308 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2311 | # Try to be reasonably smart about not re-indenting pasted input more | |
2309 | # than necessary. We do this by trimming out the auto-indent initial |
|
2312 | # than necessary. We do this by trimming out the auto-indent initial | |
2310 | # spaces, if the user's actual input started itself with whitespace. |
|
2313 | # spaces, if the user's actual input started itself with whitespace. | |
2311 | #debugx('self.buffer[-1]') |
|
2314 | #debugx('self.buffer[-1]') | |
2312 |
|
2315 | |||
2313 | if self.autoindent: |
|
2316 | if self.autoindent: | |
2314 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2317 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2315 | line = line[self.indent_current_nsp:] |
|
2318 | line = line[self.indent_current_nsp:] | |
2316 | self.indent_current_nsp = 0 |
|
2319 | self.indent_current_nsp = 0 | |
2317 |
|
2320 | |||
2318 | # store the unfiltered input before the user has any chance to modify |
|
2321 | # store the unfiltered input before the user has any chance to modify | |
2319 | # it. |
|
2322 | # it. | |
2320 | if line.strip(): |
|
2323 | if line.strip(): | |
2321 | if continue_prompt: |
|
2324 | if continue_prompt: | |
2322 | self.input_hist_raw[-1] += '%s\n' % line |
|
2325 | self.input_hist_raw[-1] += '%s\n' % line | |
2323 | if self.has_readline: # and some config option is set? |
|
2326 | if self.has_readline: # and some config option is set? | |
2324 | try: |
|
2327 | try: | |
2325 | histlen = self.readline.get_current_history_length() |
|
2328 | histlen = self.readline.get_current_history_length() | |
2326 | if histlen > 1: |
|
2329 | if histlen > 1: | |
2327 | newhist = self.input_hist_raw[-1].rstrip() |
|
2330 | newhist = self.input_hist_raw[-1].rstrip() | |
2328 | self.readline.remove_history_item(histlen-1) |
|
2331 | self.readline.remove_history_item(histlen-1) | |
2329 | self.readline.replace_history_item(histlen-2, |
|
2332 | self.readline.replace_history_item(histlen-2, | |
2330 | newhist.encode(self.stdin_encoding)) |
|
2333 | newhist.encode(self.stdin_encoding)) | |
2331 | except AttributeError: |
|
2334 | except AttributeError: | |
2332 | pass # re{move,place}_history_item are new in 2.4. |
|
2335 | pass # re{move,place}_history_item are new in 2.4. | |
2333 | else: |
|
2336 | else: | |
2334 | self.input_hist_raw.append('%s\n' % line) |
|
2337 | self.input_hist_raw.append('%s\n' % line) | |
2335 | # only entries starting at first column go to shadow history |
|
2338 | # only entries starting at first column go to shadow history | |
2336 | if line.lstrip() == line: |
|
2339 | if line.lstrip() == line: | |
2337 | self.shadowhist.add(line.strip()) |
|
2340 | self.shadowhist.add(line.strip()) | |
2338 | elif not continue_prompt: |
|
2341 | elif not continue_prompt: | |
2339 | self.input_hist_raw.append('\n') |
|
2342 | self.input_hist_raw.append('\n') | |
2340 | try: |
|
2343 | try: | |
2341 | lineout = self.prefilter(line,continue_prompt) |
|
2344 | lineout = self.prefilter(line,continue_prompt) | |
2342 | except: |
|
2345 | except: | |
2343 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2346 | # blanket except, in case a user-defined prefilter crashes, so it | |
2344 | # can't take all of ipython with it. |
|
2347 | # can't take all of ipython with it. | |
2345 | self.showtraceback() |
|
2348 | self.showtraceback() | |
2346 | return '' |
|
2349 | return '' | |
2347 | else: |
|
2350 | else: | |
2348 | return lineout |
|
2351 | return lineout | |
2349 |
|
2352 | |||
2350 | def _prefilter(self, line, continue_prompt): |
|
2353 | def _prefilter(self, line, continue_prompt): | |
2351 | """Calls different preprocessors, depending on the form of line.""" |
|
2354 | """Calls different preprocessors, depending on the form of line.""" | |
2352 |
|
2355 | |||
2353 | # All handlers *must* return a value, even if it's blank (''). |
|
2356 | # All handlers *must* return a value, even if it's blank (''). | |
2354 |
|
2357 | |||
2355 | # Lines are NOT logged here. Handlers should process the line as |
|
2358 | # Lines are NOT logged here. Handlers should process the line as | |
2356 | # needed, update the cache AND log it (so that the input cache array |
|
2359 | # needed, update the cache AND log it (so that the input cache array | |
2357 | # stays synced). |
|
2360 | # stays synced). | |
2358 |
|
2361 | |||
2359 | #..................................................................... |
|
2362 | #..................................................................... | |
2360 | # Code begins |
|
2363 | # Code begins | |
2361 |
|
2364 | |||
2362 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2365 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
2363 |
|
2366 | |||
2364 | # save the line away in case we crash, so the post-mortem handler can |
|
2367 | # save the line away in case we crash, so the post-mortem handler can | |
2365 | # record it |
|
2368 | # record it | |
2366 | self._last_input_line = line |
|
2369 | self._last_input_line = line | |
2367 |
|
2370 | |||
2368 | #print '***line: <%s>' % line # dbg |
|
2371 | #print '***line: <%s>' % line # dbg | |
2369 |
|
2372 | |||
2370 | if not line: |
|
2373 | if not line: | |
2371 | # Return immediately on purely empty lines, so that if the user |
|
2374 | # Return immediately on purely empty lines, so that if the user | |
2372 | # previously typed some whitespace that started a continuation |
|
2375 | # previously typed some whitespace that started a continuation | |
2373 | # prompt, he can break out of that loop with just an empty line. |
|
2376 | # prompt, he can break out of that loop with just an empty line. | |
2374 | # This is how the default python prompt works. |
|
2377 | # This is how the default python prompt works. | |
2375 |
|
2378 | |||
2376 | # Only return if the accumulated input buffer was just whitespace! |
|
2379 | # Only return if the accumulated input buffer was just whitespace! | |
2377 | if ''.join(self.buffer).isspace(): |
|
2380 | if ''.join(self.buffer).isspace(): | |
2378 | self.buffer[:] = [] |
|
2381 | self.buffer[:] = [] | |
2379 | return '' |
|
2382 | return '' | |
2380 |
|
2383 | |||
2381 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2384 | line_info = prefilter.LineInfo(line, continue_prompt) | |
2382 |
|
2385 | |||
2383 | # the input history needs to track even empty lines |
|
2386 | # the input history needs to track even empty lines | |
2384 | stripped = line.strip() |
|
2387 | stripped = line.strip() | |
2385 |
|
2388 | |||
2386 | if not stripped: |
|
2389 | if not stripped: | |
2387 | if not continue_prompt: |
|
2390 | if not continue_prompt: | |
2388 | self.outputcache.prompt_count -= 1 |
|
2391 | self.outputcache.prompt_count -= 1 | |
2389 | return self.handle_normal(line_info) |
|
2392 | return self.handle_normal(line_info) | |
2390 |
|
2393 | |||
2391 | # print '***cont',continue_prompt # dbg |
|
2394 | # print '***cont',continue_prompt # dbg | |
2392 | # special handlers are only allowed for single line statements |
|
2395 | # special handlers are only allowed for single line statements | |
2393 | if continue_prompt and not self.rc.multi_line_specials: |
|
2396 | if continue_prompt and not self.rc.multi_line_specials: | |
2394 | return self.handle_normal(line_info) |
|
2397 | return self.handle_normal(line_info) | |
2395 |
|
2398 | |||
2396 |
|
2399 | |||
2397 | # See whether any pre-existing handler can take care of it |
|
2400 | # See whether any pre-existing handler can take care of it | |
2398 | rewritten = self.hooks.input_prefilter(stripped) |
|
2401 | rewritten = self.hooks.input_prefilter(stripped) | |
2399 | if rewritten != stripped: # ok, some prefilter did something |
|
2402 | if rewritten != stripped: # ok, some prefilter did something | |
2400 | rewritten = line_info.pre + rewritten # add indentation |
|
2403 | rewritten = line_info.pre + rewritten # add indentation | |
2401 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2404 | return self.handle_normal(prefilter.LineInfo(rewritten, | |
2402 | continue_prompt)) |
|
2405 | continue_prompt)) | |
2403 |
|
2406 | |||
2404 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2407 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2405 |
|
2408 | |||
2406 | return prefilter.prefilter(line_info, self) |
|
2409 | return prefilter.prefilter(line_info, self) | |
2407 |
|
2410 | |||
2408 |
|
2411 | |||
2409 | def _prefilter_dumb(self, line, continue_prompt): |
|
2412 | def _prefilter_dumb(self, line, continue_prompt): | |
2410 | """simple prefilter function, for debugging""" |
|
2413 | """simple prefilter function, for debugging""" | |
2411 | return self.handle_normal(line,continue_prompt) |
|
2414 | return self.handle_normal(line,continue_prompt) | |
2412 |
|
2415 | |||
2413 |
|
2416 | |||
2414 | def multiline_prefilter(self, line, continue_prompt): |
|
2417 | def multiline_prefilter(self, line, continue_prompt): | |
2415 | """ Run _prefilter for each line of input |
|
2418 | """ Run _prefilter for each line of input | |
2416 |
|
2419 | |||
2417 | Covers cases where there are multiple lines in the user entry, |
|
2420 | Covers cases where there are multiple lines in the user entry, | |
2418 | which is the case when the user goes back to a multiline history |
|
2421 | which is the case when the user goes back to a multiline history | |
2419 | entry and presses enter. |
|
2422 | entry and presses enter. | |
2420 |
|
2423 | |||
2421 | """ |
|
2424 | """ | |
2422 | out = [] |
|
2425 | out = [] | |
2423 | for l in line.rstrip('\n').split('\n'): |
|
2426 | for l in line.rstrip('\n').split('\n'): | |
2424 | out.append(self._prefilter(l, continue_prompt)) |
|
2427 | out.append(self._prefilter(l, continue_prompt)) | |
2425 | return '\n'.join(out) |
|
2428 | return '\n'.join(out) | |
2426 |
|
2429 | |||
2427 | # Set the default prefilter() function (this can be user-overridden) |
|
2430 | # Set the default prefilter() function (this can be user-overridden) | |
2428 | prefilter = multiline_prefilter |
|
2431 | prefilter = multiline_prefilter | |
2429 |
|
2432 | |||
2430 | def handle_normal(self,line_info): |
|
2433 | def handle_normal(self,line_info): | |
2431 | """Handle normal input lines. Use as a template for handlers.""" |
|
2434 | """Handle normal input lines. Use as a template for handlers.""" | |
2432 |
|
2435 | |||
2433 | # With autoindent on, we need some way to exit the input loop, and I |
|
2436 | # With autoindent on, we need some way to exit the input loop, and I | |
2434 | # don't want to force the user to have to backspace all the way to |
|
2437 | # don't want to force the user to have to backspace all the way to | |
2435 | # clear the line. The rule will be in this case, that either two |
|
2438 | # clear the line. The rule will be in this case, that either two | |
2436 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2439 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2437 | # of a size different to the indent level, will exit the input loop. |
|
2440 | # of a size different to the indent level, will exit the input loop. | |
2438 | line = line_info.line |
|
2441 | line = line_info.line | |
2439 | continue_prompt = line_info.continue_prompt |
|
2442 | continue_prompt = line_info.continue_prompt | |
2440 |
|
2443 | |||
2441 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2444 | if (continue_prompt and self.autoindent and line.isspace() and | |
2442 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2445 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2443 | (self.buffer[-1]).isspace() )): |
|
2446 | (self.buffer[-1]).isspace() )): | |
2444 | line = '' |
|
2447 | line = '' | |
2445 |
|
2448 | |||
2446 | self.log(line,line,continue_prompt) |
|
2449 | self.log(line,line,continue_prompt) | |
2447 | return line |
|
2450 | return line | |
2448 |
|
2451 | |||
2449 | def handle_alias(self,line_info): |
|
2452 | def handle_alias(self,line_info): | |
2450 | """Handle alias input lines. """ |
|
2453 | """Handle alias input lines. """ | |
2451 | tgt = self.alias_table[line_info.iFun] |
|
2454 | tgt = self.alias_table[line_info.iFun] | |
2452 | # print "=>",tgt #dbg |
|
2455 | # print "=>",tgt #dbg | |
2453 | if callable(tgt): |
|
2456 | if callable(tgt): | |
2454 | if '$' in line_info.line: |
|
2457 | if '$' in line_info.line: | |
2455 | call_meth = '(_ip, _ip.itpl(%s))' |
|
2458 | call_meth = '(_ip, _ip.itpl(%s))' | |
2456 | else: |
|
2459 | else: | |
2457 | call_meth = '(_ip,%s)' |
|
2460 | call_meth = '(_ip,%s)' | |
2458 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2461 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, | |
2459 | line_info.iFun, |
|
2462 | line_info.iFun, | |
2460 | make_quoted_expr(line_info.line)) |
|
2463 | make_quoted_expr(line_info.line)) | |
2461 | else: |
|
2464 | else: | |
2462 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2465 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) | |
2463 |
|
2466 | |||
2464 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2467 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2465 | # aliases won't work in indented sections. |
|
2468 | # aliases won't work in indented sections. | |
2466 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2469 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2467 | make_quoted_expr( transformed )) |
|
2470 | make_quoted_expr( transformed )) | |
2468 |
|
2471 | |||
2469 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2472 | self.log(line_info.line,line_out,line_info.continue_prompt) | |
2470 | #print 'line out:',line_out # dbg |
|
2473 | #print 'line out:',line_out # dbg | |
2471 | return line_out |
|
2474 | return line_out | |
2472 |
|
2475 | |||
2473 | def handle_shell_escape(self, line_info): |
|
2476 | def handle_shell_escape(self, line_info): | |
2474 | """Execute the line in a shell, empty return value""" |
|
2477 | """Execute the line in a shell, empty return value""" | |
2475 | #print 'line in :', `line` # dbg |
|
2478 | #print 'line in :', `line` # dbg | |
2476 | line = line_info.line |
|
2479 | line = line_info.line | |
2477 | if line.lstrip().startswith('!!'): |
|
2480 | if line.lstrip().startswith('!!'): | |
2478 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2481 | # rewrite LineInfo's line, iFun and theRest to properly hold the | |
2479 | # call to %sx and the actual command to be executed, so |
|
2482 | # call to %sx and the actual command to be executed, so | |
2480 | # handle_magic can work correctly. Note that this works even if |
|
2483 | # handle_magic can work correctly. Note that this works even if | |
2481 | # the line is indented, so it handles multi_line_specials |
|
2484 | # the line is indented, so it handles multi_line_specials | |
2482 | # properly. |
|
2485 | # properly. | |
2483 | new_rest = line.lstrip()[2:] |
|
2486 | new_rest = line.lstrip()[2:] | |
2484 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2487 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) | |
2485 | line_info.iFun = 'sx' |
|
2488 | line_info.iFun = 'sx' | |
2486 | line_info.theRest = new_rest |
|
2489 | line_info.theRest = new_rest | |
2487 | return self.handle_magic(line_info) |
|
2490 | return self.handle_magic(line_info) | |
2488 | else: |
|
2491 | else: | |
2489 | cmd = line.lstrip().lstrip('!') |
|
2492 | cmd = line.lstrip().lstrip('!') | |
2490 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2493 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2491 | make_quoted_expr(cmd)) |
|
2494 | make_quoted_expr(cmd)) | |
2492 | # update cache/log and return |
|
2495 | # update cache/log and return | |
2493 | self.log(line,line_out,line_info.continue_prompt) |
|
2496 | self.log(line,line_out,line_info.continue_prompt) | |
2494 | return line_out |
|
2497 | return line_out | |
2495 |
|
2498 | |||
2496 | def handle_magic(self, line_info): |
|
2499 | def handle_magic(self, line_info): | |
2497 | """Execute magic functions.""" |
|
2500 | """Execute magic functions.""" | |
2498 | iFun = line_info.iFun |
|
2501 | iFun = line_info.iFun | |
2499 | theRest = line_info.theRest |
|
2502 | theRest = line_info.theRest | |
2500 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2503 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, | |
2501 | make_quoted_expr(iFun + " " + theRest)) |
|
2504 | make_quoted_expr(iFun + " " + theRest)) | |
2502 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2505 | self.log(line_info.line,cmd,line_info.continue_prompt) | |
2503 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2506 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2504 | return cmd |
|
2507 | return cmd | |
2505 |
|
2508 | |||
2506 | def handle_auto(self, line_info): |
|
2509 | def handle_auto(self, line_info): | |
2507 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2510 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2508 |
|
2511 | |||
2509 | line = line_info.line |
|
2512 | line = line_info.line | |
2510 | iFun = line_info.iFun |
|
2513 | iFun = line_info.iFun | |
2511 | theRest = line_info.theRest |
|
2514 | theRest = line_info.theRest | |
2512 | pre = line_info.pre |
|
2515 | pre = line_info.pre | |
2513 | continue_prompt = line_info.continue_prompt |
|
2516 | continue_prompt = line_info.continue_prompt | |
2514 | obj = line_info.ofind(self)['obj'] |
|
2517 | obj = line_info.ofind(self)['obj'] | |
2515 |
|
2518 | |||
2516 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2519 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2517 |
|
2520 | |||
2518 | # This should only be active for single-line input! |
|
2521 | # This should only be active for single-line input! | |
2519 | if continue_prompt: |
|
2522 | if continue_prompt: | |
2520 | self.log(line,line,continue_prompt) |
|
2523 | self.log(line,line,continue_prompt) | |
2521 | return line |
|
2524 | return line | |
2522 |
|
2525 | |||
2523 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) |
|
2526 | force_auto = isinstance(obj, IPython.ipapi.IPyAutocall) | |
2524 | auto_rewrite = True |
|
2527 | auto_rewrite = True | |
2525 |
|
2528 | |||
2526 | if pre == self.ESC_QUOTE: |
|
2529 | if pre == self.ESC_QUOTE: | |
2527 | # Auto-quote splitting on whitespace |
|
2530 | # Auto-quote splitting on whitespace | |
2528 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2531 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2529 | elif pre == self.ESC_QUOTE2: |
|
2532 | elif pre == self.ESC_QUOTE2: | |
2530 | # Auto-quote whole string |
|
2533 | # Auto-quote whole string | |
2531 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2534 | newcmd = '%s("%s")' % (iFun,theRest) | |
2532 | elif pre == self.ESC_PAREN: |
|
2535 | elif pre == self.ESC_PAREN: | |
2533 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2536 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2534 | else: |
|
2537 | else: | |
2535 | # Auto-paren. |
|
2538 | # Auto-paren. | |
2536 | # We only apply it to argument-less calls if the autocall |
|
2539 | # We only apply it to argument-less calls if the autocall | |
2537 | # parameter is set to 2. We only need to check that autocall is < |
|
2540 | # parameter is set to 2. We only need to check that autocall is < | |
2538 | # 2, since this function isn't called unless it's at least 1. |
|
2541 | # 2, since this function isn't called unless it's at least 1. | |
2539 | if not theRest and (self.rc.autocall < 2) and not force_auto: |
|
2542 | if not theRest and (self.rc.autocall < 2) and not force_auto: | |
2540 | newcmd = '%s %s' % (iFun,theRest) |
|
2543 | newcmd = '%s %s' % (iFun,theRest) | |
2541 | auto_rewrite = False |
|
2544 | auto_rewrite = False | |
2542 | else: |
|
2545 | else: | |
2543 | if not force_auto and theRest.startswith('['): |
|
2546 | if not force_auto and theRest.startswith('['): | |
2544 | if hasattr(obj,'__getitem__'): |
|
2547 | if hasattr(obj,'__getitem__'): | |
2545 | # Don't autocall in this case: item access for an object |
|
2548 | # Don't autocall in this case: item access for an object | |
2546 | # which is BOTH callable and implements __getitem__. |
|
2549 | # which is BOTH callable and implements __getitem__. | |
2547 | newcmd = '%s %s' % (iFun,theRest) |
|
2550 | newcmd = '%s %s' % (iFun,theRest) | |
2548 | auto_rewrite = False |
|
2551 | auto_rewrite = False | |
2549 | else: |
|
2552 | else: | |
2550 | # if the object doesn't support [] access, go ahead and |
|
2553 | # if the object doesn't support [] access, go ahead and | |
2551 | # autocall |
|
2554 | # autocall | |
2552 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2555 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2553 | elif theRest.endswith(';'): |
|
2556 | elif theRest.endswith(';'): | |
2554 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2557 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2555 | else: |
|
2558 | else: | |
2556 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2559 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2557 |
|
2560 | |||
2558 | if auto_rewrite: |
|
2561 | if auto_rewrite: | |
2559 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2562 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd | |
2560 |
|
2563 | |||
2561 | try: |
|
2564 | try: | |
2562 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2565 | # plain ascii works better w/ pyreadline, on some machines, so | |
2563 | # we use it and only print uncolored rewrite if we have unicode |
|
2566 | # we use it and only print uncolored rewrite if we have unicode | |
2564 | rw = str(rw) |
|
2567 | rw = str(rw) | |
2565 | print >>Term.cout, rw |
|
2568 | print >>Term.cout, rw | |
2566 | except UnicodeEncodeError: |
|
2569 | except UnicodeEncodeError: | |
2567 | print "-------------->" + newcmd |
|
2570 | print "-------------->" + newcmd | |
2568 |
|
2571 | |||
2569 | # log what is now valid Python, not the actual user input (without the |
|
2572 | # log what is now valid Python, not the actual user input (without the | |
2570 | # final newline) |
|
2573 | # final newline) | |
2571 | self.log(line,newcmd,continue_prompt) |
|
2574 | self.log(line,newcmd,continue_prompt) | |
2572 | return newcmd |
|
2575 | return newcmd | |
2573 |
|
2576 | |||
2574 | def handle_help(self, line_info): |
|
2577 | def handle_help(self, line_info): | |
2575 | """Try to get some help for the object. |
|
2578 | """Try to get some help for the object. | |
2576 |
|
2579 | |||
2577 | obj? or ?obj -> basic information. |
|
2580 | obj? or ?obj -> basic information. | |
2578 | obj?? or ??obj -> more details. |
|
2581 | obj?? or ??obj -> more details. | |
2579 | """ |
|
2582 | """ | |
2580 |
|
2583 | |||
2581 | line = line_info.line |
|
2584 | line = line_info.line | |
2582 | # We need to make sure that we don't process lines which would be |
|
2585 | # We need to make sure that we don't process lines which would be | |
2583 | # otherwise valid python, such as "x=1 # what?" |
|
2586 | # otherwise valid python, such as "x=1 # what?" | |
2584 | try: |
|
2587 | try: | |
2585 | codeop.compile_command(line) |
|
2588 | codeop.compile_command(line) | |
2586 | except SyntaxError: |
|
2589 | except SyntaxError: | |
2587 | # We should only handle as help stuff which is NOT valid syntax |
|
2590 | # We should only handle as help stuff which is NOT valid syntax | |
2588 | if line[0]==self.ESC_HELP: |
|
2591 | if line[0]==self.ESC_HELP: | |
2589 | line = line[1:] |
|
2592 | line = line[1:] | |
2590 | elif line[-1]==self.ESC_HELP: |
|
2593 | elif line[-1]==self.ESC_HELP: | |
2591 | line = line[:-1] |
|
2594 | line = line[:-1] | |
2592 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2595 | self.log(line,'#?'+line,line_info.continue_prompt) | |
2593 | if line: |
|
2596 | if line: | |
2594 | #print 'line:<%r>' % line # dbg |
|
2597 | #print 'line:<%r>' % line # dbg | |
2595 | self.magic_pinfo(line) |
|
2598 | self.magic_pinfo(line) | |
2596 | else: |
|
2599 | else: | |
2597 | page(self.usage,screen_lines=self.rc.screen_length) |
|
2600 | page(self.usage,screen_lines=self.rc.screen_length) | |
2598 | return '' # Empty string is needed here! |
|
2601 | return '' # Empty string is needed here! | |
2599 | except: |
|
2602 | except: | |
2600 | # Pass any other exceptions through to the normal handler |
|
2603 | # Pass any other exceptions through to the normal handler | |
2601 | return self.handle_normal(line_info) |
|
2604 | return self.handle_normal(line_info) | |
2602 | else: |
|
2605 | else: | |
2603 | # If the code compiles ok, we should handle it normally |
|
2606 | # If the code compiles ok, we should handle it normally | |
2604 | return self.handle_normal(line_info) |
|
2607 | return self.handle_normal(line_info) | |
2605 |
|
2608 | |||
2606 | def getapi(self): |
|
2609 | def getapi(self): | |
2607 | """ Get an IPApi object for this shell instance |
|
2610 | """ Get an IPApi object for this shell instance | |
2608 |
|
2611 | |||
2609 | Getting an IPApi object is always preferable to accessing the shell |
|
2612 | Getting an IPApi object is always preferable to accessing the shell | |
2610 | directly, but this holds true especially for extensions. |
|
2613 | directly, but this holds true especially for extensions. | |
2611 |
|
2614 | |||
2612 | It should always be possible to implement an extension with IPApi |
|
2615 | It should always be possible to implement an extension with IPApi | |
2613 | alone. If not, contact maintainer to request an addition. |
|
2616 | alone. If not, contact maintainer to request an addition. | |
2614 |
|
2617 | |||
2615 | """ |
|
2618 | """ | |
2616 | return self.api |
|
2619 | return self.api | |
2617 |
|
2620 | |||
2618 | def handle_emacs(self, line_info): |
|
2621 | def handle_emacs(self, line_info): | |
2619 | """Handle input lines marked by python-mode.""" |
|
2622 | """Handle input lines marked by python-mode.""" | |
2620 |
|
2623 | |||
2621 | # Currently, nothing is done. Later more functionality can be added |
|
2624 | # Currently, nothing is done. Later more functionality can be added | |
2622 | # here if needed. |
|
2625 | # here if needed. | |
2623 |
|
2626 | |||
2624 | # The input cache shouldn't be updated |
|
2627 | # The input cache shouldn't be updated | |
2625 | return line_info.line |
|
2628 | return line_info.line | |
2626 |
|
2629 | |||
2627 |
|
2630 | |||
2628 | def mktempfile(self,data=None): |
|
2631 | def mktempfile(self,data=None): | |
2629 | """Make a new tempfile and return its filename. |
|
2632 | """Make a new tempfile and return its filename. | |
2630 |
|
2633 | |||
2631 | This makes a call to tempfile.mktemp, but it registers the created |
|
2634 | This makes a call to tempfile.mktemp, but it registers the created | |
2632 | filename internally so ipython cleans it up at exit time. |
|
2635 | filename internally so ipython cleans it up at exit time. | |
2633 |
|
2636 | |||
2634 | Optional inputs: |
|
2637 | Optional inputs: | |
2635 |
|
2638 | |||
2636 | - data(None): if data is given, it gets written out to the temp file |
|
2639 | - data(None): if data is given, it gets written out to the temp file | |
2637 | immediately, and the file is closed again.""" |
|
2640 | immediately, and the file is closed again.""" | |
2638 |
|
2641 | |||
2639 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2642 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2640 | self.tempfiles.append(filename) |
|
2643 | self.tempfiles.append(filename) | |
2641 |
|
2644 | |||
2642 | if data: |
|
2645 | if data: | |
2643 | tmp_file = open(filename,'w') |
|
2646 | tmp_file = open(filename,'w') | |
2644 | tmp_file.write(data) |
|
2647 | tmp_file.write(data) | |
2645 | tmp_file.close() |
|
2648 | tmp_file.close() | |
2646 | return filename |
|
2649 | return filename | |
2647 |
|
2650 | |||
2648 | def write(self,data): |
|
2651 | def write(self,data): | |
2649 | """Write a string to the default output""" |
|
2652 | """Write a string to the default output""" | |
2650 | Term.cout.write(data) |
|
2653 | Term.cout.write(data) | |
2651 |
|
2654 | |||
2652 | def write_err(self,data): |
|
2655 | def write_err(self,data): | |
2653 | """Write a string to the default error output""" |
|
2656 | """Write a string to the default error output""" | |
2654 | Term.cerr.write(data) |
|
2657 | Term.cerr.write(data) | |
2655 |
|
2658 | |||
2656 | def ask_exit(self): |
|
2659 | def ask_exit(self): | |
2657 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2660 | """ Call for exiting. Can be overiden and used as a callback. """ | |
2658 | self.exit_now = True |
|
2661 | self.exit_now = True | |
2659 |
|
2662 | |||
2660 | def exit(self): |
|
2663 | def exit(self): | |
2661 | """Handle interactive exit. |
|
2664 | """Handle interactive exit. | |
2662 |
|
2665 | |||
2663 | This method calls the ask_exit callback.""" |
|
2666 | This method calls the ask_exit callback.""" | |
2664 |
|
2667 | |||
2665 | if self.rc.confirm_exit: |
|
2668 | if self.rc.confirm_exit: | |
2666 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2669 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2667 | self.ask_exit() |
|
2670 | self.ask_exit() | |
2668 | else: |
|
2671 | else: | |
2669 | self.ask_exit() |
|
2672 | self.ask_exit() | |
2670 |
|
2673 | |||
2671 | def safe_execfile(self,fname,*where,**kw): |
|
2674 | def safe_execfile(self,fname,*where,**kw): | |
2672 | """A safe version of the builtin execfile(). |
|
2675 | """A safe version of the builtin execfile(). | |
2673 |
|
2676 | |||
2674 | This version will never throw an exception, and knows how to handle |
|
2677 | This version will never throw an exception, and knows how to handle | |
2675 | ipython logs as well. |
|
2678 | ipython logs as well. | |
2676 |
|
2679 | |||
2677 | :Parameters: |
|
2680 | :Parameters: | |
2678 | fname : string |
|
2681 | fname : string | |
2679 | Name of the file to be executed. |
|
2682 | Name of the file to be executed. | |
2680 |
|
2683 | |||
2681 | where : tuple |
|
2684 | where : tuple | |
2682 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2685 | One or two namespaces, passed to execfile() as (globals,locals). | |
2683 | If only one is given, it is passed as both. |
|
2686 | If only one is given, it is passed as both. | |
2684 |
|
2687 | |||
2685 | :Keywords: |
|
2688 | :Keywords: | |
2686 | islog : boolean (False) |
|
2689 | islog : boolean (False) | |
2687 |
|
2690 | |||
2688 | quiet : boolean (True) |
|
2691 | quiet : boolean (True) | |
2689 |
|
2692 | |||
2690 | exit_ignore : boolean (False) |
|
2693 | exit_ignore : boolean (False) | |
2691 | """ |
|
2694 | """ | |
2692 |
|
2695 | |||
2693 | def syspath_cleanup(): |
|
2696 | def syspath_cleanup(): | |
2694 | """Internal cleanup routine for sys.path.""" |
|
2697 | """Internal cleanup routine for sys.path.""" | |
2695 | if add_dname: |
|
2698 | if add_dname: | |
2696 | try: |
|
2699 | try: | |
2697 | sys.path.remove(dname) |
|
2700 | sys.path.remove(dname) | |
2698 | except ValueError: |
|
2701 | except ValueError: | |
2699 | # For some reason the user has already removed it, ignore. |
|
2702 | # For some reason the user has already removed it, ignore. | |
2700 | pass |
|
2703 | pass | |
2701 |
|
2704 | |||
2702 | fname = os.path.expanduser(fname) |
|
2705 | fname = os.path.expanduser(fname) | |
2703 |
|
2706 | |||
2704 | # Find things also in current directory. This is needed to mimic the |
|
2707 | # Find things also in current directory. This is needed to mimic the | |
2705 | # behavior of running a script from the system command line, where |
|
2708 | # behavior of running a script from the system command line, where | |
2706 | # Python inserts the script's directory into sys.path |
|
2709 | # Python inserts the script's directory into sys.path | |
2707 | dname = os.path.dirname(os.path.abspath(fname)) |
|
2710 | dname = os.path.dirname(os.path.abspath(fname)) | |
2708 | add_dname = False |
|
2711 | add_dname = False | |
2709 | if dname not in sys.path: |
|
2712 | if dname not in sys.path: | |
2710 | sys.path.insert(0,dname) |
|
2713 | sys.path.insert(0,dname) | |
2711 | add_dname = True |
|
2714 | add_dname = True | |
2712 |
|
2715 | |||
2713 | try: |
|
2716 | try: | |
2714 | xfile = open(fname) |
|
2717 | xfile = open(fname) | |
2715 | except: |
|
2718 | except: | |
2716 | print >> Term.cerr, \ |
|
2719 | print >> Term.cerr, \ | |
2717 | 'Could not open file <%s> for safe execution.' % fname |
|
2720 | 'Could not open file <%s> for safe execution.' % fname | |
2718 | syspath_cleanup() |
|
2721 | syspath_cleanup() | |
2719 | return None |
|
2722 | return None | |
2720 |
|
2723 | |||
2721 | kw.setdefault('islog',0) |
|
2724 | kw.setdefault('islog',0) | |
2722 | kw.setdefault('quiet',1) |
|
2725 | kw.setdefault('quiet',1) | |
2723 | kw.setdefault('exit_ignore',0) |
|
2726 | kw.setdefault('exit_ignore',0) | |
2724 |
|
2727 | |||
2725 | first = xfile.readline() |
|
2728 | first = xfile.readline() | |
2726 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
2729 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2727 | xfile.close() |
|
2730 | xfile.close() | |
2728 | # line by line execution |
|
2731 | # line by line execution | |
2729 | if first.startswith(loghead) or kw['islog']: |
|
2732 | if first.startswith(loghead) or kw['islog']: | |
2730 | print 'Loading log file <%s> one line at a time...' % fname |
|
2733 | print 'Loading log file <%s> one line at a time...' % fname | |
2731 | if kw['quiet']: |
|
2734 | if kw['quiet']: | |
2732 | stdout_save = sys.stdout |
|
2735 | stdout_save = sys.stdout | |
2733 | sys.stdout = StringIO.StringIO() |
|
2736 | sys.stdout = StringIO.StringIO() | |
2734 | try: |
|
2737 | try: | |
2735 | globs,locs = where[0:2] |
|
2738 | globs,locs = where[0:2] | |
2736 | except: |
|
2739 | except: | |
2737 | try: |
|
2740 | try: | |
2738 | globs = locs = where[0] |
|
2741 | globs = locs = where[0] | |
2739 | except: |
|
2742 | except: | |
2740 | globs = locs = globals() |
|
2743 | globs = locs = globals() | |
2741 | badblocks = [] |
|
2744 | badblocks = [] | |
2742 |
|
2745 | |||
2743 | # we also need to identify indented blocks of code when replaying |
|
2746 | # we also need to identify indented blocks of code when replaying | |
2744 | # logs and put them together before passing them to an exec |
|
2747 | # logs and put them together before passing them to an exec | |
2745 | # statement. This takes a bit of regexp and look-ahead work in the |
|
2748 | # statement. This takes a bit of regexp and look-ahead work in the | |
2746 | # file. It's easiest if we swallow the whole thing in memory |
|
2749 | # file. It's easiest if we swallow the whole thing in memory | |
2747 | # first, and manually walk through the lines list moving the |
|
2750 | # first, and manually walk through the lines list moving the | |
2748 | # counter ourselves. |
|
2751 | # counter ourselves. | |
2749 | indent_re = re.compile('\s+\S') |
|
2752 | indent_re = re.compile('\s+\S') | |
2750 | xfile = open(fname) |
|
2753 | xfile = open(fname) | |
2751 | filelines = xfile.readlines() |
|
2754 | filelines = xfile.readlines() | |
2752 | xfile.close() |
|
2755 | xfile.close() | |
2753 | nlines = len(filelines) |
|
2756 | nlines = len(filelines) | |
2754 | lnum = 0 |
|
2757 | lnum = 0 | |
2755 | while lnum < nlines: |
|
2758 | while lnum < nlines: | |
2756 | line = filelines[lnum] |
|
2759 | line = filelines[lnum] | |
2757 | lnum += 1 |
|
2760 | lnum += 1 | |
2758 | # don't re-insert logger status info into cache |
|
2761 | # don't re-insert logger status info into cache | |
2759 | if line.startswith('#log#'): |
|
2762 | if line.startswith('#log#'): | |
2760 | continue |
|
2763 | continue | |
2761 | else: |
|
2764 | else: | |
2762 | # build a block of code (maybe a single line) for execution |
|
2765 | # build a block of code (maybe a single line) for execution | |
2763 | block = line |
|
2766 | block = line | |
2764 | try: |
|
2767 | try: | |
2765 | next = filelines[lnum] # lnum has already incremented |
|
2768 | next = filelines[lnum] # lnum has already incremented | |
2766 | except: |
|
2769 | except: | |
2767 | next = None |
|
2770 | next = None | |
2768 | while next and indent_re.match(next): |
|
2771 | while next and indent_re.match(next): | |
2769 | block += next |
|
2772 | block += next | |
2770 | lnum += 1 |
|
2773 | lnum += 1 | |
2771 | try: |
|
2774 | try: | |
2772 | next = filelines[lnum] |
|
2775 | next = filelines[lnum] | |
2773 | except: |
|
2776 | except: | |
2774 | next = None |
|
2777 | next = None | |
2775 | # now execute the block of one or more lines |
|
2778 | # now execute the block of one or more lines | |
2776 | try: |
|
2779 | try: | |
2777 | exec block in globs,locs |
|
2780 | exec block in globs,locs | |
2778 | except SystemExit: |
|
2781 | except SystemExit: | |
2779 | pass |
|
2782 | pass | |
2780 | except: |
|
2783 | except: | |
2781 | badblocks.append(block.rstrip()) |
|
2784 | badblocks.append(block.rstrip()) | |
2782 | if kw['quiet']: # restore stdout |
|
2785 | if kw['quiet']: # restore stdout | |
2783 | sys.stdout.close() |
|
2786 | sys.stdout.close() | |
2784 | sys.stdout = stdout_save |
|
2787 | sys.stdout = stdout_save | |
2785 | print 'Finished replaying log file <%s>' % fname |
|
2788 | print 'Finished replaying log file <%s>' % fname | |
2786 | if badblocks: |
|
2789 | if badblocks: | |
2787 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2790 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2788 | '<%s> reported errors:' % fname) |
|
2791 | '<%s> reported errors:' % fname) | |
2789 |
|
2792 | |||
2790 | for badline in badblocks: |
|
2793 | for badline in badblocks: | |
2791 | print >> sys.stderr, badline |
|
2794 | print >> sys.stderr, badline | |
2792 | else: # regular file execution |
|
2795 | else: # regular file execution | |
2793 | try: |
|
2796 | try: | |
2794 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2797 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
2795 | # Work around a bug in Python for Windows. The bug was |
|
2798 | # Work around a bug in Python for Windows. The bug was | |
2796 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2799 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |
2797 | # SVN Python as of March/07. For details, see: |
|
2800 | # SVN Python as of March/07. For details, see: | |
2798 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2801 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |
2799 | try: |
|
2802 | try: | |
2800 | globs,locs = where[0:2] |
|
2803 | globs,locs = where[0:2] | |
2801 | except: |
|
2804 | except: | |
2802 | try: |
|
2805 | try: | |
2803 | globs = locs = where[0] |
|
2806 | globs = locs = where[0] | |
2804 | except: |
|
2807 | except: | |
2805 | globs = locs = globals() |
|
2808 | globs = locs = globals() | |
2806 | exec file(fname) in globs,locs |
|
2809 | exec file(fname) in globs,locs | |
2807 | else: |
|
2810 | else: | |
2808 | execfile(fname,*where) |
|
2811 | execfile(fname,*where) | |
2809 | except SyntaxError: |
|
2812 | except SyntaxError: | |
2810 | self.showsyntaxerror() |
|
2813 | self.showsyntaxerror() | |
2811 | warn('Failure executing file: <%s>' % fname) |
|
2814 | warn('Failure executing file: <%s>' % fname) | |
2812 | except SystemExit,status: |
|
2815 | except SystemExit,status: | |
2813 | # Code that correctly sets the exit status flag to success (0) |
|
2816 | # Code that correctly sets the exit status flag to success (0) | |
2814 | # shouldn't be bothered with a traceback. Note that a plain |
|
2817 | # shouldn't be bothered with a traceback. Note that a plain | |
2815 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2818 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |
2816 | # will still get a traceback. Note that the structure of the |
|
2819 | # will still get a traceback. Note that the structure of the | |
2817 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2820 | # SystemExit exception changed between Python 2.4 and 2.5, so | |
2818 | # the checks must be done in a version-dependent way. |
|
2821 | # the checks must be done in a version-dependent way. | |
2819 | show = False |
|
2822 | show = False | |
2820 |
|
2823 | |||
2821 | if sys.version_info[:2] > (2,5): |
|
2824 | if sys.version_info[:2] > (2,5): | |
2822 | if status.message!=0 and not kw['exit_ignore']: |
|
2825 | if status.message!=0 and not kw['exit_ignore']: | |
2823 | show = True |
|
2826 | show = True | |
2824 | else: |
|
2827 | else: | |
2825 | if status.code and not kw['exit_ignore']: |
|
2828 | if status.code and not kw['exit_ignore']: | |
2826 | show = True |
|
2829 | show = True | |
2827 | if show: |
|
2830 | if show: | |
2828 | self.showtraceback() |
|
2831 | self.showtraceback() | |
2829 | warn('Failure executing file: <%s>' % fname) |
|
2832 | warn('Failure executing file: <%s>' % fname) | |
2830 | except: |
|
2833 | except: | |
2831 | self.showtraceback() |
|
2834 | self.showtraceback() | |
2832 | warn('Failure executing file: <%s>' % fname) |
|
2835 | warn('Failure executing file: <%s>' % fname) | |
2833 |
|
2836 | |||
2834 | syspath_cleanup() |
|
2837 | syspath_cleanup() | |
2835 |
|
2838 | |||
2836 | #************************* end of file <iplib.py> ***************************** |
|
2839 | #************************* end of file <iplib.py> ***************************** |
@@ -1,133 +1,149 b'' | |||||
1 | """Tests for various magic functions. |
|
1 | """Tests for various magic functions. | |
2 |
|
2 | |||
3 | Needs to be run by nose (to make ipython session available). |
|
3 | Needs to be run by nose (to make ipython session available). | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | # Standard library imports |
|
6 | # Standard library imports | |
7 | import os |
|
7 | import os | |
8 | import sys |
|
8 | import sys | |
9 |
|
9 | |||
10 | # Third-party imports |
|
10 | # Third-party imports | |
11 | import nose.tools as nt |
|
11 | import nose.tools as nt | |
12 |
|
12 | |||
13 | # From our own code |
|
13 | # From our own code | |
14 | from IPython.testing import decorators as dec |
|
14 | from IPython.testing import decorators as dec | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Test functions begin |
|
17 | # Test functions begin | |
18 |
|
18 | |||
19 | def test_rehashx(): |
|
19 | def test_rehashx(): | |
20 | # clear up everything |
|
20 | # clear up everything | |
21 | _ip.IP.alias_table.clear() |
|
21 | _ip.IP.alias_table.clear() | |
22 | del _ip.db['syscmdlist'] |
|
22 | del _ip.db['syscmdlist'] | |
23 |
|
23 | |||
24 | _ip.magic('rehashx') |
|
24 | _ip.magic('rehashx') | |
25 | # Practically ALL ipython development systems will have more than 10 aliases |
|
25 | # Practically ALL ipython development systems will have more than 10 aliases | |
26 |
|
26 | |||
27 | assert len(_ip.IP.alias_table) > 10 |
|
27 | assert len(_ip.IP.alias_table) > 10 | |
28 | for key, val in _ip.IP.alias_table.items(): |
|
28 | for key, val in _ip.IP.alias_table.items(): | |
29 | # we must strip dots from alias names |
|
29 | # we must strip dots from alias names | |
30 | assert '.' not in key |
|
30 | assert '.' not in key | |
31 |
|
31 | |||
32 | # rehashx must fill up syscmdlist |
|
32 | # rehashx must fill up syscmdlist | |
33 | scoms = _ip.db['syscmdlist'] |
|
33 | scoms = _ip.db['syscmdlist'] | |
34 | assert len(scoms) > 10 |
|
34 | assert len(scoms) > 10 | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | def doctest_run_ns(): |
|
37 | def doctest_run_ns(): | |
38 | """Classes declared %run scripts must be instantiable afterwards. |
|
38 | """Classes declared %run scripts must be instantiable afterwards. | |
39 |
|
39 | |||
40 | In [11]: run tclass foo |
|
40 | In [11]: run tclass foo | |
41 |
|
41 | |||
42 | In [12]: isinstance(f(),foo) |
|
42 | In [12]: isinstance(f(),foo) | |
43 | Out[12]: True |
|
43 | Out[12]: True | |
44 | """ |
|
44 | """ | |
45 |
|
45 | |||
46 |
|
46 | |||
47 | def doctest_run_ns2(): |
|
47 | def doctest_run_ns2(): | |
48 | """Classes declared %run scripts must be instantiable afterwards. |
|
48 | """Classes declared %run scripts must be instantiable afterwards. | |
49 |
|
49 | |||
50 | In [4]: run tclass C-first_pass |
|
50 | In [4]: run tclass C-first_pass | |
51 |
|
51 | |||
52 | In [5]: run tclass C-second_pass |
|
52 | In [5]: run tclass C-second_pass | |
53 | tclass.py: deleting object: C-first_pass |
|
53 | tclass.py: deleting object: C-first_pass | |
54 | """ |
|
54 | """ | |
55 |
|
55 | |||
56 |
|
56 | |||
57 | def doctest_hist_f(): |
|
57 | def doctest_hist_f(): | |
58 | """Test %hist -f with temporary filename. |
|
58 | """Test %hist -f with temporary filename. | |
59 |
|
59 | |||
60 | In [9]: import tempfile |
|
60 | In [9]: import tempfile | |
61 |
|
61 | |||
62 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') |
|
62 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') | |
63 |
|
63 | |||
64 | In [11]: %history -n -f $tfile 3 |
|
64 | In [11]: %history -n -f $tfile 3 | |
65 | """ |
|
65 | """ | |
66 |
|
66 | |||
67 |
|
67 | |||
68 | def doctest_hist_r(): |
|
68 | def doctest_hist_r(): | |
69 | """Test %hist -r |
|
69 | """Test %hist -r | |
70 |
|
70 | |||
71 | XXX - This test is not recording the output correctly. Not sure why... |
|
71 | XXX - This test is not recording the output correctly. Not sure why... | |
72 |
|
72 | |||
73 | In [6]: x=1 |
|
73 | In [6]: x=1 | |
74 |
|
74 | |||
75 | In [7]: hist -n -r 2 |
|
75 | In [7]: hist -n -r 2 | |
76 | x=1 # random |
|
76 | x=1 # random | |
77 | hist -n -r 2 # random |
|
77 | hist -n -r 2 # random | |
78 | """ |
|
78 | """ | |
79 |
|
79 | |||
80 |
|
80 | |||
81 | def test_obj_del(): |
|
81 | def test_obj_del(): | |
82 | """Test that object's __del__ methods are called on exit.""" |
|
82 | """Test that object's __del__ methods are called on exit.""" | |
83 | test_dir = os.path.dirname(__file__) |
|
83 | test_dir = os.path.dirname(__file__) | |
84 | del_file = os.path.join(test_dir,'obj_del.py') |
|
84 | del_file = os.path.join(test_dir,'obj_del.py') | |
85 | out = _ip.IP.getoutput('ipython %s' % del_file) |
|
85 | out = _ip.IP.getoutput('ipython %s' % del_file) | |
86 | nt.assert_equals(out,'obj_del.py: object A deleted') |
|
86 | nt.assert_equals(out,'obj_del.py: object A deleted') | |
87 |
|
87 | |||
88 |
|
88 | |||
89 | def test_shist(): |
|
89 | def test_shist(): | |
90 | # Simple tests of ShadowHist class - test generator. |
|
90 | # Simple tests of ShadowHist class - test generator. | |
91 | import os, shutil, tempfile |
|
91 | import os, shutil, tempfile | |
92 |
|
92 | |||
93 | from IPython.Extensions import pickleshare |
|
93 | from IPython.Extensions import pickleshare | |
94 | from IPython.history import ShadowHist |
|
94 | from IPython.history import ShadowHist | |
95 |
|
95 | |||
96 | tfile = tempfile.mktemp('','tmp-ipython-') |
|
96 | tfile = tempfile.mktemp('','tmp-ipython-') | |
97 |
|
97 | |||
98 | db = pickleshare.PickleShareDB(tfile) |
|
98 | db = pickleshare.PickleShareDB(tfile) | |
99 | s = ShadowHist(db) |
|
99 | s = ShadowHist(db) | |
100 | s.add('hello') |
|
100 | s.add('hello') | |
101 | s.add('world') |
|
101 | s.add('world') | |
102 | s.add('hello') |
|
102 | s.add('hello') | |
103 | s.add('hello') |
|
103 | s.add('hello') | |
104 | s.add('karhu') |
|
104 | s.add('karhu') | |
105 |
|
105 | |||
106 | yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')] |
|
106 | yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')] | |
107 |
|
107 | |||
108 | yield nt.assert_equal,s.get(2),'world' |
|
108 | yield nt.assert_equal,s.get(2),'world' | |
109 |
|
109 | |||
110 | shutil.rmtree(tfile) |
|
110 | shutil.rmtree(tfile) | |
111 |
|
111 | |||
112 | @dec.skipif_not_numpy |
|
112 | @dec.skipif_not_numpy | |
113 | def test_numpy_clear_array_undec(): |
|
113 | def test_numpy_clear_array_undec(): | |
114 | _ip.ex('import numpy as np') |
|
114 | _ip.ex('import numpy as np') | |
115 | _ip.ex('a = np.empty(2)') |
|
115 | _ip.ex('a = np.empty(2)') | |
116 |
|
116 | |||
117 | yield nt.assert_true,'a' in _ip.user_ns |
|
117 | yield nt.assert_true,'a' in _ip.user_ns | |
118 | _ip.magic('clear array') |
|
118 | _ip.magic('clear array') | |
119 | yield nt.assert_false,'a' in _ip.user_ns |
|
119 | yield nt.assert_false,'a' in _ip.user_ns | |
120 |
|
120 | |||
121 |
|
121 | |||
122 | @dec.skip() |
|
122 | @dec.skip() | |
123 | def test_fail_dec(*a,**k): |
|
123 | def test_fail_dec(*a,**k): | |
124 | yield nt.assert_true, False |
|
124 | yield nt.assert_true, False | |
125 |
|
125 | |||
126 | @dec.skip('This one shouldn not run') |
|
126 | @dec.skip('This one shouldn not run') | |
127 | def test_fail_dec2(*a,**k): |
|
127 | def test_fail_dec2(*a,**k): | |
128 | yield nt.assert_true, False |
|
128 | yield nt.assert_true, False | |
129 |
|
129 | |||
130 | @dec.skipknownfailure |
|
130 | @dec.skipknownfailure | |
131 | def test_fail_dec3(*a,**k): |
|
131 | def test_fail_dec3(*a,**k): | |
132 | yield nt.assert_true, False |
|
132 | yield nt.assert_true, False | |
133 |
|
133 | |||
|
134 | ||||
|
135 | def doctest_refbug(): | |||
|
136 | """Very nasty problem with references held by multiple runs of a script. | |||
|
137 | See: https://bugs.launchpad.net/ipython/+bug/269966 | |||
|
138 | ||||
|
139 | In [2]: run refbug | |||
|
140 | ||||
|
141 | In [3]: call_f() | |||
|
142 | lowercased: hello | |||
|
143 | ||||
|
144 | In [4]: run refbug | |||
|
145 | ||||
|
146 | In [5]: call_f() | |||
|
147 | lowercased: hello | |||
|
148 | lowercased: hello | |||
|
149 | """ |
General Comments 0
You need to be logged in to leave comments.
Login now