Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,76 +1,76 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Release data for the IPython project. |
|
2 | """Release data for the IPython project. | |
3 |
|
3 | |||
4 |
$Id: Release.py 98 |
|
4 | $Id: Release.py 982 2005-12-30 23:57:07Z fperez $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> | |
8 | # |
|
8 | # | |
9 | # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray |
|
9 | # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray | |
10 | # <n8gray@caltech.edu> |
|
10 | # <n8gray@caltech.edu> | |
11 | # |
|
11 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #***************************************************************************** |
|
14 | #***************************************************************************** | |
15 |
|
15 | |||
16 | # Name of the package for release purposes. This is the name which labels |
|
16 | # Name of the package for release purposes. This is the name which labels | |
17 | # the tarballs and RPMs made by distutils, so it's best to lowercase it. |
|
17 | # the tarballs and RPMs made by distutils, so it's best to lowercase it. | |
18 | name = 'ipython' |
|
18 | name = 'ipython' | |
19 |
|
19 | |||
20 | # For versions with substrings (like 0.6.16.svn), use an extra . to separate |
|
20 | # For versions with substrings (like 0.6.16.svn), use an extra . to separate | |
21 | # the new substring. We have to avoid using either dashes or underscores, |
|
21 | # the new substring. We have to avoid using either dashes or underscores, | |
22 | # because bdist_rpm does not accept dashes (an RPM) convention, and |
|
22 | # because bdist_rpm does not accept dashes (an RPM) convention, and | |
23 | # bdist_deb does not accept underscores (a Debian convention). |
|
23 | # bdist_deb does not accept underscores (a Debian convention). | |
24 |
|
24 | |||
25 |
version = '0.7.0.rc |
|
25 | version = '0.7.0.rc3' | |
26 |
|
26 | |||
27 |
revision = '$Revision: 98 |
|
27 | revision = '$Revision: 982 $' | |
28 |
|
28 | |||
29 | description = "An enhanced interactive Python shell." |
|
29 | description = "An enhanced interactive Python shell." | |
30 |
|
30 | |||
31 | long_description = \ |
|
31 | long_description = \ | |
32 | """ |
|
32 | """ | |
33 | IPython provides a replacement for the interactive Python interpreter with |
|
33 | IPython provides a replacement for the interactive Python interpreter with | |
34 | extra functionality. |
|
34 | extra functionality. | |
35 |
|
35 | |||
36 | Main features: |
|
36 | Main features: | |
37 |
|
37 | |||
38 | * Comprehensive object introspection. |
|
38 | * Comprehensive object introspection. | |
39 |
|
39 | |||
40 | * Input history, persistent across sessions. |
|
40 | * Input history, persistent across sessions. | |
41 |
|
41 | |||
42 | * Caching of output results during a session with automatically generated |
|
42 | * Caching of output results during a session with automatically generated | |
43 | references. |
|
43 | references. | |
44 |
|
44 | |||
45 | * Readline based name completion. |
|
45 | * Readline based name completion. | |
46 |
|
46 | |||
47 | * Extensible system of 'magic' commands for controlling the environment and |
|
47 | * Extensible system of 'magic' commands for controlling the environment and | |
48 | performing many tasks related either to IPython or the operating system. |
|
48 | performing many tasks related either to IPython or the operating system. | |
49 |
|
49 | |||
50 | * Configuration system with easy switching between different setups (simpler |
|
50 | * Configuration system with easy switching between different setups (simpler | |
51 | than changing $PYTHONSTARTUP environment variables every time). |
|
51 | than changing $PYTHONSTARTUP environment variables every time). | |
52 |
|
52 | |||
53 | * Session logging and reloading. |
|
53 | * Session logging and reloading. | |
54 |
|
54 | |||
55 | * Extensible syntax processing for special purpose situations. |
|
55 | * Extensible syntax processing for special purpose situations. | |
56 |
|
56 | |||
57 | * Access to the system shell with user-extensible alias system. |
|
57 | * Access to the system shell with user-extensible alias system. | |
58 |
|
58 | |||
59 | * Easily embeddable in other Python programs. |
|
59 | * Easily embeddable in other Python programs. | |
60 |
|
60 | |||
61 | * Integrated access to the pdb debugger and the Python profiler. """ |
|
61 | * Integrated access to the pdb debugger and the Python profiler. """ | |
62 |
|
62 | |||
63 | license = 'BSD' |
|
63 | license = 'BSD' | |
64 |
|
64 | |||
65 | authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'), |
|
65 | authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'), | |
66 | 'Janko' : ('Janko Hauser','jhauser@zscout.de'), |
|
66 | 'Janko' : ('Janko Hauser','jhauser@zscout.de'), | |
67 | 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu') |
|
67 | 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu') | |
68 | } |
|
68 | } | |
69 |
|
69 | |||
70 | url = 'http://ipython.scipy.org' |
|
70 | url = 'http://ipython.scipy.org' | |
71 |
|
71 | |||
72 | download_url = 'http://ipython.scipy.org/dist' |
|
72 | download_url = 'http://ipython.scipy.org/dist' | |
73 |
|
73 | |||
74 | platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME'] |
|
74 | platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME'] | |
75 |
|
75 | |||
76 | keywords = ['Interactive','Interpreter','Shell'] |
|
76 | keywords = ['Interactive','Interpreter','Shell'] |
@@ -1,2056 +1,2060 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | Requires Python 2.1 or newer. |
|
5 | Requires Python 2.1 or newer. | |
6 |
|
6 | |||
7 | This file contains all the classes and helper functions specific to IPython. |
|
7 | This file contains all the classes and helper functions specific to IPython. | |
8 |
|
8 | |||
9 |
$Id: iplib.py 9 |
|
9 | $Id: iplib.py 982 2005-12-30 23:57:07Z fperez $ | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
14 | # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu> |
|
14 | # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu> | |
15 | # |
|
15 | # | |
16 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | # Distributed under the terms of the BSD License. The full license is in | |
17 | # the file COPYING, distributed as part of this software. |
|
17 | # the file COPYING, distributed as part of this software. | |
18 | # |
|
18 | # | |
19 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
19 | # Note: this code originally subclassed code.InteractiveConsole from the | |
20 | # Python standard library. Over time, all of that class has been copied |
|
20 | # Python standard library. Over time, all of that class has been copied | |
21 | # verbatim here for modifications which could not be accomplished by |
|
21 | # verbatim here for modifications which could not be accomplished by | |
22 | # subclassing. At this point, there are no dependencies at all on the code |
|
22 | # subclassing. At this point, there are no dependencies at all on the code | |
23 | # module anymore (it is not even imported). The Python License (sec. 2) |
|
23 | # module anymore (it is not even imported). The Python License (sec. 2) | |
24 | # allows for this, but it's always nice to acknowledge credit where credit is |
|
24 | # allows for this, but it's always nice to acknowledge credit where credit is | |
25 | # due. |
|
25 | # due. | |
26 | #***************************************************************************** |
|
26 | #***************************************************************************** | |
27 |
|
27 | |||
28 | #**************************************************************************** |
|
28 | #**************************************************************************** | |
29 | # Modules and globals |
|
29 | # Modules and globals | |
30 |
|
30 | |||
31 | from __future__ import generators # for 2.2 backwards-compatibility |
|
31 | from __future__ import generators # for 2.2 backwards-compatibility | |
32 |
|
32 | |||
33 | from IPython import Release |
|
33 | from IPython import Release | |
34 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
34 | __author__ = '%s <%s>\n%s <%s>' % \ | |
35 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
35 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
36 | __license__ = Release.license |
|
36 | __license__ = Release.license | |
37 | __version__ = Release.version |
|
37 | __version__ = Release.version | |
38 |
|
38 | |||
39 | # Python standard modules |
|
39 | # Python standard modules | |
40 | import __main__ |
|
40 | import __main__ | |
41 | import __builtin__ |
|
41 | import __builtin__ | |
42 | import StringIO |
|
42 | import StringIO | |
43 | import bdb |
|
43 | import bdb | |
44 | import cPickle as pickle |
|
44 | import cPickle as pickle | |
45 | import codeop |
|
45 | import codeop | |
46 | import exceptions |
|
46 | import exceptions | |
47 | import glob |
|
47 | import glob | |
48 | import inspect |
|
48 | import inspect | |
49 | import keyword |
|
49 | import keyword | |
50 | import new |
|
50 | import new | |
51 | import os |
|
51 | import os | |
52 | import pdb |
|
52 | import pdb | |
53 | import pydoc |
|
53 | import pydoc | |
54 | import re |
|
54 | import re | |
55 | import shutil |
|
55 | import shutil | |
56 | import string |
|
56 | import string | |
57 | import sys |
|
57 | import sys | |
58 | import traceback |
|
58 | import traceback | |
59 | import types |
|
59 | import types | |
60 |
|
60 | |||
61 | from pprint import pprint, pformat |
|
61 | from pprint import pprint, pformat | |
62 |
|
62 | |||
63 | # IPython's own modules |
|
63 | # IPython's own modules | |
64 | import IPython |
|
64 | import IPython | |
65 | from IPython import OInspect,PyColorize,ultraTB |
|
65 | from IPython import OInspect,PyColorize,ultraTB | |
66 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
66 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names | |
67 | from IPython.FakeModule import FakeModule |
|
67 | from IPython.FakeModule import FakeModule | |
68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
68 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
69 | from IPython.Logger import Logger |
|
69 | from IPython.Logger import Logger | |
70 | from IPython.Magic import Magic |
|
70 | from IPython.Magic import Magic | |
71 | from IPython.Prompts import CachedOutput |
|
71 | from IPython.Prompts import CachedOutput | |
72 | from IPython.Struct import Struct |
|
72 | from IPython.Struct import Struct | |
73 | from IPython.background_jobs import BackgroundJobManager |
|
73 | from IPython.background_jobs import BackgroundJobManager | |
74 | from IPython.usage import cmd_line_usage,interactive_usage |
|
74 | from IPython.usage import cmd_line_usage,interactive_usage | |
75 | from IPython.genutils import * |
|
75 | from IPython.genutils import * | |
76 |
|
76 | |||
77 | # store the builtin raw_input globally, and use this always, in case user code |
|
77 | # store the builtin raw_input globally, and use this always, in case user code | |
78 | # overwrites it (like wx.py.PyShell does) |
|
78 | # overwrites it (like wx.py.PyShell does) | |
79 | raw_input_original = raw_input |
|
79 | raw_input_original = raw_input | |
80 |
|
80 | |||
81 | # compiled regexps for autoindent management |
|
81 | # compiled regexps for autoindent management | |
82 | ini_spaces_re = re.compile(r'^(\s+)') |
|
82 | ini_spaces_re = re.compile(r'^(\s+)') | |
83 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
83 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
84 |
|
84 | |||
85 | #**************************************************************************** |
|
85 | #**************************************************************************** | |
86 | # Some utility function definitions |
|
86 | # Some utility function definitions | |
87 |
|
87 | |||
88 | def softspace(file, newvalue): |
|
88 | def softspace(file, newvalue): | |
89 | """Copied from code.py, to remove the dependency""" |
|
89 | """Copied from code.py, to remove the dependency""" | |
90 | oldvalue = 0 |
|
90 | oldvalue = 0 | |
91 | try: |
|
91 | try: | |
92 | oldvalue = file.softspace |
|
92 | oldvalue = file.softspace | |
93 | except AttributeError: |
|
93 | except AttributeError: | |
94 | pass |
|
94 | pass | |
95 | try: |
|
95 | try: | |
96 | file.softspace = newvalue |
|
96 | file.softspace = newvalue | |
97 | except (AttributeError, TypeError): |
|
97 | except (AttributeError, TypeError): | |
98 | # "attribute-less object" or "read-only attributes" |
|
98 | # "attribute-less object" or "read-only attributes" | |
99 | pass |
|
99 | pass | |
100 | return oldvalue |
|
100 | return oldvalue | |
101 |
|
101 | |||
102 | #**************************************************************************** |
|
102 | #**************************************************************************** | |
103 | # These special functions get installed in the builtin namespace, to provide |
|
103 | # These special functions get installed in the builtin namespace, to provide | |
104 | # programmatic (pure python) access to magics, aliases and system calls. This |
|
104 | # programmatic (pure python) access to magics, aliases and system calls. This | |
105 | # is important for logging, user scripting, and more. |
|
105 | # is important for logging, user scripting, and more. | |
106 |
|
106 | |||
107 | # We are basically exposing, via normal python functions, the three mechanisms |
|
107 | # We are basically exposing, via normal python functions, the three mechanisms | |
108 | # in which ipython offers special call modes (magics for internal control, |
|
108 | # in which ipython offers special call modes (magics for internal control, | |
109 | # aliases for direct system access via pre-selected names, and !cmd for |
|
109 | # aliases for direct system access via pre-selected names, and !cmd for | |
110 | # calling arbitrary system commands). |
|
110 | # calling arbitrary system commands). | |
111 |
|
111 | |||
112 | def ipmagic(arg_s): |
|
112 | def ipmagic(arg_s): | |
113 | """Call a magic function by name. |
|
113 | """Call a magic function by name. | |
114 |
|
114 | |||
115 | Input: a string containing the name of the magic function to call and any |
|
115 | Input: a string containing the name of the magic function to call and any | |
116 | additional arguments to be passed to the magic. |
|
116 | additional arguments to be passed to the magic. | |
117 |
|
117 | |||
118 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
118 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
119 | prompt: |
|
119 | prompt: | |
120 |
|
120 | |||
121 | In[1]: %name -opt foo bar |
|
121 | In[1]: %name -opt foo bar | |
122 |
|
122 | |||
123 | To call a magic without arguments, simply use ipmagic('name'). |
|
123 | To call a magic without arguments, simply use ipmagic('name'). | |
124 |
|
124 | |||
125 | This provides a proper Python function to call IPython's magics in any |
|
125 | This provides a proper Python function to call IPython's magics in any | |
126 | valid Python code you can type at the interpreter, including loops and |
|
126 | valid Python code you can type at the interpreter, including loops and | |
127 | compound statements. It is added by IPython to the Python builtin |
|
127 | compound statements. It is added by IPython to the Python builtin | |
128 | namespace upon initialization.""" |
|
128 | namespace upon initialization.""" | |
129 |
|
129 | |||
130 | args = arg_s.split(' ',1) |
|
130 | args = arg_s.split(' ',1) | |
131 | magic_name = args[0] |
|
131 | magic_name = args[0] | |
132 | if magic_name.startswith(__IPYTHON__.ESC_MAGIC): |
|
132 | if magic_name.startswith(__IPYTHON__.ESC_MAGIC): | |
133 | magic_name = magic_name[1:] |
|
133 | magic_name = magic_name[1:] | |
134 | try: |
|
134 | try: | |
135 | magic_args = args[1] |
|
135 | magic_args = args[1] | |
136 | except IndexError: |
|
136 | except IndexError: | |
137 | magic_args = '' |
|
137 | magic_args = '' | |
138 | fn = getattr(__IPYTHON__,'magic_'+magic_name,None) |
|
138 | fn = getattr(__IPYTHON__,'magic_'+magic_name,None) | |
139 | if fn is None: |
|
139 | if fn is None: | |
140 | error("Magic function `%s` not found." % magic_name) |
|
140 | error("Magic function `%s` not found." % magic_name) | |
141 | else: |
|
141 | else: | |
142 | magic_args = __IPYTHON__.var_expand(magic_args) |
|
142 | magic_args = __IPYTHON__.var_expand(magic_args) | |
143 | return fn(magic_args) |
|
143 | return fn(magic_args) | |
144 |
|
144 | |||
145 | def ipalias(arg_s): |
|
145 | def ipalias(arg_s): | |
146 | """Call an alias by name. |
|
146 | """Call an alias by name. | |
147 |
|
147 | |||
148 | Input: a string containing the name of the alias to call and any |
|
148 | Input: a string containing the name of the alias to call and any | |
149 | additional arguments to be passed to the magic. |
|
149 | additional arguments to be passed to the magic. | |
150 |
|
150 | |||
151 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
151 | ipalias('name -opt foo bar') is equivalent to typing at the ipython | |
152 | prompt: |
|
152 | prompt: | |
153 |
|
153 | |||
154 | In[1]: name -opt foo bar |
|
154 | In[1]: name -opt foo bar | |
155 |
|
155 | |||
156 | To call an alias without arguments, simply use ipalias('name'). |
|
156 | To call an alias without arguments, simply use ipalias('name'). | |
157 |
|
157 | |||
158 | This provides a proper Python function to call IPython's aliases in any |
|
158 | This provides a proper Python function to call IPython's aliases in any | |
159 | valid Python code you can type at the interpreter, including loops and |
|
159 | valid Python code you can type at the interpreter, including loops and | |
160 | compound statements. It is added by IPython to the Python builtin |
|
160 | compound statements. It is added by IPython to the Python builtin | |
161 | namespace upon initialization.""" |
|
161 | namespace upon initialization.""" | |
162 |
|
162 | |||
163 | args = arg_s.split(' ',1) |
|
163 | args = arg_s.split(' ',1) | |
164 | alias_name = args[0] |
|
164 | alias_name = args[0] | |
165 | try: |
|
165 | try: | |
166 | alias_args = args[1] |
|
166 | alias_args = args[1] | |
167 | except IndexError: |
|
167 | except IndexError: | |
168 | alias_args = '' |
|
168 | alias_args = '' | |
169 | if alias_name in __IPYTHON__.alias_table: |
|
169 | if alias_name in __IPYTHON__.alias_table: | |
170 | __IPYTHON__.call_alias(alias_name,alias_args) |
|
170 | __IPYTHON__.call_alias(alias_name,alias_args) | |
171 | else: |
|
171 | else: | |
172 | error("Alias `%s` not found." % alias_name) |
|
172 | error("Alias `%s` not found." % alias_name) | |
173 |
|
173 | |||
174 | def ipsystem(arg_s): |
|
174 | def ipsystem(arg_s): | |
175 | """Make a system call, using IPython.""" |
|
175 | """Make a system call, using IPython.""" | |
176 | __IPYTHON__.system(arg_s) |
|
176 | __IPYTHON__.system(arg_s) | |
177 |
|
177 | |||
178 |
|
178 | |||
179 | #**************************************************************************** |
|
179 | #**************************************************************************** | |
180 | # Local use exceptions |
|
180 | # Local use exceptions | |
181 | class SpaceInInput(exceptions.Exception): pass |
|
181 | class SpaceInInput(exceptions.Exception): pass | |
182 |
|
182 | |||
183 | #**************************************************************************** |
|
183 | #**************************************************************************** | |
184 | # Local use classes |
|
184 | # Local use classes | |
185 | class Bunch: pass |
|
185 | class Bunch: pass | |
186 |
|
186 | |||
187 | class InputList(list): |
|
187 | class InputList(list): | |
188 | """Class to store user input. |
|
188 | """Class to store user input. | |
189 |
|
189 | |||
190 | It's basically a list, but slices return a string instead of a list, thus |
|
190 | It's basically a list, but slices return a string instead of a list, thus | |
191 | allowing things like (assuming 'In' is an instance): |
|
191 | allowing things like (assuming 'In' is an instance): | |
192 |
|
192 | |||
193 | exec In[4:7] |
|
193 | exec In[4:7] | |
194 |
|
194 | |||
195 | or |
|
195 | or | |
196 |
|
196 | |||
197 | exec In[5:9] + In[14] + In[21:25]""" |
|
197 | exec In[5:9] + In[14] + In[21:25]""" | |
198 |
|
198 | |||
199 | def __getslice__(self,i,j): |
|
199 | def __getslice__(self,i,j): | |
200 | return ''.join(list.__getslice__(self,i,j)) |
|
200 | return ''.join(list.__getslice__(self,i,j)) | |
201 |
|
201 | |||
202 | class SyntaxTB(ultraTB.ListTB): |
|
202 | class SyntaxTB(ultraTB.ListTB): | |
203 | """Extension which holds some state: the last exception value""" |
|
203 | """Extension which holds some state: the last exception value""" | |
204 |
|
204 | |||
205 | def __init__(self,color_scheme = 'NoColor'): |
|
205 | def __init__(self,color_scheme = 'NoColor'): | |
206 | ultraTB.ListTB.__init__(self,color_scheme) |
|
206 | ultraTB.ListTB.__init__(self,color_scheme) | |
207 | self.last_syntax_error = None |
|
207 | self.last_syntax_error = None | |
208 |
|
208 | |||
209 | def __call__(self, etype, value, elist): |
|
209 | def __call__(self, etype, value, elist): | |
210 | self.last_syntax_error = value |
|
210 | self.last_syntax_error = value | |
211 | ultraTB.ListTB.__call__(self,etype,value,elist) |
|
211 | ultraTB.ListTB.__call__(self,etype,value,elist) | |
212 |
|
212 | |||
213 | def clear_err_state(self): |
|
213 | def clear_err_state(self): | |
214 | """Return the current error state and clear it""" |
|
214 | """Return the current error state and clear it""" | |
215 | e = self.last_syntax_error |
|
215 | e = self.last_syntax_error | |
216 | self.last_syntax_error = None |
|
216 | self.last_syntax_error = None | |
217 | return e |
|
217 | return e | |
218 |
|
218 | |||
219 | #**************************************************************************** |
|
219 | #**************************************************************************** | |
220 | # Main IPython class |
|
220 | # Main IPython class | |
221 |
|
221 | |||
222 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so |
|
222 | # FIXME: the Magic class is a mixin for now, and will unfortunately remain so | |
223 | # until a full rewrite is made. I've cleaned all cross-class uses of |
|
223 | # until a full rewrite is made. I've cleaned all cross-class uses of | |
224 | # attributes and methods, but too much user code out there relies on the |
|
224 | # attributes and methods, but too much user code out there relies on the | |
225 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. |
|
225 | # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage. | |
226 | # |
|
226 | # | |
227 | # But at least now, all the pieces have been separated and we could, in |
|
227 | # But at least now, all the pieces have been separated and we could, in | |
228 | # principle, stop using the mixin. This will ease the transition to the |
|
228 | # principle, stop using the mixin. This will ease the transition to the | |
229 | # chainsaw branch. |
|
229 | # chainsaw branch. | |
230 |
|
230 | |||
231 | # For reference, the following is the list of 'self.foo' uses in the Magic |
|
231 | # For reference, the following is the list of 'self.foo' uses in the Magic | |
232 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython |
|
232 | # class as of 2005-12-28. These are names we CAN'T use in the main ipython | |
233 | # class, to prevent clashes. |
|
233 | # class, to prevent clashes. | |
234 |
|
234 | |||
235 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', |
|
235 | # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind', | |
236 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', |
|
236 | # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic', | |
237 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', |
|
237 | # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell', | |
238 | # 'self.value'] |
|
238 | # 'self.value'] | |
239 |
|
239 | |||
240 | class InteractiveShell(Magic): |
|
240 | class InteractiveShell(Magic): | |
241 | """An enhanced console for Python.""" |
|
241 | """An enhanced console for Python.""" | |
242 |
|
242 | |||
243 | # class attribute to indicate whether the class supports threads or not. |
|
243 | # class attribute to indicate whether the class supports threads or not. | |
244 | # Subclasses with thread support should override this as needed. |
|
244 | # Subclasses with thread support should override this as needed. | |
245 | isthreaded = False |
|
245 | isthreaded = False | |
246 |
|
246 | |||
247 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
247 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
248 | user_ns = None,user_global_ns=None,banner2='', |
|
248 | user_ns = None,user_global_ns=None,banner2='', | |
249 | custom_exceptions=((),None),embedded=False): |
|
249 | custom_exceptions=((),None),embedded=False): | |
250 |
|
250 | |||
251 | # some minimal strict typechecks. For some core data structures, I |
|
251 | # some minimal strict typechecks. For some core data structures, I | |
252 | # want actual basic python types, not just anything that looks like |
|
252 | # want actual basic python types, not just anything that looks like | |
253 | # one. This is especially true for namespaces. |
|
253 | # one. This is especially true for namespaces. | |
254 | for ns in (user_ns,user_global_ns): |
|
254 | for ns in (user_ns,user_global_ns): | |
255 | if ns is not None and type(ns) != types.DictType: |
|
255 | if ns is not None and type(ns) != types.DictType: | |
256 | raise TypeError,'namespace must be a dictionary' |
|
256 | raise TypeError,'namespace must be a dictionary' | |
257 |
|
257 | |||
258 | # Put a reference to self in builtins so that any form of embedded or |
|
258 | # Put a reference to self in builtins so that any form of embedded or | |
259 | # imported code can test for being inside IPython. |
|
259 | # imported code can test for being inside IPython. | |
260 | __builtin__.__IPYTHON__ = self |
|
260 | __builtin__.__IPYTHON__ = self | |
261 |
|
261 | |||
262 | # And load into builtins ipmagic/ipalias/ipsystem as well |
|
262 | # And load into builtins ipmagic/ipalias/ipsystem as well | |
263 | __builtin__.ipmagic = ipmagic |
|
263 | __builtin__.ipmagic = ipmagic | |
264 | __builtin__.ipalias = ipalias |
|
264 | __builtin__.ipalias = ipalias | |
265 | __builtin__.ipsystem = ipsystem |
|
265 | __builtin__.ipsystem = ipsystem | |
266 |
|
266 | |||
267 | # Add to __builtin__ other parts of IPython's public API |
|
267 | # Add to __builtin__ other parts of IPython's public API | |
268 | __builtin__.ip_set_hook = self.set_hook |
|
268 | __builtin__.ip_set_hook = self.set_hook | |
269 |
|
269 | |||
270 | # Keep in the builtins a flag for when IPython is active. We set it |
|
270 | # Keep in the builtins a flag for when IPython is active. We set it | |
271 | # with setdefault so that multiple nested IPythons don't clobber one |
|
271 | # with setdefault so that multiple nested IPythons don't clobber one | |
272 | # another. Each will increase its value by one upon being activated, |
|
272 | # another. Each will increase its value by one upon being activated, | |
273 | # which also gives us a way to determine the nesting level. |
|
273 | # which also gives us a way to determine the nesting level. | |
274 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
274 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
275 |
|
275 | |||
276 | # Do the intuitively correct thing for quit/exit: we remove the |
|
276 | # Do the intuitively correct thing for quit/exit: we remove the | |
277 | # builtins if they exist, and our own prefilter routine will handle |
|
277 | # builtins if they exist, and our own prefilter routine will handle | |
278 | # these special cases |
|
278 | # these special cases | |
279 | try: |
|
279 | try: | |
280 | del __builtin__.exit, __builtin__.quit |
|
280 | del __builtin__.exit, __builtin__.quit | |
281 | except AttributeError: |
|
281 | except AttributeError: | |
282 | pass |
|
282 | pass | |
283 |
|
283 | |||
284 | # Store the actual shell's name |
|
284 | # Store the actual shell's name | |
285 | self.name = name |
|
285 | self.name = name | |
286 |
|
286 | |||
287 | # We need to know whether the instance is meant for embedding, since |
|
287 | # We need to know whether the instance is meant for embedding, since | |
288 | # global/local namespaces need to be handled differently in that case |
|
288 | # global/local namespaces need to be handled differently in that case | |
289 | self.embedded = embedded |
|
289 | self.embedded = embedded | |
290 |
|
290 | |||
291 | # command compiler |
|
291 | # command compiler | |
292 | self.compile = codeop.CommandCompiler() |
|
292 | self.compile = codeop.CommandCompiler() | |
293 |
|
293 | |||
294 | # User input buffer |
|
294 | # User input buffer | |
295 | self.buffer = [] |
|
295 | self.buffer = [] | |
296 |
|
296 | |||
297 | # Default name given in compilation of code |
|
297 | # Default name given in compilation of code | |
298 | self.filename = '<ipython console>' |
|
298 | self.filename = '<ipython console>' | |
299 |
|
299 | |||
300 | # Create the namespace where the user will operate. user_ns is |
|
300 | # Create the namespace where the user will operate. user_ns is | |
301 | # normally the only one used, and it is passed to the exec calls as |
|
301 | # normally the only one used, and it is passed to the exec calls as | |
302 | # the locals argument. But we do carry a user_global_ns namespace |
|
302 | # the locals argument. But we do carry a user_global_ns namespace | |
303 | # given as the exec 'globals' argument, This is useful in embedding |
|
303 | # given as the exec 'globals' argument, This is useful in embedding | |
304 | # situations where the ipython shell opens in a context where the |
|
304 | # situations where the ipython shell opens in a context where the | |
305 | # distinction between locals and globals is meaningful. |
|
305 | # distinction between locals and globals is meaningful. | |
306 |
|
306 | |||
307 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
307 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
308 | # level as a dict instead of a module. This is a manual fix, but I |
|
308 | # level as a dict instead of a module. This is a manual fix, but I | |
309 | # should really track down where the problem is coming from. Alex |
|
309 | # should really track down where the problem is coming from. Alex | |
310 | # Schmolck reported this problem first. |
|
310 | # Schmolck reported this problem first. | |
311 |
|
311 | |||
312 | # A useful post by Alex Martelli on this topic: |
|
312 | # A useful post by Alex Martelli on this topic: | |
313 | # Re: inconsistent value from __builtins__ |
|
313 | # Re: inconsistent value from __builtins__ | |
314 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
314 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
315 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
315 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
316 | # Gruppen: comp.lang.python |
|
316 | # Gruppen: comp.lang.python | |
317 |
|
317 | |||
318 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
318 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
319 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
319 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
320 | # > <type 'dict'> |
|
320 | # > <type 'dict'> | |
321 | # > >>> print type(__builtins__) |
|
321 | # > >>> print type(__builtins__) | |
322 | # > <type 'module'> |
|
322 | # > <type 'module'> | |
323 | # > Is this difference in return value intentional? |
|
323 | # > Is this difference in return value intentional? | |
324 |
|
324 | |||
325 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
325 | # Well, it's documented that '__builtins__' can be either a dictionary | |
326 | # or a module, and it's been that way for a long time. Whether it's |
|
326 | # or a module, and it's been that way for a long time. Whether it's | |
327 | # intentional (or sensible), I don't know. In any case, the idea is |
|
327 | # intentional (or sensible), I don't know. In any case, the idea is | |
328 | # that if you need to access the built-in namespace directly, you |
|
328 | # that if you need to access the built-in namespace directly, you | |
329 | # should start with "import __builtin__" (note, no 's') which will |
|
329 | # should start with "import __builtin__" (note, no 's') which will | |
330 | # definitely give you a module. Yeah, it's somewhatΒ confusing:-(. |
|
330 | # definitely give you a module. Yeah, it's somewhatΒ confusing:-(. | |
331 |
|
331 | |||
332 | if user_ns is None: |
|
332 | if user_ns is None: | |
333 | # Set __name__ to __main__ to better match the behavior of the |
|
333 | # Set __name__ to __main__ to better match the behavior of the | |
334 | # normal interpreter. |
|
334 | # normal interpreter. | |
335 | user_ns = {'__name__' :'__main__', |
|
335 | user_ns = {'__name__' :'__main__', | |
336 | '__builtins__' : __builtin__, |
|
336 | '__builtins__' : __builtin__, | |
337 | } |
|
337 | } | |
338 |
|
338 | |||
339 | if user_global_ns is None: |
|
339 | if user_global_ns is None: | |
340 | user_global_ns = {} |
|
340 | user_global_ns = {} | |
341 |
|
341 | |||
342 | # Assign namespaces |
|
342 | # Assign namespaces | |
343 | # This is the namespace where all normal user variables live |
|
343 | # This is the namespace where all normal user variables live | |
344 | self.user_ns = user_ns |
|
344 | self.user_ns = user_ns | |
345 | # Embedded instances require a separate namespace for globals. |
|
345 | # Embedded instances require a separate namespace for globals. | |
346 | # Normally this one is unused by non-embedded instances. |
|
346 | # Normally this one is unused by non-embedded instances. | |
347 | self.user_global_ns = user_global_ns |
|
347 | self.user_global_ns = user_global_ns | |
348 | # A namespace to keep track of internal data structures to prevent |
|
348 | # A namespace to keep track of internal data structures to prevent | |
349 | # them from cluttering user-visible stuff. Will be updated later |
|
349 | # them from cluttering user-visible stuff. Will be updated later | |
350 | self.internal_ns = {} |
|
350 | self.internal_ns = {} | |
351 |
|
351 | |||
352 | # Namespace of system aliases. Each entry in the alias |
|
352 | # Namespace of system aliases. Each entry in the alias | |
353 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
353 | # table must be a 2-tuple of the form (N,name), where N is the number | |
354 | # of positional arguments of the alias. |
|
354 | # of positional arguments of the alias. | |
355 | self.alias_table = {} |
|
355 | self.alias_table = {} | |
356 |
|
356 | |||
357 | # A table holding all the namespaces IPython deals with, so that |
|
357 | # A table holding all the namespaces IPython deals with, so that | |
358 | # introspection facilities can search easily. |
|
358 | # introspection facilities can search easily. | |
359 | self.ns_table = {'user':user_ns, |
|
359 | self.ns_table = {'user':user_ns, | |
360 | 'user_global':user_global_ns, |
|
360 | 'user_global':user_global_ns, | |
361 | 'alias':self.alias_table, |
|
361 | 'alias':self.alias_table, | |
362 | 'internal':self.internal_ns, |
|
362 | 'internal':self.internal_ns, | |
363 | 'builtin':__builtin__.__dict__ |
|
363 | 'builtin':__builtin__.__dict__ | |
364 | } |
|
364 | } | |
365 |
|
365 | |||
366 | # The user namespace MUST have a pointer to the shell itself. |
|
366 | # The user namespace MUST have a pointer to the shell itself. | |
367 | self.user_ns[name] = self |
|
367 | self.user_ns[name] = self | |
368 |
|
368 | |||
369 | # We need to insert into sys.modules something that looks like a |
|
369 | # We need to insert into sys.modules something that looks like a | |
370 | # module but which accesses the IPython namespace, for shelve and |
|
370 | # module but which accesses the IPython namespace, for shelve and | |
371 | # pickle to work interactively. Normally they rely on getting |
|
371 | # pickle to work interactively. Normally they rely on getting | |
372 | # everything out of __main__, but for embedding purposes each IPython |
|
372 | # everything out of __main__, but for embedding purposes each IPython | |
373 | # instance has its own private namespace, so we can't go shoving |
|
373 | # instance has its own private namespace, so we can't go shoving | |
374 | # everything into __main__. |
|
374 | # everything into __main__. | |
375 |
|
375 | |||
376 | # note, however, that we should only do this for non-embedded |
|
376 | # note, however, that we should only do this for non-embedded | |
377 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
377 | # ipythons, which really mimic the __main__.__dict__ with their own | |
378 | # namespace. Embedded instances, on the other hand, should not do |
|
378 | # namespace. Embedded instances, on the other hand, should not do | |
379 | # this because they need to manage the user local/global namespaces |
|
379 | # this because they need to manage the user local/global namespaces | |
380 | # only, but they live within a 'normal' __main__ (meaning, they |
|
380 | # only, but they live within a 'normal' __main__ (meaning, they | |
381 | # shouldn't overtake the execution environment of the script they're |
|
381 | # shouldn't overtake the execution environment of the script they're | |
382 | # embedded in). |
|
382 | # embedded in). | |
383 |
|
383 | |||
384 | if not embedded: |
|
384 | if not embedded: | |
385 | try: |
|
385 | try: | |
386 | main_name = self.user_ns['__name__'] |
|
386 | main_name = self.user_ns['__name__'] | |
387 | except KeyError: |
|
387 | except KeyError: | |
388 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' |
|
388 | raise KeyError,'user_ns dictionary MUST have a "__name__" key' | |
389 | else: |
|
389 | else: | |
390 | #print "pickle hack in place" # dbg |
|
390 | #print "pickle hack in place" # dbg | |
391 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
391 | sys.modules[main_name] = FakeModule(self.user_ns) | |
392 |
|
392 | |||
393 | # List of input with multi-line handling. |
|
393 | # List of input with multi-line handling. | |
394 | # Fill its zero entry, user counter starts at 1 |
|
394 | # Fill its zero entry, user counter starts at 1 | |
395 | self.input_hist = InputList(['\n']) |
|
395 | self.input_hist = InputList(['\n']) | |
396 |
|
396 | |||
397 | # list of visited directories |
|
397 | # list of visited directories | |
398 | try: |
|
398 | try: | |
399 | self.dir_hist = [os.getcwd()] |
|
399 | self.dir_hist = [os.getcwd()] | |
400 | except IOError, e: |
|
400 | except IOError, e: | |
401 | self.dir_hist = [] |
|
401 | self.dir_hist = [] | |
402 |
|
402 | |||
403 | # dict of output history |
|
403 | # dict of output history | |
404 | self.output_hist = {} |
|
404 | self.output_hist = {} | |
405 |
|
405 | |||
406 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
406 | # dict of things NOT to alias (keywords, builtins and some magics) | |
407 | no_alias = {} |
|
407 | no_alias = {} | |
408 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
408 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
409 | for key in keyword.kwlist + no_alias_magics: |
|
409 | for key in keyword.kwlist + no_alias_magics: | |
410 | no_alias[key] = 1 |
|
410 | no_alias[key] = 1 | |
411 | no_alias.update(__builtin__.__dict__) |
|
411 | no_alias.update(__builtin__.__dict__) | |
412 | self.no_alias = no_alias |
|
412 | self.no_alias = no_alias | |
413 |
|
413 | |||
414 | # make global variables for user access to these |
|
414 | # make global variables for user access to these | |
415 | self.user_ns['_ih'] = self.input_hist |
|
415 | self.user_ns['_ih'] = self.input_hist | |
416 | self.user_ns['_oh'] = self.output_hist |
|
416 | self.user_ns['_oh'] = self.output_hist | |
417 | self.user_ns['_dh'] = self.dir_hist |
|
417 | self.user_ns['_dh'] = self.dir_hist | |
418 |
|
418 | |||
419 | # user aliases to input and output histories |
|
419 | # user aliases to input and output histories | |
420 | self.user_ns['In'] = self.input_hist |
|
420 | self.user_ns['In'] = self.input_hist | |
421 | self.user_ns['Out'] = self.output_hist |
|
421 | self.user_ns['Out'] = self.output_hist | |
422 |
|
422 | |||
423 | # Object variable to store code object waiting execution. This is |
|
423 | # Object variable to store code object waiting execution. This is | |
424 | # used mainly by the multithreaded shells, but it can come in handy in |
|
424 | # used mainly by the multithreaded shells, but it can come in handy in | |
425 | # other situations. No need to use a Queue here, since it's a single |
|
425 | # other situations. No need to use a Queue here, since it's a single | |
426 | # item which gets cleared once run. |
|
426 | # item which gets cleared once run. | |
427 | self.code_to_run = None |
|
427 | self.code_to_run = None | |
428 |
|
428 | |||
429 | # Job manager (for jobs run as background threads) |
|
429 | # Job manager (for jobs run as background threads) | |
430 | self.jobs = BackgroundJobManager() |
|
430 | self.jobs = BackgroundJobManager() | |
431 | # Put the job manager into builtins so it's always there. |
|
431 | # Put the job manager into builtins so it's always there. | |
432 | __builtin__.jobs = self.jobs |
|
432 | __builtin__.jobs = self.jobs | |
433 |
|
433 | |||
434 | # escapes for automatic behavior on the command line |
|
434 | # escapes for automatic behavior on the command line | |
435 | self.ESC_SHELL = '!' |
|
435 | self.ESC_SHELL = '!' | |
436 | self.ESC_HELP = '?' |
|
436 | self.ESC_HELP = '?' | |
437 | self.ESC_MAGIC = '%' |
|
437 | self.ESC_MAGIC = '%' | |
438 | self.ESC_QUOTE = ',' |
|
438 | self.ESC_QUOTE = ',' | |
439 | self.ESC_QUOTE2 = ';' |
|
439 | self.ESC_QUOTE2 = ';' | |
440 | self.ESC_PAREN = '/' |
|
440 | self.ESC_PAREN = '/' | |
441 |
|
441 | |||
442 | # And their associated handlers |
|
442 | # And their associated handlers | |
443 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
443 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
444 | self.ESC_QUOTE : self.handle_auto, |
|
444 | self.ESC_QUOTE : self.handle_auto, | |
445 | self.ESC_QUOTE2 : self.handle_auto, |
|
445 | self.ESC_QUOTE2 : self.handle_auto, | |
446 | self.ESC_MAGIC : self.handle_magic, |
|
446 | self.ESC_MAGIC : self.handle_magic, | |
447 | self.ESC_HELP : self.handle_help, |
|
447 | self.ESC_HELP : self.handle_help, | |
448 | self.ESC_SHELL : self.handle_shell_escape, |
|
448 | self.ESC_SHELL : self.handle_shell_escape, | |
449 | } |
|
449 | } | |
450 |
|
450 | |||
451 | # class initializations |
|
451 | # class initializations | |
452 | Magic.__init__(self,self) |
|
452 | Magic.__init__(self,self) | |
453 |
|
453 | |||
454 | # Python source parser/formatter for syntax highlighting |
|
454 | # Python source parser/formatter for syntax highlighting | |
455 | pyformat = PyColorize.Parser().format |
|
455 | pyformat = PyColorize.Parser().format | |
456 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) |
|
456 | self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors']) | |
457 |
|
457 | |||
458 | # hooks holds pointers used for user-side customizations |
|
458 | # hooks holds pointers used for user-side customizations | |
459 | self.hooks = Struct() |
|
459 | self.hooks = Struct() | |
460 |
|
460 | |||
461 | # Set all default hooks, defined in the IPython.hooks module. |
|
461 | # Set all default hooks, defined in the IPython.hooks module. | |
462 | hooks = IPython.hooks |
|
462 | hooks = IPython.hooks | |
463 | for hook_name in hooks.__all__: |
|
463 | for hook_name in hooks.__all__: | |
464 | self.set_hook(hook_name,getattr(hooks,hook_name)) |
|
464 | self.set_hook(hook_name,getattr(hooks,hook_name)) | |
465 |
|
465 | |||
466 | # Flag to mark unconditional exit |
|
466 | # Flag to mark unconditional exit | |
467 | self.exit_now = False |
|
467 | self.exit_now = False | |
468 |
|
468 | |||
469 | self.usage_min = """\ |
|
469 | self.usage_min = """\ | |
470 | An enhanced console for Python. |
|
470 | An enhanced console for Python. | |
471 | Some of its features are: |
|
471 | Some of its features are: | |
472 | - Readline support if the readline library is present. |
|
472 | - Readline support if the readline library is present. | |
473 | - Tab completion in the local namespace. |
|
473 | - Tab completion in the local namespace. | |
474 | - Logging of input, see command-line options. |
|
474 | - Logging of input, see command-line options. | |
475 | - System shell escape via ! , eg !ls. |
|
475 | - System shell escape via ! , eg !ls. | |
476 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
476 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
477 | - Keeps track of locally defined variables via %who, %whos. |
|
477 | - Keeps track of locally defined variables via %who, %whos. | |
478 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
478 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
479 | """ |
|
479 | """ | |
480 | if usage: self.usage = usage |
|
480 | if usage: self.usage = usage | |
481 | else: self.usage = self.usage_min |
|
481 | else: self.usage = self.usage_min | |
482 |
|
482 | |||
483 | # Storage |
|
483 | # Storage | |
484 | self.rc = rc # This will hold all configuration information |
|
484 | self.rc = rc # This will hold all configuration information | |
485 | self.pager = 'less' |
|
485 | self.pager = 'less' | |
486 | # temporary files used for various purposes. Deleted at exit. |
|
486 | # temporary files used for various purposes. Deleted at exit. | |
487 | self.tempfiles = [] |
|
487 | self.tempfiles = [] | |
488 |
|
488 | |||
489 | # Keep track of readline usage (later set by init_readline) |
|
489 | # Keep track of readline usage (later set by init_readline) | |
490 | self.has_readline = False |
|
490 | self.has_readline = False | |
491 |
|
491 | |||
492 | # template for logfile headers. It gets resolved at runtime by the |
|
492 | # template for logfile headers. It gets resolved at runtime by the | |
493 | # logstart method. |
|
493 | # logstart method. | |
494 | self.loghead_tpl = \ |
|
494 | self.loghead_tpl = \ | |
495 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
495 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
496 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
496 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
497 | #log# opts = %s |
|
497 | #log# opts = %s | |
498 | #log# args = %s |
|
498 | #log# args = %s | |
499 | #log# It is safe to make manual edits below here. |
|
499 | #log# It is safe to make manual edits below here. | |
500 | #log#----------------------------------------------------------------------- |
|
500 | #log#----------------------------------------------------------------------- | |
501 | """ |
|
501 | """ | |
502 | # for pushd/popd management |
|
502 | # for pushd/popd management | |
503 | try: |
|
503 | try: | |
504 | self.home_dir = get_home_dir() |
|
504 | self.home_dir = get_home_dir() | |
505 | except HomeDirError,msg: |
|
505 | except HomeDirError,msg: | |
506 | fatal(msg) |
|
506 | fatal(msg) | |
507 |
|
507 | |||
508 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] |
|
508 | self.dir_stack = [os.getcwd().replace(self.home_dir,'~')] | |
509 |
|
509 | |||
510 | # Functions to call the underlying shell. |
|
510 | # Functions to call the underlying shell. | |
511 |
|
511 | |||
512 | # utility to expand user variables via Itpl |
|
512 | # utility to expand user variables via Itpl | |
513 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), |
|
513 | self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'), | |
514 | self.user_ns)) |
|
514 | self.user_ns)) | |
515 | # The first is similar to os.system, but it doesn't return a value, |
|
515 | # The first is similar to os.system, but it doesn't return a value, | |
516 | # and it allows interpolation of variables in the user's namespace. |
|
516 | # and it allows interpolation of variables in the user's namespace. | |
517 | self.system = lambda cmd: shell(self.var_expand(cmd), |
|
517 | self.system = lambda cmd: shell(self.var_expand(cmd), | |
518 | header='IPython system call: ', |
|
518 | header='IPython system call: ', | |
519 | verbose=self.rc.system_verbose) |
|
519 | verbose=self.rc.system_verbose) | |
520 | # These are for getoutput and getoutputerror: |
|
520 | # These are for getoutput and getoutputerror: | |
521 | self.getoutput = lambda cmd: \ |
|
521 | self.getoutput = lambda cmd: \ | |
522 | getoutput(self.var_expand(cmd), |
|
522 | getoutput(self.var_expand(cmd), | |
523 | header='IPython system call: ', |
|
523 | header='IPython system call: ', | |
524 | verbose=self.rc.system_verbose) |
|
524 | verbose=self.rc.system_verbose) | |
525 | self.getoutputerror = lambda cmd: \ |
|
525 | self.getoutputerror = lambda cmd: \ | |
526 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), |
|
526 | getoutputerror(str(ItplNS(cmd.replace('#','\#'), | |
527 | self.user_ns)), |
|
527 | self.user_ns)), | |
528 | header='IPython system call: ', |
|
528 | header='IPython system call: ', | |
529 | verbose=self.rc.system_verbose) |
|
529 | verbose=self.rc.system_verbose) | |
530 |
|
530 | |||
531 | # RegExp for splitting line contents into pre-char//first |
|
531 | # RegExp for splitting line contents into pre-char//first | |
532 | # word-method//rest. For clarity, each group in on one line. |
|
532 | # word-method//rest. For clarity, each group in on one line. | |
533 |
|
533 | |||
534 | # WARNING: update the regexp if the above escapes are changed, as they |
|
534 | # WARNING: update the regexp if the above escapes are changed, as they | |
535 | # are hardwired in. |
|
535 | # are hardwired in. | |
536 |
|
536 | |||
537 | # Don't get carried away with trying to make the autocalling catch too |
|
537 | # Don't get carried away with trying to make the autocalling catch too | |
538 | # much: it's better to be conservative rather than to trigger hidden |
|
538 | # much: it's better to be conservative rather than to trigger hidden | |
539 | # evals() somewhere and end up causing side effects. |
|
539 | # evals() somewhere and end up causing side effects. | |
540 |
|
540 | |||
541 | self.line_split = re.compile(r'^([\s*,;/])' |
|
541 | self.line_split = re.compile(r'^([\s*,;/])' | |
542 | r'([\?\w\.]+\w*\s*)' |
|
542 | r'([\?\w\.]+\w*\s*)' | |
543 | r'(\(?.*$)') |
|
543 | r'(\(?.*$)') | |
544 |
|
544 | |||
545 | # Original re, keep around for a while in case changes break something |
|
545 | # Original re, keep around for a while in case changes break something | |
546 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' |
|
546 | #self.line_split = re.compile(r'(^[\s*!\?%,/]?)' | |
547 | # r'(\s*[\?\w\.]+\w*\s*)' |
|
547 | # r'(\s*[\?\w\.]+\w*\s*)' | |
548 | # r'(\(?.*$)') |
|
548 | # r'(\(?.*$)') | |
549 |
|
549 | |||
550 | # RegExp to identify potential function names |
|
550 | # RegExp to identify potential function names | |
551 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
551 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
552 | # RegExp to exclude strings with this start from autocalling |
|
552 | # RegExp to exclude strings with this start from autocalling | |
553 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') |
|
553 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') | |
554 |
|
554 | |||
555 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
555 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
556 | # (experimental). For this to work, the line_split regexp would need |
|
556 | # (experimental). For this to work, the line_split regexp would need | |
557 | # to be modified so it wouldn't break things at '['. That line is |
|
557 | # to be modified so it wouldn't break things at '['. That line is | |
558 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
558 | # nasty enough that I shouldn't change it until I can test it _well_. | |
559 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
559 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
560 |
|
560 | |||
561 | # keep track of where we started running (mainly for crash post-mortem) |
|
561 | # keep track of where we started running (mainly for crash post-mortem) | |
562 | self.starting_dir = os.getcwd() |
|
562 | self.starting_dir = os.getcwd() | |
563 |
|
563 | |||
564 | # Various switches which can be set |
|
564 | # Various switches which can be set | |
565 | self.CACHELENGTH = 5000 # this is cheap, it's just text |
|
565 | self.CACHELENGTH = 5000 # this is cheap, it's just text | |
566 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ |
|
566 | self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__ | |
567 | self.banner2 = banner2 |
|
567 | self.banner2 = banner2 | |
568 |
|
568 | |||
569 | # TraceBack handlers: |
|
569 | # TraceBack handlers: | |
570 |
|
570 | |||
571 | # Syntax error handler. |
|
571 | # Syntax error handler. | |
572 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
572 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
573 |
|
573 | |||
574 | # The interactive one is initialized with an offset, meaning we always |
|
574 | # The interactive one is initialized with an offset, meaning we always | |
575 | # want to remove the topmost item in the traceback, which is our own |
|
575 | # want to remove the topmost item in the traceback, which is our own | |
576 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
576 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
577 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', |
|
577 | self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain', | |
578 | color_scheme='NoColor', |
|
578 | color_scheme='NoColor', | |
579 | tb_offset = 1) |
|
579 | tb_offset = 1) | |
580 |
|
580 | |||
581 | # IPython itself shouldn't crash. This will produce a detailed |
|
581 | # IPython itself shouldn't crash. This will produce a detailed | |
582 | # post-mortem if it does. But we only install the crash handler for |
|
582 | # post-mortem if it does. But we only install the crash handler for | |
583 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
583 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
584 | # and lose the crash handler. This is because exceptions in the main |
|
584 | # and lose the crash handler. This is because exceptions in the main | |
585 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
585 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
586 | # and there's no point in printing crash dumps for every user exception. |
|
586 | # and there's no point in printing crash dumps for every user exception. | |
587 | if self.isthreaded: |
|
587 | if self.isthreaded: | |
588 | sys.excepthook = ultraTB.FormattedTB() |
|
588 | sys.excepthook = ultraTB.FormattedTB() | |
589 | else: |
|
589 | else: | |
590 | from IPython import CrashHandler |
|
590 | from IPython import CrashHandler | |
591 | sys.excepthook = CrashHandler.CrashHandler(self) |
|
591 | sys.excepthook = CrashHandler.CrashHandler(self) | |
592 |
|
592 | |||
593 | # The instance will store a pointer to this, so that runtime code |
|
593 | # The instance will store a pointer to this, so that runtime code | |
594 | # (such as magics) can access it. This is because during the |
|
594 | # (such as magics) can access it. This is because during the | |
595 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
595 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
596 | # frameworks). |
|
596 | # frameworks). | |
597 | self.sys_excepthook = sys.excepthook |
|
597 | self.sys_excepthook = sys.excepthook | |
598 |
|
598 | |||
599 | # and add any custom exception handlers the user may have specified |
|
599 | # and add any custom exception handlers the user may have specified | |
600 | self.set_custom_exc(*custom_exceptions) |
|
600 | self.set_custom_exc(*custom_exceptions) | |
601 |
|
601 | |||
602 | # Object inspector |
|
602 | # Object inspector | |
603 | self.inspector = OInspect.Inspector(OInspect.InspectColors, |
|
603 | self.inspector = OInspect.Inspector(OInspect.InspectColors, | |
604 | PyColorize.ANSICodeColors, |
|
604 | PyColorize.ANSICodeColors, | |
605 | 'NoColor') |
|
605 | 'NoColor') | |
606 | # indentation management |
|
606 | # indentation management | |
607 | self.autoindent = False |
|
607 | self.autoindent = False | |
608 | self.indent_current_nsp = 0 |
|
608 | self.indent_current_nsp = 0 | |
609 | self.indent_current = '' # actual indent string |
|
609 | self.indent_current = '' # actual indent string | |
610 |
|
610 | |||
611 | # Make some aliases automatically |
|
611 | # Make some aliases automatically | |
612 | # Prepare list of shell aliases to auto-define |
|
612 | # Prepare list of shell aliases to auto-define | |
613 | if os.name == 'posix': |
|
613 | if os.name == 'posix': | |
614 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
614 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |
615 | 'mv mv -i','rm rm -i','cp cp -i', |
|
615 | 'mv mv -i','rm rm -i','cp cp -i', | |
616 | 'cat cat','less less','clear clear', |
|
616 | 'cat cat','less less','clear clear', | |
617 | # a better ls |
|
617 | # a better ls | |
618 | 'ls ls -F', |
|
618 | 'ls ls -F', | |
619 | # long ls |
|
619 | # long ls | |
620 | 'll ls -lF', |
|
620 | 'll ls -lF', | |
621 | # color ls |
|
621 | # color ls | |
622 | 'lc ls -F -o --color', |
|
622 | 'lc ls -F -o --color', | |
623 | # ls normal files only |
|
623 | # ls normal files only | |
624 | 'lf ls -F -o --color %l | grep ^-', |
|
624 | 'lf ls -F -o --color %l | grep ^-', | |
625 | # ls symbolic links |
|
625 | # ls symbolic links | |
626 | 'lk ls -F -o --color %l | grep ^l', |
|
626 | 'lk ls -F -o --color %l | grep ^l', | |
627 | # directories or links to directories, |
|
627 | # directories or links to directories, | |
628 | 'ldir ls -F -o --color %l | grep /$', |
|
628 | 'ldir ls -F -o --color %l | grep /$', | |
629 | # things which are executable |
|
629 | # things which are executable | |
630 | 'lx ls -F -o --color %l | grep ^-..x', |
|
630 | 'lx ls -F -o --color %l | grep ^-..x', | |
631 | ) |
|
631 | ) | |
632 | elif os.name in ['nt','dos']: |
|
632 | elif os.name in ['nt','dos']: | |
633 | auto_alias = ('dir dir /on', 'ls dir /on', |
|
633 | auto_alias = ('dir dir /on', 'ls dir /on', | |
634 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
634 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |
635 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
635 | 'mkdir mkdir','rmdir rmdir','echo echo', | |
636 | 'ren ren','cls cls','copy copy') |
|
636 | 'ren ren','cls cls','copy copy') | |
637 | else: |
|
637 | else: | |
638 | auto_alias = () |
|
638 | auto_alias = () | |
639 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) |
|
639 | self.auto_alias = map(lambda s:s.split(None,1),auto_alias) | |
640 | # Call the actual (public) initializer |
|
640 | # Call the actual (public) initializer | |
641 | self.init_auto_alias() |
|
641 | self.init_auto_alias() | |
642 | # end __init__ |
|
642 | # end __init__ | |
643 |
|
643 | |||
644 | def post_config_initialization(self): |
|
644 | def post_config_initialization(self): | |
645 | """Post configuration init method |
|
645 | """Post configuration init method | |
646 |
|
646 | |||
647 | This is called after the configuration files have been processed to |
|
647 | This is called after the configuration files have been processed to | |
648 | 'finalize' the initialization.""" |
|
648 | 'finalize' the initialization.""" | |
649 |
|
649 | |||
650 | rc = self.rc |
|
650 | rc = self.rc | |
651 |
|
651 | |||
652 | # Load readline proper |
|
652 | # Load readline proper | |
653 | if rc.readline: |
|
653 | if rc.readline: | |
654 | self.init_readline() |
|
654 | self.init_readline() | |
655 |
|
655 | |||
656 | # log system |
|
656 | # log system | |
657 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') |
|
657 | self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate') | |
658 | # local shortcut, this is used a LOT |
|
658 | # local shortcut, this is used a LOT | |
659 | self.log = self.logger.log |
|
659 | self.log = self.logger.log | |
660 |
|
660 | |||
661 | # Initialize cache, set in/out prompts and printing system |
|
661 | # Initialize cache, set in/out prompts and printing system | |
662 | self.outputcache = CachedOutput(self, |
|
662 | self.outputcache = CachedOutput(self, | |
663 | rc.cache_size, |
|
663 | rc.cache_size, | |
664 | rc.pprint, |
|
664 | rc.pprint, | |
665 | input_sep = rc.separate_in, |
|
665 | input_sep = rc.separate_in, | |
666 | output_sep = rc.separate_out, |
|
666 | output_sep = rc.separate_out, | |
667 | output_sep2 = rc.separate_out2, |
|
667 | output_sep2 = rc.separate_out2, | |
668 | ps1 = rc.prompt_in1, |
|
668 | ps1 = rc.prompt_in1, | |
669 | ps2 = rc.prompt_in2, |
|
669 | ps2 = rc.prompt_in2, | |
670 | ps_out = rc.prompt_out, |
|
670 | ps_out = rc.prompt_out, | |
671 | pad_left = rc.prompts_pad_left) |
|
671 | pad_left = rc.prompts_pad_left) | |
672 |
|
672 | |||
673 | # user may have over-ridden the default print hook: |
|
673 | # user may have over-ridden the default print hook: | |
674 | try: |
|
674 | try: | |
675 | self.outputcache.__class__.display = self.hooks.display |
|
675 | self.outputcache.__class__.display = self.hooks.display | |
676 | except AttributeError: |
|
676 | except AttributeError: | |
677 | pass |
|
677 | pass | |
678 |
|
678 | |||
679 | # I don't like assigning globally to sys, because it means when embedding |
|
679 | # I don't like assigning globally to sys, because it means when embedding | |
680 | # instances, each embedded instance overrides the previous choice. But |
|
680 | # instances, each embedded instance overrides the previous choice. But | |
681 | # sys.displayhook seems to be called internally by exec, so I don't see a |
|
681 | # sys.displayhook seems to be called internally by exec, so I don't see a | |
682 | # way around it. |
|
682 | # way around it. | |
683 | sys.displayhook = self.outputcache |
|
683 | sys.displayhook = self.outputcache | |
684 |
|
684 | |||
685 | # Set user colors (don't do it in the constructor above so that it |
|
685 | # Set user colors (don't do it in the constructor above so that it | |
686 | # doesn't crash if colors option is invalid) |
|
686 | # doesn't crash if colors option is invalid) | |
687 | self.magic_colors(rc.colors) |
|
687 | self.magic_colors(rc.colors) | |
688 |
|
688 | |||
689 | # Set calling of pdb on exceptions |
|
689 | # Set calling of pdb on exceptions | |
690 | self.call_pdb = rc.pdb |
|
690 | self.call_pdb = rc.pdb | |
691 |
|
691 | |||
692 | # Load user aliases |
|
692 | # Load user aliases | |
693 | for alias in rc.alias: |
|
693 | for alias in rc.alias: | |
694 | self.magic_alias(alias) |
|
694 | self.magic_alias(alias) | |
695 |
|
695 | |||
696 | # dynamic data that survives through sessions |
|
696 | # dynamic data that survives through sessions | |
697 | # XXX make the filename a config option? |
|
697 | # XXX make the filename a config option? | |
698 | persist_base = 'persist' |
|
698 | persist_base = 'persist' | |
699 | if rc.profile: |
|
699 | if rc.profile: | |
700 | persist_base += '_%s' % rc.profile |
|
700 | persist_base += '_%s' % rc.profile | |
701 | self.persist_fname = os.path.join(rc.ipythondir,persist_base) |
|
701 | self.persist_fname = os.path.join(rc.ipythondir,persist_base) | |
702 |
|
702 | |||
703 | try: |
|
703 | try: | |
704 | self.persist = pickle.load(file(self.persist_fname)) |
|
704 | self.persist = pickle.load(file(self.persist_fname)) | |
705 | except: |
|
705 | except: | |
706 | self.persist = {} |
|
706 | self.persist = {} | |
707 |
|
707 | |||
708 |
|
708 | |||
709 | for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]: |
|
709 | for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]: | |
710 | try: |
|
710 | try: | |
711 | obj = pickle.loads(value) |
|
711 | obj = pickle.loads(value) | |
712 | except: |
|
712 | except: | |
713 |
|
713 | |||
714 | print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key |
|
714 | print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key | |
715 | print "The error was:",sys.exc_info()[0] |
|
715 | print "The error was:",sys.exc_info()[0] | |
716 | continue |
|
716 | continue | |
717 |
|
717 | |||
718 |
|
718 | |||
719 | self.user_ns[key] = obj |
|
719 | self.user_ns[key] = obj | |
720 |
|
720 | |||
721 |
|
721 | |||
722 |
|
722 | |||
723 |
|
723 | |||
724 | def set_hook(self,name,hook): |
|
724 | def set_hook(self,name,hook): | |
725 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
725 | """set_hook(name,hook) -> sets an internal IPython hook. | |
726 |
|
726 | |||
727 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
727 | IPython exposes some of its internal API as user-modifiable hooks. By | |
728 | resetting one of these hooks, you can modify IPython's behavior to |
|
728 | resetting one of these hooks, you can modify IPython's behavior to | |
729 | call at runtime your own routines.""" |
|
729 | call at runtime your own routines.""" | |
730 |
|
730 | |||
731 | # At some point in the future, this should validate the hook before it |
|
731 | # At some point in the future, this should validate the hook before it | |
732 | # accepts it. Probably at least check that the hook takes the number |
|
732 | # accepts it. Probably at least check that the hook takes the number | |
733 | # of args it's supposed to. |
|
733 | # of args it's supposed to. | |
734 | setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) |
|
734 | setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__)) | |
735 |
|
735 | |||
736 | def set_custom_exc(self,exc_tuple,handler): |
|
736 | def set_custom_exc(self,exc_tuple,handler): | |
737 | """set_custom_exc(exc_tuple,handler) |
|
737 | """set_custom_exc(exc_tuple,handler) | |
738 |
|
738 | |||
739 | Set a custom exception handler, which will be called if any of the |
|
739 | Set a custom exception handler, which will be called if any of the | |
740 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
740 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
741 | runcode() method. |
|
741 | runcode() method. | |
742 |
|
742 | |||
743 | Inputs: |
|
743 | Inputs: | |
744 |
|
744 | |||
745 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
745 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
746 | handler for. It is very important that you use a tuple, and NOT A |
|
746 | handler for. It is very important that you use a tuple, and NOT A | |
747 | LIST here, because of the way Python's except statement works. If |
|
747 | LIST here, because of the way Python's except statement works. If | |
748 | you only want to trap a single exception, use a singleton tuple: |
|
748 | you only want to trap a single exception, use a singleton tuple: | |
749 |
|
749 | |||
750 | exc_tuple == (MyCustomException,) |
|
750 | exc_tuple == (MyCustomException,) | |
751 |
|
751 | |||
752 | - handler: this must be defined as a function with the following |
|
752 | - handler: this must be defined as a function with the following | |
753 | basic interface: def my_handler(self,etype,value,tb). |
|
753 | basic interface: def my_handler(self,etype,value,tb). | |
754 |
|
754 | |||
755 | This will be made into an instance method (via new.instancemethod) |
|
755 | This will be made into an instance method (via new.instancemethod) | |
756 | of IPython itself, and it will be called if any of the exceptions |
|
756 | of IPython itself, and it will be called if any of the exceptions | |
757 | listed in the exc_tuple are caught. If the handler is None, an |
|
757 | listed in the exc_tuple are caught. If the handler is None, an | |
758 | internal basic one is used, which just prints basic info. |
|
758 | internal basic one is used, which just prints basic info. | |
759 |
|
759 | |||
760 | WARNING: by putting in your own exception handler into IPython's main |
|
760 | WARNING: by putting in your own exception handler into IPython's main | |
761 | execution loop, you run a very good chance of nasty crashes. This |
|
761 | execution loop, you run a very good chance of nasty crashes. This | |
762 | facility should only be used if you really know what you are doing.""" |
|
762 | facility should only be used if you really know what you are doing.""" | |
763 |
|
763 | |||
764 | assert type(exc_tuple)==type(()) , \ |
|
764 | assert type(exc_tuple)==type(()) , \ | |
765 | "The custom exceptions must be given AS A TUPLE." |
|
765 | "The custom exceptions must be given AS A TUPLE." | |
766 |
|
766 | |||
767 | def dummy_handler(self,etype,value,tb): |
|
767 | def dummy_handler(self,etype,value,tb): | |
768 | print '*** Simple custom exception handler ***' |
|
768 | print '*** Simple custom exception handler ***' | |
769 | print 'Exception type :',etype |
|
769 | print 'Exception type :',etype | |
770 | print 'Exception value:',value |
|
770 | print 'Exception value:',value | |
771 | print 'Traceback :',tb |
|
771 | print 'Traceback :',tb | |
772 | print 'Source code :','\n'.join(self.buffer) |
|
772 | print 'Source code :','\n'.join(self.buffer) | |
773 |
|
773 | |||
774 | if handler is None: handler = dummy_handler |
|
774 | if handler is None: handler = dummy_handler | |
775 |
|
775 | |||
776 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
776 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
777 | self.custom_exceptions = exc_tuple |
|
777 | self.custom_exceptions = exc_tuple | |
778 |
|
778 | |||
779 | def set_custom_completer(self,completer,pos=0): |
|
779 | def set_custom_completer(self,completer,pos=0): | |
780 | """set_custom_completer(completer,pos=0) |
|
780 | """set_custom_completer(completer,pos=0) | |
781 |
|
781 | |||
782 | Adds a new custom completer function. |
|
782 | Adds a new custom completer function. | |
783 |
|
783 | |||
784 | The position argument (defaults to 0) is the index in the completers |
|
784 | The position argument (defaults to 0) is the index in the completers | |
785 | list where you want the completer to be inserted.""" |
|
785 | list where you want the completer to be inserted.""" | |
786 |
|
786 | |||
787 | newcomp = new.instancemethod(completer,self.Completer, |
|
787 | newcomp = new.instancemethod(completer,self.Completer, | |
788 | self.Completer.__class__) |
|
788 | self.Completer.__class__) | |
789 | self.Completer.matchers.insert(pos,newcomp) |
|
789 | self.Completer.matchers.insert(pos,newcomp) | |
790 |
|
790 | |||
791 | def _get_call_pdb(self): |
|
791 | def _get_call_pdb(self): | |
792 | return self._call_pdb |
|
792 | return self._call_pdb | |
793 |
|
793 | |||
794 | def _set_call_pdb(self,val): |
|
794 | def _set_call_pdb(self,val): | |
795 |
|
795 | |||
796 | if val not in (0,1,False,True): |
|
796 | if val not in (0,1,False,True): | |
797 | raise ValueError,'new call_pdb value must be boolean' |
|
797 | raise ValueError,'new call_pdb value must be boolean' | |
798 |
|
798 | |||
799 | # store value in instance |
|
799 | # store value in instance | |
800 | self._call_pdb = val |
|
800 | self._call_pdb = val | |
801 |
|
801 | |||
802 | # notify the actual exception handlers |
|
802 | # notify the actual exception handlers | |
803 | self.InteractiveTB.call_pdb = val |
|
803 | self.InteractiveTB.call_pdb = val | |
804 | if self.isthreaded: |
|
804 | if self.isthreaded: | |
805 | try: |
|
805 | try: | |
806 | self.sys_excepthook.call_pdb = val |
|
806 | self.sys_excepthook.call_pdb = val | |
807 | except: |
|
807 | except: | |
808 | warn('Failed to activate pdb for threaded exception handler') |
|
808 | warn('Failed to activate pdb for threaded exception handler') | |
809 |
|
809 | |||
810 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
810 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
811 | 'Control auto-activation of pdb at exceptions') |
|
811 | 'Control auto-activation of pdb at exceptions') | |
812 |
|
812 | |||
813 | def complete(self,text): |
|
813 | def complete(self,text): | |
814 | """Return a sorted list of all possible completions on text. |
|
814 | """Return a sorted list of all possible completions on text. | |
815 |
|
815 | |||
816 | Inputs: |
|
816 | Inputs: | |
817 |
|
817 | |||
818 | - text: a string of text to be completed on. |
|
818 | - text: a string of text to be completed on. | |
819 |
|
819 | |||
820 | This is a wrapper around the completion mechanism, similar to what |
|
820 | This is a wrapper around the completion mechanism, similar to what | |
821 | readline does at the command line when the TAB key is hit. By |
|
821 | readline does at the command line when the TAB key is hit. By | |
822 | exposing it as a method, it can be used by other non-readline |
|
822 | exposing it as a method, it can be used by other non-readline | |
823 | environments (such as GUIs) for text completion. |
|
823 | environments (such as GUIs) for text completion. | |
824 |
|
824 | |||
825 | Simple usage example: |
|
825 | Simple usage example: | |
826 |
|
826 | |||
827 | In [1]: x = 'hello' |
|
827 | In [1]: x = 'hello' | |
828 |
|
828 | |||
829 | In [2]: __IP.complete('x.l') |
|
829 | In [2]: __IP.complete('x.l') | |
830 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" |
|
830 | Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']""" | |
831 |
|
831 | |||
832 | complete = self.Completer.complete |
|
832 | complete = self.Completer.complete | |
833 | state = 0 |
|
833 | state = 0 | |
834 | # use a dict so we get unique keys, since ipyhton's multiple |
|
834 | # use a dict so we get unique keys, since ipyhton's multiple | |
835 | # completers can return duplicates. |
|
835 | # completers can return duplicates. | |
836 | comps = {} |
|
836 | comps = {} | |
837 | while True: |
|
837 | while True: | |
838 | newcomp = complete(text,state) |
|
838 | newcomp = complete(text,state) | |
839 | if newcomp is None: |
|
839 | if newcomp is None: | |
840 | break |
|
840 | break | |
841 | comps[newcomp] = 1 |
|
841 | comps[newcomp] = 1 | |
842 | state += 1 |
|
842 | state += 1 | |
843 | outcomps = comps.keys() |
|
843 | outcomps = comps.keys() | |
844 | outcomps.sort() |
|
844 | outcomps.sort() | |
845 | return outcomps |
|
845 | return outcomps | |
846 |
|
846 | |||
847 | def set_completer_frame(self, frame): |
|
847 | def set_completer_frame(self, frame): | |
848 | if frame: |
|
848 | if frame: | |
849 | self.Completer.namespace = frame.f_locals |
|
849 | self.Completer.namespace = frame.f_locals | |
850 | self.Completer.global_namespace = frame.f_globals |
|
850 | self.Completer.global_namespace = frame.f_globals | |
851 | else: |
|
851 | else: | |
852 | self.Completer.namespace = self.user_ns |
|
852 | self.Completer.namespace = self.user_ns | |
853 | self.Completer.global_namespace = self.user_global_ns |
|
853 | self.Completer.global_namespace = self.user_global_ns | |
854 |
|
854 | |||
855 | def init_auto_alias(self): |
|
855 | def init_auto_alias(self): | |
856 | """Define some aliases automatically. |
|
856 | """Define some aliases automatically. | |
857 |
|
857 | |||
858 | These are ALL parameter-less aliases""" |
|
858 | These are ALL parameter-less aliases""" | |
859 | for alias,cmd in self.auto_alias: |
|
859 | for alias,cmd in self.auto_alias: | |
860 | self.alias_table[alias] = (0,cmd) |
|
860 | self.alias_table[alias] = (0,cmd) | |
861 |
|
861 | |||
862 | def alias_table_validate(self,verbose=0): |
|
862 | def alias_table_validate(self,verbose=0): | |
863 | """Update information about the alias table. |
|
863 | """Update information about the alias table. | |
864 |
|
864 | |||
865 | In particular, make sure no Python keywords/builtins are in it.""" |
|
865 | In particular, make sure no Python keywords/builtins are in it.""" | |
866 |
|
866 | |||
867 | no_alias = self.no_alias |
|
867 | no_alias = self.no_alias | |
868 | for k in self.alias_table.keys(): |
|
868 | for k in self.alias_table.keys(): | |
869 | if k in no_alias: |
|
869 | if k in no_alias: | |
870 | del self.alias_table[k] |
|
870 | del self.alias_table[k] | |
871 | if verbose: |
|
871 | if verbose: | |
872 | print ("Deleting alias <%s>, it's a Python " |
|
872 | print ("Deleting alias <%s>, it's a Python " | |
873 | "keyword or builtin." % k) |
|
873 | "keyword or builtin." % k) | |
874 |
|
874 | |||
875 | def set_autoindent(self,value=None): |
|
875 | def set_autoindent(self,value=None): | |
876 | """Set the autoindent flag, checking for readline support. |
|
876 | """Set the autoindent flag, checking for readline support. | |
877 |
|
877 | |||
878 | If called with no arguments, it acts as a toggle.""" |
|
878 | If called with no arguments, it acts as a toggle.""" | |
879 |
|
879 | |||
880 | if not self.has_readline: |
|
880 | if not self.has_readline: | |
881 | if os.name == 'posix': |
|
881 | if os.name == 'posix': | |
882 | warn("The auto-indent feature requires the readline library") |
|
882 | warn("The auto-indent feature requires the readline library") | |
883 | self.autoindent = 0 |
|
883 | self.autoindent = 0 | |
884 | return |
|
884 | return | |
885 | if value is None: |
|
885 | if value is None: | |
886 | self.autoindent = not self.autoindent |
|
886 | self.autoindent = not self.autoindent | |
887 | else: |
|
887 | else: | |
888 | self.autoindent = value |
|
888 | self.autoindent = value | |
889 |
|
889 | |||
890 | def rc_set_toggle(self,rc_field,value=None): |
|
890 | def rc_set_toggle(self,rc_field,value=None): | |
891 | """Set or toggle a field in IPython's rc config. structure. |
|
891 | """Set or toggle a field in IPython's rc config. structure. | |
892 |
|
892 | |||
893 | If called with no arguments, it acts as a toggle. |
|
893 | If called with no arguments, it acts as a toggle. | |
894 |
|
894 | |||
895 | If called with a non-existent field, the resulting AttributeError |
|
895 | If called with a non-existent field, the resulting AttributeError | |
896 | exception will propagate out.""" |
|
896 | exception will propagate out.""" | |
897 |
|
897 | |||
898 | rc_val = getattr(self.rc,rc_field) |
|
898 | rc_val = getattr(self.rc,rc_field) | |
899 | if value is None: |
|
899 | if value is None: | |
900 | value = not rc_val |
|
900 | value = not rc_val | |
901 | setattr(self.rc,rc_field,value) |
|
901 | setattr(self.rc,rc_field,value) | |
902 |
|
902 | |||
903 | def user_setup(self,ipythondir,rc_suffix,mode='install'): |
|
903 | def user_setup(self,ipythondir,rc_suffix,mode='install'): | |
904 | """Install the user configuration directory. |
|
904 | """Install the user configuration directory. | |
905 |
|
905 | |||
906 | Can be called when running for the first time or to upgrade the user's |
|
906 | Can be called when running for the first time or to upgrade the user's | |
907 | .ipython/ directory with the mode parameter. Valid modes are 'install' |
|
907 | .ipython/ directory with the mode parameter. Valid modes are 'install' | |
908 | and 'upgrade'.""" |
|
908 | and 'upgrade'.""" | |
909 |
|
909 | |||
910 | def wait(): |
|
910 | def wait(): | |
911 | try: |
|
911 | try: | |
912 | raw_input("Please press <RETURN> to start IPython.") |
|
912 | raw_input("Please press <RETURN> to start IPython.") | |
913 | except EOFError: |
|
913 | except EOFError: | |
914 | print >> Term.cout |
|
914 | print >> Term.cout | |
915 | print '*'*70 |
|
915 | print '*'*70 | |
916 |
|
916 | |||
917 | cwd = os.getcwd() # remember where we started |
|
917 | cwd = os.getcwd() # remember where we started | |
918 | glb = glob.glob |
|
918 | glb = glob.glob | |
919 | print '*'*70 |
|
919 | print '*'*70 | |
920 | if mode == 'install': |
|
920 | if mode == 'install': | |
921 | print \ |
|
921 | print \ | |
922 | """Welcome to IPython. I will try to create a personal configuration directory |
|
922 | """Welcome to IPython. I will try to create a personal configuration directory | |
923 | where you can customize many aspects of IPython's functionality in:\n""" |
|
923 | where you can customize many aspects of IPython's functionality in:\n""" | |
924 | else: |
|
924 | else: | |
925 | print 'I am going to upgrade your configuration in:' |
|
925 | print 'I am going to upgrade your configuration in:' | |
926 |
|
926 | |||
927 | print ipythondir |
|
927 | print ipythondir | |
928 |
|
928 | |||
929 | rcdirend = os.path.join('IPython','UserConfig') |
|
929 | rcdirend = os.path.join('IPython','UserConfig') | |
930 | cfg = lambda d: os.path.join(d,rcdirend) |
|
930 | cfg = lambda d: os.path.join(d,rcdirend) | |
931 | try: |
|
931 | try: | |
932 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] |
|
932 | rcdir = filter(os.path.isdir,map(cfg,sys.path))[0] | |
933 | except IOError: |
|
933 | except IOError: | |
934 | warning = """ |
|
934 | warning = """ | |
935 | Installation error. IPython's directory was not found. |
|
935 | Installation error. IPython's directory was not found. | |
936 |
|
936 | |||
937 | Check the following: |
|
937 | Check the following: | |
938 |
|
938 | |||
939 | The ipython/IPython directory should be in a directory belonging to your |
|
939 | The ipython/IPython directory should be in a directory belonging to your | |
940 | PYTHONPATH environment variable (that is, it should be in a directory |
|
940 | PYTHONPATH environment variable (that is, it should be in a directory | |
941 | belonging to sys.path). You can copy it explicitly there or just link to it. |
|
941 | belonging to sys.path). You can copy it explicitly there or just link to it. | |
942 |
|
942 | |||
943 | IPython will proceed with builtin defaults. |
|
943 | IPython will proceed with builtin defaults. | |
944 | """ |
|
944 | """ | |
945 | warn(warning) |
|
945 | warn(warning) | |
946 | wait() |
|
946 | wait() | |
947 | return |
|
947 | return | |
948 |
|
948 | |||
949 | if mode == 'install': |
|
949 | if mode == 'install': | |
950 | try: |
|
950 | try: | |
951 | shutil.copytree(rcdir,ipythondir) |
|
951 | shutil.copytree(rcdir,ipythondir) | |
952 | os.chdir(ipythondir) |
|
952 | os.chdir(ipythondir) | |
953 | rc_files = glb("ipythonrc*") |
|
953 | rc_files = glb("ipythonrc*") | |
954 | for rc_file in rc_files: |
|
954 | for rc_file in rc_files: | |
955 | os.rename(rc_file,rc_file+rc_suffix) |
|
955 | os.rename(rc_file,rc_file+rc_suffix) | |
956 | except: |
|
956 | except: | |
957 | warning = """ |
|
957 | warning = """ | |
958 |
|
958 | |||
959 | There was a problem with the installation: |
|
959 | There was a problem with the installation: | |
960 | %s |
|
960 | %s | |
961 | Try to correct it or contact the developers if you think it's a bug. |
|
961 | Try to correct it or contact the developers if you think it's a bug. | |
962 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] |
|
962 | IPython will proceed with builtin defaults.""" % sys.exc_info()[1] | |
963 | warn(warning) |
|
963 | warn(warning) | |
964 | wait() |
|
964 | wait() | |
965 | return |
|
965 | return | |
966 |
|
966 | |||
967 | elif mode == 'upgrade': |
|
967 | elif mode == 'upgrade': | |
968 | try: |
|
968 | try: | |
969 | os.chdir(ipythondir) |
|
969 | os.chdir(ipythondir) | |
970 | except: |
|
970 | except: | |
971 | print """ |
|
971 | print """ | |
972 | Can not upgrade: changing to directory %s failed. Details: |
|
972 | Can not upgrade: changing to directory %s failed. Details: | |
973 | %s |
|
973 | %s | |
974 | """ % (ipythondir,sys.exc_info()[1]) |
|
974 | """ % (ipythondir,sys.exc_info()[1]) | |
975 | wait() |
|
975 | wait() | |
976 | return |
|
976 | return | |
977 | else: |
|
977 | else: | |
978 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) |
|
978 | sources = glb(os.path.join(rcdir,'[A-Za-z]*')) | |
979 | for new_full_path in sources: |
|
979 | for new_full_path in sources: | |
980 | new_filename = os.path.basename(new_full_path) |
|
980 | new_filename = os.path.basename(new_full_path) | |
981 | if new_filename.startswith('ipythonrc'): |
|
981 | if new_filename.startswith('ipythonrc'): | |
982 | new_filename = new_filename + rc_suffix |
|
982 | new_filename = new_filename + rc_suffix | |
983 | # The config directory should only contain files, skip any |
|
983 | # The config directory should only contain files, skip any | |
984 | # directories which may be there (like CVS) |
|
984 | # directories which may be there (like CVS) | |
985 | if os.path.isdir(new_full_path): |
|
985 | if os.path.isdir(new_full_path): | |
986 | continue |
|
986 | continue | |
987 | if os.path.exists(new_filename): |
|
987 | if os.path.exists(new_filename): | |
988 | old_file = new_filename+'.old' |
|
988 | old_file = new_filename+'.old' | |
989 | if os.path.exists(old_file): |
|
989 | if os.path.exists(old_file): | |
990 | os.remove(old_file) |
|
990 | os.remove(old_file) | |
991 | os.rename(new_filename,old_file) |
|
991 | os.rename(new_filename,old_file) | |
992 | shutil.copy(new_full_path,new_filename) |
|
992 | shutil.copy(new_full_path,new_filename) | |
993 | else: |
|
993 | else: | |
994 | raise ValueError,'unrecognized mode for install:',`mode` |
|
994 | raise ValueError,'unrecognized mode for install:',`mode` | |
995 |
|
995 | |||
996 | # Fix line-endings to those native to each platform in the config |
|
996 | # Fix line-endings to those native to each platform in the config | |
997 | # directory. |
|
997 | # directory. | |
998 | try: |
|
998 | try: | |
999 | os.chdir(ipythondir) |
|
999 | os.chdir(ipythondir) | |
1000 | except: |
|
1000 | except: | |
1001 | print """ |
|
1001 | print """ | |
1002 | Problem: changing to directory %s failed. |
|
1002 | Problem: changing to directory %s failed. | |
1003 | Details: |
|
1003 | Details: | |
1004 | %s |
|
1004 | %s | |
1005 |
|
1005 | |||
1006 | Some configuration files may have incorrect line endings. This should not |
|
1006 | Some configuration files may have incorrect line endings. This should not | |
1007 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) |
|
1007 | cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) | |
1008 | wait() |
|
1008 | wait() | |
1009 | else: |
|
1009 | else: | |
1010 | for fname in glb('ipythonrc*'): |
|
1010 | for fname in glb('ipythonrc*'): | |
1011 | try: |
|
1011 | try: | |
1012 | native_line_ends(fname,backup=0) |
|
1012 | native_line_ends(fname,backup=0) | |
1013 | except IOError: |
|
1013 | except IOError: | |
1014 | pass |
|
1014 | pass | |
1015 |
|
1015 | |||
1016 | if mode == 'install': |
|
1016 | if mode == 'install': | |
1017 | print """ |
|
1017 | print """ | |
1018 | Successful installation! |
|
1018 | Successful installation! | |
1019 |
|
1019 | |||
1020 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the |
|
1020 | Please read the sections 'Initial Configuration' and 'Quick Tips' in the | |
1021 | IPython manual (there are both HTML and PDF versions supplied with the |
|
1021 | IPython manual (there are both HTML and PDF versions supplied with the | |
1022 | distribution) to make sure that your system environment is properly configured |
|
1022 | distribution) to make sure that your system environment is properly configured | |
1023 | to take advantage of IPython's features.""" |
|
1023 | to take advantage of IPython's features.""" | |
1024 | else: |
|
1024 | else: | |
1025 | print """ |
|
1025 | print """ | |
1026 | Successful upgrade! |
|
1026 | Successful upgrade! | |
1027 |
|
1027 | |||
1028 | All files in your directory: |
|
1028 | All files in your directory: | |
1029 | %(ipythondir)s |
|
1029 | %(ipythondir)s | |
1030 | which would have been overwritten by the upgrade were backed up with a .old |
|
1030 | which would have been overwritten by the upgrade were backed up with a .old | |
1031 | extension. If you had made particular customizations in those files you may |
|
1031 | extension. If you had made particular customizations in those files you may | |
1032 | want to merge them back into the new files.""" % locals() |
|
1032 | want to merge them back into the new files.""" % locals() | |
1033 | wait() |
|
1033 | wait() | |
1034 | os.chdir(cwd) |
|
1034 | os.chdir(cwd) | |
1035 | # end user_setup() |
|
1035 | # end user_setup() | |
1036 |
|
1036 | |||
1037 | def atexit_operations(self): |
|
1037 | def atexit_operations(self): | |
1038 | """This will be executed at the time of exit. |
|
1038 | """This will be executed at the time of exit. | |
1039 |
|
1039 | |||
1040 | Saving of persistent data should be performed here. """ |
|
1040 | Saving of persistent data should be performed here. """ | |
1041 |
|
1041 | |||
1042 | # input history |
|
1042 | # input history | |
1043 | self.savehist() |
|
1043 | self.savehist() | |
1044 |
|
1044 | |||
1045 | # Cleanup all tempfiles left around |
|
1045 | # Cleanup all tempfiles left around | |
1046 | for tfile in self.tempfiles: |
|
1046 | for tfile in self.tempfiles: | |
1047 | try: |
|
1047 | try: | |
1048 | os.unlink(tfile) |
|
1048 | os.unlink(tfile) | |
1049 | except OSError: |
|
1049 | except OSError: | |
1050 | pass |
|
1050 | pass | |
1051 |
|
1051 | |||
1052 | # save the "persistent data" catch-all dictionary |
|
1052 | # save the "persistent data" catch-all dictionary | |
1053 | try: |
|
1053 | try: | |
1054 | pickle.dump(self.persist, open(self.persist_fname,"w")) |
|
1054 | pickle.dump(self.persist, open(self.persist_fname,"w")) | |
1055 | except: |
|
1055 | except: | |
1056 | print "*** ERROR *** persistent data saving failed." |
|
1056 | print "*** ERROR *** persistent data saving failed." | |
1057 |
|
1057 | |||
1058 | def savehist(self): |
|
1058 | def savehist(self): | |
1059 | """Save input history to a file (via readline library).""" |
|
1059 | """Save input history to a file (via readline library).""" | |
1060 | try: |
|
1060 | try: | |
1061 | self.readline.write_history_file(self.histfile) |
|
1061 | self.readline.write_history_file(self.histfile) | |
1062 | except: |
|
1062 | except: | |
1063 | print 'Unable to save IPython command history to file: ' + \ |
|
1063 | print 'Unable to save IPython command history to file: ' + \ | |
1064 | `self.histfile` |
|
1064 | `self.histfile` | |
1065 |
|
1065 | |||
1066 | def pre_readline(self): |
|
1066 | def pre_readline(self): | |
1067 | """readline hook to be used at the start of each line. |
|
1067 | """readline hook to be used at the start of each line. | |
1068 |
|
1068 | |||
1069 | Currently it handles auto-indent only.""" |
|
1069 | Currently it handles auto-indent only.""" | |
1070 |
|
1070 | |||
1071 | self.readline.insert_text(self.indent_current) |
|
1071 | self.readline.insert_text(self.indent_current) | |
1072 |
|
1072 | |||
1073 | def init_readline(self): |
|
1073 | def init_readline(self): | |
1074 | """Command history completion/saving/reloading.""" |
|
1074 | """Command history completion/saving/reloading.""" | |
1075 | try: |
|
1075 | try: | |
1076 | import readline |
|
1076 | import readline | |
1077 | except ImportError: |
|
1077 | except ImportError: | |
1078 | self.has_readline = 0 |
|
1078 | self.has_readline = 0 | |
1079 | self.readline = None |
|
1079 | self.readline = None | |
1080 | # no point in bugging windows users with this every time: |
|
1080 | # no point in bugging windows users with this every time: | |
1081 | if os.name == 'posix': |
|
1081 | if os.name == 'posix': | |
1082 | warn('Readline services not available on this platform.') |
|
1082 | warn('Readline services not available on this platform.') | |
1083 | else: |
|
1083 | else: | |
1084 | import atexit |
|
1084 | import atexit | |
1085 | from IPython.completer import IPCompleter |
|
1085 | from IPython.completer import IPCompleter | |
1086 | self.Completer = IPCompleter(self, |
|
1086 | self.Completer = IPCompleter(self, | |
1087 | self.user_ns, |
|
1087 | self.user_ns, | |
1088 | self.user_global_ns, |
|
1088 | self.user_global_ns, | |
1089 | self.rc.readline_omit__names, |
|
1089 | self.rc.readline_omit__names, | |
1090 | self.alias_table) |
|
1090 | self.alias_table) | |
1091 |
|
1091 | |||
1092 | # Platform-specific configuration |
|
1092 | # Platform-specific configuration | |
1093 | if os.name == 'nt': |
|
1093 | if os.name == 'nt': | |
1094 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1094 | self.readline_startup_hook = readline.set_pre_input_hook | |
1095 | else: |
|
1095 | else: | |
1096 | self.readline_startup_hook = readline.set_startup_hook |
|
1096 | self.readline_startup_hook = readline.set_startup_hook | |
1097 |
|
1097 | |||
1098 | # Load user's initrc file (readline config) |
|
1098 | # Load user's initrc file (readline config) | |
1099 | inputrc_name = os.environ.get('INPUTRC') |
|
1099 | inputrc_name = os.environ.get('INPUTRC') | |
1100 | if inputrc_name is None: |
|
1100 | if inputrc_name is None: | |
1101 | home_dir = get_home_dir() |
|
1101 | home_dir = get_home_dir() | |
1102 | if home_dir is not None: |
|
1102 | if home_dir is not None: | |
1103 | inputrc_name = os.path.join(home_dir,'.inputrc') |
|
1103 | inputrc_name = os.path.join(home_dir,'.inputrc') | |
1104 | if os.path.isfile(inputrc_name): |
|
1104 | if os.path.isfile(inputrc_name): | |
1105 | try: |
|
1105 | try: | |
1106 | readline.read_init_file(inputrc_name) |
|
1106 | readline.read_init_file(inputrc_name) | |
1107 | except: |
|
1107 | except: | |
1108 | warn('Problems reading readline initialization file <%s>' |
|
1108 | warn('Problems reading readline initialization file <%s>' | |
1109 | % inputrc_name) |
|
1109 | % inputrc_name) | |
1110 |
|
1110 | |||
1111 | self.has_readline = 1 |
|
1111 | self.has_readline = 1 | |
1112 | self.readline = readline |
|
1112 | self.readline = readline | |
1113 | # save this in sys so embedded copies can restore it properly |
|
1113 | # save this in sys so embedded copies can restore it properly | |
1114 | sys.ipcompleter = self.Completer.complete |
|
1114 | sys.ipcompleter = self.Completer.complete | |
1115 | readline.set_completer(self.Completer.complete) |
|
1115 | readline.set_completer(self.Completer.complete) | |
1116 |
|
1116 | |||
1117 | # Configure readline according to user's prefs |
|
1117 | # Configure readline according to user's prefs | |
1118 | for rlcommand in self.rc.readline_parse_and_bind: |
|
1118 | for rlcommand in self.rc.readline_parse_and_bind: | |
1119 | readline.parse_and_bind(rlcommand) |
|
1119 | readline.parse_and_bind(rlcommand) | |
1120 |
|
1120 | |||
1121 | # remove some chars from the delimiters list |
|
1121 | # remove some chars from the delimiters list | |
1122 | delims = readline.get_completer_delims() |
|
1122 | delims = readline.get_completer_delims() | |
1123 | delims = delims.translate(string._idmap, |
|
1123 | delims = delims.translate(string._idmap, | |
1124 | self.rc.readline_remove_delims) |
|
1124 | self.rc.readline_remove_delims) | |
1125 | readline.set_completer_delims(delims) |
|
1125 | readline.set_completer_delims(delims) | |
1126 | # otherwise we end up with a monster history after a while: |
|
1126 | # otherwise we end up with a monster history after a while: | |
1127 | readline.set_history_length(1000) |
|
1127 | readline.set_history_length(1000) | |
1128 | try: |
|
1128 | try: | |
1129 | #print '*** Reading readline history' # dbg |
|
1129 | #print '*** Reading readline history' # dbg | |
1130 | readline.read_history_file(self.histfile) |
|
1130 | readline.read_history_file(self.histfile) | |
1131 | except IOError: |
|
1131 | except IOError: | |
1132 | pass # It doesn't exist yet. |
|
1132 | pass # It doesn't exist yet. | |
1133 |
|
1133 | |||
1134 | atexit.register(self.atexit_operations) |
|
1134 | atexit.register(self.atexit_operations) | |
1135 | del atexit |
|
1135 | del atexit | |
1136 |
|
1136 | |||
1137 | # Configure auto-indent for all platforms |
|
1137 | # Configure auto-indent for all platforms | |
1138 | self.set_autoindent(self.rc.autoindent) |
|
1138 | self.set_autoindent(self.rc.autoindent) | |
1139 |
|
1139 | |||
1140 | def _should_recompile(self,e): |
|
1140 | def _should_recompile(self,e): | |
1141 | """Utility routine for edit_syntax_error""" |
|
1141 | """Utility routine for edit_syntax_error""" | |
1142 |
|
1142 | |||
1143 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1143 | if e.filename in ('<ipython console>','<input>','<string>', | |
1144 | '<console>'): |
|
1144 | '<console>'): | |
1145 | return False |
|
1145 | return False | |
1146 | try: |
|
1146 | try: | |
1147 | if not ask_yes_no('Return to editor to correct syntax error? ' |
|
1147 | if not ask_yes_no('Return to editor to correct syntax error? ' | |
1148 | '[Y/n] ','y'): |
|
1148 | '[Y/n] ','y'): | |
1149 | return False |
|
1149 | return False | |
1150 | except EOFError: |
|
1150 | except EOFError: | |
1151 | return False |
|
1151 | return False | |
1152 | self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg) |
|
1152 | self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg) | |
1153 | return True |
|
1153 | return True | |
1154 |
|
1154 | |||
1155 | def edit_syntax_error(self): |
|
1155 | def edit_syntax_error(self): | |
1156 | """The bottom half of the syntax error handler called in the main loop. |
|
1156 | """The bottom half of the syntax error handler called in the main loop. | |
1157 |
|
1157 | |||
1158 | Loop until syntax error is fixed or user cancels. |
|
1158 | Loop until syntax error is fixed or user cancels. | |
1159 | """ |
|
1159 | """ | |
1160 |
|
1160 | |||
1161 | while self.SyntaxTB.last_syntax_error: |
|
1161 | while self.SyntaxTB.last_syntax_error: | |
1162 | # copy and clear last_syntax_error |
|
1162 | # copy and clear last_syntax_error | |
1163 | err = self.SyntaxTB.clear_err_state() |
|
1163 | err = self.SyntaxTB.clear_err_state() | |
1164 | if not self._should_recompile(err): |
|
1164 | if not self._should_recompile(err): | |
1165 | return |
|
1165 | return | |
1166 | try: |
|
1166 | try: | |
1167 | # may set last_syntax_error again if a SyntaxError is raised |
|
1167 | # may set last_syntax_error again if a SyntaxError is raised | |
1168 | self.safe_execfile(err.filename,self.shell.user_ns) |
|
1168 | self.safe_execfile(err.filename,self.shell.user_ns) | |
1169 | except: |
|
1169 | except: | |
1170 | self.showtraceback() |
|
1170 | self.showtraceback() | |
1171 | else: |
|
1171 | else: | |
1172 | f = file(err.filename) |
|
1172 | f = file(err.filename) | |
1173 | try: |
|
1173 | try: | |
1174 | sys.displayhook(f.read()) |
|
1174 | sys.displayhook(f.read()) | |
1175 | finally: |
|
1175 | finally: | |
1176 | f.close() |
|
1176 | f.close() | |
1177 |
|
1177 | |||
1178 | def showsyntaxerror(self, filename=None): |
|
1178 | def showsyntaxerror(self, filename=None): | |
1179 | """Display the syntax error that just occurred. |
|
1179 | """Display the syntax error that just occurred. | |
1180 |
|
1180 | |||
1181 | This doesn't display a stack trace because there isn't one. |
|
1181 | This doesn't display a stack trace because there isn't one. | |
1182 |
|
1182 | |||
1183 | If a filename is given, it is stuffed in the exception instead |
|
1183 | If a filename is given, it is stuffed in the exception instead | |
1184 | of what was there before (because Python's parser always uses |
|
1184 | of what was there before (because Python's parser always uses | |
1185 | "<string>" when reading from a string). |
|
1185 | "<string>" when reading from a string). | |
1186 | """ |
|
1186 | """ | |
1187 | etype, value, last_traceback = sys.exc_info() |
|
1187 | etype, value, last_traceback = sys.exc_info() | |
1188 | if filename and etype is SyntaxError: |
|
1188 | if filename and etype is SyntaxError: | |
1189 | # Work hard to stuff the correct filename in the exception |
|
1189 | # Work hard to stuff the correct filename in the exception | |
1190 | try: |
|
1190 | try: | |
1191 | msg, (dummy_filename, lineno, offset, line) = value |
|
1191 | msg, (dummy_filename, lineno, offset, line) = value | |
1192 | except: |
|
1192 | except: | |
1193 | # Not the format we expect; leave it alone |
|
1193 | # Not the format we expect; leave it alone | |
1194 | pass |
|
1194 | pass | |
1195 | else: |
|
1195 | else: | |
1196 | # Stuff in the right filename |
|
1196 | # Stuff in the right filename | |
1197 | try: |
|
1197 | try: | |
1198 | # Assume SyntaxError is a class exception |
|
1198 | # Assume SyntaxError is a class exception | |
1199 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1199 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1200 | except: |
|
1200 | except: | |
1201 | # If that failed, assume SyntaxError is a string |
|
1201 | # If that failed, assume SyntaxError is a string | |
1202 | value = msg, (filename, lineno, offset, line) |
|
1202 | value = msg, (filename, lineno, offset, line) | |
1203 | self.SyntaxTB(etype,value,[]) |
|
1203 | self.SyntaxTB(etype,value,[]) | |
1204 |
|
1204 | |||
1205 | def debugger(self): |
|
1205 | def debugger(self): | |
1206 | """Call the pdb debugger.""" |
|
1206 | """Call the pdb debugger.""" | |
1207 |
|
1207 | |||
1208 | if not self.rc.pdb: |
|
1208 | if not self.rc.pdb: | |
1209 | return |
|
1209 | return | |
1210 | pdb.pm() |
|
1210 | pdb.pm() | |
1211 |
|
1211 | |||
1212 | def showtraceback(self,exc_tuple = None,filename=None): |
|
1212 | def showtraceback(self,exc_tuple = None,filename=None): | |
1213 | """Display the exception that just occurred.""" |
|
1213 | """Display the exception that just occurred.""" | |
1214 |
|
1214 | |||
1215 | # Though this won't be called by syntax errors in the input line, |
|
1215 | # Though this won't be called by syntax errors in the input line, | |
1216 | # there may be SyntaxError cases whith imported code. |
|
1216 | # there may be SyntaxError cases whith imported code. | |
1217 | if exc_tuple is None: |
|
1217 | if exc_tuple is None: | |
1218 | type, value, tb = sys.exc_info() |
|
1218 | type, value, tb = sys.exc_info() | |
1219 | else: |
|
1219 | else: | |
1220 | type, value, tb = exc_tuple |
|
1220 | type, value, tb = exc_tuple | |
1221 | if type is SyntaxError: |
|
1221 | if type is SyntaxError: | |
1222 | self.showsyntaxerror(filename) |
|
1222 | self.showsyntaxerror(filename) | |
1223 | else: |
|
1223 | else: | |
1224 | self.InteractiveTB() |
|
1224 | self.InteractiveTB() | |
1225 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1225 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1226 | # pdb mucks up readline, fix it back |
|
1226 | # pdb mucks up readline, fix it back | |
1227 | self.readline.set_completer(self.Completer.complete) |
|
1227 | self.readline.set_completer(self.Completer.complete) | |
1228 |
|
1228 | |||
1229 | def mainloop(self,banner=None): |
|
1229 | def mainloop(self,banner=None): | |
1230 | """Creates the local namespace and starts the mainloop. |
|
1230 | """Creates the local namespace and starts the mainloop. | |
1231 |
|
1231 | |||
1232 | If an optional banner argument is given, it will override the |
|
1232 | If an optional banner argument is given, it will override the | |
1233 | internally created default banner.""" |
|
1233 | internally created default banner.""" | |
1234 |
|
1234 | |||
1235 | if self.rc.c: # Emulate Python's -c option |
|
1235 | if self.rc.c: # Emulate Python's -c option | |
1236 | self.exec_init_cmd() |
|
1236 | self.exec_init_cmd() | |
1237 | if banner is None: |
|
1237 | if banner is None: | |
1238 | if self.rc.banner: |
|
1238 | if self.rc.banner: | |
1239 | banner = self.BANNER+self.banner2 |
|
1239 | banner = self.BANNER+self.banner2 | |
1240 | else: |
|
1240 | else: | |
1241 | banner = '' |
|
1241 | banner = '' | |
1242 | self.interact(banner) |
|
1242 | self.interact(banner) | |
1243 |
|
1243 | |||
1244 | def exec_init_cmd(self): |
|
1244 | def exec_init_cmd(self): | |
1245 | """Execute a command given at the command line. |
|
1245 | """Execute a command given at the command line. | |
1246 |
|
1246 | |||
1247 | This emulates Python's -c option.""" |
|
1247 | This emulates Python's -c option.""" | |
1248 |
|
1248 | |||
1249 | sys.argv = ['-c'] |
|
1249 | sys.argv = ['-c'] | |
1250 | self.push(self.rc.c) |
|
1250 | self.push(self.rc.c) | |
1251 |
|
1251 | |||
1252 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): |
|
1252 | def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0): | |
1253 | """Embeds IPython into a running python program. |
|
1253 | """Embeds IPython into a running python program. | |
1254 |
|
1254 | |||
1255 | Input: |
|
1255 | Input: | |
1256 |
|
1256 | |||
1257 | - header: An optional header message can be specified. |
|
1257 | - header: An optional header message can be specified. | |
1258 |
|
1258 | |||
1259 | - local_ns, global_ns: working namespaces. If given as None, the |
|
1259 | - local_ns, global_ns: working namespaces. If given as None, the | |
1260 | IPython-initialized one is updated with __main__.__dict__, so that |
|
1260 | IPython-initialized one is updated with __main__.__dict__, so that | |
1261 | program variables become visible but user-specific configuration |
|
1261 | program variables become visible but user-specific configuration | |
1262 | remains possible. |
|
1262 | remains possible. | |
1263 |
|
1263 | |||
1264 | - stack_depth: specifies how many levels in the stack to go to |
|
1264 | - stack_depth: specifies how many levels in the stack to go to | |
1265 | looking for namespaces (when local_ns and global_ns are None). This |
|
1265 | looking for namespaces (when local_ns and global_ns are None). This | |
1266 | allows an intermediate caller to make sure that this function gets |
|
1266 | allows an intermediate caller to make sure that this function gets | |
1267 | the namespace from the intended level in the stack. By default (0) |
|
1267 | the namespace from the intended level in the stack. By default (0) | |
1268 | it will get its locals and globals from the immediate caller. |
|
1268 | it will get its locals and globals from the immediate caller. | |
1269 |
|
1269 | |||
1270 | Warning: it's possible to use this in a program which is being run by |
|
1270 | Warning: it's possible to use this in a program which is being run by | |
1271 | IPython itself (via %run), but some funny things will happen (a few |
|
1271 | IPython itself (via %run), but some funny things will happen (a few | |
1272 | globals get overwritten). In the future this will be cleaned up, as |
|
1272 | globals get overwritten). In the future this will be cleaned up, as | |
1273 | there is no fundamental reason why it can't work perfectly.""" |
|
1273 | there is no fundamental reason why it can't work perfectly.""" | |
1274 |
|
1274 | |||
1275 | # Get locals and globals from caller |
|
1275 | # Get locals and globals from caller | |
1276 | if local_ns is None or global_ns is None: |
|
1276 | if local_ns is None or global_ns is None: | |
1277 | call_frame = sys._getframe(stack_depth).f_back |
|
1277 | call_frame = sys._getframe(stack_depth).f_back | |
1278 |
|
1278 | |||
1279 | if local_ns is None: |
|
1279 | if local_ns is None: | |
1280 | local_ns = call_frame.f_locals |
|
1280 | local_ns = call_frame.f_locals | |
1281 | if global_ns is None: |
|
1281 | if global_ns is None: | |
1282 | global_ns = call_frame.f_globals |
|
1282 | global_ns = call_frame.f_globals | |
1283 |
|
1283 | |||
1284 | # Update namespaces and fire up interpreter |
|
1284 | # Update namespaces and fire up interpreter | |
1285 | self.user_ns = local_ns |
|
1285 | self.user_ns = local_ns | |
1286 | self.user_global_ns = global_ns |
|
1286 | self.user_global_ns = global_ns | |
1287 |
|
1287 | |||
1288 | # Patch for global embedding to make sure that things don't overwrite |
|
1288 | # Patch for global embedding to make sure that things don't overwrite | |
1289 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
1289 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
1290 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
1290 | # FIXME. Test this a bit more carefully (the if.. is new) | |
1291 | if local_ns is None and global_ns is None: |
|
1291 | if local_ns is None and global_ns is None: | |
1292 | self.user_global_ns.update(__main__.__dict__) |
|
1292 | self.user_global_ns.update(__main__.__dict__) | |
1293 |
|
1293 | |||
1294 | # make sure the tab-completer has the correct frame information, so it |
|
1294 | # make sure the tab-completer has the correct frame information, so it | |
1295 | # actually completes using the frame's locals/globals |
|
1295 | # actually completes using the frame's locals/globals | |
1296 | self.set_completer_frame(call_frame) |
|
1296 | self.set_completer_frame(call_frame) | |
1297 |
|
1297 | |||
1298 | self.interact(header) |
|
1298 | self.interact(header) | |
1299 |
|
1299 | |||
1300 | def interact(self, banner=None): |
|
1300 | def interact(self, banner=None): | |
1301 | """Closely emulate the interactive Python console. |
|
1301 | """Closely emulate the interactive Python console. | |
1302 |
|
1302 | |||
1303 | The optional banner argument specify the banner to print |
|
1303 | The optional banner argument specify the banner to print | |
1304 | before the first interaction; by default it prints a banner |
|
1304 | before the first interaction; by default it prints a banner | |
1305 | similar to the one printed by the real Python interpreter, |
|
1305 | similar to the one printed by the real Python interpreter, | |
1306 | followed by the current class name in parentheses (so as not |
|
1306 | followed by the current class name in parentheses (so as not | |
1307 | to confuse this with the real interpreter -- since it's so |
|
1307 | to confuse this with the real interpreter -- since it's so | |
1308 | close!). |
|
1308 | close!). | |
1309 |
|
1309 | |||
1310 | """ |
|
1310 | """ | |
1311 | cprt = 'Type "copyright", "credits" or "license" for more information.' |
|
1311 | cprt = 'Type "copyright", "credits" or "license" for more information.' | |
1312 | if banner is None: |
|
1312 | if banner is None: | |
1313 | self.write("Python %s on %s\n%s\n(%s)\n" % |
|
1313 | self.write("Python %s on %s\n%s\n(%s)\n" % | |
1314 | (sys.version, sys.platform, cprt, |
|
1314 | (sys.version, sys.platform, cprt, | |
1315 | self.__class__.__name__)) |
|
1315 | self.__class__.__name__)) | |
1316 | else: |
|
1316 | else: | |
1317 | self.write(banner) |
|
1317 | self.write(banner) | |
1318 |
|
1318 | |||
1319 | more = 0 |
|
1319 | more = 0 | |
1320 |
|
1320 | |||
1321 | # Mark activity in the builtins |
|
1321 | # Mark activity in the builtins | |
1322 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1322 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1323 |
|
1323 | |||
1324 | # exit_now is set by a call to %Exit or %Quit |
|
1324 | # exit_now is set by a call to %Exit or %Quit | |
1325 | while not self.exit_now: |
|
1325 | while not self.exit_now: | |
1326 | try: |
|
1326 | try: | |
1327 | if more: |
|
1327 | if more: | |
1328 | prompt = self.outputcache.prompt2 |
|
1328 | prompt = self.outputcache.prompt2 | |
1329 | if self.autoindent: |
|
1329 | if self.autoindent: | |
1330 | self.readline_startup_hook(self.pre_readline) |
|
1330 | self.readline_startup_hook(self.pre_readline) | |
1331 | else: |
|
1331 | else: | |
1332 | prompt = self.outputcache.prompt1 |
|
1332 | prompt = self.outputcache.prompt1 | |
1333 | try: |
|
1333 | try: | |
1334 | line = self.raw_input(prompt,more) |
|
1334 | line = self.raw_input(prompt,more) | |
1335 | if self.autoindent: |
|
1335 | if self.autoindent: | |
1336 | self.readline_startup_hook(None) |
|
1336 | self.readline_startup_hook(None) | |
1337 | except EOFError: |
|
1337 | except EOFError: | |
1338 | if self.autoindent: |
|
1338 | if self.autoindent: | |
1339 | self.readline_startup_hook(None) |
|
1339 | self.readline_startup_hook(None) | |
1340 | self.write("\n") |
|
1340 | self.write("\n") | |
1341 | self.exit() |
|
1341 | self.exit() | |
1342 | else: |
|
1342 | else: | |
1343 | more = self.push(line) |
|
1343 | more = self.push(line) | |
1344 |
|
1344 | |||
1345 | if (self.SyntaxTB.last_syntax_error and |
|
1345 | if (self.SyntaxTB.last_syntax_error and | |
1346 | self.rc.autoedit_syntax): |
|
1346 | self.rc.autoedit_syntax): | |
1347 | self.edit_syntax_error() |
|
1347 | self.edit_syntax_error() | |
1348 |
|
1348 | |||
1349 | except KeyboardInterrupt: |
|
1349 | except KeyboardInterrupt: | |
1350 | self.write("\nKeyboardInterrupt\n") |
|
1350 | self.write("\nKeyboardInterrupt\n") | |
1351 | self.resetbuffer() |
|
1351 | self.resetbuffer() | |
1352 | more = 0 |
|
1352 | more = 0 | |
1353 | # keep cache in sync with the prompt counter: |
|
1353 | # keep cache in sync with the prompt counter: | |
1354 | self.outputcache.prompt_count -= 1 |
|
1354 | self.outputcache.prompt_count -= 1 | |
1355 |
|
1355 | |||
1356 | if self.autoindent: |
|
1356 | if self.autoindent: | |
1357 | self.indent_current_nsp = 0 |
|
1357 | self.indent_current_nsp = 0 | |
1358 | self.indent_current = ' '* self.indent_current_nsp |
|
1358 | self.indent_current = ' '* self.indent_current_nsp | |
1359 |
|
1359 | |||
1360 | except bdb.BdbQuit: |
|
1360 | except bdb.BdbQuit: | |
1361 | warn("The Python debugger has exited with a BdbQuit exception.\n" |
|
1361 | warn("The Python debugger has exited with a BdbQuit exception.\n" | |
1362 | "Because of how pdb handles the stack, it is impossible\n" |
|
1362 | "Because of how pdb handles the stack, it is impossible\n" | |
1363 | "for IPython to properly format this particular exception.\n" |
|
1363 | "for IPython to properly format this particular exception.\n" | |
1364 | "IPython will resume normal operation.") |
|
1364 | "IPython will resume normal operation.") | |
1365 |
|
1365 | |||
1366 | # We are off again... |
|
1366 | # We are off again... | |
1367 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1367 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1368 |
|
1368 | |||
1369 | def excepthook(self, type, value, tb): |
|
1369 | def excepthook(self, type, value, tb): | |
1370 | """One more defense for GUI apps that call sys.excepthook. |
|
1370 | """One more defense for GUI apps that call sys.excepthook. | |
1371 |
|
1371 | |||
1372 | GUI frameworks like wxPython trap exceptions and call |
|
1372 | GUI frameworks like wxPython trap exceptions and call | |
1373 | sys.excepthook themselves. I guess this is a feature that |
|
1373 | sys.excepthook themselves. I guess this is a feature that | |
1374 | enables them to keep running after exceptions that would |
|
1374 | enables them to keep running after exceptions that would | |
1375 | otherwise kill their mainloop. This is a bother for IPython |
|
1375 | otherwise kill their mainloop. This is a bother for IPython | |
1376 | which excepts to catch all of the program exceptions with a try: |
|
1376 | which excepts to catch all of the program exceptions with a try: | |
1377 | except: statement. |
|
1377 | except: statement. | |
1378 |
|
1378 | |||
1379 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1379 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1380 | any app directly invokes sys.excepthook, it will look to the user like |
|
1380 | any app directly invokes sys.excepthook, it will look to the user like | |
1381 | IPython crashed. In order to work around this, we can disable the |
|
1381 | IPython crashed. In order to work around this, we can disable the | |
1382 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1382 | CrashHandler and replace it with this excepthook instead, which prints a | |
1383 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1383 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1384 | call sys.excepthook will generate a regular-looking exception from |
|
1384 | call sys.excepthook will generate a regular-looking exception from | |
1385 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1385 | IPython, and the CrashHandler will only be triggered by real IPython | |
1386 | crashes. |
|
1386 | crashes. | |
1387 |
|
1387 | |||
1388 | This hook should be used sparingly, only in places which are not likely |
|
1388 | This hook should be used sparingly, only in places which are not likely | |
1389 | to be true IPython errors. |
|
1389 | to be true IPython errors. | |
1390 | """ |
|
1390 | """ | |
1391 |
|
1391 | |||
1392 | self.InteractiveTB(type, value, tb, tb_offset=0) |
|
1392 | self.InteractiveTB(type, value, tb, tb_offset=0) | |
1393 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1393 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1394 | self.readline.set_completer(self.Completer.complete) |
|
1394 | self.readline.set_completer(self.Completer.complete) | |
1395 |
|
1395 | |||
1396 | def call_alias(self,alias,rest=''): |
|
1396 | def call_alias(self,alias,rest=''): | |
1397 | """Call an alias given its name and the rest of the line. |
|
1397 | """Call an alias given its name and the rest of the line. | |
1398 |
|
1398 | |||
1399 | This function MUST be given a proper alias, because it doesn't make |
|
1399 | This function MUST be given a proper alias, because it doesn't make | |
1400 | any checks when looking up into the alias table. The caller is |
|
1400 | any checks when looking up into the alias table. The caller is | |
1401 | responsible for invoking it only with a valid alias.""" |
|
1401 | responsible for invoking it only with a valid alias.""" | |
1402 |
|
1402 | |||
1403 | #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg |
|
1403 | #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg | |
1404 | nargs,cmd = self.alias_table[alias] |
|
1404 | nargs,cmd = self.alias_table[alias] | |
1405 | # Expand the %l special to be the user's input line |
|
1405 | # Expand the %l special to be the user's input line | |
1406 | if cmd.find('%l') >= 0: |
|
1406 | if cmd.find('%l') >= 0: | |
1407 | cmd = cmd.replace('%l',rest) |
|
1407 | cmd = cmd.replace('%l',rest) | |
1408 | rest = '' |
|
1408 | rest = '' | |
1409 | if nargs==0: |
|
1409 | if nargs==0: | |
1410 | # Simple, argument-less aliases |
|
1410 | # Simple, argument-less aliases | |
1411 | cmd = '%s %s' % (cmd,rest) |
|
1411 | cmd = '%s %s' % (cmd,rest) | |
1412 | else: |
|
1412 | else: | |
1413 | # Handle aliases with positional arguments |
|
1413 | # Handle aliases with positional arguments | |
1414 | args = rest.split(None,nargs) |
|
1414 | args = rest.split(None,nargs) | |
1415 | if len(args)< nargs: |
|
1415 | if len(args)< nargs: | |
1416 | error('Alias <%s> requires %s arguments, %s given.' % |
|
1416 | error('Alias <%s> requires %s arguments, %s given.' % | |
1417 | (alias,nargs,len(args))) |
|
1417 | (alias,nargs,len(args))) | |
1418 | return |
|
1418 | return | |
1419 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
1419 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |
1420 | # Now call the macro, evaluating in the user's namespace |
|
1420 | # Now call the macro, evaluating in the user's namespace | |
1421 | try: |
|
1421 | try: | |
1422 | self.system(cmd) |
|
1422 | self.system(cmd) | |
1423 | except: |
|
1423 | except: | |
1424 | self.showtraceback() |
|
1424 | self.showtraceback() | |
1425 |
|
1425 | |||
1426 | def autoindent_update(self,line): |
|
1426 | def autoindent_update(self,line): | |
1427 | """Keep track of the indent level.""" |
|
1427 | """Keep track of the indent level.""" | |
1428 | if self.autoindent: |
|
1428 | if self.autoindent: | |
1429 | if line: |
|
1429 | if line: | |
1430 | ini_spaces = ini_spaces_re.match(line) |
|
1430 | ini_spaces = ini_spaces_re.match(line) | |
1431 | if ini_spaces: |
|
1431 | if ini_spaces: | |
1432 | nspaces = ini_spaces.end() |
|
1432 | nspaces = ini_spaces.end() | |
1433 | else: |
|
1433 | else: | |
1434 | nspaces = 0 |
|
1434 | nspaces = 0 | |
1435 | self.indent_current_nsp = nspaces |
|
1435 | self.indent_current_nsp = nspaces | |
1436 |
|
1436 | |||
1437 | if line[-1] == ':': |
|
1437 | if line[-1] == ':': | |
1438 | self.indent_current_nsp += 4 |
|
1438 | self.indent_current_nsp += 4 | |
1439 | elif dedent_re.match(line): |
|
1439 | elif dedent_re.match(line): | |
1440 | self.indent_current_nsp -= 4 |
|
1440 | self.indent_current_nsp -= 4 | |
1441 | else: |
|
1441 | else: | |
1442 | self.indent_current_nsp = 0 |
|
1442 | self.indent_current_nsp = 0 | |
1443 |
|
1443 | |||
1444 | # indent_current is the actual string to be inserted |
|
1444 | # indent_current is the actual string to be inserted | |
1445 | # by the readline hooks for indentation |
|
1445 | # by the readline hooks for indentation | |
1446 | self.indent_current = ' '* self.indent_current_nsp |
|
1446 | self.indent_current = ' '* self.indent_current_nsp | |
1447 |
|
1447 | |||
1448 | def runlines(self,lines): |
|
1448 | def runlines(self,lines): | |
1449 | """Run a string of one or more lines of source. |
|
1449 | """Run a string of one or more lines of source. | |
1450 |
|
1450 | |||
1451 | This method is capable of running a string containing multiple source |
|
1451 | This method is capable of running a string containing multiple source | |
1452 | lines, as if they had been entered at the IPython prompt. Since it |
|
1452 | lines, as if they had been entered at the IPython prompt. Since it | |
1453 | exposes IPython's processing machinery, the given strings can contain |
|
1453 | exposes IPython's processing machinery, the given strings can contain | |
1454 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
1454 | magic calls (%magic), special shell access (!cmd), etc.""" | |
1455 |
|
1455 | |||
1456 | # We must start with a clean buffer, in case this is run from an |
|
1456 | # We must start with a clean buffer, in case this is run from an | |
1457 | # interactive IPython session (via a magic, for example). |
|
1457 | # interactive IPython session (via a magic, for example). | |
1458 | self.resetbuffer() |
|
1458 | self.resetbuffer() | |
1459 | lines = lines.split('\n') |
|
1459 | lines = lines.split('\n') | |
1460 | more = 0 |
|
1460 | more = 0 | |
1461 | for line in lines: |
|
1461 | for line in lines: | |
1462 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1462 | # skip blank lines so we don't mess up the prompt counter, but do | |
1463 | # NOT skip even a blank line if we are in a code block (more is |
|
1463 | # NOT skip even a blank line if we are in a code block (more is | |
1464 | # true) |
|
1464 | # true) | |
1465 | if line or more: |
|
1465 | if line or more: | |
1466 | more = self.push(self.prefilter(line,more)) |
|
1466 | more = self.push(self.prefilter(line,more)) | |
1467 | # IPython's runsource returns None if there was an error |
|
1467 | # IPython's runsource returns None if there was an error | |
1468 | # compiling the code. This allows us to stop processing right |
|
1468 | # compiling the code. This allows us to stop processing right | |
1469 | # away, so the user gets the error message at the right place. |
|
1469 | # away, so the user gets the error message at the right place. | |
1470 | if more is None: |
|
1470 | if more is None: | |
1471 | break |
|
1471 | break | |
1472 | # final newline in case the input didn't have it, so that the code |
|
1472 | # final newline in case the input didn't have it, so that the code | |
1473 | # actually does get executed |
|
1473 | # actually does get executed | |
1474 | if more: |
|
1474 | if more: | |
1475 | self.push('\n') |
|
1475 | self.push('\n') | |
1476 |
|
1476 | |||
1477 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1477 | def runsource(self, source, filename='<input>', symbol='single'): | |
1478 | """Compile and run some source in the interpreter. |
|
1478 | """Compile and run some source in the interpreter. | |
1479 |
|
1479 | |||
1480 | Arguments are as for compile_command(). |
|
1480 | Arguments are as for compile_command(). | |
1481 |
|
1481 | |||
1482 | One several things can happen: |
|
1482 | One several things can happen: | |
1483 |
|
1483 | |||
1484 | 1) The input is incorrect; compile_command() raised an |
|
1484 | 1) The input is incorrect; compile_command() raised an | |
1485 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1485 | exception (SyntaxError or OverflowError). A syntax traceback | |
1486 | will be printed by calling the showsyntaxerror() method. |
|
1486 | will be printed by calling the showsyntaxerror() method. | |
1487 |
|
1487 | |||
1488 | 2) The input is incomplete, and more input is required; |
|
1488 | 2) The input is incomplete, and more input is required; | |
1489 | compile_command() returned None. Nothing happens. |
|
1489 | compile_command() returned None. Nothing happens. | |
1490 |
|
1490 | |||
1491 | 3) The input is complete; compile_command() returned a code |
|
1491 | 3) The input is complete; compile_command() returned a code | |
1492 | object. The code is executed by calling self.runcode() (which |
|
1492 | object. The code is executed by calling self.runcode() (which | |
1493 | also handles run-time exceptions, except for SystemExit). |
|
1493 | also handles run-time exceptions, except for SystemExit). | |
1494 |
|
1494 | |||
1495 | The return value is: |
|
1495 | The return value is: | |
1496 |
|
1496 | |||
1497 | - True in case 2 |
|
1497 | - True in case 2 | |
1498 |
|
1498 | |||
1499 | - False in the other cases, unless an exception is raised, where |
|
1499 | - False in the other cases, unless an exception is raised, where | |
1500 | None is returned instead. This can be used by external callers to |
|
1500 | None is returned instead. This can be used by external callers to | |
1501 | know whether to continue feeding input or not. |
|
1501 | know whether to continue feeding input or not. | |
1502 |
|
1502 | |||
1503 | The return value can be used to decide whether to use sys.ps1 or |
|
1503 | The return value can be used to decide whether to use sys.ps1 or | |
1504 | sys.ps2 to prompt the next line.""" |
|
1504 | sys.ps2 to prompt the next line.""" | |
1505 |
|
1505 | |||
1506 | try: |
|
1506 | try: | |
1507 | code = self.compile(source,filename,symbol) |
|
1507 | code = self.compile(source,filename,symbol) | |
1508 | except (OverflowError, SyntaxError, ValueError): |
|
1508 | except (OverflowError, SyntaxError, ValueError): | |
1509 | # Case 1 |
|
1509 | # Case 1 | |
1510 | self.showsyntaxerror(filename) |
|
1510 | self.showsyntaxerror(filename) | |
1511 | return None |
|
1511 | return None | |
1512 |
|
1512 | |||
1513 | if code is None: |
|
1513 | if code is None: | |
1514 | # Case 2 |
|
1514 | # Case 2 | |
1515 | return True |
|
1515 | return True | |
1516 |
|
1516 | |||
1517 | # Case 3 |
|
1517 | # Case 3 | |
1518 | # We store the code object so that threaded shells and |
|
1518 | # We store the code object so that threaded shells and | |
1519 | # custom exception handlers can access all this info if needed. |
|
1519 | # custom exception handlers can access all this info if needed. | |
1520 | # The source corresponding to this can be obtained from the |
|
1520 | # The source corresponding to this can be obtained from the | |
1521 | # buffer attribute as '\n'.join(self.buffer). |
|
1521 | # buffer attribute as '\n'.join(self.buffer). | |
1522 | self.code_to_run = code |
|
1522 | self.code_to_run = code | |
1523 | # now actually execute the code object |
|
1523 | # now actually execute the code object | |
1524 | if self.runcode(code) == 0: |
|
1524 | if self.runcode(code) == 0: | |
1525 | return False |
|
1525 | return False | |
1526 | else: |
|
1526 | else: | |
1527 | return None |
|
1527 | return None | |
1528 |
|
1528 | |||
1529 | def runcode(self,code_obj): |
|
1529 | def runcode(self,code_obj): | |
1530 | """Execute a code object. |
|
1530 | """Execute a code object. | |
1531 |
|
1531 | |||
1532 | When an exception occurs, self.showtraceback() is called to display a |
|
1532 | When an exception occurs, self.showtraceback() is called to display a | |
1533 | traceback. |
|
1533 | traceback. | |
1534 |
|
1534 | |||
1535 | Return value: a flag indicating whether the code to be run completed |
|
1535 | Return value: a flag indicating whether the code to be run completed | |
1536 | successfully: |
|
1536 | successfully: | |
1537 |
|
1537 | |||
1538 | - 0: successful execution. |
|
1538 | - 0: successful execution. | |
1539 | - 1: an error occurred. |
|
1539 | - 1: an error occurred. | |
1540 | """ |
|
1540 | """ | |
1541 |
|
1541 | |||
1542 | # Set our own excepthook in case the user code tries to call it |
|
1542 | # Set our own excepthook in case the user code tries to call it | |
1543 | # directly, so that the IPython crash handler doesn't get triggered |
|
1543 | # directly, so that the IPython crash handler doesn't get triggered | |
1544 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1544 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
1545 |
|
1545 | |||
1546 | # we save the original sys.excepthook in the instance, in case config |
|
1546 | # we save the original sys.excepthook in the instance, in case config | |
1547 | # code (such as magics) needs access to it. |
|
1547 | # code (such as magics) needs access to it. | |
1548 | self.sys_excepthook = old_excepthook |
|
1548 | self.sys_excepthook = old_excepthook | |
1549 | outflag = 1 # happens in more places, so it's easier as default |
|
1549 | outflag = 1 # happens in more places, so it's easier as default | |
1550 | try: |
|
1550 | try: | |
1551 | try: |
|
1551 | try: | |
1552 | # Embedded instances require separate global/local namespaces |
|
1552 | # Embedded instances require separate global/local namespaces | |
1553 | # so they can see both the surrounding (local) namespace and |
|
1553 | # so they can see both the surrounding (local) namespace and | |
1554 | # the module-level globals when called inside another function. |
|
1554 | # the module-level globals when called inside another function. | |
1555 | if self.embedded: |
|
1555 | if self.embedded: | |
1556 | exec code_obj in self.user_global_ns, self.user_ns |
|
1556 | exec code_obj in self.user_global_ns, self.user_ns | |
1557 | # Normal (non-embedded) instances should only have a single |
|
1557 | # Normal (non-embedded) instances should only have a single | |
1558 | # namespace for user code execution, otherwise functions won't |
|
1558 | # namespace for user code execution, otherwise functions won't | |
1559 | # see interactive top-level globals. |
|
1559 | # see interactive top-level globals. | |
1560 | else: |
|
1560 | else: | |
1561 | exec code_obj in self.user_ns |
|
1561 | exec code_obj in self.user_ns | |
1562 | finally: |
|
1562 | finally: | |
1563 | # Reset our crash handler in place |
|
1563 | # Reset our crash handler in place | |
1564 | sys.excepthook = old_excepthook |
|
1564 | sys.excepthook = old_excepthook | |
1565 | except SystemExit: |
|
1565 | except SystemExit: | |
1566 | self.resetbuffer() |
|
1566 | self.resetbuffer() | |
1567 | self.showtraceback() |
|
1567 | self.showtraceback() | |
1568 | warn("Type exit or quit to exit IPython " |
|
1568 | warn("Type exit or quit to exit IPython " | |
1569 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
1569 | "(%Exit or %Quit do so unconditionally).",level=1) | |
1570 | except self.custom_exceptions: |
|
1570 | except self.custom_exceptions: | |
1571 | etype,value,tb = sys.exc_info() |
|
1571 | etype,value,tb = sys.exc_info() | |
1572 | self.CustomTB(etype,value,tb) |
|
1572 | self.CustomTB(etype,value,tb) | |
1573 | except: |
|
1573 | except: | |
1574 | self.showtraceback() |
|
1574 | self.showtraceback() | |
1575 | else: |
|
1575 | else: | |
1576 | outflag = 0 |
|
1576 | outflag = 0 | |
1577 | if softspace(sys.stdout, 0): |
|
1577 | if softspace(sys.stdout, 0): | |
1578 |
|
1578 | |||
1579 | # Flush out code object which has been run (and source) |
|
1579 | # Flush out code object which has been run (and source) | |
1580 | self.code_to_run = None |
|
1580 | self.code_to_run = None | |
1581 | return outflag |
|
1581 | return outflag | |
1582 |
|
1582 | |||
1583 | def push(self, line): |
|
1583 | def push(self, line): | |
1584 | """Push a line to the interpreter. |
|
1584 | """Push a line to the interpreter. | |
1585 |
|
1585 | |||
1586 | The line should not have a trailing newline; it may have |
|
1586 | The line should not have a trailing newline; it may have | |
1587 | internal newlines. The line is appended to a buffer and the |
|
1587 | internal newlines. The line is appended to a buffer and the | |
1588 | interpreter's runsource() method is called with the |
|
1588 | interpreter's runsource() method is called with the | |
1589 | concatenated contents of the buffer as source. If this |
|
1589 | concatenated contents of the buffer as source. If this | |
1590 | indicates that the command was executed or invalid, the buffer |
|
1590 | indicates that the command was executed or invalid, the buffer | |
1591 | is reset; otherwise, the command is incomplete, and the buffer |
|
1591 | is reset; otherwise, the command is incomplete, and the buffer | |
1592 | is left as it was after the line was appended. The return |
|
1592 | is left as it was after the line was appended. The return | |
1593 | value is 1 if more input is required, 0 if the line was dealt |
|
1593 | value is 1 if more input is required, 0 if the line was dealt | |
1594 | with in some way (this is the same as runsource()). |
|
1594 | with in some way (this is the same as runsource()). | |
1595 | """ |
|
1595 | """ | |
1596 |
|
1596 | |||
1597 | # autoindent management should be done here, and not in the |
|
1597 | # autoindent management should be done here, and not in the | |
1598 | # interactive loop, since that one is only seen by keyboard input. We |
|
1598 | # interactive loop, since that one is only seen by keyboard input. We | |
1599 | # need this done correctly even for code run via runlines (which uses |
|
1599 | # need this done correctly even for code run via runlines (which uses | |
1600 | # push). |
|
1600 | # push). | |
|
1601 | ||||
|
1602 | print 'push line: <%s>' % line # dbg | |||
1601 | self.autoindent_update(line) |
|
1603 | self.autoindent_update(line) | |
1602 |
|
1604 | |||
1603 | self.buffer.append(line) |
|
1605 | self.buffer.append(line) | |
1604 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
1606 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
1605 | if not more: |
|
1607 | if not more: | |
1606 | self.resetbuffer() |
|
1608 | self.resetbuffer() | |
1607 | return more |
|
1609 | return more | |
1608 |
|
1610 | |||
1609 | def resetbuffer(self): |
|
1611 | def resetbuffer(self): | |
1610 | """Reset the input buffer.""" |
|
1612 | """Reset the input buffer.""" | |
1611 | self.buffer[:] = [] |
|
1613 | self.buffer[:] = [] | |
1612 |
|
1614 | |||
1613 | def raw_input(self,prompt='',continue_prompt=False): |
|
1615 | def raw_input(self,prompt='',continue_prompt=False): | |
1614 | """Write a prompt and read a line. |
|
1616 | """Write a prompt and read a line. | |
1615 |
|
1617 | |||
1616 | The returned line does not include the trailing newline. |
|
1618 | The returned line does not include the trailing newline. | |
1617 | When the user enters the EOF key sequence, EOFError is raised. |
|
1619 | When the user enters the EOF key sequence, EOFError is raised. | |
1618 |
|
1620 | |||
1619 | Optional inputs: |
|
1621 | Optional inputs: | |
1620 |
|
1622 | |||
1621 | - prompt(''): a string to be printed to prompt the user. |
|
1623 | - prompt(''): a string to be printed to prompt the user. | |
1622 |
|
1624 | |||
1623 | - continue_prompt(False): whether this line is the first one or a |
|
1625 | - continue_prompt(False): whether this line is the first one or a | |
1624 | continuation in a sequence of inputs. |
|
1626 | continuation in a sequence of inputs. | |
1625 | """ |
|
1627 | """ | |
1626 |
|
1628 | |||
1627 | line = raw_input_original(prompt) |
|
1629 | line = raw_input_original(prompt) | |
1628 | # Try to be reasonably smart about not re-indenting pasted input more |
|
1630 | # Try to be reasonably smart about not re-indenting pasted input more | |
1629 | # than necessary. We do this by trimming out the auto-indent initial |
|
1631 | # than necessary. We do this by trimming out the auto-indent initial | |
1630 | # spaces, if the user's actual input started itself with whitespace. |
|
1632 | # spaces, if the user's actual input started itself with whitespace. | |
1631 | if self.autoindent: |
|
1633 | if self.autoindent: | |
1632 | line2 = line[self.indent_current_nsp:] |
|
1634 | line2 = line[self.indent_current_nsp:] | |
1633 | if line2[0:1] in (' ','\t'): |
|
1635 | if line2[0:1] in (' ','\t'): | |
1634 | line = line2 |
|
1636 | line = line2 | |
1635 | return self.prefilter(line,continue_prompt) |
|
1637 | return self.prefilter(line,continue_prompt) | |
1636 |
|
1638 | |||
1637 | def split_user_input(self,line): |
|
1639 | def split_user_input(self,line): | |
1638 | """Split user input into pre-char, function part and rest.""" |
|
1640 | """Split user input into pre-char, function part and rest.""" | |
1639 |
|
1641 | |||
1640 | lsplit = self.line_split.match(line) |
|
1642 | lsplit = self.line_split.match(line) | |
1641 | if lsplit is None: # no regexp match returns None |
|
1643 | if lsplit is None: # no regexp match returns None | |
1642 | try: |
|
1644 | try: | |
1643 | iFun,theRest = line.split(None,1) |
|
1645 | iFun,theRest = line.split(None,1) | |
1644 | except ValueError: |
|
1646 | except ValueError: | |
1645 | iFun,theRest = line,'' |
|
1647 | iFun,theRest = line,'' | |
1646 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
1648 | pre = re.match('^(\s*)(.*)',line).groups()[0] | |
1647 | else: |
|
1649 | else: | |
1648 | pre,iFun,theRest = lsplit.groups() |
|
1650 | pre,iFun,theRest = lsplit.groups() | |
1649 |
|
1651 | |||
1650 | #print 'line:<%s>' % line # dbg |
|
1652 | #print 'line:<%s>' % line # dbg | |
1651 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
1653 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg | |
1652 | return pre,iFun.strip(),theRest |
|
1654 | return pre,iFun.strip(),theRest | |
1653 |
|
1655 | |||
1654 | def _prefilter(self, line, continue_prompt): |
|
1656 | def _prefilter(self, line, continue_prompt): | |
1655 | """Calls different preprocessors, depending on the form of line.""" |
|
1657 | """Calls different preprocessors, depending on the form of line.""" | |
1656 |
|
1658 | |||
1657 | # All handlers *must* return a value, even if it's blank (''). |
|
1659 | # All handlers *must* return a value, even if it's blank (''). | |
1658 |
|
1660 | |||
1659 | # Lines are NOT logged here. Handlers should process the line as |
|
1661 | # Lines are NOT logged here. Handlers should process the line as | |
1660 | # needed, update the cache AND log it (so that the input cache array |
|
1662 | # needed, update the cache AND log it (so that the input cache array | |
1661 | # stays synced). |
|
1663 | # stays synced). | |
1662 |
|
1664 | |||
1663 | # This function is _very_ delicate, and since it's also the one which |
|
1665 | # This function is _very_ delicate, and since it's also the one which | |
1664 | # determines IPython's response to user input, it must be as efficient |
|
1666 | # determines IPython's response to user input, it must be as efficient | |
1665 | # as possible. For this reason it has _many_ returns in it, trying |
|
1667 | # as possible. For this reason it has _many_ returns in it, trying | |
1666 | # always to exit as quickly as it can figure out what it needs to do. |
|
1668 | # always to exit as quickly as it can figure out what it needs to do. | |
1667 |
|
1669 | |||
1668 | # This function is the main responsible for maintaining IPython's |
|
1670 | # This function is the main responsible for maintaining IPython's | |
1669 | # behavior respectful of Python's semantics. So be _very_ careful if |
|
1671 | # behavior respectful of Python's semantics. So be _very_ careful if | |
1670 | # making changes to anything here. |
|
1672 | # making changes to anything here. | |
1671 |
|
1673 | |||
1672 | #..................................................................... |
|
1674 | #..................................................................... | |
1673 | # Code begins |
|
1675 | # Code begins | |
1674 |
|
1676 | |||
1675 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
1677 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
1676 |
|
1678 | |||
1677 | # save the line away in case we crash, so the post-mortem handler can |
|
1679 | # save the line away in case we crash, so the post-mortem handler can | |
1678 | # record it |
|
1680 | # record it | |
1679 | self._last_input_line = line |
|
1681 | self._last_input_line = line | |
1680 |
|
1682 | |||
1681 | #print '***line: <%s>' % line # dbg |
|
1683 | #print '***line: <%s>' % line # dbg | |
1682 |
|
1684 | |||
1683 | # the input history needs to track even empty lines |
|
1685 | # the input history needs to track even empty lines | |
1684 | if not line.strip(): |
|
1686 | if not line.strip(): | |
1685 | if not continue_prompt: |
|
1687 | if not continue_prompt: | |
1686 | self.outputcache.prompt_count -= 1 |
|
1688 | self.outputcache.prompt_count -= 1 | |
1687 | return self.handle_normal(line,continue_prompt) |
|
1689 | return self.handle_normal(line,continue_prompt) | |
1688 | #return self.handle_normal('',continue_prompt) |
|
1690 | #return self.handle_normal('',continue_prompt) | |
1689 |
|
1691 | |||
1690 | # print '***cont',continue_prompt # dbg |
|
1692 | # print '***cont',continue_prompt # dbg | |
1691 | # special handlers are only allowed for single line statements |
|
1693 | # special handlers are only allowed for single line statements | |
1692 | if continue_prompt and not self.rc.multi_line_specials: |
|
1694 | if continue_prompt and not self.rc.multi_line_specials: | |
1693 | return self.handle_normal(line,continue_prompt) |
|
1695 | return self.handle_normal(line,continue_prompt) | |
1694 |
|
1696 | |||
1695 | # For the rest, we need the structure of the input |
|
1697 | # For the rest, we need the structure of the input | |
1696 | pre,iFun,theRest = self.split_user_input(line) |
|
1698 | pre,iFun,theRest = self.split_user_input(line) | |
1697 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1699 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
1698 |
|
1700 | |||
1699 | # First check for explicit escapes in the last/first character |
|
1701 | # First check for explicit escapes in the last/first character | |
1700 | handler = None |
|
1702 | handler = None | |
1701 | if line[-1] == self.ESC_HELP: |
|
1703 | if line[-1] == self.ESC_HELP: | |
1702 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end |
|
1704 | handler = self.esc_handlers.get(line[-1]) # the ? can be at the end | |
1703 | if handler is None: |
|
1705 | if handler is None: | |
1704 | # look at the first character of iFun, NOT of line, so we skip |
|
1706 | # look at the first character of iFun, NOT of line, so we skip | |
1705 | # leading whitespace in multiline input |
|
1707 | # leading whitespace in multiline input | |
1706 | handler = self.esc_handlers.get(iFun[0:1]) |
|
1708 | handler = self.esc_handlers.get(iFun[0:1]) | |
1707 | if handler is not None: |
|
1709 | if handler is not None: | |
1708 | return handler(line,continue_prompt,pre,iFun,theRest) |
|
1710 | return handler(line,continue_prompt,pre,iFun,theRest) | |
1709 | # Emacs ipython-mode tags certain input lines |
|
1711 | # Emacs ipython-mode tags certain input lines | |
1710 | if line.endswith('# PYTHON-MODE'): |
|
1712 | if line.endswith('# PYTHON-MODE'): | |
1711 | return self.handle_emacs(line,continue_prompt) |
|
1713 | return self.handle_emacs(line,continue_prompt) | |
1712 |
|
1714 | |||
1713 | # Next, check if we can automatically execute this thing |
|
1715 | # Next, check if we can automatically execute this thing | |
1714 |
|
1716 | |||
1715 | # Allow ! in multi-line statements if multi_line_specials is on: |
|
1717 | # Allow ! in multi-line statements if multi_line_specials is on: | |
1716 | if continue_prompt and self.rc.multi_line_specials and \ |
|
1718 | if continue_prompt and self.rc.multi_line_specials and \ | |
1717 | iFun.startswith(self.ESC_SHELL): |
|
1719 | iFun.startswith(self.ESC_SHELL): | |
1718 | return self.handle_shell_escape(line,continue_prompt, |
|
1720 | return self.handle_shell_escape(line,continue_prompt, | |
1719 | pre=pre,iFun=iFun, |
|
1721 | pre=pre,iFun=iFun, | |
1720 | theRest=theRest) |
|
1722 | theRest=theRest) | |
1721 |
|
1723 | |||
1722 | # Let's try to find if the input line is a magic fn |
|
1724 | # Let's try to find if the input line is a magic fn | |
1723 | oinfo = None |
|
1725 | oinfo = None | |
1724 | if hasattr(self,'magic_'+iFun): |
|
1726 | if hasattr(self,'magic_'+iFun): | |
1725 | # WARNING: _ofind uses getattr(), so it can consume generators and |
|
1727 | # WARNING: _ofind uses getattr(), so it can consume generators and | |
1726 | # cause other side effects. |
|
1728 | # cause other side effects. | |
1727 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1729 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
1728 | if oinfo['ismagic']: |
|
1730 | if oinfo['ismagic']: | |
1729 | # Be careful not to call magics when a variable assignment is |
|
1731 | # Be careful not to call magics when a variable assignment is | |
1730 | # being made (ls='hi', for example) |
|
1732 | # being made (ls='hi', for example) | |
1731 | if self.rc.automagic and \ |
|
1733 | if self.rc.automagic and \ | |
1732 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ |
|
1734 | (len(theRest)==0 or theRest[0] not in '!=()<>,') and \ | |
1733 | (self.rc.multi_line_specials or not continue_prompt): |
|
1735 | (self.rc.multi_line_specials or not continue_prompt): | |
1734 | return self.handle_magic(line,continue_prompt, |
|
1736 | return self.handle_magic(line,continue_prompt, | |
1735 | pre,iFun,theRest) |
|
1737 | pre,iFun,theRest) | |
1736 | else: |
|
1738 | else: | |
1737 | return self.handle_normal(line,continue_prompt) |
|
1739 | return self.handle_normal(line,continue_prompt) | |
1738 |
|
1740 | |||
1739 | # If the rest of the line begins with an (in)equality, assginment or |
|
1741 | # If the rest of the line begins with an (in)equality, assginment or | |
1740 | # function call, we should not call _ofind but simply execute it. |
|
1742 | # function call, we should not call _ofind but simply execute it. | |
1741 | # This avoids spurious geattr() accesses on objects upon assignment. |
|
1743 | # This avoids spurious geattr() accesses on objects upon assignment. | |
1742 | # |
|
1744 | # | |
1743 | # It also allows users to assign to either alias or magic names true |
|
1745 | # It also allows users to assign to either alias or magic names true | |
1744 | # python variables (the magic/alias systems always take second seat to |
|
1746 | # python variables (the magic/alias systems always take second seat to | |
1745 | # true python code). |
|
1747 | # true python code). | |
1746 | if theRest and theRest[0] in '!=()': |
|
1748 | if theRest and theRest[0] in '!=()': | |
1747 | return self.handle_normal(line,continue_prompt) |
|
1749 | return self.handle_normal(line,continue_prompt) | |
1748 |
|
1750 | |||
1749 | if oinfo is None: |
|
1751 | if oinfo is None: | |
1750 | # let's try to ensure that _oinfo is ONLY called when autocall is |
|
1752 | # let's try to ensure that _oinfo is ONLY called when autocall is | |
1751 | # on. Since it has inevitable potential side effects, at least |
|
1753 | # on. Since it has inevitable potential side effects, at least | |
1752 | # having autocall off should be a guarantee to the user that no |
|
1754 | # having autocall off should be a guarantee to the user that no | |
1753 | # weird things will happen. |
|
1755 | # weird things will happen. | |
1754 |
|
1756 | |||
1755 | if self.rc.autocall: |
|
1757 | if self.rc.autocall: | |
1756 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1758 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
1757 | else: |
|
1759 | else: | |
1758 | # in this case, all that's left is either an alias or |
|
1760 | # in this case, all that's left is either an alias or | |
1759 | # processing the line normally. |
|
1761 | # processing the line normally. | |
1760 | if iFun in self.alias_table: |
|
1762 | if iFun in self.alias_table: | |
1761 | return self.handle_alias(line,continue_prompt, |
|
1763 | return self.handle_alias(line,continue_prompt, | |
1762 | pre,iFun,theRest) |
|
1764 | pre,iFun,theRest) | |
1763 | else: |
|
1765 | else: | |
1764 | return self.handle_normal(line,continue_prompt) |
|
1766 | return self.handle_normal(line,continue_prompt) | |
1765 |
|
1767 | |||
1766 | if not oinfo['found']: |
|
1768 | if not oinfo['found']: | |
1767 | return self.handle_normal(line,continue_prompt) |
|
1769 | return self.handle_normal(line,continue_prompt) | |
1768 | else: |
|
1770 | else: | |
1769 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg |
|
1771 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg | |
1770 | if oinfo['isalias']: |
|
1772 | if oinfo['isalias']: | |
1771 | return self.handle_alias(line,continue_prompt, |
|
1773 | return self.handle_alias(line,continue_prompt, | |
1772 | pre,iFun,theRest) |
|
1774 | pre,iFun,theRest) | |
1773 |
|
1775 | |||
1774 | if self.rc.autocall and \ |
|
1776 | if self.rc.autocall and \ | |
1775 | not self.re_exclude_auto.match(theRest) and \ |
|
1777 | not self.re_exclude_auto.match(theRest) and \ | |
1776 | self.re_fun_name.match(iFun) and \ |
|
1778 | self.re_fun_name.match(iFun) and \ | |
1777 | callable(oinfo['obj']) : |
|
1779 | callable(oinfo['obj']) : | |
1778 | #print 'going auto' # dbg |
|
1780 | #print 'going auto' # dbg | |
1779 | return self.handle_auto(line,continue_prompt,pre,iFun,theRest) |
|
1781 | return self.handle_auto(line,continue_prompt,pre,iFun,theRest) | |
1780 | else: |
|
1782 | else: | |
1781 | #print 'was callable?', callable(oinfo['obj']) # dbg |
|
1783 | #print 'was callable?', callable(oinfo['obj']) # dbg | |
1782 | return self.handle_normal(line,continue_prompt) |
|
1784 | return self.handle_normal(line,continue_prompt) | |
1783 |
|
1785 | |||
1784 | # If we get here, we have a normal Python line. Log and return. |
|
1786 | # If we get here, we have a normal Python line. Log and return. | |
1785 | return self.handle_normal(line,continue_prompt) |
|
1787 | return self.handle_normal(line,continue_prompt) | |
1786 |
|
1788 | |||
1787 | def _prefilter_dumb(self, line, continue_prompt): |
|
1789 | def _prefilter_dumb(self, line, continue_prompt): | |
1788 | """simple prefilter function, for debugging""" |
|
1790 | """simple prefilter function, for debugging""" | |
1789 | return self.handle_normal(line,continue_prompt) |
|
1791 | return self.handle_normal(line,continue_prompt) | |
1790 |
|
1792 | |||
1791 | # Set the default prefilter() function (this can be user-overridden) |
|
1793 | # Set the default prefilter() function (this can be user-overridden) | |
1792 | prefilter = _prefilter |
|
1794 | prefilter = _prefilter | |
1793 |
|
1795 | |||
1794 | def handle_normal(self,line,continue_prompt=None, |
|
1796 | def handle_normal(self,line,continue_prompt=None, | |
1795 | pre=None,iFun=None,theRest=None): |
|
1797 | pre=None,iFun=None,theRest=None): | |
1796 | """Handle normal input lines. Use as a template for handlers.""" |
|
1798 | """Handle normal input lines. Use as a template for handlers.""" | |
1797 |
|
1799 | |||
1798 | # With autoindent on, we need some way to exit the input loop, and I |
|
1800 | # With autoindent on, we need some way to exit the input loop, and I | |
1799 | # don't want to force the user to have to backspace all the way to |
|
1801 | # don't want to force the user to have to backspace all the way to | |
1800 | # clear the line. The rule will be in this case, that either two |
|
1802 | # clear the line. The rule will be in this case, that either two | |
1801 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
1803 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
1802 | # of a size different to the indent level, will exit the input loop. |
|
1804 | # of a size different to the indent level, will exit the input loop. | |
1803 |
|
1805 | |||
1804 | if (continue_prompt and self.autoindent and isspace(line) and |
|
1806 | if (continue_prompt and self.autoindent and isspace(line) and | |
1805 | (line != self.indent_current or isspace(self.buffer[-1]))): |
|
1807 | (line != self.indent_current or isspace(self.buffer[-1]))): | |
1806 | line = '' |
|
1808 | line = '' | |
1807 |
|
1809 | |||
1808 | self.log(line,continue_prompt) |
|
1810 | self.log(line,continue_prompt) | |
1809 | return line |
|
1811 | return line | |
1810 |
|
1812 | |||
1811 | def handle_alias(self,line,continue_prompt=None, |
|
1813 | def handle_alias(self,line,continue_prompt=None, | |
1812 | pre=None,iFun=None,theRest=None): |
|
1814 | pre=None,iFun=None,theRest=None): | |
1813 | """Handle alias input lines. """ |
|
1815 | """Handle alias input lines. """ | |
1814 |
|
1816 | |||
1815 | line_out = 'ipalias("%s %s")' % (iFun,esc_quotes(theRest)) |
|
1817 | # pre is needed, because it carries the leading whitespace. Otherwise | |
|
1818 | # aliases won't work in indented sections. | |||
|
1819 | line_out = '%sipalias("%s %s")' % (pre,iFun,esc_quotes(theRest)) | |||
1816 | self.log(line_out,continue_prompt) |
|
1820 | self.log(line_out,continue_prompt) | |
1817 | return line_out |
|
1821 | return line_out | |
1818 |
|
1822 | |||
1819 | def handle_shell_escape(self, line, continue_prompt=None, |
|
1823 | def handle_shell_escape(self, line, continue_prompt=None, | |
1820 | pre=None,iFun=None,theRest=None): |
|
1824 | pre=None,iFun=None,theRest=None): | |
1821 | """Execute the line in a shell, empty return value""" |
|
1825 | """Execute the line in a shell, empty return value""" | |
1822 |
|
1826 | |||
1823 | #print 'line in :', `line` # dbg |
|
1827 | #print 'line in :', `line` # dbg | |
1824 | # Example of a special handler. Others follow a similar pattern. |
|
1828 | # Example of a special handler. Others follow a similar pattern. | |
1825 | if continue_prompt: # multi-line statements |
|
1829 | if continue_prompt: # multi-line statements | |
1826 | if iFun.startswith('!!'): |
|
1830 | if iFun.startswith('!!'): | |
1827 | print 'SyntaxError: !! is not allowed in multiline statements' |
|
1831 | print 'SyntaxError: !! is not allowed in multiline statements' | |
1828 | return pre |
|
1832 | return pre | |
1829 | else: |
|
1833 | else: | |
1830 | cmd = ("%s %s" % (iFun[1:],theRest)) |
|
1834 | cmd = ("%s %s" % (iFun[1:],theRest)) | |
1831 | line_out = 'ipsystem(r"""%s"""[:-1])' % (cmd + "_") |
|
1835 | line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd + "_") | |
1832 | else: # single-line input |
|
1836 | else: # single-line input | |
1833 | if line.startswith('!!'): |
|
1837 | if line.startswith('!!'): | |
1834 | # rewrite iFun/theRest to properly hold the call to %sx and |
|
1838 | # rewrite iFun/theRest to properly hold the call to %sx and | |
1835 | # the actual command to be executed, so handle_magic can work |
|
1839 | # the actual command to be executed, so handle_magic can work | |
1836 | # correctly |
|
1840 | # correctly | |
1837 | theRest = '%s %s' % (iFun[2:],theRest) |
|
1841 | theRest = '%s %s' % (iFun[2:],theRest) | |
1838 | iFun = 'sx' |
|
1842 | iFun = 'sx' | |
1839 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]), |
|
1843 | return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]), | |
1840 | continue_prompt,pre,iFun,theRest) |
|
1844 | continue_prompt,pre,iFun,theRest) | |
1841 | else: |
|
1845 | else: | |
1842 | cmd=line[1:] |
|
1846 | cmd=line[1:] | |
1843 | line_out = 'ipsystem(r"""%s"""[:-1])' % (cmd +"_") |
|
1847 | line_out = '%sipsystem(r"""%s"""[:-1])' % (pre,cmd +"_") | |
1844 | # update cache/log and return |
|
1848 | # update cache/log and return | |
1845 | self.log(line_out,continue_prompt) |
|
1849 | self.log(line_out,continue_prompt) | |
1846 | return line_out |
|
1850 | return line_out | |
1847 |
|
1851 | |||
1848 | def handle_magic(self, line, continue_prompt=None, |
|
1852 | def handle_magic(self, line, continue_prompt=None, | |
1849 | pre=None,iFun=None,theRest=None): |
|
1853 | pre=None,iFun=None,theRest=None): | |
1850 | """Execute magic functions. |
|
1854 | """Execute magic functions. | |
1851 |
|
1855 | |||
1852 | Also log them with a prepended # so the log is clean Python.""" |
|
1856 | Also log them with a prepended # so the log is clean Python.""" | |
1853 |
|
1857 | |||
1854 | cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest))) |
|
1858 | cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest))) | |
1855 | self.log(cmd,continue_prompt) |
|
1859 | self.log(cmd,continue_prompt) | |
1856 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
1860 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
1857 | return cmd |
|
1861 | return cmd | |
1858 |
|
1862 | |||
1859 | def handle_auto(self, line, continue_prompt=None, |
|
1863 | def handle_auto(self, line, continue_prompt=None, | |
1860 | pre=None,iFun=None,theRest=None): |
|
1864 | pre=None,iFun=None,theRest=None): | |
1861 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
1865 | """Hande lines which can be auto-executed, quoting if requested.""" | |
1862 |
|
1866 | |||
1863 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
1867 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
1864 |
|
1868 | |||
1865 | # This should only be active for single-line input! |
|
1869 | # This should only be active for single-line input! | |
1866 | if continue_prompt: |
|
1870 | if continue_prompt: | |
1867 | return line |
|
1871 | return line | |
1868 |
|
1872 | |||
1869 | if pre == self.ESC_QUOTE: |
|
1873 | if pre == self.ESC_QUOTE: | |
1870 | # Auto-quote splitting on whitespace |
|
1874 | # Auto-quote splitting on whitespace | |
1871 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
1875 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
1872 | elif pre == self.ESC_QUOTE2: |
|
1876 | elif pre == self.ESC_QUOTE2: | |
1873 | # Auto-quote whole string |
|
1877 | # Auto-quote whole string | |
1874 | newcmd = '%s("%s")' % (iFun,theRest) |
|
1878 | newcmd = '%s("%s")' % (iFun,theRest) | |
1875 | else: |
|
1879 | else: | |
1876 | # Auto-paren |
|
1880 | # Auto-paren | |
1877 | if theRest[0:1] in ('=','['): |
|
1881 | if theRest[0:1] in ('=','['): | |
1878 | # Don't autocall in these cases. They can be either |
|
1882 | # Don't autocall in these cases. They can be either | |
1879 | # rebindings of an existing callable's name, or item access |
|
1883 | # rebindings of an existing callable's name, or item access | |
1880 | # for an object which is BOTH callable and implements |
|
1884 | # for an object which is BOTH callable and implements | |
1881 | # __getitem__. |
|
1885 | # __getitem__. | |
1882 | return '%s %s' % (iFun,theRest) |
|
1886 | return '%s %s' % (iFun,theRest) | |
1883 | if theRest.endswith(';'): |
|
1887 | if theRest.endswith(';'): | |
1884 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
1888 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
1885 | else: |
|
1889 | else: | |
1886 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
1890 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
1887 |
|
1891 | |||
1888 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd |
|
1892 | print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd | |
1889 | # log what is now valid Python, not the actual user input (without the |
|
1893 | # log what is now valid Python, not the actual user input (without the | |
1890 | # final newline) |
|
1894 | # final newline) | |
1891 | self.log(newcmd,continue_prompt) |
|
1895 | self.log(newcmd,continue_prompt) | |
1892 | return newcmd |
|
1896 | return newcmd | |
1893 |
|
1897 | |||
1894 | def handle_help(self, line, continue_prompt=None, |
|
1898 | def handle_help(self, line, continue_prompt=None, | |
1895 | pre=None,iFun=None,theRest=None): |
|
1899 | pre=None,iFun=None,theRest=None): | |
1896 | """Try to get some help for the object. |
|
1900 | """Try to get some help for the object. | |
1897 |
|
1901 | |||
1898 | obj? or ?obj -> basic information. |
|
1902 | obj? or ?obj -> basic information. | |
1899 | obj?? or ??obj -> more details. |
|
1903 | obj?? or ??obj -> more details. | |
1900 | """ |
|
1904 | """ | |
1901 |
|
1905 | |||
1902 | # We need to make sure that we don't process lines which would be |
|
1906 | # We need to make sure that we don't process lines which would be | |
1903 | # otherwise valid python, such as "x=1 # what?" |
|
1907 | # otherwise valid python, such as "x=1 # what?" | |
1904 | try: |
|
1908 | try: | |
1905 | codeop.compile_command(line) |
|
1909 | codeop.compile_command(line) | |
1906 | except SyntaxError: |
|
1910 | except SyntaxError: | |
1907 | # We should only handle as help stuff which is NOT valid syntax |
|
1911 | # We should only handle as help stuff which is NOT valid syntax | |
1908 | if line[0]==self.ESC_HELP: |
|
1912 | if line[0]==self.ESC_HELP: | |
1909 | line = line[1:] |
|
1913 | line = line[1:] | |
1910 | elif line[-1]==self.ESC_HELP: |
|
1914 | elif line[-1]==self.ESC_HELP: | |
1911 | line = line[:-1] |
|
1915 | line = line[:-1] | |
1912 | self.log('#?'+line) |
|
1916 | self.log('#?'+line) | |
1913 | if line: |
|
1917 | if line: | |
1914 | self.magic_pinfo(line) |
|
1918 | self.magic_pinfo(line) | |
1915 | else: |
|
1919 | else: | |
1916 | page(self.usage,screen_lines=self.rc.screen_length) |
|
1920 | page(self.usage,screen_lines=self.rc.screen_length) | |
1917 | return '' # Empty string is needed here! |
|
1921 | return '' # Empty string is needed here! | |
1918 | except: |
|
1922 | except: | |
1919 | # Pass any other exceptions through to the normal handler |
|
1923 | # Pass any other exceptions through to the normal handler | |
1920 | return self.handle_normal(line,continue_prompt) |
|
1924 | return self.handle_normal(line,continue_prompt) | |
1921 | else: |
|
1925 | else: | |
1922 | # If the code compiles ok, we should handle it normally |
|
1926 | # If the code compiles ok, we should handle it normally | |
1923 | return self.handle_normal(line,continue_prompt) |
|
1927 | return self.handle_normal(line,continue_prompt) | |
1924 |
|
1928 | |||
1925 | def handle_emacs(self,line,continue_prompt=None, |
|
1929 | def handle_emacs(self,line,continue_prompt=None, | |
1926 | pre=None,iFun=None,theRest=None): |
|
1930 | pre=None,iFun=None,theRest=None): | |
1927 | """Handle input lines marked by python-mode.""" |
|
1931 | """Handle input lines marked by python-mode.""" | |
1928 |
|
1932 | |||
1929 | # Currently, nothing is done. Later more functionality can be added |
|
1933 | # Currently, nothing is done. Later more functionality can be added | |
1930 | # here if needed. |
|
1934 | # here if needed. | |
1931 |
|
1935 | |||
1932 | # The input cache shouldn't be updated |
|
1936 | # The input cache shouldn't be updated | |
1933 |
|
1937 | |||
1934 | return line |
|
1938 | return line | |
1935 |
|
1939 | |||
1936 | def write(self,data): |
|
1940 | def write(self,data): | |
1937 | """Write a string to the default output""" |
|
1941 | """Write a string to the default output""" | |
1938 | Term.cout.write(data) |
|
1942 | Term.cout.write(data) | |
1939 |
|
1943 | |||
1940 | def write_err(self,data): |
|
1944 | def write_err(self,data): | |
1941 | """Write a string to the default error output""" |
|
1945 | """Write a string to the default error output""" | |
1942 | Term.cerr.write(data) |
|
1946 | Term.cerr.write(data) | |
1943 |
|
1947 | |||
1944 | def exit(self): |
|
1948 | def exit(self): | |
1945 | """Handle interactive exit. |
|
1949 | """Handle interactive exit. | |
1946 |
|
1950 | |||
1947 | This method sets the exit_now attribute.""" |
|
1951 | This method sets the exit_now attribute.""" | |
1948 |
|
1952 | |||
1949 | if self.rc.confirm_exit: |
|
1953 | if self.rc.confirm_exit: | |
1950 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
1954 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
1951 | self.exit_now = True |
|
1955 | self.exit_now = True | |
1952 | else: |
|
1956 | else: | |
1953 | self.exit_now = True |
|
1957 | self.exit_now = True | |
1954 | return self.exit_now |
|
1958 | return self.exit_now | |
1955 |
|
1959 | |||
1956 | def safe_execfile(self,fname,*where,**kw): |
|
1960 | def safe_execfile(self,fname,*where,**kw): | |
1957 | fname = os.path.expanduser(fname) |
|
1961 | fname = os.path.expanduser(fname) | |
1958 |
|
1962 | |||
1959 | # find things also in current directory |
|
1963 | # find things also in current directory | |
1960 | dname = os.path.dirname(fname) |
|
1964 | dname = os.path.dirname(fname) | |
1961 | if not sys.path.count(dname): |
|
1965 | if not sys.path.count(dname): | |
1962 | sys.path.append(dname) |
|
1966 | sys.path.append(dname) | |
1963 |
|
1967 | |||
1964 | try: |
|
1968 | try: | |
1965 | xfile = open(fname) |
|
1969 | xfile = open(fname) | |
1966 | except: |
|
1970 | except: | |
1967 | print >> Term.cerr, \ |
|
1971 | print >> Term.cerr, \ | |
1968 | 'Could not open file <%s> for safe execution.' % fname |
|
1972 | 'Could not open file <%s> for safe execution.' % fname | |
1969 | return None |
|
1973 | return None | |
1970 |
|
1974 | |||
1971 | kw.setdefault('islog',0) |
|
1975 | kw.setdefault('islog',0) | |
1972 | kw.setdefault('quiet',1) |
|
1976 | kw.setdefault('quiet',1) | |
1973 | kw.setdefault('exit_ignore',0) |
|
1977 | kw.setdefault('exit_ignore',0) | |
1974 | first = xfile.readline() |
|
1978 | first = xfile.readline() | |
1975 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
1979 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
1976 | xfile.close() |
|
1980 | xfile.close() | |
1977 | # line by line execution |
|
1981 | # line by line execution | |
1978 | if first.startswith(loghead) or kw['islog']: |
|
1982 | if first.startswith(loghead) or kw['islog']: | |
1979 | print 'Loading log file <%s> one line at a time...' % fname |
|
1983 | print 'Loading log file <%s> one line at a time...' % fname | |
1980 | if kw['quiet']: |
|
1984 | if kw['quiet']: | |
1981 | stdout_save = sys.stdout |
|
1985 | stdout_save = sys.stdout | |
1982 | sys.stdout = StringIO.StringIO() |
|
1986 | sys.stdout = StringIO.StringIO() | |
1983 | try: |
|
1987 | try: | |
1984 | globs,locs = where[0:2] |
|
1988 | globs,locs = where[0:2] | |
1985 | except: |
|
1989 | except: | |
1986 | try: |
|
1990 | try: | |
1987 | globs = locs = where[0] |
|
1991 | globs = locs = where[0] | |
1988 | except: |
|
1992 | except: | |
1989 | globs = locs = globals() |
|
1993 | globs = locs = globals() | |
1990 | badblocks = [] |
|
1994 | badblocks = [] | |
1991 |
|
1995 | |||
1992 | # we also need to identify indented blocks of code when replaying |
|
1996 | # we also need to identify indented blocks of code when replaying | |
1993 | # logs and put them together before passing them to an exec |
|
1997 | # logs and put them together before passing them to an exec | |
1994 | # statement. This takes a bit of regexp and look-ahead work in the |
|
1998 | # statement. This takes a bit of regexp and look-ahead work in the | |
1995 | # file. It's easiest if we swallow the whole thing in memory |
|
1999 | # file. It's easiest if we swallow the whole thing in memory | |
1996 | # first, and manually walk through the lines list moving the |
|
2000 | # first, and manually walk through the lines list moving the | |
1997 | # counter ourselves. |
|
2001 | # counter ourselves. | |
1998 | indent_re = re.compile('\s+\S') |
|
2002 | indent_re = re.compile('\s+\S') | |
1999 | xfile = open(fname) |
|
2003 | xfile = open(fname) | |
2000 | filelines = xfile.readlines() |
|
2004 | filelines = xfile.readlines() | |
2001 | xfile.close() |
|
2005 | xfile.close() | |
2002 | nlines = len(filelines) |
|
2006 | nlines = len(filelines) | |
2003 | lnum = 0 |
|
2007 | lnum = 0 | |
2004 | while lnum < nlines: |
|
2008 | while lnum < nlines: | |
2005 | line = filelines[lnum] |
|
2009 | line = filelines[lnum] | |
2006 | lnum += 1 |
|
2010 | lnum += 1 | |
2007 | # don't re-insert logger status info into cache |
|
2011 | # don't re-insert logger status info into cache | |
2008 | if line.startswith('#log#'): |
|
2012 | if line.startswith('#log#'): | |
2009 | continue |
|
2013 | continue | |
2010 | else: |
|
2014 | else: | |
2011 | # build a block of code (maybe a single line) for execution |
|
2015 | # build a block of code (maybe a single line) for execution | |
2012 | block = line |
|
2016 | block = line | |
2013 | try: |
|
2017 | try: | |
2014 | next = filelines[lnum] # lnum has already incremented |
|
2018 | next = filelines[lnum] # lnum has already incremented | |
2015 | except: |
|
2019 | except: | |
2016 | next = None |
|
2020 | next = None | |
2017 | while next and indent_re.match(next): |
|
2021 | while next and indent_re.match(next): | |
2018 | block += next |
|
2022 | block += next | |
2019 | lnum += 1 |
|
2023 | lnum += 1 | |
2020 | try: |
|
2024 | try: | |
2021 | next = filelines[lnum] |
|
2025 | next = filelines[lnum] | |
2022 | except: |
|
2026 | except: | |
2023 | next = None |
|
2027 | next = None | |
2024 | # now execute the block of one or more lines |
|
2028 | # now execute the block of one or more lines | |
2025 | try: |
|
2029 | try: | |
2026 | exec block in globs,locs |
|
2030 | exec block in globs,locs | |
2027 | except SystemExit: |
|
2031 | except SystemExit: | |
2028 | pass |
|
2032 | pass | |
2029 | except: |
|
2033 | except: | |
2030 | badblocks.append(block.rstrip()) |
|
2034 | badblocks.append(block.rstrip()) | |
2031 | if kw['quiet']: # restore stdout |
|
2035 | if kw['quiet']: # restore stdout | |
2032 | sys.stdout.close() |
|
2036 | sys.stdout.close() | |
2033 | sys.stdout = stdout_save |
|
2037 | sys.stdout = stdout_save | |
2034 | print 'Finished replaying log file <%s>' % fname |
|
2038 | print 'Finished replaying log file <%s>' % fname | |
2035 | if badblocks: |
|
2039 | if badblocks: | |
2036 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2040 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2037 | '<%s> reported errors:' % fname) |
|
2041 | '<%s> reported errors:' % fname) | |
2038 |
|
2042 | |||
2039 | for badline in badblocks: |
|
2043 | for badline in badblocks: | |
2040 | print >> sys.stderr, badline |
|
2044 | print >> sys.stderr, badline | |
2041 | else: # regular file execution |
|
2045 | else: # regular file execution | |
2042 | try: |
|
2046 | try: | |
2043 | execfile(fname,*where) |
|
2047 | execfile(fname,*where) | |
2044 | except SyntaxError: |
|
2048 | except SyntaxError: | |
2045 | etype,evalue = sys.exc_info()[:2] |
|
2049 | etype,evalue = sys.exc_info()[:2] | |
2046 | self.SyntaxTB(etype,evalue,[]) |
|
2050 | self.SyntaxTB(etype,evalue,[]) | |
2047 | warn('Failure executing file: <%s>' % fname) |
|
2051 | warn('Failure executing file: <%s>' % fname) | |
2048 | except SystemExit,status: |
|
2052 | except SystemExit,status: | |
2049 | if not kw['exit_ignore']: |
|
2053 | if not kw['exit_ignore']: | |
2050 | self.InteractiveTB() |
|
2054 | self.InteractiveTB() | |
2051 | warn('Failure executing file: <%s>' % fname) |
|
2055 | warn('Failure executing file: <%s>' % fname) | |
2052 | except: |
|
2056 | except: | |
2053 | self.InteractiveTB() |
|
2057 | self.InteractiveTB() | |
2054 | warn('Failure executing file: <%s>' % fname) |
|
2058 | warn('Failure executing file: <%s>' % fname) | |
2055 |
|
2059 | |||
2056 | #************************* end of file <iplib.py> ***************************** |
|
2060 | #************************* end of file <iplib.py> ***************************** |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
@@ -1,1345 +1,1358 b'' | |||||
1 | #LyX 1.3 created this file. For more info see http://www.lyx.org/ |
|
1 | #LyX 1.3 created this file. For more info see http://www.lyx.org/ | |
2 | \lyxformat 221 |
|
2 | \lyxformat 221 | |
3 | \textclass article |
|
3 | \textclass article | |
4 | \begin_preamble |
|
4 | \begin_preamble | |
5 | \usepackage{ae,aecompl} |
|
5 | \usepackage{ae,aecompl} | |
6 | \usepackage{hyperref} |
|
6 | \usepackage{hyperref} | |
7 | \usepackage{html} |
|
7 | \usepackage{html} | |
8 | \end_preamble |
|
8 | \end_preamble | |
9 | \language english |
|
9 | \language english | |
10 | \inputencoding auto |
|
10 | \inputencoding auto | |
11 | \fontscheme default |
|
11 | \fontscheme default | |
12 | \graphics default |
|
12 | \graphics default | |
13 | \paperfontsize default |
|
13 | \paperfontsize default | |
14 | \spacing single |
|
14 | \spacing single | |
15 | \papersize Default |
|
15 | \papersize Default | |
16 | \paperpackage a4 |
|
16 | \paperpackage a4 | |
17 | \use_geometry 1 |
|
17 | \use_geometry 1 | |
18 | \use_amsmath 0 |
|
18 | \use_amsmath 0 | |
19 | \use_natbib 0 |
|
19 | \use_natbib 0 | |
20 | \use_numerical_citations 0 |
|
20 | \use_numerical_citations 0 | |
21 | \paperorientation portrait |
|
21 | \paperorientation portrait | |
22 | \leftmargin 1.25in |
|
22 | \leftmargin 1.25in | |
23 | \topmargin 1in |
|
23 | \topmargin 1in | |
24 | \rightmargin 1.25in |
|
24 | \rightmargin 1.25in | |
25 | \bottommargin 1in |
|
25 | \bottommargin 1in | |
26 | \secnumdepth 3 |
|
26 | \secnumdepth 3 | |
27 | \tocdepth 3 |
|
27 | \tocdepth 3 | |
28 | \paragraph_separation skip |
|
28 | \paragraph_separation skip | |
29 | \defskip medskip |
|
29 | \defskip medskip | |
30 | \quotes_language english |
|
30 | \quotes_language english | |
31 | \quotes_times 2 |
|
31 | \quotes_times 2 | |
32 | \papercolumns 1 |
|
32 | \papercolumns 1 | |
33 | \papersides 1 |
|
33 | \papersides 1 | |
34 | \paperpagestyle default |
|
34 | \paperpagestyle default | |
35 |
|
35 | |||
36 | \layout Title |
|
36 | \layout Title | |
37 |
|
37 | |||
38 | IPython |
|
38 | IPython | |
39 | \newline |
|
39 | \newline | |
40 |
|
40 | |||
41 | \size larger |
|
41 | \size larger | |
42 | New design notes |
|
42 | New design notes | |
43 | \layout Author |
|
43 | \layout Author | |
44 |
|
44 | |||
45 | Fernando PοΏ½rez |
|
45 | Fernando PοΏ½rez | |
46 | \layout Section |
|
46 | \layout Section | |
47 |
|
47 | |||
48 | Introduction |
|
48 | Introduction | |
49 | \layout Standard |
|
49 | \layout Standard | |
50 |
|
50 | |||
51 | This is a draft document with notes and ideas for the IPython rewrite. |
|
51 | This is a draft document with notes and ideas for the IPython rewrite. | |
52 | The section order and structure of this document roughly reflects in which |
|
52 | The section order and structure of this document roughly reflects in which | |
53 | order things should be done and what the dependencies are. |
|
53 | order things should be done and what the dependencies are. | |
54 | This document is mainly a draft for developers, a pdf version is provided |
|
54 | This document is mainly a draft for developers, a pdf version is provided | |
55 | with the standard distribution in case regular users are interested and |
|
55 | with the standard distribution in case regular users are interested and | |
56 | wish to contribute ideas. |
|
56 | wish to contribute ideas. | |
57 | \layout Standard |
|
57 | \layout Standard | |
58 |
|
58 | |||
59 | A tentative plan for the future: |
|
59 | A tentative plan for the future: | |
60 | \layout Itemize |
|
60 | \layout Itemize | |
61 |
|
61 | |||
62 | 0.6.x series: in practice, enough people are using IPython for real work that |
|
62 | 0.6.x series: in practice, enough people are using IPython for real work that | |
63 | I think it warrants a higher number. |
|
63 | I think it warrants a higher number. | |
64 | This series will continue to evolve with bugfixes and incremental improvements. |
|
64 | This series will continue to evolve with bugfixes and incremental improvements. | |
65 | \layout Itemize |
|
65 | \layout Itemize | |
66 |
|
66 | |||
67 | 0.7.x series: (maybe) If resources allow, there may be a branch for 'unstable' |
|
67 | 0.7.x series: (maybe) If resources allow, there may be a branch for 'unstable' | |
68 | development, where the architectural rewrite may take place. |
|
68 | development, where the architectural rewrite may take place. | |
69 | \layout Standard |
|
69 | \layout Standard | |
70 |
|
70 | |||
71 | However, I am starting to doubt it is feasible to keep two separate branches. |
|
71 | However, I am starting to doubt it is feasible to keep two separate branches. | |
72 | I am leaning more towards a |
|
72 | I am leaning more towards a | |
73 | \begin_inset ERT |
|
73 | \begin_inset ERT | |
74 | status Collapsed |
|
74 | status Collapsed | |
75 |
|
75 | |||
76 | \layout Standard |
|
76 | \layout Standard | |
77 |
|
77 | |||
78 | \backslash |
|
78 | \backslash | |
79 | LyX |
|
79 | LyX | |
80 | \end_inset |
|
80 | \end_inset | |
81 |
|
81 | |||
82 | -like approach, where the main branch slowly transforms and evolves. |
|
82 | -like approach, where the main branch slowly transforms and evolves. | |
83 | Having CVS support now makes this a reasonable alternative, as I don't |
|
83 | Having CVS support now makes this a reasonable alternative, as I don't | |
84 | have to make pre-releases as often. |
|
84 | have to make pre-releases as often. | |
85 | The active branch can remain the mainline of development, and users interested |
|
85 | The active branch can remain the mainline of development, and users interested | |
86 | in the bleeding-edge stuff can always grab the CVS code. |
|
86 | in the bleeding-edge stuff can always grab the CVS code. | |
87 | \layout Standard |
|
87 | \layout Standard | |
88 |
|
88 | |||
89 | Ideally, IPython should have a clean class setup that would allow further |
|
89 | Ideally, IPython should have a clean class setup that would allow further | |
90 | extensions for special-purpose systems. |
|
90 | extensions for special-purpose systems. | |
91 | I view IPython as a base system that provides a great interactive environment |
|
91 | I view IPython as a base system that provides a great interactive environment | |
92 | with full access to the Python language, and which could be used in many |
|
92 | with full access to the Python language, and which could be used in many | |
93 | different contexts. |
|
93 | different contexts. | |
94 | The basic hooks are there: the magic extension syntax and the flexible |
|
94 | The basic hooks are there: the magic extension syntax and the flexible | |
95 | system of recursive configuration files and profiles. |
|
95 | system of recursive configuration files and profiles. | |
96 | But with a code as messy as the current one, nobody is going to touch it. |
|
96 | But with a code as messy as the current one, nobody is going to touch it. | |
97 | \layout Section |
|
97 | \layout Section | |
98 |
|
98 | |||
99 | Immediate TODO and bug list |
|
99 | Immediate TODO and bug list | |
100 | \layout Standard |
|
100 | \layout Standard | |
101 |
|
101 | |||
102 | Things that should be done for the current series, before starting major |
|
102 | Things that should be done for the current series, before starting major | |
103 | changes. |
|
103 | changes. | |
104 | \layout Itemize |
|
104 | \layout Itemize | |
105 |
|
105 | |||
106 | Fix any bugs reported at the online bug tracker. |
|
106 | Fix any bugs reported at the online bug tracker. | |
107 | \layout Itemize |
|
107 | \layout Itemize | |
108 |
|
108 | |||
|
109 | History bug: I often see that, under certain circumstances, the input history | |||
|
110 | is incorrect. | |||
|
111 | The problem is that so far, I've failed to find a simple way to reproduce | |||
|
112 | it consistently, so I can't easily track it down. | |||
|
113 | It seems to me that it happens when output is generated multiple times | |||
|
114 | for the same input (for i in range(10): i will do it). | |||
|
115 | But even this isn't reliable... | |||
|
116 | Ultimately the right solution for this is to cleanly separate the dataflow | |||
|
117 | for input/output history management; right now that happens all over the | |||
|
118 | place, which makes the code impossible to debug, and almost guaranteed | |||
|
119 | to be buggy in the first place. | |||
|
120 | \layout Itemize | |||
|
121 | ||||
109 |
|
122 | |||
110 | \series bold |
|
123 | \series bold | |
111 | Redesign the output traps. |
|
124 | Redesign the output traps. | |
112 |
|
125 | |||
113 | \series default |
|
126 | \series default | |
114 | They cause problems when users try to execute code which relies on sys.stdout |
|
127 | They cause problems when users try to execute code which relies on sys.stdout | |
115 | being the 'true' sys.stdout. |
|
128 | being the 'true' sys.stdout. | |
116 | They also prevent scripts which use raw_input() to work as command-line |
|
129 | They also prevent scripts which use raw_input() to work as command-line | |
117 | arguments. |
|
130 | arguments. | |
118 | \newline |
|
131 | \newline | |
119 | The best solution is probably to print the banner first, and then just execute |
|
132 | The best solution is probably to print the banner first, and then just execute | |
120 | all the user code straight with no output traps at all. |
|
133 | all the user code straight with no output traps at all. | |
121 | Whatever comes out comes out. |
|
134 | Whatever comes out comes out. | |
122 | This makes the ipython code actually simpler, and eliminates the problem |
|
135 | This makes the ipython code actually simpler, and eliminates the problem | |
123 | altogether. |
|
136 | altogether. | |
124 | \newline |
|
137 | \newline | |
125 | These things need to be ripped out, they cause no end of problems. |
|
138 | These things need to be ripped out, they cause no end of problems. | |
126 | For example, if user code requires acces to stdin during startup, the process |
|
139 | For example, if user code requires acces to stdin during startup, the process | |
127 | just hangs indefinitely. |
|
140 | just hangs indefinitely. | |
128 | For now I've just disabled them, and I'll live with the ugly error messages. |
|
141 | For now I've just disabled them, and I'll live with the ugly error messages. | |
129 | \layout Itemize |
|
142 | \layout Itemize | |
130 |
|
143 | |||
131 | The prompt specials dictionary should be turned into a class which does |
|
144 | The prompt specials dictionary should be turned into a class which does | |
132 | proper namespace management, since the prompt specials need to be evaluated |
|
145 | proper namespace management, since the prompt specials need to be evaluated | |
133 | in a certain namespace. |
|
146 | in a certain namespace. | |
134 | Currently it's just globals, which need to be managed manually by code |
|
147 | Currently it's just globals, which need to be managed manually by code | |
135 | below. |
|
148 | below. | |
136 |
|
149 | |||
137 | \layout Itemize |
|
150 | \layout Itemize | |
138 |
|
151 | |||
139 | Fix coloring of prompts: the pysh color strings don't have any effect on |
|
152 | Fix coloring of prompts: the pysh color strings don't have any effect on | |
140 | prompt numbers, b/c these are controlled by the global scheme. |
|
153 | prompt numbers, b/c these are controlled by the global scheme. | |
141 | Make the prompts fully user-definable, colors and all. |
|
154 | Make the prompts fully user-definable, colors and all. | |
142 | This is what I said to a user: |
|
155 | This is what I said to a user: | |
143 | \newline |
|
156 | \newline | |
144 | As far as the green |
|
157 | As far as the green | |
145 | \backslash |
|
158 | \backslash | |
146 | #, this is a minor bug of the coloring code due to the vagaries of history. |
|
159 | #, this is a minor bug of the coloring code due to the vagaries of history. | |
147 | While the color strings allow you to control the coloring of most elements, |
|
160 | While the color strings allow you to control the coloring of most elements, | |
148 | there are a few which are still controlled by the old ipython internal |
|
161 | there are a few which are still controlled by the old ipython internal | |
149 | coloring code, which only accepts a global 'color scheme' choice. |
|
162 | coloring code, which only accepts a global 'color scheme' choice. | |
150 | So basically the input/output numbers are hardwired to the choice in the |
|
163 | So basically the input/output numbers are hardwired to the choice in the | |
151 | color scheme, and there are only 'Linux', 'LightBG' and 'NoColor' schemes |
|
164 | color scheme, and there are only 'Linux', 'LightBG' and 'NoColor' schemes | |
152 | to choose from. |
|
165 | to choose from. | |
153 |
|
166 | |||
154 | \layout Itemize |
|
167 | \layout Itemize | |
155 |
|
168 | |||
156 | Clean up FakeModule issues. |
|
169 | Clean up FakeModule issues. | |
157 | Currently, unittesting with embedded ipython breaks because a FakeModule |
|
170 | Currently, unittesting with embedded ipython breaks because a FakeModule | |
158 | instance overwrites __main__. |
|
171 | instance overwrites __main__. | |
159 | Maybe ipython should revert back to using __main__ directly as the user |
|
172 | Maybe ipython should revert back to using __main__ directly as the user | |
160 | namespace? Handling a separate namespace is proving |
|
173 | namespace? Handling a separate namespace is proving | |
161 | \emph on |
|
174 | \emph on | |
162 | very |
|
175 | very | |
163 | \emph default |
|
176 | \emph default | |
164 | tricky in all corner cases. |
|
177 | tricky in all corner cases. | |
165 | \layout Itemize |
|
178 | \layout Itemize | |
166 |
|
179 | |||
167 | Make the output cache depth independent of the input one. |
|
180 | Make the output cache depth independent of the input one. | |
168 | This way one can have say only the last 10 results stored and still have |
|
181 | This way one can have say only the last 10 results stored and still have | |
169 | a long input history/cache. |
|
182 | a long input history/cache. | |
170 | \layout Itemize |
|
183 | \layout Itemize | |
171 |
|
184 | |||
172 | Fix the fact that importing a shell for embedding screws up the command-line |
|
185 | Fix the fact that importing a shell for embedding screws up the command-line | |
173 | history. |
|
186 | history. | |
174 | This can be done by not importing the history file when the shell is already |
|
187 | This can be done by not importing the history file when the shell is already | |
175 | inside ipython. |
|
188 | inside ipython. | |
176 | \layout Itemize |
|
189 | \layout Itemize | |
177 |
|
190 | |||
178 | Lay out the class structure so that embedding into a gtk/wx/qt app is trivial, |
|
191 | Lay out the class structure so that embedding into a gtk/wx/qt app is trivial, | |
179 | much like the multithreaded gui shells now provide command-line coexistence |
|
192 | much like the multithreaded gui shells now provide command-line coexistence | |
180 | with the gui toolkits. |
|
193 | with the gui toolkits. | |
181 | See |
|
194 | See | |
182 | \begin_inset LatexCommand \url{http://www.livejournal.com/users/glyf/32396.html} |
|
195 | \begin_inset LatexCommand \url{http://www.livejournal.com/users/glyf/32396.html} | |
183 |
|
196 | |||
184 | \end_inset |
|
197 | \end_inset | |
185 |
|
198 | |||
186 |
|
199 | |||
187 | \layout Itemize |
|
200 | \layout Itemize | |
188 |
|
201 | |||
189 | Get Holger's completer in, once he adds filename completion. |
|
202 | Get Holger's completer in, once he adds filename completion. | |
190 | \layout Standard |
|
203 | \layout Standard | |
191 |
|
204 | |||
192 | Lower priority stuff: |
|
205 | Lower priority stuff: | |
193 | \layout Itemize |
|
206 | \layout Itemize | |
194 |
|
207 | |||
195 | Add @showopt/@setopt (decide name) for viewing/setting all options. |
|
208 | Add @showopt/@setopt (decide name) for viewing/setting all options. | |
196 | The existing option-setting magics should become aliases for setopt calls. |
|
209 | The existing option-setting magics should become aliases for setopt calls. | |
197 | \layout Itemize |
|
210 | \layout Itemize | |
198 |
|
211 | |||
199 | It would be nice to be able to continue with python stuff after an @ command. |
|
212 | It would be nice to be able to continue with python stuff after an @ command. | |
200 | For instance "@run something; test_stuff()" in order to test stuff even |
|
213 | For instance "@run something; test_stuff()" in order to test stuff even | |
201 | faster. |
|
214 | faster. | |
202 | Suggestion by Kasper Souren <Kasper.Souren@ircam.fr> |
|
215 | Suggestion by Kasper Souren <Kasper.Souren@ircam.fr> | |
203 | \layout Itemize |
|
216 | \layout Itemize | |
204 |
|
217 | |||
205 | Run a 'first time wizard' which configures a few things for the user, such |
|
218 | Run a 'first time wizard' which configures a few things for the user, such | |
206 | as color_info, editor and the like. |
|
219 | as color_info, editor and the like. | |
207 | \layout Itemize |
|
220 | \layout Itemize | |
208 |
|
221 | |||
209 | Logging: @logstart and -log should start logfiles in ~.ipython, but with |
|
222 | Logging: @logstart and -log should start logfiles in ~.ipython, but with | |
210 | unique names in case of collisions. |
|
223 | unique names in case of collisions. | |
211 | This would prevent ipython.log files all over while also allowing multiple |
|
224 | This would prevent ipython.log files all over while also allowing multiple | |
212 | sessions. |
|
225 | sessions. | |
213 | Also the -log option should take an optional filename, instead of having |
|
226 | Also the -log option should take an optional filename, instead of having | |
214 | a separate -logfile option. |
|
227 | a separate -logfile option. | |
215 | \newline |
|
228 | \newline | |
216 | In general the logging system needs a serious cleanup. |
|
229 | In general the logging system needs a serious cleanup. | |
217 | Many functions now in Magic should be moved to Logger, and the magic @s |
|
230 | Many functions now in Magic should be moved to Logger, and the magic @s | |
218 | should be very simple wrappers to the Logger methods. |
|
231 | should be very simple wrappers to the Logger methods. | |
219 | \layout Section |
|
232 | \layout Section | |
220 |
|
233 | |||
221 | Lighten the code |
|
234 | Lighten the code | |
222 | \layout Standard |
|
235 | \layout Standard | |
223 |
|
236 | |||
224 | If we decide to base future versions of IPython on Python 2.3, which has |
|
237 | If we decide to base future versions of IPython on Python 2.3, which has | |
225 | the new Optik module (called optparse), it should be possible to drop DPyGetOpt. |
|
238 | the new Optik module (called optparse), it should be possible to drop DPyGetOpt. | |
226 | We should also remove the need for Itpl. |
|
239 | We should also remove the need for Itpl. | |
227 | Another area for trimming is the Gnuplot stuff: much of that could be merged |
|
240 | Another area for trimming is the Gnuplot stuff: much of that could be merged | |
228 | into the mainline project. |
|
241 | into the mainline project. | |
229 | \layout Standard |
|
242 | \layout Standard | |
230 |
|
243 | |||
231 | Double check whether we really need FlexCompleter. |
|
244 | Double check whether we really need FlexCompleter. | |
232 | This was written as an enhanced rlcompleter, but my patches went in for |
|
245 | This was written as an enhanced rlcompleter, but my patches went in for | |
233 | python 2.2 (or 2.3, can't remember). |
|
246 | python 2.2 (or 2.3, can't remember). | |
234 | \layout Standard |
|
247 | \layout Standard | |
235 |
|
248 | |||
236 | With these changes we could shed a fair bit of code from the main trunk. |
|
249 | With these changes we could shed a fair bit of code from the main trunk. | |
237 | \layout Section |
|
250 | \layout Section | |
238 |
|
251 | |||
239 | Unit testing |
|
252 | Unit testing | |
240 | \layout Standard |
|
253 | \layout Standard | |
241 |
|
254 | |||
242 | All new code should use a testing framework. |
|
255 | All new code should use a testing framework. | |
243 | Python seems to have very good testing facilities, I just need to learn |
|
256 | Python seems to have very good testing facilities, I just need to learn | |
244 | how to use them. |
|
257 | how to use them. | |
245 | I should also check out QMTest at |
|
258 | I should also check out QMTest at | |
246 | \begin_inset LatexCommand \htmlurl{http://www.codesourcery.com/qm/qmtest} |
|
259 | \begin_inset LatexCommand \htmlurl{http://www.codesourcery.com/qm/qmtest} | |
247 |
|
260 | |||
248 | \end_inset |
|
261 | \end_inset | |
249 |
|
262 | |||
250 | , it sounds interesting (it's Python-based too). |
|
263 | , it sounds interesting (it's Python-based too). | |
251 | \layout Section |
|
264 | \layout Section | |
252 |
|
265 | |||
253 | Configuration system |
|
266 | Configuration system | |
254 | \layout Standard |
|
267 | \layout Standard | |
255 |
|
268 | |||
256 | Move away from the current ipythonrc format to using standard python files |
|
269 | Move away from the current ipythonrc format to using standard python files | |
257 | for configuration. |
|
270 | for configuration. | |
258 | This will require users to be slightly more careful in their syntax, but |
|
271 | This will require users to be slightly more careful in their syntax, but | |
259 | reduces code in IPython, is more in line with Python's normal form (using |
|
272 | reduces code in IPython, is more in line with Python's normal form (using | |
260 | the $PYTHONSTARTUP file) and allows much more flexibility. |
|
273 | the $PYTHONSTARTUP file) and allows much more flexibility. | |
261 | I also think it's more 'pythonic', in using a single language for everything. |
|
274 | I also think it's more 'pythonic', in using a single language for everything. | |
262 | \layout Standard |
|
275 | \layout Standard | |
263 |
|
276 | |||
264 | Options can be set up with a function call which takes keywords and updates |
|
277 | Options can be set up with a function call which takes keywords and updates | |
265 | the options Struct. |
|
278 | the options Struct. | |
266 | \layout Standard |
|
279 | \layout Standard | |
267 |
|
280 | |||
268 | In order to maintain the recursive inclusion system, write an 'include' |
|
281 | In order to maintain the recursive inclusion system, write an 'include' | |
269 | function which is basically a wrapper around safe_execfile(). |
|
282 | function which is basically a wrapper around safe_execfile(). | |
270 | Also for alias definitions an alias() function will do. |
|
283 | Also for alias definitions an alias() function will do. | |
271 | All functionality which we want to have at startup time for the users can |
|
284 | All functionality which we want to have at startup time for the users can | |
272 | be wrapped in a small module so that config files look like: |
|
285 | be wrapped in a small module so that config files look like: | |
273 | \layout Standard |
|
286 | \layout Standard | |
274 |
|
287 | |||
275 |
|
288 | |||
276 | \family typewriter |
|
289 | \family typewriter | |
277 | from IPython.Startup import * |
|
290 | from IPython.Startup import * | |
278 | \newline |
|
291 | \newline | |
279 | ... |
|
292 | ... | |
280 | \newline |
|
293 | \newline | |
281 | set_options(automagic=1,colors='NoColor',...) |
|
294 | set_options(automagic=1,colors='NoColor',...) | |
282 | \newline |
|
295 | \newline | |
283 | ... |
|
296 | ... | |
284 | \newline |
|
297 | \newline | |
285 | include('mysetup.py') |
|
298 | include('mysetup.py') | |
286 | \newline |
|
299 | \newline | |
287 | ... |
|
300 | ... | |
288 | \newline |
|
301 | \newline | |
289 | alias('ls ls --color -l') |
|
302 | alias('ls ls --color -l') | |
290 | \newline |
|
303 | \newline | |
291 | ... |
|
304 | ... | |
292 | etc. |
|
305 | etc. | |
293 | \layout Standard |
|
306 | \layout Standard | |
294 |
|
307 | |||
295 | Also, put |
|
308 | Also, put | |
296 | \series bold |
|
309 | \series bold | |
297 | all |
|
310 | all | |
298 | \series default |
|
311 | \series default | |
299 | aliases in here, out of the core code. |
|
312 | aliases in here, out of the core code. | |
300 | \layout Standard |
|
313 | \layout Standard | |
301 |
|
314 | |||
302 | The new system should allow for more seamless upgrading, so that: |
|
315 | The new system should allow for more seamless upgrading, so that: | |
303 | \layout Itemize |
|
316 | \layout Itemize | |
304 |
|
317 | |||
305 | It automatically recognizes when the config files need updating and does |
|
318 | It automatically recognizes when the config files need updating and does | |
306 | the upgrade. |
|
319 | the upgrade. | |
307 | \layout Itemize |
|
320 | \layout Itemize | |
308 |
|
321 | |||
309 | It simply adds the new options to the user's config file without overwriting |
|
322 | It simply adds the new options to the user's config file without overwriting | |
310 | it. |
|
323 | it. | |
311 | The current system is annoying since users need to manually re-sync their |
|
324 | The current system is annoying since users need to manually re-sync their | |
312 | configuration after every update. |
|
325 | configuration after every update. | |
313 | \layout Itemize |
|
326 | \layout Itemize | |
314 |
|
327 | |||
315 | It detects obsolete options and informs the user to remove them from his |
|
328 | It detects obsolete options and informs the user to remove them from his | |
316 | config file. |
|
329 | config file. | |
317 | \layout Standard |
|
330 | \layout Standard | |
318 |
|
331 | |||
319 | Here's a copy of Arnd Baecker suggestions on the matter: |
|
332 | Here's a copy of Arnd Baecker suggestions on the matter: | |
320 | \layout Standard |
|
333 | \layout Standard | |
321 |
|
334 | |||
322 | 1.) upgrade: it might be nice to have an "auto" upgrade procedure: i.e. |
|
335 | 1.) upgrade: it might be nice to have an "auto" upgrade procedure: i.e. | |
323 | imagine that IPython is installed system-wide and gets upgraded, how does |
|
336 | imagine that IPython is installed system-wide and gets upgraded, how does | |
324 | a user know, that an upgrade of the stuff in ~/.ipython is necessary ? So |
|
337 | a user know, that an upgrade of the stuff in ~/.ipython is necessary ? So | |
325 | maybe one has to a keep a version number in ~/.ipython and if there is a |
|
338 | maybe one has to a keep a version number in ~/.ipython and if there is a | |
326 | mismatch with the started ipython, then invoke the upgrade procedure. |
|
339 | mismatch with the started ipython, then invoke the upgrade procedure. | |
327 | \layout Standard |
|
340 | \layout Standard | |
328 |
|
341 | |||
329 | 2.) upgrade: I find that replacing the old files in ~/.ipython (after copying |
|
342 | 2.) upgrade: I find that replacing the old files in ~/.ipython (after copying | |
330 | them to .old not optimal (for example, after every update, I have to change |
|
343 | them to .old not optimal (for example, after every update, I have to change | |
331 | my color settings (and some others) in ~/.ipython/ipthonrc). |
|
344 | my color settings (and some others) in ~/.ipython/ipthonrc). | |
332 | So somehow keeping the old files and merging the new features would be |
|
345 | So somehow keeping the old files and merging the new features would be | |
333 | nice. |
|
346 | nice. | |
334 | (but how to distinguish changes from version to version with changes made |
|
347 | (but how to distinguish changes from version to version with changes made | |
335 | by the user ?) For, example, I would have to change in GnuplotMagic.py gnuplot_m |
|
348 | by the user ?) For, example, I would have to change in GnuplotMagic.py gnuplot_m | |
336 | ouse to 1 after every upgrade ... |
|
349 | ouse to 1 after every upgrade ... | |
337 | \layout Standard |
|
350 | \layout Standard | |
338 |
|
351 | |||
339 | This is surely a minor point - also things will change during the "BIG" |
|
352 | This is surely a minor point - also things will change during the "BIG" | |
340 | rewrite, but maybe this is a point to keep in mind for this ? |
|
353 | rewrite, but maybe this is a point to keep in mind for this ? | |
341 | \layout Standard |
|
354 | \layout Standard | |
342 |
|
355 | |||
343 | 3.) upgrade: old, sometimes obsolete files stay in the ~/.ipython subdirectory. |
|
356 | 3.) upgrade: old, sometimes obsolete files stay in the ~/.ipython subdirectory. | |
344 | (hmm, maybe one could move all these into some subdirectory, but which |
|
357 | (hmm, maybe one could move all these into some subdirectory, but which | |
345 | name for that (via version-number ?) ?) |
|
358 | name for that (via version-number ?) ?) | |
346 | \layout Subsection |
|
359 | \layout Subsection | |
347 |
|
360 | |||
348 | Command line options |
|
361 | Command line options | |
349 | \layout Standard |
|
362 | \layout Standard | |
350 |
|
363 | |||
351 | It would be great to design the command-line processing system so that it |
|
364 | It would be great to design the command-line processing system so that it | |
352 | can be dynamically modified in some easy way. |
|
365 | can be dynamically modified in some easy way. | |
353 | This would allow systems based on IPython to include their own command-line |
|
366 | This would allow systems based on IPython to include their own command-line | |
354 | processing to either extend or fully replace IPython's. |
|
367 | processing to either extend or fully replace IPython's. | |
355 | Probably moving to the new optparse library (also known as optik) will |
|
368 | Probably moving to the new optparse library (also known as optik) will | |
356 | make this a lot easier. |
|
369 | make this a lot easier. | |
357 | \layout Section |
|
370 | \layout Section | |
358 |
|
371 | |||
359 | OS-dependent code |
|
372 | OS-dependent code | |
360 | \layout Standard |
|
373 | \layout Standard | |
361 |
|
374 | |||
362 | Options which are OS-dependent (such as colors and aliases) should be loaded |
|
375 | Options which are OS-dependent (such as colors and aliases) should be loaded | |
363 | via include files. |
|
376 | via include files. | |
364 | That is, the general file will have: |
|
377 | That is, the general file will have: | |
365 | \layout Standard |
|
378 | \layout Standard | |
366 |
|
379 | |||
367 |
|
380 | |||
368 | \family typewriter |
|
381 | \family typewriter | |
369 | if os.name == 'posix': |
|
382 | if os.name == 'posix': | |
370 | \newline |
|
383 | \newline | |
371 | include('ipythonrc-posix.py') |
|
384 | include('ipythonrc-posix.py') | |
372 | \newline |
|
385 | \newline | |
373 | elif os.name == 'nt': |
|
386 | elif os.name == 'nt': | |
374 | \newline |
|
387 | \newline | |
375 | include('ipythonrc-nt.py')... |
|
388 | include('ipythonrc-nt.py')... | |
376 | \layout Standard |
|
389 | \layout Standard | |
377 |
|
390 | |||
378 | In the |
|
391 | In the | |
379 | \family typewriter |
|
392 | \family typewriter | |
380 | -posix |
|
393 | -posix | |
381 | \family default |
|
394 | \family default | |
382 | , |
|
395 | , | |
383 | \family typewriter |
|
396 | \family typewriter | |
384 | -nt |
|
397 | -nt | |
385 | \family default |
|
398 | \family default | |
386 | , etc. |
|
399 | , etc. | |
387 | files we'll set all os-specific options. |
|
400 | files we'll set all os-specific options. | |
388 | \layout Section |
|
401 | \layout Section | |
389 |
|
402 | |||
390 | Merging with other shell systems |
|
403 | Merging with other shell systems | |
391 | \layout Standard |
|
404 | \layout Standard | |
392 |
|
405 | |||
393 | This is listed before the big design issues, as it is something which should |
|
406 | This is listed before the big design issues, as it is something which should | |
394 | be kept in mind when that design is made. |
|
407 | be kept in mind when that design is made. | |
395 | \layout Standard |
|
408 | \layout Standard | |
396 |
|
409 | |||
397 | The following shell systems are out there and I think the whole design of |
|
410 | The following shell systems are out there and I think the whole design of | |
398 | IPython should try to be modular enough to make it possible to integrate |
|
411 | IPython should try to be modular enough to make it possible to integrate | |
399 | its features into these. |
|
412 | its features into these. | |
400 | In all cases IPython should exist as a stand-alone, terminal based program. |
|
413 | In all cases IPython should exist as a stand-alone, terminal based program. | |
401 | But it would be great if users of these other shells (some of them which |
|
414 | But it would be great if users of these other shells (some of them which | |
402 | have very nice features of their own, especially the graphical ones) could |
|
415 | have very nice features of their own, especially the graphical ones) could | |
403 | keep their environment but gain IPython's features. |
|
416 | keep their environment but gain IPython's features. | |
404 | \layout List |
|
417 | \layout List | |
405 | \labelwidthstring 00.00.0000 |
|
418 | \labelwidthstring 00.00.0000 | |
406 |
|
419 | |||
407 | IDLE This is the standard, distributed as part of Python. |
|
420 | IDLE This is the standard, distributed as part of Python. | |
408 |
|
421 | |||
409 | \layout List |
|
422 | \layout List | |
410 | \labelwidthstring 00.00.0000 |
|
423 | \labelwidthstring 00.00.0000 | |
411 |
|
424 | |||
412 | pyrepl |
|
425 | pyrepl | |
413 | \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mwh/hacks/pyrepl.html} |
|
426 | \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mwh/hacks/pyrepl.html} | |
414 |
|
427 | |||
415 | \end_inset |
|
428 | \end_inset | |
416 |
|
429 | |||
417 | . |
|
430 | . | |
418 | This is a text (curses-based) shell-like replacement which doesn't have |
|
431 | This is a text (curses-based) shell-like replacement which doesn't have | |
419 | some of IPython's features, but has a crucially useful (and hard to implement) |
|
432 | some of IPython's features, but has a crucially useful (and hard to implement) | |
420 | one: full multi-line editing. |
|
433 | one: full multi-line editing. | |
421 | This turns the interactive interpreter into a true code testing and development |
|
434 | This turns the interactive interpreter into a true code testing and development | |
422 | environment. |
|
435 | environment. | |
423 |
|
436 | |||
424 | \layout List |
|
437 | \layout List | |
425 | \labelwidthstring 00.00.0000 |
|
438 | \labelwidthstring 00.00.0000 | |
426 |
|
439 | |||
427 | PyCrust |
|
440 | PyCrust | |
428 | \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/pycrust} |
|
441 | \begin_inset LatexCommand \htmlurl{http://sourceforge.net/projects/pycrust} | |
429 |
|
442 | |||
430 | \end_inset |
|
443 | \end_inset | |
431 |
|
444 | |||
432 | . |
|
445 | . | |
433 | Very nice, wxWindows based system. |
|
446 | Very nice, wxWindows based system. | |
434 | \layout List |
|
447 | \layout List | |
435 | \labelwidthstring 00.00.0000 |
|
448 | \labelwidthstring 00.00.0000 | |
436 |
|
449 | |||
437 | PythonWin |
|
450 | PythonWin | |
438 | \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond} |
|
451 | \begin_inset LatexCommand \htmlurl{http://starship.python.net/crew/mhammond} | |
439 |
|
452 | |||
440 | \end_inset |
|
453 | \end_inset | |
441 |
|
454 | |||
442 | . |
|
455 | . | |
443 | Similar to PyCrust in some respects, a very good and free Python development |
|
456 | Similar to PyCrust in some respects, a very good and free Python development | |
444 | environment for Windows systems. |
|
457 | environment for Windows systems. | |
445 | \layout Section |
|
458 | \layout Section | |
446 |
|
459 | |||
447 | Class design |
|
460 | Class design | |
448 | \layout Standard |
|
461 | \layout Standard | |
449 |
|
462 | |||
450 | This is the big one. |
|
463 | This is the big one. | |
451 | Currently classes use each other in a very messy way, poking inside one |
|
464 | Currently classes use each other in a very messy way, poking inside one | |
452 | another for data and methods. |
|
465 | another for data and methods. | |
453 | ipmaker() adds tons of stuff to the main __IP instance by hand, and the |
|
466 | ipmaker() adds tons of stuff to the main __IP instance by hand, and the | |
454 | mix-ins used (Logger, Magic, etc) mean the final __IP instance has a million |
|
467 | mix-ins used (Logger, Magic, etc) mean the final __IP instance has a million | |
455 | things in it. |
|
468 | things in it. | |
456 | All that needs to be cleanly broken down with well defined interfaces amongst |
|
469 | All that needs to be cleanly broken down with well defined interfaces amongst | |
457 | the different classes, and probably no mix-ins. |
|
470 | the different classes, and probably no mix-ins. | |
458 | \layout Standard |
|
471 | \layout Standard | |
459 |
|
472 | |||
460 | The best approach is probably to have all the sub-systems which are currently |
|
473 | The best approach is probably to have all the sub-systems which are currently | |
461 | mixins be fully independent classes which talk back only to the main instance |
|
474 | mixins be fully independent classes which talk back only to the main instance | |
462 | (and |
|
475 | (and | |
463 | \series bold |
|
476 | \series bold | |
464 | not |
|
477 | not | |
465 | \series default |
|
478 | \series default | |
466 | to each other). |
|
479 | to each other). | |
467 | In the main instance there should be an object whose job is to handle communica |
|
480 | In the main instance there should be an object whose job is to handle communica | |
468 | tion with the sub-systems. |
|
481 | tion with the sub-systems. | |
469 | \layout Standard |
|
482 | \layout Standard | |
470 |
|
483 | |||
471 | I should probably learn a little UML and diagram this whole thing before |
|
484 | I should probably learn a little UML and diagram this whole thing before | |
472 | I start coding. |
|
485 | I start coding. | |
473 | \layout Subsection |
|
486 | \layout Subsection | |
474 |
|
487 | |||
475 | Magic |
|
488 | Magic | |
476 | \layout Standard |
|
489 | \layout Standard | |
477 |
|
490 | |||
478 | Now all methods which will become publicly available are called Magic.magic_name, |
|
491 | Now all methods which will become publicly available are called Magic.magic_name, | |
479 | the magic_ should go away. |
|
492 | the magic_ should go away. | |
480 | Then, Magic instead of being a mix-in should simply be an attribute of |
|
493 | Then, Magic instead of being a mix-in should simply be an attribute of | |
481 | __IP: |
|
494 | __IP: | |
482 | \layout Standard |
|
495 | \layout Standard | |
483 |
|
496 | |||
484 | __IP.Magic = Magic() |
|
497 | __IP.Magic = Magic() | |
485 | \layout Standard |
|
498 | \layout Standard | |
486 |
|
499 | |||
487 | This will then give all the magic functions as __IP.Magic.name(), which is |
|
500 | This will then give all the magic functions as __IP.Magic.name(), which is | |
488 | much cleaner. |
|
501 | much cleaner. | |
489 | This will also force a better separation so that Magic doesn't poke inside |
|
502 | This will also force a better separation so that Magic doesn't poke inside | |
490 | __IP so much. |
|
503 | __IP so much. | |
491 | In the constructor, Magic should get whatever information it needs to know |
|
504 | In the constructor, Magic should get whatever information it needs to know | |
492 | about __IP (even if it means a pointer to __IP itself, but at least we'll |
|
505 | about __IP (even if it means a pointer to __IP itself, but at least we'll | |
493 | know where it is. |
|
506 | know where it is. | |
494 | Right now since it's a mix-in, there's no way to know which variables belong |
|
507 | Right now since it's a mix-in, there's no way to know which variables belong | |
495 | to whom). |
|
508 | to whom). | |
496 | \layout Standard |
|
509 | \layout Standard | |
497 |
|
510 | |||
498 | Build a class MagicFunction so that adding new functions is a matter of: |
|
511 | Build a class MagicFunction so that adding new functions is a matter of: | |
499 | \layout Standard |
|
512 | \layout Standard | |
500 |
|
513 | |||
501 |
|
514 | |||
502 | \family typewriter |
|
515 | \family typewriter | |
503 | my_magic = MagicFunction(category = 'System utilities') |
|
516 | my_magic = MagicFunction(category = 'System utilities') | |
504 | \newline |
|
517 | \newline | |
505 | my_magic.__call__ = ... |
|
518 | my_magic.__call__ = ... | |
506 | \layout Standard |
|
519 | \layout Standard | |
507 |
|
520 | |||
508 | Features: |
|
521 | Features: | |
509 | \layout Itemize |
|
522 | \layout Itemize | |
510 |
|
523 | |||
511 | The class constructor should automatically register the functions and keep |
|
524 | The class constructor should automatically register the functions and keep | |
512 | a table with category sections for easy sorting/viewing. |
|
525 | a table with category sections for easy sorting/viewing. | |
513 | \layout Itemize |
|
526 | \layout Itemize | |
514 |
|
527 | |||
515 | The object interface must allow automatic building of a GUI for them. |
|
528 | The object interface must allow automatic building of a GUI for them. | |
516 | This requires registering the options the command takes, the number of |
|
529 | This requires registering the options the command takes, the number of | |
517 | arguments, etc, in a formal way. |
|
530 | arguments, etc, in a formal way. | |
518 | The advantage of this approach is that it allows not only to add GUIs to |
|
531 | The advantage of this approach is that it allows not only to add GUIs to | |
519 | the magics, but also for a much more intelligent building of docstrings, |
|
532 | the magics, but also for a much more intelligent building of docstrings, | |
520 | and better parsing of options and arguments. |
|
533 | and better parsing of options and arguments. | |
521 | \layout Standard |
|
534 | \layout Standard | |
522 |
|
535 | |||
523 | Also think through better an alias system for magics. |
|
536 | Also think through better an alias system for magics. | |
524 | Since the magic system is like a command shell inside ipython, the relation |
|
537 | Since the magic system is like a command shell inside ipython, the relation | |
525 | between these aliases and system aliases should be cleanly thought out. |
|
538 | between these aliases and system aliases should be cleanly thought out. | |
526 | \layout Subsection |
|
539 | \layout Subsection | |
527 |
|
540 | |||
528 | Color schemes |
|
541 | Color schemes | |
529 | \layout Standard |
|
542 | \layout Standard | |
530 |
|
543 | |||
531 | These should be loaded from some kind of resource file so they are easier |
|
544 | These should be loaded from some kind of resource file so they are easier | |
532 | to modify by the user. |
|
545 | to modify by the user. | |
533 | \layout Section |
|
546 | \layout Section | |
534 |
|
547 | |||
535 | Hooks |
|
548 | Hooks | |
536 | \layout Standard |
|
549 | \layout Standard | |
537 |
|
550 | |||
538 | IPython should have a modular system where functions can register themselves |
|
551 | IPython should have a modular system where functions can register themselves | |
539 | for certain tasks. |
|
552 | for certain tasks. | |
540 | Currently changing functionality requires overriding certain specific methods, |
|
553 | Currently changing functionality requires overriding certain specific methods, | |
541 | there should be a clean API for this to be done. |
|
554 | there should be a clean API for this to be done. | |
542 | \layout Subsection |
|
555 | \layout Subsection | |
543 |
|
556 | |||
544 | whos hook |
|
557 | whos hook | |
545 | \layout Standard |
|
558 | \layout Standard | |
546 |
|
559 | |||
547 | This was a very nice suggestion from Alexander Schmolck <a.schmolck@gmx.net>: |
|
560 | This was a very nice suggestion from Alexander Schmolck <a.schmolck@gmx.net>: | |
548 | \layout Standard |
|
561 | \layout Standard | |
549 |
|
562 | |||
550 | 2. |
|
563 | 2. | |
551 | I think it would also be very helpful if there where some sort of hook |
|
564 | I think it would also be very helpful if there where some sort of hook | |
552 | for ``whos`` that let one customize display formaters depending on the |
|
565 | for ``whos`` that let one customize display formaters depending on the | |
553 | object type. |
|
566 | object type. | |
554 | \layout Standard |
|
567 | \layout Standard | |
555 |
|
568 | |||
556 | For example I'd rather have a whos that formats an array like: |
|
569 | For example I'd rather have a whos that formats an array like: | |
557 | \layout Standard |
|
570 | \layout Standard | |
558 |
|
571 | |||
559 |
|
572 | |||
560 | \family typewriter |
|
573 | \family typewriter | |
561 | Variable Type Data/Length |
|
574 | Variable Type Data/Length | |
562 | \newline |
|
575 | \newline | |
563 | ------------------------------ |
|
576 | ------------------------------ | |
564 | \newline |
|
577 | \newline | |
565 | a array size: 4x3 type: 'Float' |
|
578 | a array size: 4x3 type: 'Float' | |
566 | \layout Standard |
|
579 | \layout Standard | |
567 |
|
580 | |||
568 | than |
|
581 | than | |
569 | \layout Standard |
|
582 | \layout Standard | |
570 |
|
583 | |||
571 |
|
584 | |||
572 | \family typewriter |
|
585 | \family typewriter | |
573 | Variable Type Data/Length |
|
586 | Variable Type Data/Length | |
574 | \newline |
|
587 | \newline | |
575 | ------------------------------ |
|
588 | ------------------------------ | |
576 | \newline |
|
589 | \newline | |
577 | a array [[ 0. |
|
590 | a array [[ 0. | |
578 | 1. |
|
591 | 1. | |
579 | 2. |
|
592 | 2. | |
580 | 3<...> 8. |
|
593 | 3<...> 8. | |
581 | 9. |
|
594 | 9. | |
582 | 10. |
|
595 | 10. | |
583 | 11.]] |
|
596 | 11.]] | |
584 | \layout Section |
|
597 | \layout Section | |
585 |
|
598 | |||
586 | Parallel support |
|
599 | Parallel support | |
587 | \layout Standard |
|
600 | \layout Standard | |
588 |
|
601 | |||
589 | For integration with graphical shells and other systems, it will be best |
|
602 | For integration with graphical shells and other systems, it will be best | |
590 | if ipython is split into a kernel/client model, much like Mathematica works. |
|
603 | if ipython is split into a kernel/client model, much like Mathematica works. | |
591 | This simultaneously opens the door for support of interactive parallel |
|
604 | This simultaneously opens the door for support of interactive parallel | |
592 | computing. |
|
605 | computing. | |
593 | Currenlty %bg provides a threads-based proof of concept, and Brian Granger's |
|
606 | Currenlty %bg provides a threads-based proof of concept, and Brian Granger's | |
594 | XGrid project is a much more realistic such system. |
|
607 | XGrid project is a much more realistic such system. | |
595 | The new design should integrates ideas as core elements. |
|
608 | The new design should integrates ideas as core elements. | |
596 | Some notes from Brian on this topic: |
|
609 | Some notes from Brian on this topic: | |
597 | \layout Standard |
|
610 | \layout Standard | |
598 |
|
611 | |||
599 | 1. |
|
612 | 1. | |
600 | How should the remote python server/kernel be designed? Multithreaded? |
|
613 | How should the remote python server/kernel be designed? Multithreaded? | |
601 | Blocking? Connected/disconnected modes? Load balancing? |
|
614 | Blocking? Connected/disconnected modes? Load balancing? | |
602 | \layout Standard |
|
615 | \layout Standard | |
603 |
|
616 | |||
604 | 2. |
|
617 | 2. | |
605 | What APi/protocol should the server/kernel expose to clients? |
|
618 | What APi/protocol should the server/kernel expose to clients? | |
606 | \layout Standard |
|
619 | \layout Standard | |
607 |
|
620 | |||
608 | 3. |
|
621 | 3. | |
609 | How should the client classes (which the user uses to interact with the |
|
622 | How should the client classes (which the user uses to interact with the | |
610 | cluster) be designed? |
|
623 | cluster) be designed? | |
611 | \layout Standard |
|
624 | \layout Standard | |
612 |
|
625 | |||
613 | 4. |
|
626 | 4. | |
614 | What API should the client classes expose? |
|
627 | What API should the client classes expose? | |
615 | \layout Standard |
|
628 | \layout Standard | |
616 |
|
629 | |||
617 | 5. |
|
630 | 5. | |
618 | How should the client API be wrapped in a few simple magic functions? |
|
631 | How should the client API be wrapped in a few simple magic functions? | |
619 | \layout Standard |
|
632 | \layout Standard | |
620 |
|
633 | |||
621 | 6. |
|
634 | 6. | |
622 | How should security be handled? |
|
635 | How should security be handled? | |
623 | \layout Standard |
|
636 | \layout Standard | |
624 |
|
637 | |||
625 | 7. |
|
638 | 7. | |
626 | How to work around the issues of the GIL and threads? |
|
639 | How to work around the issues of the GIL and threads? | |
627 | \layout Standard |
|
640 | \layout Standard | |
628 |
|
641 | |||
629 | I think the most important things to work out are the client API (#4) the |
|
642 | I think the most important things to work out are the client API (#4) the | |
630 | server/kernel API/protocol (#2) and the magic function API (#5). |
|
643 | server/kernel API/protocol (#2) and the magic function API (#5). | |
631 | We should let these determine the design and architecture of the components. |
|
644 | We should let these determine the design and architecture of the components. | |
632 | \layout Standard |
|
645 | \layout Standard | |
633 |
|
646 | |||
634 | One other thing. |
|
647 | One other thing. | |
635 | What is your impression of twisted? I have been looking at it and it looks |
|
648 | What is your impression of twisted? I have been looking at it and it looks | |
636 | like a _very_ powerful set of tools for this type of stuff. |
|
649 | like a _very_ powerful set of tools for this type of stuff. | |
637 | I am wondering if it might make sense to think about using twisted for |
|
650 | I am wondering if it might make sense to think about using twisted for | |
638 | this project. |
|
651 | this project. | |
639 | \layout Section |
|
652 | \layout Section | |
640 |
|
653 | |||
641 | Manuals |
|
654 | Manuals | |
642 | \layout Standard |
|
655 | \layout Standard | |
643 |
|
656 | |||
644 | The documentation should be generated from docstrings for the command line |
|
657 | The documentation should be generated from docstrings for the command line | |
645 | args and all the magic commands. |
|
658 | args and all the magic commands. | |
646 | Look into one of the simple text markup systems to see if we can get latex |
|
659 | Look into one of the simple text markup systems to see if we can get latex | |
647 | (for reLyXing later) out of this. |
|
660 | (for reLyXing later) out of this. | |
648 | Part of the build command would then be to make an update of the docs based |
|
661 | Part of the build command would then be to make an update of the docs based | |
649 | on this, thus giving more complete manual (and guaranteed to be in sync |
|
662 | on this, thus giving more complete manual (and guaranteed to be in sync | |
650 | with the code docstrings). |
|
663 | with the code docstrings). | |
651 | \layout Standard |
|
664 | \layout Standard | |
652 |
|
665 | |||
653 | [PARTLY DONE] At least now all magics are auto-documented, works farily |
|
666 | [PARTLY DONE] At least now all magics are auto-documented, works farily | |
654 | well. |
|
667 | well. | |
655 | Limited Latex formatting yet. |
|
668 | Limited Latex formatting yet. | |
656 | \layout Subsection |
|
669 | \layout Subsection | |
657 |
|
670 | |||
658 | Integration with pydoc-help |
|
671 | Integration with pydoc-help | |
659 | \layout Standard |
|
672 | \layout Standard | |
660 |
|
673 | |||
661 | It should be possible to have access to the manual via the pydoc help system |
|
674 | It should be possible to have access to the manual via the pydoc help system | |
662 | somehow. |
|
675 | somehow. | |
663 | This might require subclassing the pydoc help, or figuring out how to add |
|
676 | This might require subclassing the pydoc help, or figuring out how to add | |
664 | the IPython docs in the right form so that help() finds them. |
|
677 | the IPython docs in the right form so that help() finds them. | |
665 | \layout Standard |
|
678 | \layout Standard | |
666 |
|
679 | |||
667 | Some comments from Arnd and my reply on this topic: |
|
680 | Some comments from Arnd and my reply on this topic: | |
668 | \layout Standard |
|
681 | \layout Standard | |
669 |
|
682 | |||
670 | > ((Generally I would like to have the nice documentation > more easily |
|
683 | > ((Generally I would like to have the nice documentation > more easily | |
671 | accessable from within ipython ... |
|
684 | accessable from within ipython ... | |
672 | > Many people just don't read documentation, even if it is > as good as |
|
685 | > Many people just don't read documentation, even if it is > as good as | |
673 | the one of IPython )) |
|
686 | the one of IPython )) | |
674 | \layout Standard |
|
687 | \layout Standard | |
675 |
|
688 | |||
676 | That's an excellent point. |
|
689 | That's an excellent point. | |
677 | I've added a note to this effect in new_design. |
|
690 | I've added a note to this effect in new_design. | |
678 | Basically I'd like help() to naturally access the IPython docs. |
|
691 | Basically I'd like help() to naturally access the IPython docs. | |
679 | Since they are already there in html for the user, it's probably a matter |
|
692 | Since they are already there in html for the user, it's probably a matter | |
680 | of playing a bit with pydoc to tell it where to find them. |
|
693 | of playing a bit with pydoc to tell it where to find them. | |
681 | It would definitely make for a much cleaner system. |
|
694 | It would definitely make for a much cleaner system. | |
682 | Right now the information on IPython is: |
|
695 | Right now the information on IPython is: | |
683 | \layout Standard |
|
696 | \layout Standard | |
684 |
|
697 | |||
685 | -ipython --help at the command line: info on command line switches |
|
698 | -ipython --help at the command line: info on command line switches | |
686 | \layout Standard |
|
699 | \layout Standard | |
687 |
|
700 | |||
688 | -? at the ipython prompt: overview of IPython |
|
701 | -? at the ipython prompt: overview of IPython | |
689 | \layout Standard |
|
702 | \layout Standard | |
690 |
|
703 | |||
691 | -magic at the ipython prompt: overview of the magic system |
|
704 | -magic at the ipython prompt: overview of the magic system | |
692 | \layout Standard |
|
705 | \layout Standard | |
693 |
|
706 | |||
694 | -external docs (html/pdf) |
|
707 | -external docs (html/pdf) | |
695 | \layout Standard |
|
708 | \layout Standard | |
696 |
|
709 | |||
697 | All that should be better integrated seamlessly in the help() system, so |
|
710 | All that should be better integrated seamlessly in the help() system, so | |
698 | that you can simply say: |
|
711 | that you can simply say: | |
699 | \layout Standard |
|
712 | \layout Standard | |
700 |
|
713 | |||
701 | help ipython -> full documentation access |
|
714 | help ipython -> full documentation access | |
702 | \layout Standard |
|
715 | \layout Standard | |
703 |
|
716 | |||
704 | help magic -> magic overview |
|
717 | help magic -> magic overview | |
705 | \layout Standard |
|
718 | \layout Standard | |
706 |
|
719 | |||
707 | help profile -> help on current profile |
|
720 | help profile -> help on current profile | |
708 | \layout Standard |
|
721 | \layout Standard | |
709 |
|
722 | |||
710 | help -> normal python help access. |
|
723 | help -> normal python help access. | |
711 | \layout Section |
|
724 | \layout Section | |
712 |
|
725 | |||
713 | Graphical object browsers |
|
726 | Graphical object browsers | |
714 | \layout Standard |
|
727 | \layout Standard | |
715 |
|
728 | |||
716 | I'd like a system for graphically browsing through objects. |
|
729 | I'd like a system for graphically browsing through objects. | |
717 |
|
730 | |||
718 | \family typewriter |
|
731 | \family typewriter | |
719 | @obrowse |
|
732 | @obrowse | |
720 | \family default |
|
733 | \family default | |
721 | should open a widged with all the things which |
|
734 | should open a widged with all the things which | |
722 | \family typewriter |
|
735 | \family typewriter | |
723 | @who |
|
736 | @who | |
724 | \family default |
|
737 | \family default | |
725 | lists, but cliking on each object would open a dedicated object viewer |
|
738 | lists, but cliking on each object would open a dedicated object viewer | |
726 | (also accessible as |
|
739 | (also accessible as | |
727 | \family typewriter |
|
740 | \family typewriter | |
728 | @oview <object> |
|
741 | @oview <object> | |
729 | \family default |
|
742 | \family default | |
730 | ). |
|
743 | ). | |
731 | This object viewer could show a summary of what |
|
744 | This object viewer could show a summary of what | |
732 | \family typewriter |
|
745 | \family typewriter | |
733 | <object>? |
|
746 | <object>? | |
734 | \family default |
|
747 | \family default | |
735 | currently shows, but also colorize source code and show it via an html |
|
748 | currently shows, but also colorize source code and show it via an html | |
736 | browser, show all attributes and methods of a given object (themselves |
|
749 | browser, show all attributes and methods of a given object (themselves | |
737 | openable in their own viewers, since in Python everything is an object), |
|
750 | openable in their own viewers, since in Python everything is an object), | |
738 | links to the parent classes, etc. |
|
751 | links to the parent classes, etc. | |
739 | \layout Standard |
|
752 | \layout Standard | |
740 |
|
753 | |||
741 | The object viewer widget should be extensible, so that one can add methods |
|
754 | The object viewer widget should be extensible, so that one can add methods | |
742 | to view certain types of objects in a special way (for example, plotting |
|
755 | to view certain types of objects in a special way (for example, plotting | |
743 | Numeric arrays via grace or gnuplot). |
|
756 | Numeric arrays via grace or gnuplot). | |
744 | This would be very useful when using IPython as part of an interactive |
|
757 | This would be very useful when using IPython as part of an interactive | |
745 | complex system for working with certain types of data. |
|
758 | complex system for working with certain types of data. | |
746 | \layout Standard |
|
759 | \layout Standard | |
747 |
|
760 | |||
748 | I should look at what PyCrust has to offer along these lines, at least as |
|
761 | I should look at what PyCrust has to offer along these lines, at least as | |
749 | a starting point. |
|
762 | a starting point. | |
750 | \layout Section |
|
763 | \layout Section | |
751 |
|
764 | |||
752 | Miscellaneous small things |
|
765 | Miscellaneous small things | |
753 | \layout Itemize |
|
766 | \layout Itemize | |
754 |
|
767 | |||
755 | Collect whatever variables matter from the environment in some globals for |
|
768 | Collect whatever variables matter from the environment in some globals for | |
756 | __IP, so we're not testing for them constantly (like $HOME, $TERM, etc.) |
|
769 | __IP, so we're not testing for them constantly (like $HOME, $TERM, etc.) | |
757 | \layout Section |
|
770 | \layout Section | |
758 |
|
771 | |||
759 | Session restoring |
|
772 | Session restoring | |
760 | \layout Standard |
|
773 | \layout Standard | |
761 |
|
774 | |||
762 | I've convinced myself that session restore by log replay is too fragile |
|
775 | I've convinced myself that session restore by log replay is too fragile | |
763 | and tricky to ever work reliably. |
|
776 | and tricky to ever work reliably. | |
764 | Plus it can be dog slow. |
|
777 | Plus it can be dog slow. | |
765 | I'd rather have a way of saving/restoring the *current* memory state of |
|
778 | I'd rather have a way of saving/restoring the *current* memory state of | |
766 | IPython. |
|
779 | IPython. | |
767 | I tried with pickle but failed (can't pickle modules). |
|
780 | I tried with pickle but failed (can't pickle modules). | |
768 | This seems the right way to do it to me, but it will have to wait until |
|
781 | This seems the right way to do it to me, but it will have to wait until | |
769 | someone tells me of a robust way of dumping/reloading *all* of the user |
|
782 | someone tells me of a robust way of dumping/reloading *all* of the user | |
770 | namespace in a file. |
|
783 | namespace in a file. | |
771 | \layout Standard |
|
784 | \layout Standard | |
772 |
|
785 | |||
773 | Probably the best approach will be to pickle as much as possible and record |
|
786 | Probably the best approach will be to pickle as much as possible and record | |
774 | what can not be pickled for manual reload (such as modules). |
|
787 | what can not be pickled for manual reload (such as modules). | |
775 | This is not trivial to get to work reliably, so it's best left for after |
|
788 | This is not trivial to get to work reliably, so it's best left for after | |
776 | the code restructuring. |
|
789 | the code restructuring. | |
777 | \layout Standard |
|
790 | \layout Standard | |
778 |
|
791 | |||
779 | The following issues exist (old notes, see above paragraph for my current |
|
792 | The following issues exist (old notes, see above paragraph for my current | |
780 | take on the issue): |
|
793 | take on the issue): | |
781 | \layout Itemize |
|
794 | \layout Itemize | |
782 |
|
795 | |||
783 | magic lines aren't properly re-executed when a log file is reloaded (and |
|
796 | magic lines aren't properly re-executed when a log file is reloaded (and | |
784 | some of them, like clear or run, may change the environment). |
|
797 | some of them, like clear or run, may change the environment). | |
785 | So session restore isn't 100% perfect. |
|
798 | So session restore isn't 100% perfect. | |
786 | \layout Itemize |
|
799 | \layout Itemize | |
787 |
|
800 | |||
788 | auto-quote/parens lines aren't replayed either. |
|
801 | auto-quote/parens lines aren't replayed either. | |
789 | All this could be done, but it needs some work. |
|
802 | All this could be done, but it needs some work. | |
790 | Basically it requires re-running the log through IPython itself, not through |
|
803 | Basically it requires re-running the log through IPython itself, not through | |
791 | python. |
|
804 | python. | |
792 | \layout Itemize |
|
805 | \layout Itemize | |
793 |
|
806 | |||
794 | _p variables aren't restored with a session. |
|
807 | _p variables aren't restored with a session. | |
795 | Fix: same as above. |
|
808 | Fix: same as above. | |
796 | \layout Section |
|
809 | \layout Section | |
797 |
|
810 | |||
798 | Tips system |
|
811 | Tips system | |
799 | \layout Standard |
|
812 | \layout Standard | |
800 |
|
813 | |||
801 | It would be nice to have a tip() function which gives tips to users in some |
|
814 | It would be nice to have a tip() function which gives tips to users in some | |
802 | situations, but keeps track of already-given tips so they aren't given |
|
815 | situations, but keeps track of already-given tips so they aren't given | |
803 | every time. |
|
816 | every time. | |
804 | This could be done by pickling a dict of given tips to IPYTHONDIR. |
|
817 | This could be done by pickling a dict of given tips to IPYTHONDIR. | |
805 | \layout Section |
|
818 | \layout Section | |
806 |
|
819 | |||
807 | TAB completer |
|
820 | TAB completer | |
808 | \layout Standard |
|
821 | \layout Standard | |
809 |
|
822 | |||
810 | Some suggestions from Arnd Baecker: |
|
823 | Some suggestions from Arnd Baecker: | |
811 | \layout Standard |
|
824 | \layout Standard | |
812 |
|
825 | |||
813 | a) For file related commands (ls, cat, ...) it would be nice to be able to |
|
826 | a) For file related commands (ls, cat, ...) it would be nice to be able to | |
814 | TAB complete the files in the current directory. |
|
827 | TAB complete the files in the current directory. | |
815 | (once you started typing something which is uniquely a file, this leads |
|
828 | (once you started typing something which is uniquely a file, this leads | |
816 | to this effect, apart from going through the list of possible completions |
|
829 | to this effect, apart from going through the list of possible completions | |
817 | ...). |
|
830 | ...). | |
818 | (I know that this point is in your documentation.) |
|
831 | (I know that this point is in your documentation.) | |
819 | \layout Standard |
|
832 | \layout Standard | |
820 |
|
833 | |||
821 | More general, this might lead to something like command specific completion |
|
834 | More general, this might lead to something like command specific completion | |
822 | ? |
|
835 | ? | |
823 | \layout Standard |
|
836 | \layout Standard | |
824 |
|
837 | |||
825 | Here's John Hunter's suggestion: |
|
838 | Here's John Hunter's suggestion: | |
826 | \layout Standard |
|
839 | \layout Standard | |
827 |
|
840 | |||
828 | The *right way to do it* would be to make intelligent or customizable choices |
|
841 | The *right way to do it* would be to make intelligent or customizable choices | |
829 | about which namespace to add to the completion list depending on the string |
|
842 | about which namespace to add to the completion list depending on the string | |
830 | match up to the prompt, eg programmed completions. |
|
843 | match up to the prompt, eg programmed completions. | |
831 | In the simplest implementation, one would only complete on files and directorie |
|
844 | In the simplest implementation, one would only complete on files and directorie | |
832 | s if the line preceding the tab press matched 'cd ' or 'run ' (eg you don't |
|
845 | s if the line preceding the tab press matched 'cd ' or 'run ' (eg you don't | |
833 | want callable showing up in 'cd ca<TAB>') |
|
846 | want callable showing up in 'cd ca<TAB>') | |
834 | \layout Standard |
|
847 | \layout Standard | |
835 |
|
848 | |||
836 | In a more advanced scenario, you might imaging that functions supplied the |
|
849 | In a more advanced scenario, you might imaging that functions supplied the | |
837 | TAB namespace, and the user could configure a dictionary that mapped regular |
|
850 | TAB namespace, and the user could configure a dictionary that mapped regular | |
838 | expressions to namespace providing functions (with sensible defaults). |
|
851 | expressions to namespace providing functions (with sensible defaults). | |
839 | Something like |
|
852 | Something like | |
840 | \layout Standard |
|
853 | \layout Standard | |
841 |
|
854 | |||
842 | completed = { |
|
855 | completed = { | |
843 | \newline |
|
856 | \newline | |
844 | '^cd |
|
857 | '^cd | |
845 | \backslash |
|
858 | \backslash | |
846 | s+(.*)' : complete_files_and_dirs, |
|
859 | s+(.*)' : complete_files_and_dirs, | |
847 | \newline |
|
860 | \newline | |
848 | '^run |
|
861 | '^run | |
849 | \backslash |
|
862 | \backslash | |
850 | s+(.*)' : complete_files_and_dirs, |
|
863 | s+(.*)' : complete_files_and_dirs, | |
851 | \newline |
|
864 | \newline | |
852 | '^run |
|
865 | '^run | |
853 | \backslash |
|
866 | \backslash | |
854 | s+(-.*)' : complete_run_options, |
|
867 | s+(-.*)' : complete_run_options, | |
855 | \newline |
|
868 | \newline | |
856 | } |
|
869 | } | |
857 | \layout Standard |
|
870 | \layout Standard | |
858 |
|
871 | |||
859 | I don't know if this is feasible, but I really like programmed completions, |
|
872 | I don't know if this is feasible, but I really like programmed completions, | |
860 | which I use extensively in tcsh. |
|
873 | which I use extensively in tcsh. | |
861 | My feeling is that something like this is eminently doable in ipython. |
|
874 | My feeling is that something like this is eminently doable in ipython. | |
862 | \layout Standard |
|
875 | \layout Standard | |
863 |
|
876 | |||
864 | /JDH |
|
877 | /JDH | |
865 | \layout Standard |
|
878 | \layout Standard | |
866 |
|
879 | |||
867 | For something like this to work cleanly, the magic command system needs |
|
880 | For something like this to work cleanly, the magic command system needs | |
868 | also a clean options framework, so all valid options for a given magic |
|
881 | also a clean options framework, so all valid options for a given magic | |
869 | can be extracted programatically. |
|
882 | can be extracted programatically. | |
870 | \layout Section |
|
883 | \layout Section | |
871 |
|
884 | |||
872 | Debugger |
|
885 | Debugger | |
873 | \layout Standard |
|
886 | \layout Standard | |
874 |
|
887 | |||
875 | Current system uses a minimally tweaked pdb. |
|
888 | Current system uses a minimally tweaked pdb. | |
876 | Fine-tune it a bit, to provide at least: |
|
889 | Fine-tune it a bit, to provide at least: | |
877 | \layout Itemize |
|
890 | \layout Itemize | |
878 |
|
891 | |||
879 | Tab-completion in each stack frame. |
|
892 | Tab-completion in each stack frame. | |
880 | See email to Chris Hart for details. |
|
893 | See email to Chris Hart for details. | |
881 | \layout Itemize |
|
894 | \layout Itemize | |
882 |
|
895 | |||
883 | Object information via ? at least. |
|
896 | Object information via ? at least. | |
884 | Break up magic_oinfo a bit so that pdb can call it without loading all |
|
897 | Break up magic_oinfo a bit so that pdb can call it without loading all | |
885 | of IPython. |
|
898 | of IPython. | |
886 | If possible, also have the other magics for object study: doc, source, |
|
899 | If possible, also have the other magics for object study: doc, source, | |
887 | pdef and pfile. |
|
900 | pdef and pfile. | |
888 | \layout Itemize |
|
901 | \layout Itemize | |
889 |
|
902 | |||
890 | Shell access via ! |
|
903 | Shell access via ! | |
891 | \layout Itemize |
|
904 | \layout Itemize | |
892 |
|
905 | |||
893 | Syntax highlighting in listings. |
|
906 | Syntax highlighting in listings. | |
894 | Use py2html code, implement color schemes. |
|
907 | Use py2html code, implement color schemes. | |
895 | \layout Section |
|
908 | \layout Section | |
896 |
|
909 | |||
897 | A Python-based system shell - pysh? |
|
910 | A Python-based system shell - pysh? | |
898 | \layout Standard |
|
911 | \layout Standard | |
899 |
|
912 | |||
900 | Note: as of IPython 0.6.1, most of this functionality has actually been implemente |
|
913 | Note: as of IPython 0.6.1, most of this functionality has actually been implemente | |
901 | d. |
|
914 | d. | |
902 | \layout Standard |
|
915 | \layout Standard | |
903 |
|
916 | |||
904 | This section is meant as a working draft for discussions on the possibility |
|
917 | This section is meant as a working draft for discussions on the possibility | |
905 | of having a python-based system shell. |
|
918 | of having a python-based system shell. | |
906 | It is the result of my own thinking about these issues as much of discussions |
|
919 | It is the result of my own thinking about these issues as much of discussions | |
907 | on the ipython lists. |
|
920 | on the ipython lists. | |
908 | I apologize in advance for not giving individual credit to the various |
|
921 | I apologize in advance for not giving individual credit to the various | |
909 | contributions, but right now I don't have the time to track down each message |
|
922 | contributions, but right now I don't have the time to track down each message | |
910 | from the archives. |
|
923 | from the archives. | |
911 | So please consider this as the result of a collective effort by the ipython |
|
924 | So please consider this as the result of a collective effort by the ipython | |
912 | user community. |
|
925 | user community. | |
913 | \layout Standard |
|
926 | \layout Standard | |
914 |
|
927 | |||
915 | While IPyhton is (and will remain) a python shell first, it does offer a |
|
928 | While IPyhton is (and will remain) a python shell first, it does offer a | |
916 | fair amount of system access functionality: |
|
929 | fair amount of system access functionality: | |
917 | \layout Standard |
|
930 | \layout Standard | |
918 |
|
931 | |||
919 | - ! and !! for direct system access, |
|
932 | - ! and !! for direct system access, | |
920 | \layout Standard |
|
933 | \layout Standard | |
921 |
|
934 | |||
922 | - magic commands which wrap various system commands, |
|
935 | - magic commands which wrap various system commands, | |
923 | \layout Standard |
|
936 | \layout Standard | |
924 |
|
937 | |||
925 | - @sc and @sx, for shell output capture into python variables, |
|
938 | - @sc and @sx, for shell output capture into python variables, | |
926 | \layout Standard |
|
939 | \layout Standard | |
927 |
|
940 | |||
928 | - @alias, for aliasing system commands. |
|
941 | - @alias, for aliasing system commands. | |
929 | \layout Standard |
|
942 | \layout Standard | |
930 |
|
943 | |||
931 | This has prompted many users, over time, to ask for a way of extending ipython |
|
944 | This has prompted many users, over time, to ask for a way of extending ipython | |
932 | to the point where it could be used as a full-time replacement over typical |
|
945 | to the point where it could be used as a full-time replacement over typical | |
933 | user shells like bash, csh or tcsh. |
|
946 | user shells like bash, csh or tcsh. | |
934 | While my interest in ipython is such that I'll concentrate my personal |
|
947 | While my interest in ipython is such that I'll concentrate my personal | |
935 | efforts on other fronts (debugging, architecture, improvements for scientific |
|
948 | efforts on other fronts (debugging, architecture, improvements for scientific | |
936 | use, gui access), I will be happy to do anything which could make such |
|
949 | use, gui access), I will be happy to do anything which could make such | |
937 | a development possible. |
|
950 | a development possible. | |
938 | It would be the responsibility of someone else to maintain the code, but |
|
951 | It would be the responsibility of someone else to maintain the code, but | |
939 | I would do all necessary architectural changes to ipython for such an extension |
|
952 | I would do all necessary architectural changes to ipython for such an extension | |
940 | to be feasible. |
|
953 | to be feasible. | |
941 | \layout Standard |
|
954 | \layout Standard | |
942 |
|
955 | |||
943 | I'll try to outline here what I see as the key issues which need to be taken |
|
956 | I'll try to outline here what I see as the key issues which need to be taken | |
944 | into account. |
|
957 | into account. | |
945 | This document should be considered an evolving draft. |
|
958 | This document should be considered an evolving draft. | |
946 | Feel free to submit comments/improvements, even in the form of patches. |
|
959 | Feel free to submit comments/improvements, even in the form of patches. | |
947 | \layout Standard |
|
960 | \layout Standard | |
948 |
|
961 | |||
949 | In what follows, I'll represent the hypothetical python-based shell ('pysh' |
|
962 | In what follows, I'll represent the hypothetical python-based shell ('pysh' | |
950 | for now) prompt with '>>'. |
|
963 | for now) prompt with '>>'. | |
951 | \layout Subsection |
|
964 | \layout Subsection | |
952 |
|
965 | |||
953 | Basic design principles |
|
966 | Basic design principles | |
954 | \layout Standard |
|
967 | \layout Standard | |
955 |
|
968 | |||
956 | I think the basic design guideline should be the following: a hypothetical |
|
969 | I think the basic design guideline should be the following: a hypothetical | |
957 | python system shell should behave, as much as possible, like a normal shell |
|
970 | python system shell should behave, as much as possible, like a normal shell | |
958 | that users are familiar with (bash, tcsh, etc). |
|
971 | that users are familiar with (bash, tcsh, etc). | |
959 | This means: |
|
972 | This means: | |
960 | \layout Standard |
|
973 | \layout Standard | |
961 |
|
974 | |||
962 | 1. |
|
975 | 1. | |
963 | System commands can be issued directly at the prompt with no special syntax: |
|
976 | System commands can be issued directly at the prompt with no special syntax: | |
964 | \layout Standard |
|
977 | \layout Standard | |
965 |
|
978 | |||
966 | >> ls |
|
979 | >> ls | |
967 | \layout Standard |
|
980 | \layout Standard | |
968 |
|
981 | |||
969 | >> xemacs |
|
982 | >> xemacs | |
970 | \layout Standard |
|
983 | \layout Standard | |
971 |
|
984 | |||
972 | should just work like a user expects. |
|
985 | should just work like a user expects. | |
973 | \layout Standard |
|
986 | \layout Standard | |
974 |
|
987 | |||
975 | 2. |
|
988 | 2. | |
976 | The facilities of the python language should always be available, like |
|
989 | The facilities of the python language should always be available, like | |
977 | they are in ipython: |
|
990 | they are in ipython: | |
978 | \layout Standard |
|
991 | \layout Standard | |
979 |
|
992 | |||
980 | >> 3+4 |
|
993 | >> 3+4 | |
981 | \newline |
|
994 | \newline | |
982 | 7 |
|
995 | 7 | |
983 | \layout Standard |
|
996 | \layout Standard | |
984 |
|
997 | |||
985 | 3. |
|
998 | 3. | |
986 | It should be possible to easily capture shell output into a variable. |
|
999 | It should be possible to easily capture shell output into a variable. | |
987 | bash and friends use backquotes, I think using a command (@sc) like ipython |
|
1000 | bash and friends use backquotes, I think using a command (@sc) like ipython | |
988 | currently does is an acceptable compromise. |
|
1001 | currently does is an acceptable compromise. | |
989 | \layout Standard |
|
1002 | \layout Standard | |
990 |
|
1003 | |||
991 | 4. |
|
1004 | 4. | |
992 | It should also be possible to expand python variables/commands in the middle |
|
1005 | It should also be possible to expand python variables/commands in the middle | |
993 | of system commands. |
|
1006 | of system commands. | |
994 | I thihk this will make it necessary to use $var for name expansions: |
|
1007 | I thihk this will make it necessary to use $var for name expansions: | |
995 | \layout Standard |
|
1008 | \layout Standard | |
996 |
|
1009 | |||
997 | >> var='hello' # var is a Python variable |
|
1010 | >> var='hello' # var is a Python variable | |
998 | \newline |
|
1011 | \newline | |
999 | >> print var hello # This is the result of a Python print command |
|
1012 | >> print var hello # This is the result of a Python print command | |
1000 | \newline |
|
1013 | \newline | |
1001 | >> echo $var hello # This calls the echo command, expanding 'var'. |
|
1014 | >> echo $var hello # This calls the echo command, expanding 'var'. | |
1002 | \layout Standard |
|
1015 | \layout Standard | |
1003 |
|
1016 | |||
1004 | 5. |
|
1017 | 5. | |
1005 | The above capabilities should remain possible for multi-line commands. |
|
1018 | The above capabilities should remain possible for multi-line commands. | |
1006 | One of the most annoying things I find about tcsh, is that I never quite |
|
1019 | One of the most annoying things I find about tcsh, is that I never quite | |
1007 | remember the syntactic details of looping. |
|
1020 | remember the syntactic details of looping. | |
1008 | I often want to do something at the shell which involves a simple loop, |
|
1021 | I often want to do something at the shell which involves a simple loop, | |
1009 | but I can never remember how to do it in tcsh. |
|
1022 | but I can never remember how to do it in tcsh. | |
1010 | This often means I just write a quick throwaway python script to do it |
|
1023 | This often means I just write a quick throwaway python script to do it | |
1011 | (Perl is great for this kind of quick things, but I've forgotten most its |
|
1024 | (Perl is great for this kind of quick things, but I've forgotten most its | |
1012 | syntax as well). |
|
1025 | syntax as well). | |
1013 | \layout Standard |
|
1026 | \layout Standard | |
1014 |
|
1027 | |||
1015 | It should be possible to write code like: |
|
1028 | It should be possible to write code like: | |
1016 | \layout Standard |
|
1029 | \layout Standard | |
1017 |
|
1030 | |||
1018 | >> for ext in ['.jpg','.gif']: |
|
1031 | >> for ext in ['.jpg','.gif']: | |
1019 | \newline |
|
1032 | \newline | |
1020 | .. |
|
1033 | .. | |
1021 | ls file$ext |
|
1034 | ls file$ext | |
1022 | \layout Standard |
|
1035 | \layout Standard | |
1023 |
|
1036 | |||
1024 | And have it work as 'ls file.jpg;ls file.gif'. |
|
1037 | And have it work as 'ls file.jpg;ls file.gif'. | |
1025 | \layout Subsection |
|
1038 | \layout Subsection | |
1026 |
|
1039 | |||
1027 | Smaller details |
|
1040 | Smaller details | |
1028 | \layout Standard |
|
1041 | \layout Standard | |
1029 |
|
1042 | |||
1030 | If the above are considered as valid guiding principles for how such a python |
|
1043 | If the above are considered as valid guiding principles for how such a python | |
1031 | system shell should behave, then some smaller considerations and comments |
|
1044 | system shell should behave, then some smaller considerations and comments | |
1032 | to keep in mind are listed below. |
|
1045 | to keep in mind are listed below. | |
1033 | \layout Standard |
|
1046 | \layout Standard | |
1034 |
|
1047 | |||
1035 | - it's ok for shell builtins (in this case this includes the python language) |
|
1048 | - it's ok for shell builtins (in this case this includes the python language) | |
1036 | to override system commands on the path. |
|
1049 | to override system commands on the path. | |
1037 | See tcsh's 'time' vs '/usr/bin/time'. |
|
1050 | See tcsh's 'time' vs '/usr/bin/time'. | |
1038 | This settles the 'print' issue and related. |
|
1051 | This settles the 'print' issue and related. | |
1039 | \layout Standard |
|
1052 | \layout Standard | |
1040 |
|
1053 | |||
1041 | - pysh should take |
|
1054 | - pysh should take | |
1042 | \layout Standard |
|
1055 | \layout Standard | |
1043 |
|
1056 | |||
1044 | foo args |
|
1057 | foo args | |
1045 | \layout Standard |
|
1058 | \layout Standard | |
1046 |
|
1059 | |||
1047 | as a command if (foo args is NOT valid python) and (foo is in $PATH). |
|
1060 | as a command if (foo args is NOT valid python) and (foo is in $PATH). | |
1048 | \layout Standard |
|
1061 | \layout Standard | |
1049 |
|
1062 | |||
1050 | If the user types |
|
1063 | If the user types | |
1051 | \layout Standard |
|
1064 | \layout Standard | |
1052 |
|
1065 | |||
1053 | >> ./foo args |
|
1066 | >> ./foo args | |
1054 | \layout Standard |
|
1067 | \layout Standard | |
1055 |
|
1068 | |||
1056 | it should be considered a system command always. |
|
1069 | it should be considered a system command always. | |
1057 | \layout Standard |
|
1070 | \layout Standard | |
1058 |
|
1071 | |||
1059 | - _, __ and ___ should automatically remember the previous 3 outputs captured |
|
1072 | - _, __ and ___ should automatically remember the previous 3 outputs captured | |
1060 | from stdout. |
|
1073 | from stdout. | |
1061 | In parallel, there should be _e, __e and ___e for stderr. |
|
1074 | In parallel, there should be _e, __e and ___e for stderr. | |
1062 | Whether capture is done as a single string or in list mode should be a |
|
1075 | Whether capture is done as a single string or in list mode should be a | |
1063 | user preference. |
|
1076 | user preference. | |
1064 | If users have numbered prompts, ipython's full In/Out cache system should |
|
1077 | If users have numbered prompts, ipython's full In/Out cache system should | |
1065 | be available. |
|
1078 | be available. | |
1066 | \layout Standard |
|
1079 | \layout Standard | |
1067 |
|
1080 | |||
1068 | But regardless of how variables are captured, the printout should be like |
|
1081 | But regardless of how variables are captured, the printout should be like | |
1069 | that of a plain shell (without quotes or braces to indicate strings/lists). |
|
1082 | that of a plain shell (without quotes or braces to indicate strings/lists). | |
1070 | The everyday 'feel' of pysh should be more that of bash/tcsh than that |
|
1083 | The everyday 'feel' of pysh should be more that of bash/tcsh than that | |
1071 | of ipython. |
|
1084 | of ipython. | |
1072 | \layout Standard |
|
1085 | \layout Standard | |
1073 |
|
1086 | |||
1074 | - filename completion first. |
|
1087 | - filename completion first. | |
1075 | Tab completion could work like in ipython, but with the order of priorities |
|
1088 | Tab completion could work like in ipython, but with the order of priorities | |
1076 | reversed: first files, then python names. |
|
1089 | reversed: first files, then python names. | |
1077 | \layout Standard |
|
1090 | \layout Standard | |
1078 |
|
1091 | |||
1079 | - configuration via standard python files. |
|
1092 | - configuration via standard python files. | |
1080 | Instead of 'setenv' you'd simply write into the os.environ[] dictionary. |
|
1093 | Instead of 'setenv' you'd simply write into the os.environ[] dictionary. | |
1081 | This assumes that IPython itself has been fixed to be configured via normal |
|
1094 | This assumes that IPython itself has been fixed to be configured via normal | |
1082 | python files, instead of the current clunky ipythonrc format. |
|
1095 | python files, instead of the current clunky ipythonrc format. | |
1083 | \layout Standard |
|
1096 | \layout Standard | |
1084 |
|
1097 | |||
1085 | - IPython can already configure the prompt in fairly generic ways. |
|
1098 | - IPython can already configure the prompt in fairly generic ways. | |
1086 | It should be able to generate almost any kind of prompt which bash/tcsh |
|
1099 | It should be able to generate almost any kind of prompt which bash/tcsh | |
1087 | can (within reason). |
|
1100 | can (within reason). | |
1088 | \layout Standard |
|
1101 | \layout Standard | |
1089 |
|
1102 | |||
1090 | - Keep the Magics system. |
|
1103 | - Keep the Magics system. | |
1091 | They provide a lightweight syntax for configuring and modifying the state |
|
1104 | They provide a lightweight syntax for configuring and modifying the state | |
1092 | of the user's session itself. |
|
1105 | of the user's session itself. | |
1093 | Plus, they are an extensible system so why not give the users one more |
|
1106 | Plus, they are an extensible system so why not give the users one more | |
1094 | tool which is fairly flexible by nature? Finally, having the @magic optional |
|
1107 | tool which is fairly flexible by nature? Finally, having the @magic optional | |
1095 | syntax allows a user to always be able to access the shell's control system, |
|
1108 | syntax allows a user to always be able to access the shell's control system, | |
1096 | regardless of name collisions with defined variables or system commands. |
|
1109 | regardless of name collisions with defined variables or system commands. | |
1097 | \layout Standard |
|
1110 | \layout Standard | |
1098 |
|
1111 | |||
1099 | But we need to move all magic functionality into a protected namespace, |
|
1112 | But we need to move all magic functionality into a protected namespace, | |
1100 | instead of the current messy name-mangling tricks (which don't scale well). |
|
1113 | instead of the current messy name-mangling tricks (which don't scale well). | |
1101 |
|
1114 | |||
1102 | \layout Section |
|
1115 | \layout Section | |
1103 |
|
1116 | |||
1104 | Future improvements |
|
1117 | Future improvements | |
1105 | \layout Itemize |
|
1118 | \layout Itemize | |
1106 |
|
1119 | |||
1107 | When from <mod> import * is used, first check the existing namespace and |
|
1120 | When from <mod> import * is used, first check the existing namespace and | |
1108 | at least issue a warning on screen if names are overwritten. |
|
1121 | at least issue a warning on screen if names are overwritten. | |
1109 | \layout Itemize |
|
1122 | \layout Itemize | |
1110 |
|
1123 | |||
1111 | Auto indent? Done, for users with readline support. |
|
1124 | Auto indent? Done, for users with readline support. | |
1112 | \layout Subsection |
|
1125 | \layout Subsection | |
1113 |
|
1126 | |||
1114 | Better completion a la zsh |
|
1127 | Better completion a la zsh | |
1115 | \layout Standard |
|
1128 | \layout Standard | |
1116 |
|
1129 | |||
1117 | This was suggested by Arnd: |
|
1130 | This was suggested by Arnd: | |
1118 | \layout Standard |
|
1131 | \layout Standard | |
1119 |
|
1132 | |||
1120 | > >\SpecialChar ~ |
|
1133 | > >\SpecialChar ~ | |
1121 | \SpecialChar ~ |
|
1134 | \SpecialChar ~ | |
1122 | \SpecialChar ~ |
|
1135 | \SpecialChar ~ | |
1123 | More general, this might lead to something like |
|
1136 | More general, this might lead to something like | |
1124 | \layout Standard |
|
1137 | \layout Standard | |
1125 |
|
1138 | |||
1126 | > >\SpecialChar ~ |
|
1139 | > >\SpecialChar ~ | |
1127 | \SpecialChar ~ |
|
1140 | \SpecialChar ~ | |
1128 | \SpecialChar ~ |
|
1141 | \SpecialChar ~ | |
1129 | command specific completion ? |
|
1142 | command specific completion ? | |
1130 | \layout Standard |
|
1143 | \layout Standard | |
1131 |
|
1144 | |||
1132 | > |
|
1145 | > | |
1133 | \layout Standard |
|
1146 | \layout Standard | |
1134 |
|
1147 | |||
1135 | > I'm not sure what you mean here. |
|
1148 | > I'm not sure what you mean here. | |
1136 | \layout Standard |
|
1149 | \layout Standard | |
1137 |
|
1150 | |||
1138 | \SpecialChar ~ |
|
1151 | \SpecialChar ~ | |
1139 |
|
1152 | |||
1140 | \layout Standard |
|
1153 | \layout Standard | |
1141 |
|
1154 | |||
1142 | Sorry, that was not understandable, indeed ... |
|
1155 | Sorry, that was not understandable, indeed ... | |
1143 | \layout Standard |
|
1156 | \layout Standard | |
1144 |
|
1157 | |||
1145 | I thought of something like |
|
1158 | I thought of something like | |
1146 | \layout Standard |
|
1159 | \layout Standard | |
1147 |
|
1160 | |||
1148 | \SpecialChar ~ |
|
1161 | \SpecialChar ~ | |
1149 | - cd and then use TAB to go through the list of directories |
|
1162 | - cd and then use TAB to go through the list of directories | |
1150 | \layout Standard |
|
1163 | \layout Standard | |
1151 |
|
1164 | |||
1152 | \SpecialChar ~ |
|
1165 | \SpecialChar ~ | |
1153 | - ls and then TAB to consider all files and directories |
|
1166 | - ls and then TAB to consider all files and directories | |
1154 | \layout Standard |
|
1167 | \layout Standard | |
1155 |
|
1168 | |||
1156 | \SpecialChar ~ |
|
1169 | \SpecialChar ~ | |
1157 | - cat and TAB: only files (no directories ...) |
|
1170 | - cat and TAB: only files (no directories ...) | |
1158 | \layout Standard |
|
1171 | \layout Standard | |
1159 |
|
1172 | |||
1160 | \SpecialChar ~ |
|
1173 | \SpecialChar ~ | |
1161 |
|
1174 | |||
1162 | \layout Standard |
|
1175 | \layout Standard | |
1163 |
|
1176 | |||
1164 | For zsh things like this are established by defining in .zshrc |
|
1177 | For zsh things like this are established by defining in .zshrc | |
1165 | \layout Standard |
|
1178 | \layout Standard | |
1166 |
|
1179 | |||
1167 | \SpecialChar ~ |
|
1180 | \SpecialChar ~ | |
1168 |
|
1181 | |||
1169 | \layout Standard |
|
1182 | \layout Standard | |
1170 |
|
1183 | |||
1171 | compctl -g '*.dvi' xdvi |
|
1184 | compctl -g '*.dvi' xdvi | |
1172 | \layout Standard |
|
1185 | \layout Standard | |
1173 |
|
1186 | |||
1174 | compctl -g '*.dvi' dvips |
|
1187 | compctl -g '*.dvi' dvips | |
1175 | \layout Standard |
|
1188 | \layout Standard | |
1176 |
|
1189 | |||
1177 | compctl -g '*.tex' latex |
|
1190 | compctl -g '*.tex' latex | |
1178 | \layout Standard |
|
1191 | \layout Standard | |
1179 |
|
1192 | |||
1180 | compctl -g '*.tex' tex |
|
1193 | compctl -g '*.tex' tex | |
1181 | \layout Standard |
|
1194 | \layout Standard | |
1182 |
|
1195 | |||
1183 | ... |
|
1196 | ... | |
1184 | \layout Section |
|
1197 | \layout Section | |
1185 |
|
1198 | |||
1186 | Outline of steps |
|
1199 | Outline of steps | |
1187 | \layout Standard |
|
1200 | \layout Standard | |
1188 |
|
1201 | |||
1189 | Here's a rough outline of the order in which to start implementing the various |
|
1202 | Here's a rough outline of the order in which to start implementing the various | |
1190 | parts of the redesign. |
|
1203 | parts of the redesign. | |
1191 | The first 'test of success' should be a clean pychecker run (not the mess |
|
1204 | The first 'test of success' should be a clean pychecker run (not the mess | |
1192 | we get right now). |
|
1205 | we get right now). | |
1193 | \layout Itemize |
|
1206 | \layout Itemize | |
1194 |
|
1207 | |||
1195 | Make Logger and Magic not be mixins but attributes of the main class. |
|
1208 | Make Logger and Magic not be mixins but attributes of the main class. | |
1196 |
|
1209 | |||
1197 | \begin_deeper |
|
1210 | \begin_deeper | |
1198 | \layout Itemize |
|
1211 | \layout Itemize | |
1199 |
|
1212 | |||
1200 | Magic should have a pointer back to the main instance (even if this creates |
|
1213 | Magic should have a pointer back to the main instance (even if this creates | |
1201 | a recursive structure) so it can control it with minimal message-passing |
|
1214 | a recursive structure) so it can control it with minimal message-passing | |
1202 | machinery. |
|
1215 | machinery. | |
1203 |
|
1216 | |||
1204 | \layout Itemize |
|
1217 | \layout Itemize | |
1205 |
|
1218 | |||
1206 | Logger can be a standalone object, simply with a nice, clean interface. |
|
1219 | Logger can be a standalone object, simply with a nice, clean interface. | |
1207 | \layout Itemize |
|
1220 | \layout Itemize | |
1208 |
|
1221 | |||
1209 | Logger currently handles part of the prompt caching, but other parts of |
|
1222 | Logger currently handles part of the prompt caching, but other parts of | |
1210 | that are in the prompts class itself. |
|
1223 | that are in the prompts class itself. | |
1211 | Clean up. |
|
1224 | Clean up. | |
1212 | \end_deeper |
|
1225 | \end_deeper | |
1213 | \layout Itemize |
|
1226 | \layout Itemize | |
1214 |
|
1227 | |||
1215 | Change to python-based config system. |
|
1228 | Change to python-based config system. | |
1216 | \layout Itemize |
|
1229 | \layout Itemize | |
1217 |
|
1230 | |||
1218 | Move make_IPython() into the main shell class, as part of the constructor. |
|
1231 | Move make_IPython() into the main shell class, as part of the constructor. | |
1219 | Do this |
|
1232 | Do this | |
1220 | \emph on |
|
1233 | \emph on | |
1221 | after |
|
1234 | after | |
1222 | \emph default |
|
1235 | \emph default | |
1223 | the config system has been changed, debugging will be a lot easier then. |
|
1236 | the config system has been changed, debugging will be a lot easier then. | |
1224 | \layout Itemize |
|
1237 | \layout Itemize | |
1225 |
|
1238 | |||
1226 | Merge the embeddable class and the normal one into one. |
|
1239 | Merge the embeddable class and the normal one into one. | |
1227 | After all, the standard ipython script |
|
1240 | After all, the standard ipython script | |
1228 | \emph on |
|
1241 | \emph on | |
1229 | is |
|
1242 | is | |
1230 | \emph default |
|
1243 | \emph default | |
1231 | a python program with IPython embedded in it. |
|
1244 | a python program with IPython embedded in it. | |
1232 | There's no need for two separate classes ( |
|
1245 | There's no need for two separate classes ( | |
1233 | \emph on |
|
1246 | \emph on | |
1234 | maybe |
|
1247 | maybe | |
1235 | \emph default |
|
1248 | \emph default | |
1236 | keep the old one around for the sake of backwards compatibility). |
|
1249 | keep the old one around for the sake of backwards compatibility). | |
1237 | \layout Section |
|
1250 | \layout Section | |
1238 |
|
1251 | |||
1239 | Ville Vainio's suggestions |
|
1252 | Ville Vainio's suggestions | |
1240 | \layout Standard |
|
1253 | \layout Standard | |
1241 |
|
1254 | |||
1242 | Some notes sent in by Ville Vainio |
|
1255 | Some notes sent in by Ville Vainio | |
1243 | \family typewriter |
|
1256 | \family typewriter | |
1244 | <vivainio@kolumbus.fi> |
|
1257 | <vivainio@kolumbus.fi> | |
1245 | \family default |
|
1258 | \family default | |
1246 | on Tue, 29 Jun 2004. |
|
1259 | on Tue, 29 Jun 2004. | |
1247 | Keep here for reference, some of it replicates things already said above. |
|
1260 | Keep here for reference, some of it replicates things already said above. | |
1248 | \layout Standard |
|
1261 | \layout Standard | |
1249 |
|
1262 | |||
1250 | Current ipython seems to "special case" lots of stuff - aliases, magics |
|
1263 | Current ipython seems to "special case" lots of stuff - aliases, magics | |
1251 | etc. |
|
1264 | etc. | |
1252 | It would seem to yield itself to a simpler and more extensible architecture, |
|
1265 | It would seem to yield itself to a simpler and more extensible architecture, | |
1253 | consisting of multple dictionaries, where just the order of search is determine |
|
1266 | consisting of multple dictionaries, where just the order of search is determine | |
1254 | d by profile/prefix. |
|
1267 | d by profile/prefix. | |
1255 | All the functionality would just be "pushed" to ipython core, i.e. |
|
1268 | All the functionality would just be "pushed" to ipython core, i.e. | |
1256 | the objects that represent the functionality are instantiated on "plugins" |
|
1269 | the objects that represent the functionality are instantiated on "plugins" | |
1257 | and they are registered with ipython core. |
|
1270 | and they are registered with ipython core. | |
1258 | i.e. |
|
1271 | i.e. | |
1259 | \layout Standard |
|
1272 | \layout Standard | |
1260 |
|
1273 | |||
1261 | def magic_f(options, args): pass |
|
1274 | def magic_f(options, args): pass | |
1262 | \layout Standard |
|
1275 | \layout Standard | |
1263 |
|
1276 | |||
1264 | m = MyMagic(magic_f) m.arghandler = stockhandlers.OptParseArgHandler m.options |
|
1277 | m = MyMagic(magic_f) m.arghandler = stockhandlers.OptParseArgHandler m.options | |
1265 | = .... |
|
1278 | = .... | |
1266 | # optparse options, for easy passing to magic_f and help display |
|
1279 | # optparse options, for easy passing to magic_f and help display | |
1267 | \layout Standard |
|
1280 | \layout Standard | |
1268 |
|
1281 | |||
1269 | # note that arghandler takes a peek at the instance, sees options, and proceeds |
|
1282 | # note that arghandler takes a peek at the instance, sees options, and proceeds | |
1270 | # accordingly. |
|
1283 | # accordingly. | |
1271 | Various arg handlers can ask for arbitrary options. |
|
1284 | Various arg handlers can ask for arbitrary options. | |
1272 | # some handler might optionally glob the filenames, search data folders |
|
1285 | # some handler might optionally glob the filenames, search data folders | |
1273 | for filenames etc. |
|
1286 | for filenames etc. | |
1274 | \layout Standard |
|
1287 | \layout Standard | |
1275 |
|
1288 | |||
1276 | ipythonregistry.register(category = "magic", name = "mymagic", obj = m) |
|
1289 | ipythonregistry.register(category = "magic", name = "mymagic", obj = m) | |
1277 | \layout Standard |
|
1290 | \layout Standard | |
1278 |
|
1291 | |||
1279 | I bet most of the current functionality could easily be added to such a |
|
1292 | I bet most of the current functionality could easily be added to such a | |
1280 | registry by just instantiating e.g. |
|
1293 | registry by just instantiating e.g. | |
1281 | "Magic" class and registering all the functions with some sensible default |
|
1294 | "Magic" class and registering all the functions with some sensible default | |
1282 | args. |
|
1295 | args. | |
1283 | Supporting legacy stuff in general would be easy - just implement new handlers |
|
1296 | Supporting legacy stuff in general would be easy - just implement new handlers | |
1284 | (arg and otherwise) for new stuff, and have the old handlers around forever |
|
1297 | (arg and otherwise) for new stuff, and have the old handlers around forever | |
1285 | / as long as is deemed appropriate. |
|
1298 | / as long as is deemed appropriate. | |
1286 | The 'python' namespace (locals() + globals()) should be special, of course. |
|
1299 | The 'python' namespace (locals() + globals()) should be special, of course. | |
1287 | \layout Standard |
|
1300 | \layout Standard | |
1288 |
|
1301 | |||
1289 | It should be easy to have arbitrary number of "categories" (like 'magic', |
|
1302 | It should be easy to have arbitrary number of "categories" (like 'magic', | |
1290 | 'shellcommand','projectspecific_myproject', 'projectspecific_otherproject'). |
|
1303 | 'shellcommand','projectspecific_myproject', 'projectspecific_otherproject'). | |
1291 | It would only influence the order in which the completions are suggested, |
|
1304 | It would only influence the order in which the completions are suggested, | |
1292 | and in case of name collision which one is selected. |
|
1305 | and in case of name collision which one is selected. | |
1293 | Also, I think all completions should be shown, even the ones in "later" |
|
1306 | Also, I think all completions should be shown, even the ones in "later" | |
1294 | categories in the case of a match in an "earlier" category. |
|
1307 | categories in the case of a match in an "earlier" category. | |
1295 | \layout Standard |
|
1308 | \layout Standard | |
1296 |
|
1309 | |||
1297 | The "functionality object" might also have a callable object 'expandarg', |
|
1310 | The "functionality object" might also have a callable object 'expandarg', | |
1298 | and ipython would run it (with the arg index) when tab completion is attempted |
|
1311 | and ipython would run it (with the arg index) when tab completion is attempted | |
1299 | after typing the function name. |
|
1312 | after typing the function name. | |
1300 | It would return the possible completions for that particular command... |
|
1313 | It would return the possible completions for that particular command... | |
1301 | or None to "revert to default file completions". |
|
1314 | or None to "revert to default file completions". | |
1302 | Such functionality could be useful in making ipython an "operating console" |
|
1315 | Such functionality could be useful in making ipython an "operating console" | |
1303 | of a sort. |
|
1316 | of a sort. | |
1304 | I'm talking about: |
|
1317 | I'm talking about: | |
1305 | \layout Standard |
|
1318 | \layout Standard | |
1306 |
|
1319 | |||
1307 | >> lscat reactor # list commands in category - reactor is "project specific" |
|
1320 | >> lscat reactor # list commands in category - reactor is "project specific" | |
1308 | category |
|
1321 | category | |
1309 | \layout Standard |
|
1322 | \layout Standard | |
1310 |
|
1323 | |||
1311 | r_operate |
|
1324 | r_operate | |
1312 | \layout Standard |
|
1325 | \layout Standard | |
1313 |
|
1326 | |||
1314 | >> r_operate <tab> start shutdown notify_meltdown evacuate |
|
1327 | >> r_operate <tab> start shutdown notify_meltdown evacuate | |
1315 | \layout Standard |
|
1328 | \layout Standard | |
1316 |
|
1329 | |||
1317 | >> r_operate shutdown <tab> |
|
1330 | >> r_operate shutdown <tab> | |
1318 | \layout Standard |
|
1331 | \layout Standard | |
1319 |
|
1332 | |||
1320 | 1 2 5 6 # note that 3 and 4 are already shut down |
|
1333 | 1 2 5 6 # note that 3 and 4 are already shut down | |
1321 | \layout Standard |
|
1334 | \layout Standard | |
1322 |
|
1335 | |||
1323 | >> r_operate shutdown 2 |
|
1336 | >> r_operate shutdown 2 | |
1324 | \layout Standard |
|
1337 | \layout Standard | |
1325 |
|
1338 | |||
1326 | Shutting down.. |
|
1339 | Shutting down.. | |
1327 | ok. |
|
1340 | ok. | |
1328 | \layout Standard |
|
1341 | \layout Standard | |
1329 |
|
1342 | |||
1330 | >> r_operate start <tab> |
|
1343 | >> r_operate start <tab> | |
1331 | \layout Standard |
|
1344 | \layout Standard | |
1332 |
|
1345 | |||
1333 | 2 3 4 # 2 was shut down, can be started now |
|
1346 | 2 3 4 # 2 was shut down, can be started now | |
1334 | \layout Standard |
|
1347 | \layout Standard | |
1335 |
|
1348 | |||
1336 | >> r_operate start 2 |
|
1349 | >> r_operate start 2 | |
1337 | \layout Standard |
|
1350 | \layout Standard | |
1338 |
|
1351 | |||
1339 | Starting.... |
|
1352 | Starting.... | |
1340 | ok. |
|
1353 | ok. | |
1341 | \layout Standard |
|
1354 | \layout Standard | |
1342 |
|
1355 | |||
1343 | I'm talking about having a super-configurable man-machine language here! |
|
1356 | I'm talking about having a super-configurable man-machine language here! | |
1344 | Like cmd.Cmd on steroids, as a free addition to ipython! |
|
1357 | Like cmd.Cmd on steroids, as a free addition to ipython! | |
1345 | \the_end |
|
1358 | \the_end |
General Comments 0
You need to be logged in to leave comments.
Login now