##// END OF EJS Templates
Moving and renaming in preparation of subclassing InteractiveShell....
Brian Granger -
Show More
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
@@ -1,66 +1,65 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 IPython.
4 IPython.
5
5
6 IPython is a set of tools for interactive and exploratory computing in Python.
6 IPython is a set of tools for interactive and exploratory computing in Python.
7 """
7 """
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import os
20 import os
21 import sys
21 import sys
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Setup everything
24 # Setup everything
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 if sys.version[0:3] < '2.6':
27 if sys.version[0:3] < '2.6':
28 raise ImportError('Python Version 2.6 or above is required for IPython.')
28 raise ImportError('Python Version 2.6 or above is required for IPython.')
29
29
30
30
31 # Make it easy to import extensions - they are always directly on pythonpath.
31 # Make it easy to import extensions - they are always directly on pythonpath.
32 # Therefore, non-IPython modules can be added to extensions directory.
32 # Therefore, non-IPython modules can be added to extensions directory.
33 # This should probably be in ipapp.py.
33 # This should probably be in ipapp.py.
34 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
34 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Setup the top level names
37 # Setup the top level names
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 from .config.loader import Config
40 from .config.loader import Config
41 from .core import release
41 from .core import release
42 from .core.application import Application
42 from .core.application import Application
43 from .core.ipapp import IPythonApp
43 from .frontend.terminal.embed import embed
44 from .core.embed import embed
45 from .core.error import TryNext
44 from .core.error import TryNext
46 from .core.iplib import InteractiveShell
45 from .core.interactiveshell import InteractiveShell
47 from .testing import test
46 from .testing import test
48
47
49 from .lib import (
48 from .lib import (
50 enable_wx, disable_wx,
49 enable_wx, disable_wx,
51 enable_gtk, disable_gtk,
50 enable_gtk, disable_gtk,
52 enable_qt4, disable_qt4,
51 enable_qt4, disable_qt4,
53 enable_tk, disable_tk,
52 enable_tk, disable_tk,
54 set_inputhook, clear_inputhook,
53 set_inputhook, clear_inputhook,
55 current_gui, spin,
54 current_gui, spin,
56 appstart_qt4, appstart_wx,
55 appstart_qt4, appstart_wx,
57 appstart_gtk, appstart_tk
56 appstart_gtk, appstart_tk
58 )
57 )
59
58
60 # Release data
59 # Release data
61 __author__ = ''
60 __author__ = ''
62 for author, email in release.authors.values():
61 for author, email in release.authors.values():
63 __author__ += author + ' <' + email + '>\n'
62 __author__ += author + ' <' + email + '>\n'
64 __license__ = release.license
63 __license__ = release.license
65 __version__ = release.version
64 __version__ = release.version
66 __revision__ = release.revision
65 __revision__ = release.revision
@@ -1,258 +1,258 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 System command aliases.
4 System command aliases.
5
5
6 Authors:
6 Authors:
7
7
8 * Fernando Perez
8 * Fernando Perez
9 * Brian Granger
9 * Brian Granger
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import __builtin__
23 import __builtin__
24 import keyword
24 import keyword
25 import os
25 import os
26 import re
26 import re
27 import sys
27 import sys
28
28
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.core.splitinput import split_user_input
30 from IPython.core.splitinput import split_user_input
31
31
32 from IPython.utils.traitlets import List, Instance
32 from IPython.utils.traitlets import List, Instance
33 from IPython.utils.autoattr import auto_attr
33 from IPython.utils.autoattr import auto_attr
34 from IPython.utils.warn import warn, error
34 from IPython.utils.warn import warn, error
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Utilities
37 # Utilities
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 # This is used as the pattern for calls to split_user_input.
40 # This is used as the pattern for calls to split_user_input.
41 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
41 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
42
42
43 def default_aliases():
43 def default_aliases():
44 # Make some aliases automatically
44 # Make some aliases automatically
45 # Prepare list of shell aliases to auto-define
45 # Prepare list of shell aliases to auto-define
46 if os.name == 'posix':
46 if os.name == 'posix':
47 default_aliases = ('mkdir mkdir', 'rmdir rmdir',
47 default_aliases = ('mkdir mkdir', 'rmdir rmdir',
48 'mv mv -i','rm rm -i','cp cp -i',
48 'mv mv -i','rm rm -i','cp cp -i',
49 'cat cat','less less','clear clear',
49 'cat cat','less less','clear clear',
50 # a better ls
50 # a better ls
51 'ls ls -F',
51 'ls ls -F',
52 # long ls
52 # long ls
53 'll ls -lF')
53 'll ls -lF')
54 # Extra ls aliases with color, which need special treatment on BSD
54 # Extra ls aliases with color, which need special treatment on BSD
55 # variants
55 # variants
56 ls_extra = ( # color ls
56 ls_extra = ( # color ls
57 'lc ls -F -o --color',
57 'lc ls -F -o --color',
58 # ls normal files only
58 # ls normal files only
59 'lf ls -F -o --color %l | grep ^-',
59 'lf ls -F -o --color %l | grep ^-',
60 # ls symbolic links
60 # ls symbolic links
61 'lk ls -F -o --color %l | grep ^l',
61 'lk ls -F -o --color %l | grep ^l',
62 # directories or links to directories,
62 # directories or links to directories,
63 'ldir ls -F -o --color %l | grep /$',
63 'ldir ls -F -o --color %l | grep /$',
64 # things which are executable
64 # things which are executable
65 'lx ls -F -o --color %l | grep ^-..x',
65 'lx ls -F -o --color %l | grep ^-..x',
66 )
66 )
67 # The BSDs don't ship GNU ls, so they don't understand the
67 # The BSDs don't ship GNU ls, so they don't understand the
68 # --color switch out of the box
68 # --color switch out of the box
69 if 'bsd' in sys.platform:
69 if 'bsd' in sys.platform:
70 ls_extra = ( # ls normal files only
70 ls_extra = ( # ls normal files only
71 'lf ls -lF | grep ^-',
71 'lf ls -lF | grep ^-',
72 # ls symbolic links
72 # ls symbolic links
73 'lk ls -lF | grep ^l',
73 'lk ls -lF | grep ^l',
74 # directories or links to directories,
74 # directories or links to directories,
75 'ldir ls -lF | grep /$',
75 'ldir ls -lF | grep /$',
76 # things which are executable
76 # things which are executable
77 'lx ls -lF | grep ^-..x',
77 'lx ls -lF | grep ^-..x',
78 )
78 )
79 default_aliases = default_aliases + ls_extra
79 default_aliases = default_aliases + ls_extra
80 elif os.name in ['nt','dos']:
80 elif os.name in ['nt','dos']:
81 default_aliases = ('ls dir /on',
81 default_aliases = ('ls dir /on',
82 'ddir dir /ad /on', 'ldir dir /ad /on',
82 'ddir dir /ad /on', 'ldir dir /ad /on',
83 'mkdir mkdir','rmdir rmdir','echo echo',
83 'mkdir mkdir','rmdir rmdir','echo echo',
84 'ren ren','cls cls','copy copy')
84 'ren ren','cls cls','copy copy')
85 else:
85 else:
86 default_aliases = ()
86 default_aliases = ()
87 return [s.split(None,1) for s in default_aliases]
87 return [s.split(None,1) for s in default_aliases]
88
88
89
89
90 class AliasError(Exception):
90 class AliasError(Exception):
91 pass
91 pass
92
92
93
93
94 class InvalidAliasError(AliasError):
94 class InvalidAliasError(AliasError):
95 pass
95 pass
96
96
97
97
98 #-----------------------------------------------------------------------------
98 #-----------------------------------------------------------------------------
99 # Main AliasManager class
99 # Main AliasManager class
100 #-----------------------------------------------------------------------------
100 #-----------------------------------------------------------------------------
101
101
102
102
103 class AliasManager(Configurable):
103 class AliasManager(Configurable):
104
104
105 default_aliases = List(default_aliases(), config=True)
105 default_aliases = List(default_aliases(), config=True)
106 user_aliases = List(default_value=[], config=True)
106 user_aliases = List(default_value=[], config=True)
107 shell = Instance('IPython.core.iplib.InteractiveShellABC')
107 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
108
108
109 def __init__(self, shell=None, config=None):
109 def __init__(self, shell=None, config=None):
110 super(AliasManager, self).__init__(shell=shell, config=config)
110 super(AliasManager, self).__init__(shell=shell, config=config)
111 self.alias_table = {}
111 self.alias_table = {}
112 self.exclude_aliases()
112 self.exclude_aliases()
113 self.init_aliases()
113 self.init_aliases()
114
114
115 def __contains__(self, name):
115 def __contains__(self, name):
116 if name in self.alias_table:
116 if name in self.alias_table:
117 return True
117 return True
118 else:
118 else:
119 return False
119 return False
120
120
121 @property
121 @property
122 def aliases(self):
122 def aliases(self):
123 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
123 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
124
124
125 def exclude_aliases(self):
125 def exclude_aliases(self):
126 # set of things NOT to alias (keywords, builtins and some magics)
126 # set of things NOT to alias (keywords, builtins and some magics)
127 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
127 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
128 no_alias.update(set(keyword.kwlist))
128 no_alias.update(set(keyword.kwlist))
129 no_alias.update(set(__builtin__.__dict__.keys()))
129 no_alias.update(set(__builtin__.__dict__.keys()))
130 self.no_alias = no_alias
130 self.no_alias = no_alias
131
131
132 def init_aliases(self):
132 def init_aliases(self):
133 # Load default aliases
133 # Load default aliases
134 for name, cmd in self.default_aliases:
134 for name, cmd in self.default_aliases:
135 self.soft_define_alias(name, cmd)
135 self.soft_define_alias(name, cmd)
136
136
137 # Load user aliases
137 # Load user aliases
138 for name, cmd in self.user_aliases:
138 for name, cmd in self.user_aliases:
139 self.soft_define_alias(name, cmd)
139 self.soft_define_alias(name, cmd)
140
140
141 def clear_aliases(self):
141 def clear_aliases(self):
142 self.alias_table.clear()
142 self.alias_table.clear()
143
143
144 def soft_define_alias(self, name, cmd):
144 def soft_define_alias(self, name, cmd):
145 """Define an alias, but don't raise on an AliasError."""
145 """Define an alias, but don't raise on an AliasError."""
146 try:
146 try:
147 self.define_alias(name, cmd)
147 self.define_alias(name, cmd)
148 except AliasError, e:
148 except AliasError, e:
149 error("Invalid alias: %s" % e)
149 error("Invalid alias: %s" % e)
150
150
151 def define_alias(self, name, cmd):
151 def define_alias(self, name, cmd):
152 """Define a new alias after validating it.
152 """Define a new alias after validating it.
153
153
154 This will raise an :exc:`AliasError` if there are validation
154 This will raise an :exc:`AliasError` if there are validation
155 problems.
155 problems.
156 """
156 """
157 nargs = self.validate_alias(name, cmd)
157 nargs = self.validate_alias(name, cmd)
158 self.alias_table[name] = (nargs, cmd)
158 self.alias_table[name] = (nargs, cmd)
159
159
160 def undefine_alias(self, name):
160 def undefine_alias(self, name):
161 if self.alias_table.has_key(name):
161 if self.alias_table.has_key(name):
162 del self.alias_table[name]
162 del self.alias_table[name]
163
163
164 def validate_alias(self, name, cmd):
164 def validate_alias(self, name, cmd):
165 """Validate an alias and return the its number of arguments."""
165 """Validate an alias and return the its number of arguments."""
166 if name in self.no_alias:
166 if name in self.no_alias:
167 raise InvalidAliasError("The name %s can't be aliased "
167 raise InvalidAliasError("The name %s can't be aliased "
168 "because it is a keyword or builtin." % name)
168 "because it is a keyword or builtin." % name)
169 if not (isinstance(cmd, basestring)):
169 if not (isinstance(cmd, basestring)):
170 raise InvalidAliasError("An alias command must be a string, "
170 raise InvalidAliasError("An alias command must be a string, "
171 "got: %r" % name)
171 "got: %r" % name)
172 nargs = cmd.count('%s')
172 nargs = cmd.count('%s')
173 if nargs>0 and cmd.find('%l')>=0:
173 if nargs>0 and cmd.find('%l')>=0:
174 raise InvalidAliasError('The %s and %l specifiers are mutually '
174 raise InvalidAliasError('The %s and %l specifiers are mutually '
175 'exclusive in alias definitions.')
175 'exclusive in alias definitions.')
176 return nargs
176 return nargs
177
177
178 def call_alias(self, alias, rest=''):
178 def call_alias(self, alias, rest=''):
179 """Call an alias given its name and the rest of the line."""
179 """Call an alias given its name and the rest of the line."""
180 cmd = self.transform_alias(alias, rest)
180 cmd = self.transform_alias(alias, rest)
181 try:
181 try:
182 self.shell.system(cmd)
182 self.shell.system(cmd)
183 except:
183 except:
184 self.shell.showtraceback()
184 self.shell.showtraceback()
185
185
186 def transform_alias(self, alias,rest=''):
186 def transform_alias(self, alias,rest=''):
187 """Transform alias to system command string."""
187 """Transform alias to system command string."""
188 nargs, cmd = self.alias_table[alias]
188 nargs, cmd = self.alias_table[alias]
189
189
190 if ' ' in cmd and os.path.isfile(cmd):
190 if ' ' in cmd and os.path.isfile(cmd):
191 cmd = '"%s"' % cmd
191 cmd = '"%s"' % cmd
192
192
193 # Expand the %l special to be the user's input line
193 # Expand the %l special to be the user's input line
194 if cmd.find('%l') >= 0:
194 if cmd.find('%l') >= 0:
195 cmd = cmd.replace('%l', rest)
195 cmd = cmd.replace('%l', rest)
196 rest = ''
196 rest = ''
197 if nargs==0:
197 if nargs==0:
198 # Simple, argument-less aliases
198 # Simple, argument-less aliases
199 cmd = '%s %s' % (cmd, rest)
199 cmd = '%s %s' % (cmd, rest)
200 else:
200 else:
201 # Handle aliases with positional arguments
201 # Handle aliases with positional arguments
202 args = rest.split(None, nargs)
202 args = rest.split(None, nargs)
203 if len(args) < nargs:
203 if len(args) < nargs:
204 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
204 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
205 (alias, nargs, len(args)))
205 (alias, nargs, len(args)))
206 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
206 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
207 return cmd
207 return cmd
208
208
209 def expand_alias(self, line):
209 def expand_alias(self, line):
210 """ Expand an alias in the command line
210 """ Expand an alias in the command line
211
211
212 Returns the provided command line, possibly with the first word
212 Returns the provided command line, possibly with the first word
213 (command) translated according to alias expansion rules.
213 (command) translated according to alias expansion rules.
214
214
215 [ipython]|16> _ip.expand_aliases("np myfile.txt")
215 [ipython]|16> _ip.expand_aliases("np myfile.txt")
216 <16> 'q:/opt/np/notepad++.exe myfile.txt'
216 <16> 'q:/opt/np/notepad++.exe myfile.txt'
217 """
217 """
218
218
219 pre,fn,rest = split_user_input(line)
219 pre,fn,rest = split_user_input(line)
220 res = pre + self.expand_aliases(fn, rest)
220 res = pre + self.expand_aliases(fn, rest)
221 return res
221 return res
222
222
223 def expand_aliases(self, fn, rest):
223 def expand_aliases(self, fn, rest):
224 """Expand multiple levels of aliases:
224 """Expand multiple levels of aliases:
225
225
226 if:
226 if:
227
227
228 alias foo bar /tmp
228 alias foo bar /tmp
229 alias baz foo
229 alias baz foo
230
230
231 then:
231 then:
232
232
233 baz huhhahhei -> bar /tmp huhhahhei
233 baz huhhahhei -> bar /tmp huhhahhei
234
234
235 """
235 """
236 line = fn + " " + rest
236 line = fn + " " + rest
237
237
238 done = set()
238 done = set()
239 while 1:
239 while 1:
240 pre,fn,rest = split_user_input(line, shell_line_split)
240 pre,fn,rest = split_user_input(line, shell_line_split)
241 if fn in self.alias_table:
241 if fn in self.alias_table:
242 if fn in done:
242 if fn in done:
243 warn("Cyclic alias definition, repeated '%s'" % fn)
243 warn("Cyclic alias definition, repeated '%s'" % fn)
244 return ""
244 return ""
245 done.add(fn)
245 done.add(fn)
246
246
247 l2 = self.transform_alias(fn, rest)
247 l2 = self.transform_alias(fn, rest)
248 if l2 == line:
248 if l2 == line:
249 break
249 break
250 # ls -> ls -F should not recurse forever
250 # ls -> ls -F should not recurse forever
251 if l2.split(None,1)[0] == line.split(None,1)[0]:
251 if l2.split(None,1)[0] == line.split(None,1)[0]:
252 line = l2
252 line = l2
253 break
253 break
254 line=l2
254 line=l2
255 else:
255 else:
256 break
256 break
257
257
258 return line
258 return line
@@ -1,115 +1,115 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A context manager for managing things injected into :mod:`__builtin__`.
4 A context manager for managing things injected into :mod:`__builtin__`.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import __builtin__
22 import __builtin__
23
23
24 from IPython.config.configurable import Configurable
24 from IPython.config.configurable import Configurable
25 from IPython.core.quitter import Quitter
25 from IPython.core.quitter import Quitter
26
26
27 from IPython.utils.traitlets import Instance
27 from IPython.utils.traitlets import Instance
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Classes and functions
30 # Classes and functions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33
33
34 class __BuiltinUndefined(object): pass
34 class __BuiltinUndefined(object): pass
35 BuiltinUndefined = __BuiltinUndefined()
35 BuiltinUndefined = __BuiltinUndefined()
36
36
37
37
38 class BuiltinTrap(Configurable):
38 class BuiltinTrap(Configurable):
39
39
40 shell = Instance('IPython.core.iplib.InteractiveShellABC')
40 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
41
41
42 def __init__(self, shell=None):
42 def __init__(self, shell=None):
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
44 self._orig_builtins = {}
44 self._orig_builtins = {}
45 # We define this to track if a single BuiltinTrap is nested.
45 # We define this to track if a single BuiltinTrap is nested.
46 # Only turn off the trap when the outermost call to __exit__ is made.
46 # Only turn off the trap when the outermost call to __exit__ is made.
47 self._nested_level = 0
47 self._nested_level = 0
48 self.shell = shell
48 self.shell = shell
49
49
50 def __enter__(self):
50 def __enter__(self):
51 if self._nested_level == 0:
51 if self._nested_level == 0:
52 self.set()
52 self.set()
53 self._nested_level += 1
53 self._nested_level += 1
54 # I return self, so callers can use add_builtin in a with clause.
54 # I return self, so callers can use add_builtin in a with clause.
55 return self
55 return self
56
56
57 def __exit__(self, type, value, traceback):
57 def __exit__(self, type, value, traceback):
58 if self._nested_level == 1:
58 if self._nested_level == 1:
59 self.unset()
59 self.unset()
60 self._nested_level -= 1
60 self._nested_level -= 1
61 # Returning False will cause exceptions to propagate
61 # Returning False will cause exceptions to propagate
62 return False
62 return False
63
63
64 def add_builtin(self, key, value):
64 def add_builtin(self, key, value):
65 """Add a builtin and save the original."""
65 """Add a builtin and save the original."""
66 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
66 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
67 self._orig_builtins[key] = orig
67 self._orig_builtins[key] = orig
68 __builtin__.__dict__[key] = value
68 __builtin__.__dict__[key] = value
69
69
70 def remove_builtin(self, key):
70 def remove_builtin(self, key):
71 """Remove an added builtin and re-set the original."""
71 """Remove an added builtin and re-set the original."""
72 try:
72 try:
73 orig = self._orig_builtins.pop(key)
73 orig = self._orig_builtins.pop(key)
74 except KeyError:
74 except KeyError:
75 pass
75 pass
76 else:
76 else:
77 if orig is BuiltinUndefined:
77 if orig is BuiltinUndefined:
78 del __builtin__.__dict__[key]
78 del __builtin__.__dict__[key]
79 else:
79 else:
80 __builtin__.__dict__[key] = orig
80 __builtin__.__dict__[key] = orig
81
81
82 def set(self):
82 def set(self):
83 """Store ipython references in the __builtin__ namespace."""
83 """Store ipython references in the __builtin__ namespace."""
84 self.add_builtin('exit', Quitter(self.shell, 'exit'))
84 self.add_builtin('exit', Quitter(self.shell, 'exit'))
85 self.add_builtin('quit', Quitter(self.shell, 'quit'))
85 self.add_builtin('quit', Quitter(self.shell, 'quit'))
86 self.add_builtin('get_ipython', self.shell.get_ipython)
86 self.add_builtin('get_ipython', self.shell.get_ipython)
87
87
88 # Recursive reload function
88 # Recursive reload function
89 try:
89 try:
90 from IPython.lib import deepreload
90 from IPython.lib import deepreload
91 if self.shell.deep_reload:
91 if self.shell.deep_reload:
92 self.add_builtin('reload', deepreload.reload)
92 self.add_builtin('reload', deepreload.reload)
93 else:
93 else:
94 self.add_builtin('dreload', deepreload.reload)
94 self.add_builtin('dreload', deepreload.reload)
95 del deepreload
95 del deepreload
96 except ImportError:
96 except ImportError:
97 pass
97 pass
98
98
99 # Keep in the builtins a flag for when IPython is active. We set it
99 # Keep in the builtins a flag for when IPython is active. We set it
100 # with setdefault so that multiple nested IPythons don't clobber one
100 # with setdefault so that multiple nested IPythons don't clobber one
101 # another. Each will increase its value by one upon being activated,
101 # another. Each will increase its value by one upon being activated,
102 # which also gives us a way to determine the nesting level.
102 # which also gives us a way to determine the nesting level.
103 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
103 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
104
104
105 def unset(self):
105 def unset(self):
106 """Remove any builtins which might have been added by add_builtins, or
106 """Remove any builtins which might have been added by add_builtins, or
107 restore overwritten ones to their previous values."""
107 restore overwritten ones to their previous values."""
108 for key in self._orig_builtins.keys():
108 for key in self._orig_builtins.keys():
109 self.remove_builtin(key)
109 self.remove_builtin(key)
110 self._orig_builtins.clear()
110 self._orig_builtins.clear()
111 self._builtins_added = False
111 self._builtins_added = False
112 try:
112 try:
113 del __builtin__.__dict__['__IPYTHON__active']
113 del __builtin__.__dict__['__IPYTHON__active']
114 except KeyError:
114 except KeyError:
115 pass
115 pass
@@ -1,510 +1,510 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 http://www.python.org/2.2.3/license.html"""
16 http://www.python.org/2.2.3/license.html"""
17
17
18 #*****************************************************************************
18 #*****************************************************************************
19 #
19 #
20 # This file is licensed under the PSF license.
20 # This file is licensed under the PSF license.
21 #
21 #
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 #
24 #
25 #
25 #
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 import bdb
28 import bdb
29 import linecache
29 import linecache
30 import sys
30 import sys
31
31
32 from IPython.utils import PyColorize
32 from IPython.utils import PyColorize
33 from IPython.core import ipapi
33 from IPython.core import ipapi
34 from IPython.utils import coloransi
34 from IPython.utils import coloransi
35 from IPython.utils.io import Term
35 from IPython.utils.io import Term
36 from IPython.core.excolors import exception_colors
36 from IPython.core.excolors import exception_colors
37
37
38 # See if we can use pydb.
38 # See if we can use pydb.
39 has_pydb = False
39 has_pydb = False
40 prompt = 'ipdb> '
40 prompt = 'ipdb> '
41 #We have to check this directly from sys.argv, config struct not yet available
41 #We have to check this directly from sys.argv, config struct not yet available
42 if '-pydb' in sys.argv:
42 if '-pydb' in sys.argv:
43 try:
43 try:
44 import pydb
44 import pydb
45 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
45 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
46 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
46 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
47 # better protect against it.
47 # better protect against it.
48 has_pydb = True
48 has_pydb = True
49 except ImportError:
49 except ImportError:
50 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
50 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
51
51
52 if has_pydb:
52 if has_pydb:
53 from pydb import Pdb as OldPdb
53 from pydb import Pdb as OldPdb
54 #print "Using pydb for %run -d and post-mortem" #dbg
54 #print "Using pydb for %run -d and post-mortem" #dbg
55 prompt = 'ipydb> '
55 prompt = 'ipydb> '
56 else:
56 else:
57 from pdb import Pdb as OldPdb
57 from pdb import Pdb as OldPdb
58
58
59 # Allow the set_trace code to operate outside of an ipython instance, even if
59 # Allow the set_trace code to operate outside of an ipython instance, even if
60 # it does so with some limitations. The rest of this support is implemented in
60 # it does so with some limitations. The rest of this support is implemented in
61 # the Tracer constructor.
61 # the Tracer constructor.
62 def BdbQuit_excepthook(et,ev,tb):
62 def BdbQuit_excepthook(et,ev,tb):
63 if et==bdb.BdbQuit:
63 if et==bdb.BdbQuit:
64 print 'Exiting Debugger.'
64 print 'Exiting Debugger.'
65 else:
65 else:
66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
67
67
68 def BdbQuit_IPython_excepthook(self,et,ev,tb):
68 def BdbQuit_IPython_excepthook(self,et,ev,tb):
69 print 'Exiting Debugger.'
69 print 'Exiting Debugger.'
70
70
71
71
72 class Tracer(object):
72 class Tracer(object):
73 """Class for local debugging, similar to pdb.set_trace.
73 """Class for local debugging, similar to pdb.set_trace.
74
74
75 Instances of this class, when called, behave like pdb.set_trace, but
75 Instances of this class, when called, behave like pdb.set_trace, but
76 providing IPython's enhanced capabilities.
76 providing IPython's enhanced capabilities.
77
77
78 This is implemented as a class which must be initialized in your own code
78 This is implemented as a class which must be initialized in your own code
79 and not as a standalone function because we need to detect at runtime
79 and not as a standalone function because we need to detect at runtime
80 whether IPython is already active or not. That detection is done in the
80 whether IPython is already active or not. That detection is done in the
81 constructor, ensuring that this code plays nicely with a running IPython,
81 constructor, ensuring that this code plays nicely with a running IPython,
82 while functioning acceptably (though with limitations) if outside of it.
82 while functioning acceptably (though with limitations) if outside of it.
83 """
83 """
84
84
85 def __init__(self,colors=None):
85 def __init__(self,colors=None):
86 """Create a local debugger instance.
86 """Create a local debugger instance.
87
87
88 :Parameters:
88 :Parameters:
89
89
90 - `colors` (None): a string containing the name of the color scheme to
90 - `colors` (None): a string containing the name of the color scheme to
91 use, it must be one of IPython's valid color schemes. If not given, the
91 use, it must be one of IPython's valid color schemes. If not given, the
92 function will default to the current IPython scheme when running inside
92 function will default to the current IPython scheme when running inside
93 IPython, and to 'NoColor' otherwise.
93 IPython, and to 'NoColor' otherwise.
94
94
95 Usage example:
95 Usage example:
96
96
97 from IPython.core.debugger import Tracer; debug_here = Tracer()
97 from IPython.core.debugger import Tracer; debug_here = Tracer()
98
98
99 ... later in your code
99 ... later in your code
100 debug_here() # -> will open up the debugger at that point.
100 debug_here() # -> will open up the debugger at that point.
101
101
102 Once the debugger activates, you can use all of its regular commands to
102 Once the debugger activates, you can use all of its regular commands to
103 step through code, set breakpoints, etc. See the pdb documentation
103 step through code, set breakpoints, etc. See the pdb documentation
104 from the Python standard library for usage details.
104 from the Python standard library for usage details.
105 """
105 """
106
106
107 try:
107 try:
108 ip = ipapi.get()
108 ip = ipapi.get()
109 except:
109 except:
110 # Outside of ipython, we set our own exception hook manually
110 # Outside of ipython, we set our own exception hook manually
111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
112 sys.excepthook = BdbQuit_excepthook
112 sys.excepthook = BdbQuit_excepthook
113 def_colors = 'NoColor'
113 def_colors = 'NoColor'
114 try:
114 try:
115 # Limited tab completion support
115 # Limited tab completion support
116 import readline
116 import readline
117 readline.parse_and_bind('tab: complete')
117 readline.parse_and_bind('tab: complete')
118 except ImportError:
118 except ImportError:
119 pass
119 pass
120 else:
120 else:
121 # In ipython, we use its custom exception handler mechanism
121 # In ipython, we use its custom exception handler mechanism
122 def_colors = ip.colors
122 def_colors = ip.colors
123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
124
124
125 if colors is None:
125 if colors is None:
126 colors = def_colors
126 colors = def_colors
127 self.debugger = Pdb(colors)
127 self.debugger = Pdb(colors)
128
128
129 def __call__(self):
129 def __call__(self):
130 """Starts an interactive debugger at the point where called.
130 """Starts an interactive debugger at the point where called.
131
131
132 This is similar to the pdb.set_trace() function from the std lib, but
132 This is similar to the pdb.set_trace() function from the std lib, but
133 using IPython's enhanced debugger."""
133 using IPython's enhanced debugger."""
134
134
135 self.debugger.set_trace(sys._getframe().f_back)
135 self.debugger.set_trace(sys._getframe().f_back)
136
136
137
137
138 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
138 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
139 """Make new_fn have old_fn's doc string. This is particularly useful
139 """Make new_fn have old_fn's doc string. This is particularly useful
140 for the do_... commands that hook into the help system.
140 for the do_... commands that hook into the help system.
141 Adapted from from a comp.lang.python posting
141 Adapted from from a comp.lang.python posting
142 by Duncan Booth."""
142 by Duncan Booth."""
143 def wrapper(*args, **kw):
143 def wrapper(*args, **kw):
144 return new_fn(*args, **kw)
144 return new_fn(*args, **kw)
145 if old_fn.__doc__:
145 if old_fn.__doc__:
146 wrapper.__doc__ = old_fn.__doc__ + additional_text
146 wrapper.__doc__ = old_fn.__doc__ + additional_text
147 return wrapper
147 return wrapper
148
148
149
149
150 def _file_lines(fname):
150 def _file_lines(fname):
151 """Return the contents of a named file as a list of lines.
151 """Return the contents of a named file as a list of lines.
152
152
153 This function never raises an IOError exception: if the file can't be
153 This function never raises an IOError exception: if the file can't be
154 read, it simply returns an empty list."""
154 read, it simply returns an empty list."""
155
155
156 try:
156 try:
157 outfile = open(fname)
157 outfile = open(fname)
158 except IOError:
158 except IOError:
159 return []
159 return []
160 else:
160 else:
161 out = outfile.readlines()
161 out = outfile.readlines()
162 outfile.close()
162 outfile.close()
163 return out
163 return out
164
164
165
165
166 class Pdb(OldPdb):
166 class Pdb(OldPdb):
167 """Modified Pdb class, does not load readline."""
167 """Modified Pdb class, does not load readline."""
168
168
169 def __init__(self,color_scheme='NoColor',completekey=None,
169 def __init__(self,color_scheme='NoColor',completekey=None,
170 stdin=None, stdout=None):
170 stdin=None, stdout=None):
171
171
172 # Parent constructor:
172 # Parent constructor:
173 if has_pydb and completekey is None:
173 if has_pydb and completekey is None:
174 OldPdb.__init__(self,stdin=stdin,stdout=Term.cout)
174 OldPdb.__init__(self,stdin=stdin,stdout=Term.cout)
175 else:
175 else:
176 OldPdb.__init__(self,completekey,stdin,stdout)
176 OldPdb.__init__(self,completekey,stdin,stdout)
177
177
178 self.prompt = prompt # The default prompt is '(Pdb)'
178 self.prompt = prompt # The default prompt is '(Pdb)'
179
179
180 # IPython changes...
180 # IPython changes...
181 self.is_pydb = has_pydb
181 self.is_pydb = has_pydb
182
182
183 self.shell = ipapi.get()
183 self.shell = ipapi.get()
184
184
185 if self.is_pydb:
185 if self.is_pydb:
186
186
187 # iplib.py's ipalias seems to want pdb's checkline
187 # interactiveshell.py's ipalias seems to want pdb's checkline
188 # which located in pydb.fn
188 # which located in pydb.fn
189 import pydb.fns
189 import pydb.fns
190 self.checkline = lambda filename, lineno: \
190 self.checkline = lambda filename, lineno: \
191 pydb.fns.checkline(self, filename, lineno)
191 pydb.fns.checkline(self, filename, lineno)
192
192
193 self.curframe = None
193 self.curframe = None
194 self.do_restart = self.new_do_restart
194 self.do_restart = self.new_do_restart
195
195
196 self.old_all_completions = self.shell.Completer.all_completions
196 self.old_all_completions = self.shell.Completer.all_completions
197 self.shell.Completer.all_completions=self.all_completions
197 self.shell.Completer.all_completions=self.all_completions
198
198
199 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
199 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
200 OldPdb.do_list)
200 OldPdb.do_list)
201 self.do_l = self.do_list
201 self.do_l = self.do_list
202 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
202 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
203 OldPdb.do_frame)
203 OldPdb.do_frame)
204
204
205 self.aliases = {}
205 self.aliases = {}
206
206
207 # Create color table: we copy the default one from the traceback
207 # Create color table: we copy the default one from the traceback
208 # module and add a few attributes needed for debugging
208 # module and add a few attributes needed for debugging
209 self.color_scheme_table = exception_colors()
209 self.color_scheme_table = exception_colors()
210
210
211 # shorthands
211 # shorthands
212 C = coloransi.TermColors
212 C = coloransi.TermColors
213 cst = self.color_scheme_table
213 cst = self.color_scheme_table
214
214
215 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
215 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
216 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
216 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
217
217
218 cst['Linux'].colors.breakpoint_enabled = C.LightRed
218 cst['Linux'].colors.breakpoint_enabled = C.LightRed
219 cst['Linux'].colors.breakpoint_disabled = C.Red
219 cst['Linux'].colors.breakpoint_disabled = C.Red
220
220
221 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
221 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
222 cst['LightBG'].colors.breakpoint_disabled = C.Red
222 cst['LightBG'].colors.breakpoint_disabled = C.Red
223
223
224 self.set_colors(color_scheme)
224 self.set_colors(color_scheme)
225
225
226 # Add a python parser so we can syntax highlight source while
226 # Add a python parser so we can syntax highlight source while
227 # debugging.
227 # debugging.
228 self.parser = PyColorize.Parser()
228 self.parser = PyColorize.Parser()
229
229
230 def set_colors(self, scheme):
230 def set_colors(self, scheme):
231 """Shorthand access to the color table scheme selector method."""
231 """Shorthand access to the color table scheme selector method."""
232 self.color_scheme_table.set_active_scheme(scheme)
232 self.color_scheme_table.set_active_scheme(scheme)
233
233
234 def interaction(self, frame, traceback):
234 def interaction(self, frame, traceback):
235 self.shell.set_completer_frame(frame)
235 self.shell.set_completer_frame(frame)
236 OldPdb.interaction(self, frame, traceback)
236 OldPdb.interaction(self, frame, traceback)
237
237
238 def new_do_up(self, arg):
238 def new_do_up(self, arg):
239 OldPdb.do_up(self, arg)
239 OldPdb.do_up(self, arg)
240 self.shell.set_completer_frame(self.curframe)
240 self.shell.set_completer_frame(self.curframe)
241 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
241 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
242
242
243 def new_do_down(self, arg):
243 def new_do_down(self, arg):
244 OldPdb.do_down(self, arg)
244 OldPdb.do_down(self, arg)
245 self.shell.set_completer_frame(self.curframe)
245 self.shell.set_completer_frame(self.curframe)
246
246
247 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
247 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
248
248
249 def new_do_frame(self, arg):
249 def new_do_frame(self, arg):
250 OldPdb.do_frame(self, arg)
250 OldPdb.do_frame(self, arg)
251 self.shell.set_completer_frame(self.curframe)
251 self.shell.set_completer_frame(self.curframe)
252
252
253 def new_do_quit(self, arg):
253 def new_do_quit(self, arg):
254
254
255 if hasattr(self, 'old_all_completions'):
255 if hasattr(self, 'old_all_completions'):
256 self.shell.Completer.all_completions=self.old_all_completions
256 self.shell.Completer.all_completions=self.old_all_completions
257
257
258
258
259 return OldPdb.do_quit(self, arg)
259 return OldPdb.do_quit(self, arg)
260
260
261 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
261 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
262
262
263 def new_do_restart(self, arg):
263 def new_do_restart(self, arg):
264 """Restart command. In the context of ipython this is exactly the same
264 """Restart command. In the context of ipython this is exactly the same
265 thing as 'quit'."""
265 thing as 'quit'."""
266 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
266 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
267 return self.do_quit(arg)
267 return self.do_quit(arg)
268
268
269 def postloop(self):
269 def postloop(self):
270 self.shell.set_completer_frame(None)
270 self.shell.set_completer_frame(None)
271
271
272 def print_stack_trace(self):
272 def print_stack_trace(self):
273 try:
273 try:
274 for frame_lineno in self.stack:
274 for frame_lineno in self.stack:
275 self.print_stack_entry(frame_lineno, context = 5)
275 self.print_stack_entry(frame_lineno, context = 5)
276 except KeyboardInterrupt:
276 except KeyboardInterrupt:
277 pass
277 pass
278
278
279 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
279 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
280 context = 3):
280 context = 3):
281 #frame, lineno = frame_lineno
281 #frame, lineno = frame_lineno
282 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
282 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
283
283
284 # vds: >>
284 # vds: >>
285 frame, lineno = frame_lineno
285 frame, lineno = frame_lineno
286 filename = frame.f_code.co_filename
286 filename = frame.f_code.co_filename
287 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
287 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
288 # vds: <<
288 # vds: <<
289
289
290 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
290 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
291 import linecache, repr
291 import linecache, repr
292
292
293 ret = []
293 ret = []
294
294
295 Colors = self.color_scheme_table.active_colors
295 Colors = self.color_scheme_table.active_colors
296 ColorsNormal = Colors.Normal
296 ColorsNormal = Colors.Normal
297 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
297 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
298 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
298 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
299 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
299 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
300 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
300 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
301 ColorsNormal)
301 ColorsNormal)
302
302
303 frame, lineno = frame_lineno
303 frame, lineno = frame_lineno
304
304
305 return_value = ''
305 return_value = ''
306 if '__return__' in frame.f_locals:
306 if '__return__' in frame.f_locals:
307 rv = frame.f_locals['__return__']
307 rv = frame.f_locals['__return__']
308 #return_value += '->'
308 #return_value += '->'
309 return_value += repr.repr(rv) + '\n'
309 return_value += repr.repr(rv) + '\n'
310 ret.append(return_value)
310 ret.append(return_value)
311
311
312 #s = filename + '(' + `lineno` + ')'
312 #s = filename + '(' + `lineno` + ')'
313 filename = self.canonic(frame.f_code.co_filename)
313 filename = self.canonic(frame.f_code.co_filename)
314 link = tpl_link % filename
314 link = tpl_link % filename
315
315
316 if frame.f_code.co_name:
316 if frame.f_code.co_name:
317 func = frame.f_code.co_name
317 func = frame.f_code.co_name
318 else:
318 else:
319 func = "<lambda>"
319 func = "<lambda>"
320
320
321 call = ''
321 call = ''
322 if func != '?':
322 if func != '?':
323 if '__args__' in frame.f_locals:
323 if '__args__' in frame.f_locals:
324 args = repr.repr(frame.f_locals['__args__'])
324 args = repr.repr(frame.f_locals['__args__'])
325 else:
325 else:
326 args = '()'
326 args = '()'
327 call = tpl_call % (func, args)
327 call = tpl_call % (func, args)
328
328
329 # The level info should be generated in the same format pdb uses, to
329 # The level info should be generated in the same format pdb uses, to
330 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
330 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
331 if frame is self.curframe:
331 if frame is self.curframe:
332 ret.append('> ')
332 ret.append('> ')
333 else:
333 else:
334 ret.append(' ')
334 ret.append(' ')
335 ret.append('%s(%s)%s\n' % (link,lineno,call))
335 ret.append('%s(%s)%s\n' % (link,lineno,call))
336
336
337 start = lineno - 1 - context//2
337 start = lineno - 1 - context//2
338 lines = linecache.getlines(filename)
338 lines = linecache.getlines(filename)
339 start = max(start, 0)
339 start = max(start, 0)
340 start = min(start, len(lines) - context)
340 start = min(start, len(lines) - context)
341 lines = lines[start : start + context]
341 lines = lines[start : start + context]
342
342
343 for i,line in enumerate(lines):
343 for i,line in enumerate(lines):
344 show_arrow = (start + 1 + i == lineno)
344 show_arrow = (start + 1 + i == lineno)
345 linetpl = (frame is self.curframe or show_arrow) \
345 linetpl = (frame is self.curframe or show_arrow) \
346 and tpl_line_em \
346 and tpl_line_em \
347 or tpl_line
347 or tpl_line
348 ret.append(self.__format_line(linetpl, filename,
348 ret.append(self.__format_line(linetpl, filename,
349 start + 1 + i, line,
349 start + 1 + i, line,
350 arrow = show_arrow) )
350 arrow = show_arrow) )
351
351
352 return ''.join(ret)
352 return ''.join(ret)
353
353
354 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
354 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
355 bp_mark = ""
355 bp_mark = ""
356 bp_mark_color = ""
356 bp_mark_color = ""
357
357
358 scheme = self.color_scheme_table.active_scheme_name
358 scheme = self.color_scheme_table.active_scheme_name
359 new_line, err = self.parser.format2(line, 'str', scheme)
359 new_line, err = self.parser.format2(line, 'str', scheme)
360 if not err: line = new_line
360 if not err: line = new_line
361
361
362 bp = None
362 bp = None
363 if lineno in self.get_file_breaks(filename):
363 if lineno in self.get_file_breaks(filename):
364 bps = self.get_breaks(filename, lineno)
364 bps = self.get_breaks(filename, lineno)
365 bp = bps[-1]
365 bp = bps[-1]
366
366
367 if bp:
367 if bp:
368 Colors = self.color_scheme_table.active_colors
368 Colors = self.color_scheme_table.active_colors
369 bp_mark = str(bp.number)
369 bp_mark = str(bp.number)
370 bp_mark_color = Colors.breakpoint_enabled
370 bp_mark_color = Colors.breakpoint_enabled
371 if not bp.enabled:
371 if not bp.enabled:
372 bp_mark_color = Colors.breakpoint_disabled
372 bp_mark_color = Colors.breakpoint_disabled
373
373
374 numbers_width = 7
374 numbers_width = 7
375 if arrow:
375 if arrow:
376 # This is the line with the error
376 # This is the line with the error
377 pad = numbers_width - len(str(lineno)) - len(bp_mark)
377 pad = numbers_width - len(str(lineno)) - len(bp_mark)
378 if pad >= 3:
378 if pad >= 3:
379 marker = '-'*(pad-3) + '-> '
379 marker = '-'*(pad-3) + '-> '
380 elif pad == 2:
380 elif pad == 2:
381 marker = '> '
381 marker = '> '
382 elif pad == 1:
382 elif pad == 1:
383 marker = '>'
383 marker = '>'
384 else:
384 else:
385 marker = ''
385 marker = ''
386 num = '%s%s' % (marker, str(lineno))
386 num = '%s%s' % (marker, str(lineno))
387 line = tpl_line % (bp_mark_color + bp_mark, num, line)
387 line = tpl_line % (bp_mark_color + bp_mark, num, line)
388 else:
388 else:
389 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
389 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
390 line = tpl_line % (bp_mark_color + bp_mark, num, line)
390 line = tpl_line % (bp_mark_color + bp_mark, num, line)
391
391
392 return line
392 return line
393
393
394 def list_command_pydb(self, arg):
394 def list_command_pydb(self, arg):
395 """List command to use if we have a newer pydb installed"""
395 """List command to use if we have a newer pydb installed"""
396 filename, first, last = OldPdb.parse_list_cmd(self, arg)
396 filename, first, last = OldPdb.parse_list_cmd(self, arg)
397 if filename is not None:
397 if filename is not None:
398 self.print_list_lines(filename, first, last)
398 self.print_list_lines(filename, first, last)
399
399
400 def print_list_lines(self, filename, first, last):
400 def print_list_lines(self, filename, first, last):
401 """The printing (as opposed to the parsing part of a 'list'
401 """The printing (as opposed to the parsing part of a 'list'
402 command."""
402 command."""
403 try:
403 try:
404 Colors = self.color_scheme_table.active_colors
404 Colors = self.color_scheme_table.active_colors
405 ColorsNormal = Colors.Normal
405 ColorsNormal = Colors.Normal
406 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
406 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
407 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
407 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
408 src = []
408 src = []
409 for lineno in range(first, last+1):
409 for lineno in range(first, last+1):
410 line = linecache.getline(filename, lineno)
410 line = linecache.getline(filename, lineno)
411 if not line:
411 if not line:
412 break
412 break
413
413
414 if lineno == self.curframe.f_lineno:
414 if lineno == self.curframe.f_lineno:
415 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
415 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
416 else:
416 else:
417 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
417 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
418
418
419 src.append(line)
419 src.append(line)
420 self.lineno = lineno
420 self.lineno = lineno
421
421
422 print >>Term.cout, ''.join(src)
422 print >>Term.cout, ''.join(src)
423
423
424 except KeyboardInterrupt:
424 except KeyboardInterrupt:
425 pass
425 pass
426
426
427 def do_list(self, arg):
427 def do_list(self, arg):
428 self.lastcmd = 'list'
428 self.lastcmd = 'list'
429 last = None
429 last = None
430 if arg:
430 if arg:
431 try:
431 try:
432 x = eval(arg, {}, {})
432 x = eval(arg, {}, {})
433 if type(x) == type(()):
433 if type(x) == type(()):
434 first, last = x
434 first, last = x
435 first = int(first)
435 first = int(first)
436 last = int(last)
436 last = int(last)
437 if last < first:
437 if last < first:
438 # Assume it's a count
438 # Assume it's a count
439 last = first + last
439 last = first + last
440 else:
440 else:
441 first = max(1, int(x) - 5)
441 first = max(1, int(x) - 5)
442 except:
442 except:
443 print '*** Error in argument:', `arg`
443 print '*** Error in argument:', `arg`
444 return
444 return
445 elif self.lineno is None:
445 elif self.lineno is None:
446 first = max(1, self.curframe.f_lineno - 5)
446 first = max(1, self.curframe.f_lineno - 5)
447 else:
447 else:
448 first = self.lineno + 1
448 first = self.lineno + 1
449 if last is None:
449 if last is None:
450 last = first + 10
450 last = first + 10
451 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
451 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
452
452
453 # vds: >>
453 # vds: >>
454 lineno = first
454 lineno = first
455 filename = self.curframe.f_code.co_filename
455 filename = self.curframe.f_code.co_filename
456 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
456 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
457 # vds: <<
457 # vds: <<
458
458
459 do_l = do_list
459 do_l = do_list
460
460
461 def do_pdef(self, arg):
461 def do_pdef(self, arg):
462 """The debugger interface to magic_pdef"""
462 """The debugger interface to magic_pdef"""
463 namespaces = [('Locals', self.curframe.f_locals),
463 namespaces = [('Locals', self.curframe.f_locals),
464 ('Globals', self.curframe.f_globals)]
464 ('Globals', self.curframe.f_globals)]
465 self.shell.magic_pdef(arg, namespaces=namespaces)
465 self.shell.magic_pdef(arg, namespaces=namespaces)
466
466
467 def do_pdoc(self, arg):
467 def do_pdoc(self, arg):
468 """The debugger interface to magic_pdoc"""
468 """The debugger interface to magic_pdoc"""
469 namespaces = [('Locals', self.curframe.f_locals),
469 namespaces = [('Locals', self.curframe.f_locals),
470 ('Globals', self.curframe.f_globals)]
470 ('Globals', self.curframe.f_globals)]
471 self.shell.magic_pdoc(arg, namespaces=namespaces)
471 self.shell.magic_pdoc(arg, namespaces=namespaces)
472
472
473 def do_pinfo(self, arg):
473 def do_pinfo(self, arg):
474 """The debugger equivalant of ?obj"""
474 """The debugger equivalant of ?obj"""
475 namespaces = [('Locals', self.curframe.f_locals),
475 namespaces = [('Locals', self.curframe.f_locals),
476 ('Globals', self.curframe.f_globals)]
476 ('Globals', self.curframe.f_globals)]
477 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
477 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
478
478
479 def checkline(self, filename, lineno):
479 def checkline(self, filename, lineno):
480 """Check whether specified line seems to be executable.
480 """Check whether specified line seems to be executable.
481
481
482 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
482 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
483 line or EOF). Warning: testing is not comprehensive.
483 line or EOF). Warning: testing is not comprehensive.
484 """
484 """
485 #######################################################################
485 #######################################################################
486 # XXX Hack! Use python-2.5 compatible code for this call, because with
486 # XXX Hack! Use python-2.5 compatible code for this call, because with
487 # all of our changes, we've drifted from the pdb api in 2.6. For now,
487 # all of our changes, we've drifted from the pdb api in 2.6. For now,
488 # changing:
488 # changing:
489 #
489 #
490 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
490 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
491 # to:
491 # to:
492 #
492 #
493 line = linecache.getline(filename, lineno)
493 line = linecache.getline(filename, lineno)
494 #
494 #
495 # does the trick. But in reality, we need to fix this by reconciling
495 # does the trick. But in reality, we need to fix this by reconciling
496 # our updates with the new Pdb APIs in Python 2.6.
496 # our updates with the new Pdb APIs in Python 2.6.
497 #
497 #
498 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
498 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
499 #######################################################################
499 #######################################################################
500
500
501 if not line:
501 if not line:
502 print >>self.stdout, 'End of file'
502 print >>self.stdout, 'End of file'
503 return 0
503 return 0
504 line = line.strip()
504 line = line.strip()
505 # Don't allow setting breakpoint at a blank line
505 # Don't allow setting breakpoint at a blank line
506 if (not line or (line[0] == '#') or
506 if (not line or (line[0] == '#') or
507 (line[:3] == '"""') or line[:3] == "'''"):
507 (line[:3] == '"""') or line[:3] == "'''"):
508 print >>self.stdout, '*** Blank or comment'
508 print >>self.stdout, '*** Blank or comment'
509 return 0
509 return 0
510 return lineno
510 return lineno
@@ -1,125 +1,125 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """A class for managing IPython extensions.
2 """A class for managing IPython extensions.
3
3
4 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2010 The IPython Development Team
10 # Copyright (C) 2010 The IPython Development Team
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 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 import os
20 import os
21 import sys
21 import sys
22
22
23 from IPython.config.configurable import Configurable
23 from IPython.config.configurable import Configurable
24 from IPython.utils.traitlets import Instance
24 from IPython.utils.traitlets import Instance
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Main class
27 # Main class
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class ExtensionManager(Configurable):
30 class ExtensionManager(Configurable):
31 """A class to manage IPython extensions.
31 """A class to manage IPython extensions.
32
32
33 An IPython extension is an importable Python module that has
33 An IPython extension is an importable Python module that has
34 a function with the signature::
34 a function with the signature::
35
35
36 def load_ipython_extension(ipython):
36 def load_ipython_extension(ipython):
37 # Do things with ipython
37 # Do things with ipython
38
38
39 This function is called after your extension is imported and the
39 This function is called after your extension is imported and the
40 currently active :class:`InteractiveShell` instance is passed as
40 currently active :class:`InteractiveShell` instance is passed as
41 the only argument. You can do anything you want with IPython at
41 the only argument. You can do anything you want with IPython at
42 that point, including defining new magic and aliases, adding new
42 that point, including defining new magic and aliases, adding new
43 components, etc.
43 components, etc.
44
44
45 The :func:`load_ipython_extension` will be called again is you
45 The :func:`load_ipython_extension` will be called again is you
46 load or reload the extension again. It is up to the extension
46 load or reload the extension again. It is up to the extension
47 author to add code to manage that.
47 author to add code to manage that.
48
48
49 You can put your extension modules anywhere you want, as long as
49 You can put your extension modules anywhere you want, as long as
50 they can be imported by Python's standard import mechanism. However,
50 they can be imported by Python's standard import mechanism. However,
51 to make it easy to write extensions, you can also put your extensions
51 to make it easy to write extensions, you can also put your extensions
52 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
52 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
53 is added to ``sys.path`` automatically.
53 is added to ``sys.path`` automatically.
54 """
54 """
55
55
56 shell = Instance('IPython.core.iplib.InteractiveShellABC')
56 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
57
57
58 def __init__(self, shell=None, config=None):
58 def __init__(self, shell=None, config=None):
59 super(ExtensionManager, self).__init__(shell=shell, config=config)
59 super(ExtensionManager, self).__init__(shell=shell, config=config)
60 self.shell.on_trait_change(
60 self.shell.on_trait_change(
61 self._on_ipython_dir_changed, 'ipython_dir'
61 self._on_ipython_dir_changed, 'ipython_dir'
62 )
62 )
63
63
64 def __del__(self):
64 def __del__(self):
65 self.shell.on_trait_change(
65 self.shell.on_trait_change(
66 self._on_ipython_dir_changed, 'ipython_dir', remove=True
66 self._on_ipython_dir_changed, 'ipython_dir', remove=True
67 )
67 )
68
68
69 @property
69 @property
70 def ipython_extension_dir(self):
70 def ipython_extension_dir(self):
71 return os.path.join(self.shell.ipython_dir, u'extensions')
71 return os.path.join(self.shell.ipython_dir, u'extensions')
72
72
73 def _on_ipython_dir_changed(self):
73 def _on_ipython_dir_changed(self):
74 if not os.path.isdir(self.ipython_extension_dir):
74 if not os.path.isdir(self.ipython_extension_dir):
75 os.makedirs(self.ipython_extension_dir, mode = 0777)
75 os.makedirs(self.ipython_extension_dir, mode = 0777)
76
76
77 def load_extension(self, module_str):
77 def load_extension(self, module_str):
78 """Load an IPython extension by its module name.
78 """Load an IPython extension by its module name.
79
79
80 If :func:`load_ipython_extension` returns anything, this function
80 If :func:`load_ipython_extension` returns anything, this function
81 will return that object.
81 will return that object.
82 """
82 """
83 from IPython.utils.syspathcontext import prepended_to_syspath
83 from IPython.utils.syspathcontext import prepended_to_syspath
84
84
85 if module_str not in sys.modules:
85 if module_str not in sys.modules:
86 with prepended_to_syspath(self.ipython_extension_dir):
86 with prepended_to_syspath(self.ipython_extension_dir):
87 __import__(module_str)
87 __import__(module_str)
88 mod = sys.modules[module_str]
88 mod = sys.modules[module_str]
89 return self._call_load_ipython_extension(mod)
89 return self._call_load_ipython_extension(mod)
90
90
91 def unload_extension(self, module_str):
91 def unload_extension(self, module_str):
92 """Unload an IPython extension by its module name.
92 """Unload an IPython extension by its module name.
93
93
94 This function looks up the extension's name in ``sys.modules`` and
94 This function looks up the extension's name in ``sys.modules`` and
95 simply calls ``mod.unload_ipython_extension(self)``.
95 simply calls ``mod.unload_ipython_extension(self)``.
96 """
96 """
97 if module_str in sys.modules:
97 if module_str in sys.modules:
98 mod = sys.modules[module_str]
98 mod = sys.modules[module_str]
99 self._call_unload_ipython_extension(mod)
99 self._call_unload_ipython_extension(mod)
100
100
101 def reload_extension(self, module_str):
101 def reload_extension(self, module_str):
102 """Reload an IPython extension by calling reload.
102 """Reload an IPython extension by calling reload.
103
103
104 If the module has not been loaded before,
104 If the module has not been loaded before,
105 :meth:`InteractiveShell.load_extension` is called. Otherwise
105 :meth:`InteractiveShell.load_extension` is called. Otherwise
106 :func:`reload` is called and then the :func:`load_ipython_extension`
106 :func:`reload` is called and then the :func:`load_ipython_extension`
107 function of the module, if it exists is called.
107 function of the module, if it exists is called.
108 """
108 """
109 from IPython.utils.syspathcontext import prepended_to_syspath
109 from IPython.utils.syspathcontext import prepended_to_syspath
110
110
111 with prepended_to_syspath(self.ipython_extension_dir):
111 with prepended_to_syspath(self.ipython_extension_dir):
112 if module_str in sys.modules:
112 if module_str in sys.modules:
113 mod = sys.modules[module_str]
113 mod = sys.modules[module_str]
114 reload(mod)
114 reload(mod)
115 self._call_load_ipython_extension(mod)
115 self._call_load_ipython_extension(mod)
116 else:
116 else:
117 self.load_extension(module_str)
117 self.load_extension(module_str)
118
118
119 def _call_load_ipython_extension(self, mod):
119 def _call_load_ipython_extension(self, mod):
120 if hasattr(mod, 'load_ipython_extension'):
120 if hasattr(mod, 'load_ipython_extension'):
121 return mod.load_ipython_extension(self.shell)
121 return mod.load_ipython_extension(self.shell)
122
122
123 def _call_unload_ipython_extension(self, mod):
123 def _call_unload_ipython_extension(self, mod):
124 if hasattr(mod, 'unload_ipython_extension'):
124 if hasattr(mod, 'unload_ipython_extension'):
125 return mod.unload_ipython_extension(self.shell)
125 return mod.unload_ipython_extension(self.shell)
1 NO CONTENT: file renamed from IPython/core/iplib.py to IPython/core/interactiveshell.py
NO CONTENT: file renamed from IPython/core/iplib.py to IPython/core/interactiveshell.py
@@ -1,30 +1,30 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 This module is *completely* deprecated and should no longer be used for
4 This module is *completely* deprecated and should no longer be used for
5 any purpose. Currently, we have a few parts of the core that have
5 any purpose. Currently, we have a few parts of the core that have
6 not been componentized and thus, still rely on this module. When everything
6 not been componentized and thus, still rely on this module. When everything
7 has been made into a component, this module will be sent to deathrow.
7 has been made into a component, this module will be sent to deathrow.
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2009 The IPython Development Team
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Imports
18 # Imports
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Classes and functions
22 # Classes and functions
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25
25
26 def get():
26 def get():
27 """Get the global InteractiveShell instance."""
27 """Get the global InteractiveShell instance."""
28 from IPython.core.iplib import InteractiveShell
28 from IPython.core.interactiveshell import InteractiveShell
29 return InteractiveShell.instance()
29 return InteractiveShell.instance()
30
30
@@ -1,3708 +1,3708 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 import types
28 import types
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pformat
31 from pprint import pformat
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # print_function was added to __future__ in Python2.6, remove this when we drop
44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 # 2.5 compatibility
45 # 2.5 compatibility
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48
48
49 import IPython
49 import IPython
50 from IPython.core import debugger, oinspect
50 from IPython.core import debugger, oinspect
51 from IPython.core.error import TryNext
51 from IPython.core.error import TryNext
52 from IPython.core.error import UsageError
52 from IPython.core.error import UsageError
53 from IPython.core.fakemodule import FakeModule
53 from IPython.core.fakemodule import FakeModule
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.page import page
55 from IPython.core.page import page
56 from IPython.core.prefilter import ESC_MAGIC
56 from IPython.core.prefilter import ESC_MAGIC
57 from IPython.lib.pylabtools import mpl_runner
57 from IPython.lib.pylabtools import mpl_runner
58 from IPython.lib.inputhook import enable_gui
58 from IPython.lib.inputhook import enable_gui
59 from IPython.external.Itpl import itpl, printpl
59 from IPython.external.Itpl import itpl, printpl
60 from IPython.testing import decorators as testdec
60 from IPython.testing import decorators as testdec
61 from IPython.utils.io import Term, file_read, nlprint
61 from IPython.utils.io import Term, file_read, nlprint
62 from IPython.utils.path import get_py_filename
62 from IPython.utils.path import get_py_filename
63 from IPython.utils.process import arg_split, abbrev_cwd
63 from IPython.utils.process import arg_split, abbrev_cwd
64 from IPython.utils.terminal import set_term_title
64 from IPython.utils.terminal import set_term_title
65 from IPython.utils.text import LSString, SList, StringTypes
65 from IPython.utils.text import LSString, SList, StringTypes
66 from IPython.utils.timing import clock, clock2
66 from IPython.utils.timing import clock, clock2
67 from IPython.utils.warn import warn, error
67 from IPython.utils.warn import warn, error
68 from IPython.utils.ipstruct import Struct
68 from IPython.utils.ipstruct import Struct
69 import IPython.utils.generics
69 import IPython.utils.generics
70
70
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72 # Utility functions
72 # Utility functions
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74
74
75 def on_off(tag):
75 def on_off(tag):
76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 return ['OFF','ON'][tag]
77 return ['OFF','ON'][tag]
78
78
79 class Bunch: pass
79 class Bunch: pass
80
80
81 def compress_dhist(dh):
81 def compress_dhist(dh):
82 head, tail = dh[:-10], dh[-10:]
82 head, tail = dh[:-10], dh[-10:]
83
83
84 newhead = []
84 newhead = []
85 done = set()
85 done = set()
86 for h in head:
86 for h in head:
87 if h in done:
87 if h in done:
88 continue
88 continue
89 newhead.append(h)
89 newhead.append(h)
90 done.add(h)
90 done.add(h)
91
91
92 return newhead + tail
92 return newhead + tail
93
93
94
94
95 #***************************************************************************
95 #***************************************************************************
96 # Main class implementing Magic functionality
96 # Main class implementing Magic functionality
97
97
98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # on construction of the main InteractiveShell object. Something odd is going
99 # on construction of the main InteractiveShell object. Something odd is going
100 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
100 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 # eventually this needs to be clarified.
101 # eventually this needs to be clarified.
102 # BG: This is because InteractiveShell inherits from this, but is itself a
102 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # Configurable. This messes up the MRO in some way. The fix is that we need to
103 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # make Magic a configurable that InteractiveShell does not subclass.
104 # make Magic a configurable that InteractiveShell does not subclass.
105
105
106 class Magic:
106 class Magic:
107 """Magic functions for InteractiveShell.
107 """Magic functions for InteractiveShell.
108
108
109 Shell functions which can be reached as %function_name. All magic
109 Shell functions which can be reached as %function_name. All magic
110 functions should accept a string, which they can parse for their own
110 functions should accept a string, which they can parse for their own
111 needs. This can make some functions easier to type, eg `%cd ../`
111 needs. This can make some functions easier to type, eg `%cd ../`
112 vs. `%cd("../")`
112 vs. `%cd("../")`
113
113
114 ALL definitions MUST begin with the prefix magic_. The user won't need it
114 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 at the command line, but it is is needed in the definition. """
115 at the command line, but it is is needed in the definition. """
116
116
117 # class globals
117 # class globals
118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 'Automagic is ON, % prefix NOT needed for magic functions.']
119 'Automagic is ON, % prefix NOT needed for magic functions.']
120
120
121 #......................................................................
121 #......................................................................
122 # some utility functions
122 # some utility functions
123
123
124 def __init__(self,shell):
124 def __init__(self,shell):
125
125
126 self.options_table = {}
126 self.options_table = {}
127 if profile is None:
127 if profile is None:
128 self.magic_prun = self.profile_missing_notice
128 self.magic_prun = self.profile_missing_notice
129 self.shell = shell
129 self.shell = shell
130
130
131 # namespace for holding state we may need
131 # namespace for holding state we may need
132 self._magic_state = Bunch()
132 self._magic_state = Bunch()
133
133
134 def profile_missing_notice(self, *args, **kwargs):
134 def profile_missing_notice(self, *args, **kwargs):
135 error("""\
135 error("""\
136 The profile module could not be found. It has been removed from the standard
136 The profile module could not be found. It has been removed from the standard
137 python packages because of its non-free license. To use profiling, install the
137 python packages because of its non-free license. To use profiling, install the
138 python-profiler package from non-free.""")
138 python-profiler package from non-free.""")
139
139
140 def default_option(self,fn,optstr):
140 def default_option(self,fn,optstr):
141 """Make an entry in the options_table for fn, with value optstr"""
141 """Make an entry in the options_table for fn, with value optstr"""
142
142
143 if fn not in self.lsmagic():
143 if fn not in self.lsmagic():
144 error("%s is not a magic function" % fn)
144 error("%s is not a magic function" % fn)
145 self.options_table[fn] = optstr
145 self.options_table[fn] = optstr
146
146
147 def lsmagic(self):
147 def lsmagic(self):
148 """Return a list of currently available magic functions.
148 """Return a list of currently available magic functions.
149
149
150 Gives a list of the bare names after mangling (['ls','cd', ...], not
150 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 ['magic_ls','magic_cd',...]"""
151 ['magic_ls','magic_cd',...]"""
152
152
153 # FIXME. This needs a cleanup, in the way the magics list is built.
153 # FIXME. This needs a cleanup, in the way the magics list is built.
154
154
155 # magics in class definition
155 # magics in class definition
156 class_magic = lambda fn: fn.startswith('magic_') and \
156 class_magic = lambda fn: fn.startswith('magic_') and \
157 callable(Magic.__dict__[fn])
157 callable(Magic.__dict__[fn])
158 # in instance namespace (run-time user additions)
158 # in instance namespace (run-time user additions)
159 inst_magic = lambda fn: fn.startswith('magic_') and \
159 inst_magic = lambda fn: fn.startswith('magic_') and \
160 callable(self.__dict__[fn])
160 callable(self.__dict__[fn])
161 # and bound magics by user (so they can access self):
161 # and bound magics by user (so they can access self):
162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 callable(self.__class__.__dict__[fn])
163 callable(self.__class__.__dict__[fn])
164 magics = filter(class_magic,Magic.__dict__.keys()) + \
164 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 filter(inst_magic,self.__dict__.keys()) + \
165 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_bound_magic,self.__class__.__dict__.keys())
166 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 out = []
167 out = []
168 for fn in set(magics):
168 for fn in set(magics):
169 out.append(fn.replace('magic_','',1))
169 out.append(fn.replace('magic_','',1))
170 out.sort()
170 out.sort()
171 return out
171 return out
172
172
173 def extract_input_slices(self,slices,raw=False):
173 def extract_input_slices(self,slices,raw=False):
174 """Return as a string a set of input history slices.
174 """Return as a string a set of input history slices.
175
175
176 Inputs:
176 Inputs:
177
177
178 - slices: the set of slices is given as a list of strings (like
178 - slices: the set of slices is given as a list of strings (like
179 ['1','4:8','9'], since this function is for use by magic functions
179 ['1','4:8','9'], since this function is for use by magic functions
180 which get their arguments as strings.
180 which get their arguments as strings.
181
181
182 Optional inputs:
182 Optional inputs:
183
183
184 - raw(False): by default, the processed input is used. If this is
184 - raw(False): by default, the processed input is used. If this is
185 true, the raw input history is used instead.
185 true, the raw input history is used instead.
186
186
187 Note that slices can be called with two notations:
187 Note that slices can be called with two notations:
188
188
189 N:M -> standard python form, means including items N...(M-1).
189 N:M -> standard python form, means including items N...(M-1).
190
190
191 N-M -> include items N..M (closed endpoint)."""
191 N-M -> include items N..M (closed endpoint)."""
192
192
193 if raw:
193 if raw:
194 hist = self.shell.input_hist_raw
194 hist = self.shell.input_hist_raw
195 else:
195 else:
196 hist = self.shell.input_hist
196 hist = self.shell.input_hist
197
197
198 cmds = []
198 cmds = []
199 for chunk in slices:
199 for chunk in slices:
200 if ':' in chunk:
200 if ':' in chunk:
201 ini,fin = map(int,chunk.split(':'))
201 ini,fin = map(int,chunk.split(':'))
202 elif '-' in chunk:
202 elif '-' in chunk:
203 ini,fin = map(int,chunk.split('-'))
203 ini,fin = map(int,chunk.split('-'))
204 fin += 1
204 fin += 1
205 else:
205 else:
206 ini = int(chunk)
206 ini = int(chunk)
207 fin = ini+1
207 fin = ini+1
208 cmds.append(hist[ini:fin])
208 cmds.append(hist[ini:fin])
209 return cmds
209 return cmds
210
210
211 def _ofind(self, oname, namespaces=None):
211 def _ofind(self, oname, namespaces=None):
212 """Find an object in the available namespaces.
212 """Find an object in the available namespaces.
213
213
214 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
214 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215
215
216 Has special code to detect magic functions.
216 Has special code to detect magic functions.
217 """
217 """
218 oname = oname.strip()
218 oname = oname.strip()
219 alias_ns = None
219 alias_ns = None
220 if namespaces is None:
220 if namespaces is None:
221 # Namespaces to search in:
221 # Namespaces to search in:
222 # Put them in a list. The order is important so that we
222 # Put them in a list. The order is important so that we
223 # find things in the same order that Python finds them.
223 # find things in the same order that Python finds them.
224 namespaces = [ ('Interactive', self.shell.user_ns),
224 namespaces = [ ('Interactive', self.shell.user_ns),
225 ('IPython internal', self.shell.internal_ns),
225 ('IPython internal', self.shell.internal_ns),
226 ('Python builtin', __builtin__.__dict__),
226 ('Python builtin', __builtin__.__dict__),
227 ('Alias', self.shell.alias_manager.alias_table),
227 ('Alias', self.shell.alias_manager.alias_table),
228 ]
228 ]
229 alias_ns = self.shell.alias_manager.alias_table
229 alias_ns = self.shell.alias_manager.alias_table
230
230
231 # initialize results to 'null'
231 # initialize results to 'null'
232 found = False; obj = None; ospace = None; ds = None;
232 found = False; obj = None; ospace = None; ds = None;
233 ismagic = False; isalias = False; parent = None
233 ismagic = False; isalias = False; parent = None
234
234
235 # We need to special-case 'print', which as of python2.6 registers as a
235 # We need to special-case 'print', which as of python2.6 registers as a
236 # function but should only be treated as one if print_function was
236 # function but should only be treated as one if print_function was
237 # loaded with a future import. In this case, just bail.
237 # loaded with a future import. In this case, just bail.
238 if (oname == 'print' and not (self.shell.compile.compiler.flags &
238 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 __future__.CO_FUTURE_PRINT_FUNCTION)):
239 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 return {'found':found, 'obj':obj, 'namespace':ospace,
240 return {'found':found, 'obj':obj, 'namespace':ospace,
241 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
241 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242
242
243 # Look for the given name by splitting it in parts. If the head is
243 # Look for the given name by splitting it in parts. If the head is
244 # found, then we look for all the remaining parts as members, and only
244 # found, then we look for all the remaining parts as members, and only
245 # declare success if we can find them all.
245 # declare success if we can find them all.
246 oname_parts = oname.split('.')
246 oname_parts = oname.split('.')
247 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
247 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 for nsname,ns in namespaces:
248 for nsname,ns in namespaces:
249 try:
249 try:
250 obj = ns[oname_head]
250 obj = ns[oname_head]
251 except KeyError:
251 except KeyError:
252 continue
252 continue
253 else:
253 else:
254 #print 'oname_rest:', oname_rest # dbg
254 #print 'oname_rest:', oname_rest # dbg
255 for part in oname_rest:
255 for part in oname_rest:
256 try:
256 try:
257 parent = obj
257 parent = obj
258 obj = getattr(obj,part)
258 obj = getattr(obj,part)
259 except:
259 except:
260 # Blanket except b/c some badly implemented objects
260 # Blanket except b/c some badly implemented objects
261 # allow __getattr__ to raise exceptions other than
261 # allow __getattr__ to raise exceptions other than
262 # AttributeError, which then crashes IPython.
262 # AttributeError, which then crashes IPython.
263 break
263 break
264 else:
264 else:
265 # If we finish the for loop (no break), we got all members
265 # If we finish the for loop (no break), we got all members
266 found = True
266 found = True
267 ospace = nsname
267 ospace = nsname
268 if ns == alias_ns:
268 if ns == alias_ns:
269 isalias = True
269 isalias = True
270 break # namespace loop
270 break # namespace loop
271
271
272 # Try to see if it's magic
272 # Try to see if it's magic
273 if not found:
273 if not found:
274 if oname.startswith(ESC_MAGIC):
274 if oname.startswith(ESC_MAGIC):
275 oname = oname[1:]
275 oname = oname[1:]
276 obj = getattr(self,'magic_'+oname,None)
276 obj = getattr(self,'magic_'+oname,None)
277 if obj is not None:
277 if obj is not None:
278 found = True
278 found = True
279 ospace = 'IPython internal'
279 ospace = 'IPython internal'
280 ismagic = True
280 ismagic = True
281
281
282 # Last try: special-case some literals like '', [], {}, etc:
282 # Last try: special-case some literals like '', [], {}, etc:
283 if not found and oname_head in ["''",'""','[]','{}','()']:
283 if not found and oname_head in ["''",'""','[]','{}','()']:
284 obj = eval(oname_head)
284 obj = eval(oname_head)
285 found = True
285 found = True
286 ospace = 'Interactive'
286 ospace = 'Interactive'
287
287
288 return {'found':found, 'obj':obj, 'namespace':ospace,
288 return {'found':found, 'obj':obj, 'namespace':ospace,
289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290
290
291 def arg_err(self,func):
291 def arg_err(self,func):
292 """Print docstring if incorrect arguments were passed"""
292 """Print docstring if incorrect arguments were passed"""
293 print 'Error in arguments:'
293 print 'Error in arguments:'
294 print oinspect.getdoc(func)
294 print oinspect.getdoc(func)
295
295
296 def format_latex(self,strng):
296 def format_latex(self,strng):
297 """Format a string for latex inclusion."""
297 """Format a string for latex inclusion."""
298
298
299 # Characters that need to be escaped for latex:
299 # Characters that need to be escaped for latex:
300 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
300 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 # Magic command names as headers:
301 # Magic command names as headers:
302 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
302 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 re.MULTILINE)
303 re.MULTILINE)
304 # Magic commands
304 # Magic commands
305 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
305 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 re.MULTILINE)
306 re.MULTILINE)
307 # Paragraph continue
307 # Paragraph continue
308 par_re = re.compile(r'\\$',re.MULTILINE)
308 par_re = re.compile(r'\\$',re.MULTILINE)
309
309
310 # The "\n" symbol
310 # The "\n" symbol
311 newline_re = re.compile(r'\\n')
311 newline_re = re.compile(r'\\n')
312
312
313 # Now build the string for output:
313 # Now build the string for output:
314 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
314 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
315 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 strng)
316 strng)
317 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
317 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 strng = par_re.sub(r'\\\\',strng)
318 strng = par_re.sub(r'\\\\',strng)
319 strng = escape_re.sub(r'\\\1',strng)
319 strng = escape_re.sub(r'\\\1',strng)
320 strng = newline_re.sub(r'\\textbackslash{}n',strng)
320 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 return strng
321 return strng
322
322
323 def format_screen(self,strng):
323 def format_screen(self,strng):
324 """Format a string for screen printing.
324 """Format a string for screen printing.
325
325
326 This removes some latex-type format codes."""
326 This removes some latex-type format codes."""
327 # Paragraph continue
327 # Paragraph continue
328 par_re = re.compile(r'\\$',re.MULTILINE)
328 par_re = re.compile(r'\\$',re.MULTILINE)
329 strng = par_re.sub('',strng)
329 strng = par_re.sub('',strng)
330 return strng
330 return strng
331
331
332 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
332 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 """Parse options passed to an argument string.
333 """Parse options passed to an argument string.
334
334
335 The interface is similar to that of getopt(), but it returns back a
335 The interface is similar to that of getopt(), but it returns back a
336 Struct with the options as keys and the stripped argument string still
336 Struct with the options as keys and the stripped argument string still
337 as a string.
337 as a string.
338
338
339 arg_str is quoted as a true sys.argv vector by using shlex.split.
339 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 This allows us to easily expand variables, glob files, quote
340 This allows us to easily expand variables, glob files, quote
341 arguments, etc.
341 arguments, etc.
342
342
343 Options:
343 Options:
344 -mode: default 'string'. If given as 'list', the argument string is
344 -mode: default 'string'. If given as 'list', the argument string is
345 returned as a list (split on whitespace) instead of a string.
345 returned as a list (split on whitespace) instead of a string.
346
346
347 -list_all: put all option values in lists. Normally only options
347 -list_all: put all option values in lists. Normally only options
348 appearing more than once are put in a list.
348 appearing more than once are put in a list.
349
349
350 -posix (True): whether to split the input line in POSIX mode or not,
350 -posix (True): whether to split the input line in POSIX mode or not,
351 as per the conventions outlined in the shlex module from the
351 as per the conventions outlined in the shlex module from the
352 standard library."""
352 standard library."""
353
353
354 # inject default options at the beginning of the input line
354 # inject default options at the beginning of the input line
355 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
355 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
356 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357
357
358 mode = kw.get('mode','string')
358 mode = kw.get('mode','string')
359 if mode not in ['string','list']:
359 if mode not in ['string','list']:
360 raise ValueError,'incorrect mode given: %s' % mode
360 raise ValueError,'incorrect mode given: %s' % mode
361 # Get options
361 # Get options
362 list_all = kw.get('list_all',0)
362 list_all = kw.get('list_all',0)
363 posix = kw.get('posix', os.name == 'posix')
363 posix = kw.get('posix', os.name == 'posix')
364
364
365 # Check if we have more than one argument to warrant extra processing:
365 # Check if we have more than one argument to warrant extra processing:
366 odict = {} # Dictionary with options
366 odict = {} # Dictionary with options
367 args = arg_str.split()
367 args = arg_str.split()
368 if len(args) >= 1:
368 if len(args) >= 1:
369 # If the list of inputs only has 0 or 1 thing in it, there's no
369 # If the list of inputs only has 0 or 1 thing in it, there's no
370 # need to look for options
370 # need to look for options
371 argv = arg_split(arg_str,posix)
371 argv = arg_split(arg_str,posix)
372 # Do regular option processing
372 # Do regular option processing
373 try:
373 try:
374 opts,args = getopt(argv,opt_str,*long_opts)
374 opts,args = getopt(argv,opt_str,*long_opts)
375 except GetoptError,e:
375 except GetoptError,e:
376 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
376 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 " ".join(long_opts)))
377 " ".join(long_opts)))
378 for o,a in opts:
378 for o,a in opts:
379 if o.startswith('--'):
379 if o.startswith('--'):
380 o = o[2:]
380 o = o[2:]
381 else:
381 else:
382 o = o[1:]
382 o = o[1:]
383 try:
383 try:
384 odict[o].append(a)
384 odict[o].append(a)
385 except AttributeError:
385 except AttributeError:
386 odict[o] = [odict[o],a]
386 odict[o] = [odict[o],a]
387 except KeyError:
387 except KeyError:
388 if list_all:
388 if list_all:
389 odict[o] = [a]
389 odict[o] = [a]
390 else:
390 else:
391 odict[o] = a
391 odict[o] = a
392
392
393 # Prepare opts,args for return
393 # Prepare opts,args for return
394 opts = Struct(odict)
394 opts = Struct(odict)
395 if mode == 'string':
395 if mode == 'string':
396 args = ' '.join(args)
396 args = ' '.join(args)
397
397
398 return opts,args
398 return opts,args
399
399
400 #......................................................................
400 #......................................................................
401 # And now the actual magic functions
401 # And now the actual magic functions
402
402
403 # Functions for IPython shell work (vars,funcs, config, etc)
403 # Functions for IPython shell work (vars,funcs, config, etc)
404 def magic_lsmagic(self, parameter_s = ''):
404 def magic_lsmagic(self, parameter_s = ''):
405 """List currently available magic functions."""
405 """List currently available magic functions."""
406 mesc = ESC_MAGIC
406 mesc = ESC_MAGIC
407 print 'Available magic functions:\n'+mesc+\
407 print 'Available magic functions:\n'+mesc+\
408 (' '+mesc).join(self.lsmagic())
408 (' '+mesc).join(self.lsmagic())
409 print '\n' + Magic.auto_status[self.shell.automagic]
409 print '\n' + Magic.auto_status[self.shell.automagic]
410 return None
410 return None
411
411
412 def magic_magic(self, parameter_s = ''):
412 def magic_magic(self, parameter_s = ''):
413 """Print information about the magic function system.
413 """Print information about the magic function system.
414
414
415 Supported formats: -latex, -brief, -rest
415 Supported formats: -latex, -brief, -rest
416 """
416 """
417
417
418 mode = ''
418 mode = ''
419 try:
419 try:
420 if parameter_s.split()[0] == '-latex':
420 if parameter_s.split()[0] == '-latex':
421 mode = 'latex'
421 mode = 'latex'
422 if parameter_s.split()[0] == '-brief':
422 if parameter_s.split()[0] == '-brief':
423 mode = 'brief'
423 mode = 'brief'
424 if parameter_s.split()[0] == '-rest':
424 if parameter_s.split()[0] == '-rest':
425 mode = 'rest'
425 mode = 'rest'
426 rest_docs = []
426 rest_docs = []
427 except:
427 except:
428 pass
428 pass
429
429
430 magic_docs = []
430 magic_docs = []
431 for fname in self.lsmagic():
431 for fname in self.lsmagic():
432 mname = 'magic_' + fname
432 mname = 'magic_' + fname
433 for space in (Magic,self,self.__class__):
433 for space in (Magic,self,self.__class__):
434 try:
434 try:
435 fn = space.__dict__[mname]
435 fn = space.__dict__[mname]
436 except KeyError:
436 except KeyError:
437 pass
437 pass
438 else:
438 else:
439 break
439 break
440 if mode == 'brief':
440 if mode == 'brief':
441 # only first line
441 # only first line
442 if fn.__doc__:
442 if fn.__doc__:
443 fndoc = fn.__doc__.split('\n',1)[0]
443 fndoc = fn.__doc__.split('\n',1)[0]
444 else:
444 else:
445 fndoc = 'No documentation'
445 fndoc = 'No documentation'
446 else:
446 else:
447 if fn.__doc__:
447 if fn.__doc__:
448 fndoc = fn.__doc__.rstrip()
448 fndoc = fn.__doc__.rstrip()
449 else:
449 else:
450 fndoc = 'No documentation'
450 fndoc = 'No documentation'
451
451
452
452
453 if mode == 'rest':
453 if mode == 'rest':
454 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
454 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 fname,fndoc))
455 fname,fndoc))
456
456
457 else:
457 else:
458 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
458 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 fname,fndoc))
459 fname,fndoc))
460
460
461 magic_docs = ''.join(magic_docs)
461 magic_docs = ''.join(magic_docs)
462
462
463 if mode == 'rest':
463 if mode == 'rest':
464 return "".join(rest_docs)
464 return "".join(rest_docs)
465
465
466 if mode == 'latex':
466 if mode == 'latex':
467 print self.format_latex(magic_docs)
467 print self.format_latex(magic_docs)
468 return
468 return
469 else:
469 else:
470 magic_docs = self.format_screen(magic_docs)
470 magic_docs = self.format_screen(magic_docs)
471 if mode == 'brief':
471 if mode == 'brief':
472 return magic_docs
472 return magic_docs
473
473
474 outmsg = """
474 outmsg = """
475 IPython's 'magic' functions
475 IPython's 'magic' functions
476 ===========================
476 ===========================
477
477
478 The magic function system provides a series of functions which allow you to
478 The magic function system provides a series of functions which allow you to
479 control the behavior of IPython itself, plus a lot of system-type
479 control the behavior of IPython itself, plus a lot of system-type
480 features. All these functions are prefixed with a % character, but parameters
480 features. All these functions are prefixed with a % character, but parameters
481 are given without parentheses or quotes.
481 are given without parentheses or quotes.
482
482
483 NOTE: If you have 'automagic' enabled (via the command line option or with the
483 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 %automagic function), you don't need to type in the % explicitly. By default,
484 %automagic function), you don't need to type in the % explicitly. By default,
485 IPython ships with automagic on, so you should only rarely need the % escape.
485 IPython ships with automagic on, so you should only rarely need the % escape.
486
486
487 Example: typing '%cd mydir' (without the quotes) changes you working directory
487 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 to 'mydir', if it exists.
488 to 'mydir', if it exists.
489
489
490 You can define your own magic functions to extend the system. See the supplied
490 You can define your own magic functions to extend the system. See the supplied
491 ipythonrc and example-magic.py files for details (in your ipython
491 ipythonrc and example-magic.py files for details (in your ipython
492 configuration directory, typically $HOME/.ipython/).
492 configuration directory, typically $HOME/.ipython/).
493
493
494 You can also define your own aliased names for magic functions. In your
494 You can also define your own aliased names for magic functions. In your
495 ipythonrc file, placing a line like:
495 ipythonrc file, placing a line like:
496
496
497 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
497 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498
498
499 will define %pf as a new name for %profile.
499 will define %pf as a new name for %profile.
500
500
501 You can also call magics in code using the magic() function, which IPython
501 You can also call magics in code using the magic() function, which IPython
502 automatically adds to the builtin namespace. Type 'magic?' for details.
502 automatically adds to the builtin namespace. Type 'magic?' for details.
503
503
504 For a list of the available magic functions, use %lsmagic. For a description
504 For a list of the available magic functions, use %lsmagic. For a description
505 of any of them, type %magic_name?, e.g. '%cd?'.
505 of any of them, type %magic_name?, e.g. '%cd?'.
506
506
507 Currently the magic system has the following functions:\n"""
507 Currently the magic system has the following functions:\n"""
508
508
509 mesc = ESC_MAGIC
509 mesc = ESC_MAGIC
510 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
510 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 "\n\n%s%s\n\n%s" % (outmsg,
511 "\n\n%s%s\n\n%s" % (outmsg,
512 magic_docs,mesc,mesc,
512 magic_docs,mesc,mesc,
513 (' '+mesc).join(self.lsmagic()),
513 (' '+mesc).join(self.lsmagic()),
514 Magic.auto_status[self.shell.automagic] ) )
514 Magic.auto_status[self.shell.automagic] ) )
515
515
516 page(outmsg,screen_lines=self.shell.usable_screen_length)
516 page(outmsg,screen_lines=self.shell.usable_screen_length)
517
517
518
518
519 def magic_autoindent(self, parameter_s = ''):
519 def magic_autoindent(self, parameter_s = ''):
520 """Toggle autoindent on/off (if available)."""
520 """Toggle autoindent on/off (if available)."""
521
521
522 self.shell.set_autoindent()
522 self.shell.set_autoindent()
523 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
523 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
524
524
525
525
526 def magic_automagic(self, parameter_s = ''):
526 def magic_automagic(self, parameter_s = ''):
527 """Make magic functions callable without having to type the initial %.
527 """Make magic functions callable without having to type the initial %.
528
528
529 Without argumentsl toggles on/off (when off, you must call it as
529 Without argumentsl toggles on/off (when off, you must call it as
530 %automagic, of course). With arguments it sets the value, and you can
530 %automagic, of course). With arguments it sets the value, and you can
531 use any of (case insensitive):
531 use any of (case insensitive):
532
532
533 - on,1,True: to activate
533 - on,1,True: to activate
534
534
535 - off,0,False: to deactivate.
535 - off,0,False: to deactivate.
536
536
537 Note that magic functions have lowest priority, so if there's a
537 Note that magic functions have lowest priority, so if there's a
538 variable whose name collides with that of a magic fn, automagic won't
538 variable whose name collides with that of a magic fn, automagic won't
539 work for that function (you get the variable instead). However, if you
539 work for that function (you get the variable instead). However, if you
540 delete the variable (del var), the previously shadowed magic function
540 delete the variable (del var), the previously shadowed magic function
541 becomes visible to automagic again."""
541 becomes visible to automagic again."""
542
542
543 arg = parameter_s.lower()
543 arg = parameter_s.lower()
544 if parameter_s in ('on','1','true'):
544 if parameter_s in ('on','1','true'):
545 self.shell.automagic = True
545 self.shell.automagic = True
546 elif parameter_s in ('off','0','false'):
546 elif parameter_s in ('off','0','false'):
547 self.shell.automagic = False
547 self.shell.automagic = False
548 else:
548 else:
549 self.shell.automagic = not self.shell.automagic
549 self.shell.automagic = not self.shell.automagic
550 print '\n' + Magic.auto_status[self.shell.automagic]
550 print '\n' + Magic.auto_status[self.shell.automagic]
551
551
552 @testdec.skip_doctest
552 @testdec.skip_doctest
553 def magic_autocall(self, parameter_s = ''):
553 def magic_autocall(self, parameter_s = ''):
554 """Make functions callable without having to type parentheses.
554 """Make functions callable without having to type parentheses.
555
555
556 Usage:
556 Usage:
557
557
558 %autocall [mode]
558 %autocall [mode]
559
559
560 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
560 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
561 value is toggled on and off (remembering the previous state).
561 value is toggled on and off (remembering the previous state).
562
562
563 In more detail, these values mean:
563 In more detail, these values mean:
564
564
565 0 -> fully disabled
565 0 -> fully disabled
566
566
567 1 -> active, but do not apply if there are no arguments on the line.
567 1 -> active, but do not apply if there are no arguments on the line.
568
568
569 In this mode, you get:
569 In this mode, you get:
570
570
571 In [1]: callable
571 In [1]: callable
572 Out[1]: <built-in function callable>
572 Out[1]: <built-in function callable>
573
573
574 In [2]: callable 'hello'
574 In [2]: callable 'hello'
575 ------> callable('hello')
575 ------> callable('hello')
576 Out[2]: False
576 Out[2]: False
577
577
578 2 -> Active always. Even if no arguments are present, the callable
578 2 -> Active always. Even if no arguments are present, the callable
579 object is called:
579 object is called:
580
580
581 In [2]: float
581 In [2]: float
582 ------> float()
582 ------> float()
583 Out[2]: 0.0
583 Out[2]: 0.0
584
584
585 Note that even with autocall off, you can still use '/' at the start of
585 Note that even with autocall off, you can still use '/' at the start of
586 a line to treat the first argument on the command line as a function
586 a line to treat the first argument on the command line as a function
587 and add parentheses to it:
587 and add parentheses to it:
588
588
589 In [8]: /str 43
589 In [8]: /str 43
590 ------> str(43)
590 ------> str(43)
591 Out[8]: '43'
591 Out[8]: '43'
592
592
593 # all-random (note for auto-testing)
593 # all-random (note for auto-testing)
594 """
594 """
595
595
596 if parameter_s:
596 if parameter_s:
597 arg = int(parameter_s)
597 arg = int(parameter_s)
598 else:
598 else:
599 arg = 'toggle'
599 arg = 'toggle'
600
600
601 if not arg in (0,1,2,'toggle'):
601 if not arg in (0,1,2,'toggle'):
602 error('Valid modes: (0->Off, 1->Smart, 2->Full')
602 error('Valid modes: (0->Off, 1->Smart, 2->Full')
603 return
603 return
604
604
605 if arg in (0,1,2):
605 if arg in (0,1,2):
606 self.shell.autocall = arg
606 self.shell.autocall = arg
607 else: # toggle
607 else: # toggle
608 if self.shell.autocall:
608 if self.shell.autocall:
609 self._magic_state.autocall_save = self.shell.autocall
609 self._magic_state.autocall_save = self.shell.autocall
610 self.shell.autocall = 0
610 self.shell.autocall = 0
611 else:
611 else:
612 try:
612 try:
613 self.shell.autocall = self._magic_state.autocall_save
613 self.shell.autocall = self._magic_state.autocall_save
614 except AttributeError:
614 except AttributeError:
615 self.shell.autocall = self._magic_state.autocall_save = 1
615 self.shell.autocall = self._magic_state.autocall_save = 1
616
616
617 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
617 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
618
618
619 def magic_system_verbose(self, parameter_s = ''):
619 def magic_system_verbose(self, parameter_s = ''):
620 """Set verbose printing of system calls.
620 """Set verbose printing of system calls.
621
621
622 If called without an argument, act as a toggle"""
622 If called without an argument, act as a toggle"""
623
623
624 if parameter_s:
624 if parameter_s:
625 val = bool(eval(parameter_s))
625 val = bool(eval(parameter_s))
626 else:
626 else:
627 val = None
627 val = None
628
628
629 if self.shell.system_verbose:
629 if self.shell.system_verbose:
630 self.shell.system_verbose = False
630 self.shell.system_verbose = False
631 else:
631 else:
632 self.shell.system_verbose = True
632 self.shell.system_verbose = True
633 print "System verbose printing is:",\
633 print "System verbose printing is:",\
634 ['OFF','ON'][self.shell.system_verbose]
634 ['OFF','ON'][self.shell.system_verbose]
635
635
636
636
637 def magic_page(self, parameter_s=''):
637 def magic_page(self, parameter_s=''):
638 """Pretty print the object and display it through a pager.
638 """Pretty print the object and display it through a pager.
639
639
640 %page [options] OBJECT
640 %page [options] OBJECT
641
641
642 If no object is given, use _ (last output).
642 If no object is given, use _ (last output).
643
643
644 Options:
644 Options:
645
645
646 -r: page str(object), don't pretty-print it."""
646 -r: page str(object), don't pretty-print it."""
647
647
648 # After a function contributed by Olivier Aubert, slightly modified.
648 # After a function contributed by Olivier Aubert, slightly modified.
649
649
650 # Process options/args
650 # Process options/args
651 opts,args = self.parse_options(parameter_s,'r')
651 opts,args = self.parse_options(parameter_s,'r')
652 raw = 'r' in opts
652 raw = 'r' in opts
653
653
654 oname = args and args or '_'
654 oname = args and args or '_'
655 info = self._ofind(oname)
655 info = self._ofind(oname)
656 if info['found']:
656 if info['found']:
657 txt = (raw and str or pformat)( info['obj'] )
657 txt = (raw and str or pformat)( info['obj'] )
658 page(txt)
658 page(txt)
659 else:
659 else:
660 print 'Object `%s` not found' % oname
660 print 'Object `%s` not found' % oname
661
661
662 def magic_profile(self, parameter_s=''):
662 def magic_profile(self, parameter_s=''):
663 """Print your currently active IPython profile."""
663 """Print your currently active IPython profile."""
664 if self.shell.profile:
664 if self.shell.profile:
665 printpl('Current IPython profile: $self.shell.profile.')
665 printpl('Current IPython profile: $self.shell.profile.')
666 else:
666 else:
667 print 'No profile active.'
667 print 'No profile active.'
668
668
669 def magic_pinfo(self, parameter_s='', namespaces=None):
669 def magic_pinfo(self, parameter_s='', namespaces=None):
670 """Provide detailed information about an object.
670 """Provide detailed information about an object.
671
671
672 '%pinfo object' is just a synonym for object? or ?object."""
672 '%pinfo object' is just a synonym for object? or ?object."""
673
673
674 #print 'pinfo par: <%s>' % parameter_s # dbg
674 #print 'pinfo par: <%s>' % parameter_s # dbg
675
675
676
676
677 # detail_level: 0 -> obj? , 1 -> obj??
677 # detail_level: 0 -> obj? , 1 -> obj??
678 detail_level = 0
678 detail_level = 0
679 # We need to detect if we got called as 'pinfo pinfo foo', which can
679 # We need to detect if we got called as 'pinfo pinfo foo', which can
680 # happen if the user types 'pinfo foo?' at the cmd line.
680 # happen if the user types 'pinfo foo?' at the cmd line.
681 pinfo,qmark1,oname,qmark2 = \
681 pinfo,qmark1,oname,qmark2 = \
682 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
682 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
683 if pinfo or qmark1 or qmark2:
683 if pinfo or qmark1 or qmark2:
684 detail_level = 1
684 detail_level = 1
685 if "*" in oname:
685 if "*" in oname:
686 self.magic_psearch(oname)
686 self.magic_psearch(oname)
687 else:
687 else:
688 self._inspect('pinfo', oname, detail_level=detail_level,
688 self._inspect('pinfo', oname, detail_level=detail_level,
689 namespaces=namespaces)
689 namespaces=namespaces)
690
690
691 def magic_pdef(self, parameter_s='', namespaces=None):
691 def magic_pdef(self, parameter_s='', namespaces=None):
692 """Print the definition header for any callable object.
692 """Print the definition header for any callable object.
693
693
694 If the object is a class, print the constructor information."""
694 If the object is a class, print the constructor information."""
695 self._inspect('pdef',parameter_s, namespaces)
695 self._inspect('pdef',parameter_s, namespaces)
696
696
697 def magic_pdoc(self, parameter_s='', namespaces=None):
697 def magic_pdoc(self, parameter_s='', namespaces=None):
698 """Print the docstring for an object.
698 """Print the docstring for an object.
699
699
700 If the given object is a class, it will print both the class and the
700 If the given object is a class, it will print both the class and the
701 constructor docstrings."""
701 constructor docstrings."""
702 self._inspect('pdoc',parameter_s, namespaces)
702 self._inspect('pdoc',parameter_s, namespaces)
703
703
704 def magic_psource(self, parameter_s='', namespaces=None):
704 def magic_psource(self, parameter_s='', namespaces=None):
705 """Print (or run through pager) the source code for an object."""
705 """Print (or run through pager) the source code for an object."""
706 self._inspect('psource',parameter_s, namespaces)
706 self._inspect('psource',parameter_s, namespaces)
707
707
708 def magic_pfile(self, parameter_s=''):
708 def magic_pfile(self, parameter_s=''):
709 """Print (or run through pager) the file where an object is defined.
709 """Print (or run through pager) the file where an object is defined.
710
710
711 The file opens at the line where the object definition begins. IPython
711 The file opens at the line where the object definition begins. IPython
712 will honor the environment variable PAGER if set, and otherwise will
712 will honor the environment variable PAGER if set, and otherwise will
713 do its best to print the file in a convenient form.
713 do its best to print the file in a convenient form.
714
714
715 If the given argument is not an object currently defined, IPython will
715 If the given argument is not an object currently defined, IPython will
716 try to interpret it as a filename (automatically adding a .py extension
716 try to interpret it as a filename (automatically adding a .py extension
717 if needed). You can thus use %pfile as a syntax highlighting code
717 if needed). You can thus use %pfile as a syntax highlighting code
718 viewer."""
718 viewer."""
719
719
720 # first interpret argument as an object name
720 # first interpret argument as an object name
721 out = self._inspect('pfile',parameter_s)
721 out = self._inspect('pfile',parameter_s)
722 # if not, try the input as a filename
722 # if not, try the input as a filename
723 if out == 'not found':
723 if out == 'not found':
724 try:
724 try:
725 filename = get_py_filename(parameter_s)
725 filename = get_py_filename(parameter_s)
726 except IOError,msg:
726 except IOError,msg:
727 print msg
727 print msg
728 return
728 return
729 page(self.shell.inspector.format(file(filename).read()))
729 page(self.shell.inspector.format(file(filename).read()))
730
730
731 def _inspect(self,meth,oname,namespaces=None,**kw):
731 def _inspect(self,meth,oname,namespaces=None,**kw):
732 """Generic interface to the inspector system.
732 """Generic interface to the inspector system.
733
733
734 This function is meant to be called by pdef, pdoc & friends."""
734 This function is meant to be called by pdef, pdoc & friends."""
735
735
736 #oname = oname.strip()
736 #oname = oname.strip()
737 #print '1- oname: <%r>' % oname # dbg
737 #print '1- oname: <%r>' % oname # dbg
738 try:
738 try:
739 oname = oname.strip().encode('ascii')
739 oname = oname.strip().encode('ascii')
740 #print '2- oname: <%r>' % oname # dbg
740 #print '2- oname: <%r>' % oname # dbg
741 except UnicodeEncodeError:
741 except UnicodeEncodeError:
742 print 'Python identifiers can only contain ascii characters.'
742 print 'Python identifiers can only contain ascii characters.'
743 return 'not found'
743 return 'not found'
744
744
745 info = Struct(self._ofind(oname, namespaces))
745 info = Struct(self._ofind(oname, namespaces))
746
746
747 if info.found:
747 if info.found:
748 try:
748 try:
749 IPython.utils.generics.inspect_object(info.obj)
749 IPython.utils.generics.inspect_object(info.obj)
750 return
750 return
751 except TryNext:
751 except TryNext:
752 pass
752 pass
753 # Get the docstring of the class property if it exists.
753 # Get the docstring of the class property if it exists.
754 path = oname.split('.')
754 path = oname.split('.')
755 root = '.'.join(path[:-1])
755 root = '.'.join(path[:-1])
756 if info.parent is not None:
756 if info.parent is not None:
757 try:
757 try:
758 target = getattr(info.parent, '__class__')
758 target = getattr(info.parent, '__class__')
759 # The object belongs to a class instance.
759 # The object belongs to a class instance.
760 try:
760 try:
761 target = getattr(target, path[-1])
761 target = getattr(target, path[-1])
762 # The class defines the object.
762 # The class defines the object.
763 if isinstance(target, property):
763 if isinstance(target, property):
764 oname = root + '.__class__.' + path[-1]
764 oname = root + '.__class__.' + path[-1]
765 info = Struct(self._ofind(oname))
765 info = Struct(self._ofind(oname))
766 except AttributeError: pass
766 except AttributeError: pass
767 except AttributeError: pass
767 except AttributeError: pass
768
768
769 pmethod = getattr(self.shell.inspector,meth)
769 pmethod = getattr(self.shell.inspector,meth)
770 formatter = info.ismagic and self.format_screen or None
770 formatter = info.ismagic and self.format_screen or None
771 if meth == 'pdoc':
771 if meth == 'pdoc':
772 pmethod(info.obj,oname,formatter)
772 pmethod(info.obj,oname,formatter)
773 elif meth == 'pinfo':
773 elif meth == 'pinfo':
774 pmethod(info.obj,oname,formatter,info,**kw)
774 pmethod(info.obj,oname,formatter,info,**kw)
775 else:
775 else:
776 pmethod(info.obj,oname)
776 pmethod(info.obj,oname)
777 else:
777 else:
778 print 'Object `%s` not found.' % oname
778 print 'Object `%s` not found.' % oname
779 return 'not found' # so callers can take other action
779 return 'not found' # so callers can take other action
780
780
781 def magic_psearch(self, parameter_s=''):
781 def magic_psearch(self, parameter_s=''):
782 """Search for object in namespaces by wildcard.
782 """Search for object in namespaces by wildcard.
783
783
784 %psearch [options] PATTERN [OBJECT TYPE]
784 %psearch [options] PATTERN [OBJECT TYPE]
785
785
786 Note: ? can be used as a synonym for %psearch, at the beginning or at
786 Note: ? can be used as a synonym for %psearch, at the beginning or at
787 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
787 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
788 rest of the command line must be unchanged (options come first), so
788 rest of the command line must be unchanged (options come first), so
789 for example the following forms are equivalent
789 for example the following forms are equivalent
790
790
791 %psearch -i a* function
791 %psearch -i a* function
792 -i a* function?
792 -i a* function?
793 ?-i a* function
793 ?-i a* function
794
794
795 Arguments:
795 Arguments:
796
796
797 PATTERN
797 PATTERN
798
798
799 where PATTERN is a string containing * as a wildcard similar to its
799 where PATTERN is a string containing * as a wildcard similar to its
800 use in a shell. The pattern is matched in all namespaces on the
800 use in a shell. The pattern is matched in all namespaces on the
801 search path. By default objects starting with a single _ are not
801 search path. By default objects starting with a single _ are not
802 matched, many IPython generated objects have a single
802 matched, many IPython generated objects have a single
803 underscore. The default is case insensitive matching. Matching is
803 underscore. The default is case insensitive matching. Matching is
804 also done on the attributes of objects and not only on the objects
804 also done on the attributes of objects and not only on the objects
805 in a module.
805 in a module.
806
806
807 [OBJECT TYPE]
807 [OBJECT TYPE]
808
808
809 Is the name of a python type from the types module. The name is
809 Is the name of a python type from the types module. The name is
810 given in lowercase without the ending type, ex. StringType is
810 given in lowercase without the ending type, ex. StringType is
811 written string. By adding a type here only objects matching the
811 written string. By adding a type here only objects matching the
812 given type are matched. Using all here makes the pattern match all
812 given type are matched. Using all here makes the pattern match all
813 types (this is the default).
813 types (this is the default).
814
814
815 Options:
815 Options:
816
816
817 -a: makes the pattern match even objects whose names start with a
817 -a: makes the pattern match even objects whose names start with a
818 single underscore. These names are normally ommitted from the
818 single underscore. These names are normally ommitted from the
819 search.
819 search.
820
820
821 -i/-c: make the pattern case insensitive/sensitive. If neither of
821 -i/-c: make the pattern case insensitive/sensitive. If neither of
822 these options is given, the default is read from your ipythonrc
822 these options is given, the default is read from your ipythonrc
823 file. The option name which sets this value is
823 file. The option name which sets this value is
824 'wildcards_case_sensitive'. If this option is not specified in your
824 'wildcards_case_sensitive'. If this option is not specified in your
825 ipythonrc file, IPython's internal default is to do a case sensitive
825 ipythonrc file, IPython's internal default is to do a case sensitive
826 search.
826 search.
827
827
828 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
828 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
829 specifiy can be searched in any of the following namespaces:
829 specifiy can be searched in any of the following namespaces:
830 'builtin', 'user', 'user_global','internal', 'alias', where
830 'builtin', 'user', 'user_global','internal', 'alias', where
831 'builtin' and 'user' are the search defaults. Note that you should
831 'builtin' and 'user' are the search defaults. Note that you should
832 not use quotes when specifying namespaces.
832 not use quotes when specifying namespaces.
833
833
834 'Builtin' contains the python module builtin, 'user' contains all
834 'Builtin' contains the python module builtin, 'user' contains all
835 user data, 'alias' only contain the shell aliases and no python
835 user data, 'alias' only contain the shell aliases and no python
836 objects, 'internal' contains objects used by IPython. The
836 objects, 'internal' contains objects used by IPython. The
837 'user_global' namespace is only used by embedded IPython instances,
837 'user_global' namespace is only used by embedded IPython instances,
838 and it contains module-level globals. You can add namespaces to the
838 and it contains module-level globals. You can add namespaces to the
839 search with -s or exclude them with -e (these options can be given
839 search with -s or exclude them with -e (these options can be given
840 more than once).
840 more than once).
841
841
842 Examples:
842 Examples:
843
843
844 %psearch a* -> objects beginning with an a
844 %psearch a* -> objects beginning with an a
845 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
845 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
846 %psearch a* function -> all functions beginning with an a
846 %psearch a* function -> all functions beginning with an a
847 %psearch re.e* -> objects beginning with an e in module re
847 %psearch re.e* -> objects beginning with an e in module re
848 %psearch r*.e* -> objects that start with e in modules starting in r
848 %psearch r*.e* -> objects that start with e in modules starting in r
849 %psearch r*.* string -> all strings in modules beginning with r
849 %psearch r*.* string -> all strings in modules beginning with r
850
850
851 Case sensitve search:
851 Case sensitve search:
852
852
853 %psearch -c a* list all object beginning with lower case a
853 %psearch -c a* list all object beginning with lower case a
854
854
855 Show objects beginning with a single _:
855 Show objects beginning with a single _:
856
856
857 %psearch -a _* list objects beginning with a single underscore"""
857 %psearch -a _* list objects beginning with a single underscore"""
858 try:
858 try:
859 parameter_s = parameter_s.encode('ascii')
859 parameter_s = parameter_s.encode('ascii')
860 except UnicodeEncodeError:
860 except UnicodeEncodeError:
861 print 'Python identifiers can only contain ascii characters.'
861 print 'Python identifiers can only contain ascii characters.'
862 return
862 return
863
863
864 # default namespaces to be searched
864 # default namespaces to be searched
865 def_search = ['user','builtin']
865 def_search = ['user','builtin']
866
866
867 # Process options/args
867 # Process options/args
868 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
868 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
869 opt = opts.get
869 opt = opts.get
870 shell = self.shell
870 shell = self.shell
871 psearch = shell.inspector.psearch
871 psearch = shell.inspector.psearch
872
872
873 # select case options
873 # select case options
874 if opts.has_key('i'):
874 if opts.has_key('i'):
875 ignore_case = True
875 ignore_case = True
876 elif opts.has_key('c'):
876 elif opts.has_key('c'):
877 ignore_case = False
877 ignore_case = False
878 else:
878 else:
879 ignore_case = not shell.wildcards_case_sensitive
879 ignore_case = not shell.wildcards_case_sensitive
880
880
881 # Build list of namespaces to search from user options
881 # Build list of namespaces to search from user options
882 def_search.extend(opt('s',[]))
882 def_search.extend(opt('s',[]))
883 ns_exclude = ns_exclude=opt('e',[])
883 ns_exclude = ns_exclude=opt('e',[])
884 ns_search = [nm for nm in def_search if nm not in ns_exclude]
884 ns_search = [nm for nm in def_search if nm not in ns_exclude]
885
885
886 # Call the actual search
886 # Call the actual search
887 try:
887 try:
888 psearch(args,shell.ns_table,ns_search,
888 psearch(args,shell.ns_table,ns_search,
889 show_all=opt('a'),ignore_case=ignore_case)
889 show_all=opt('a'),ignore_case=ignore_case)
890 except:
890 except:
891 shell.showtraceback()
891 shell.showtraceback()
892
892
893 def magic_who_ls(self, parameter_s=''):
893 def magic_who_ls(self, parameter_s=''):
894 """Return a sorted list of all interactive variables.
894 """Return a sorted list of all interactive variables.
895
895
896 If arguments are given, only variables of types matching these
896 If arguments are given, only variables of types matching these
897 arguments are returned."""
897 arguments are returned."""
898
898
899 user_ns = self.shell.user_ns
899 user_ns = self.shell.user_ns
900 internal_ns = self.shell.internal_ns
900 internal_ns = self.shell.internal_ns
901 user_ns_hidden = self.shell.user_ns_hidden
901 user_ns_hidden = self.shell.user_ns_hidden
902 out = [ i for i in user_ns
902 out = [ i for i in user_ns
903 if not i.startswith('_') \
903 if not i.startswith('_') \
904 and not (i in internal_ns or i in user_ns_hidden) ]
904 and not (i in internal_ns or i in user_ns_hidden) ]
905
905
906 typelist = parameter_s.split()
906 typelist = parameter_s.split()
907 if typelist:
907 if typelist:
908 typeset = set(typelist)
908 typeset = set(typelist)
909 out = [i for i in out if type(i).__name__ in typeset]
909 out = [i for i in out if type(i).__name__ in typeset]
910
910
911 out.sort()
911 out.sort()
912 return out
912 return out
913
913
914 def magic_who(self, parameter_s=''):
914 def magic_who(self, parameter_s=''):
915 """Print all interactive variables, with some minimal formatting.
915 """Print all interactive variables, with some minimal formatting.
916
916
917 If any arguments are given, only variables whose type matches one of
917 If any arguments are given, only variables whose type matches one of
918 these are printed. For example:
918 these are printed. For example:
919
919
920 %who function str
920 %who function str
921
921
922 will only list functions and strings, excluding all other types of
922 will only list functions and strings, excluding all other types of
923 variables. To find the proper type names, simply use type(var) at a
923 variables. To find the proper type names, simply use type(var) at a
924 command line to see how python prints type names. For example:
924 command line to see how python prints type names. For example:
925
925
926 In [1]: type('hello')\\
926 In [1]: type('hello')\\
927 Out[1]: <type 'str'>
927 Out[1]: <type 'str'>
928
928
929 indicates that the type name for strings is 'str'.
929 indicates that the type name for strings is 'str'.
930
930
931 %who always excludes executed names loaded through your configuration
931 %who always excludes executed names loaded through your configuration
932 file and things which are internal to IPython.
932 file and things which are internal to IPython.
933
933
934 This is deliberate, as typically you may load many modules and the
934 This is deliberate, as typically you may load many modules and the
935 purpose of %who is to show you only what you've manually defined."""
935 purpose of %who is to show you only what you've manually defined."""
936
936
937 varlist = self.magic_who_ls(parameter_s)
937 varlist = self.magic_who_ls(parameter_s)
938 if not varlist:
938 if not varlist:
939 if parameter_s:
939 if parameter_s:
940 print 'No variables match your requested type.'
940 print 'No variables match your requested type.'
941 else:
941 else:
942 print 'Interactive namespace is empty.'
942 print 'Interactive namespace is empty.'
943 return
943 return
944
944
945 # if we have variables, move on...
945 # if we have variables, move on...
946 count = 0
946 count = 0
947 for i in varlist:
947 for i in varlist:
948 print i+'\t',
948 print i+'\t',
949 count += 1
949 count += 1
950 if count > 8:
950 if count > 8:
951 count = 0
951 count = 0
952 print
952 print
953 print
953 print
954
954
955 def magic_whos(self, parameter_s=''):
955 def magic_whos(self, parameter_s=''):
956 """Like %who, but gives some extra information about each variable.
956 """Like %who, but gives some extra information about each variable.
957
957
958 The same type filtering of %who can be applied here.
958 The same type filtering of %who can be applied here.
959
959
960 For all variables, the type is printed. Additionally it prints:
960 For all variables, the type is printed. Additionally it prints:
961
961
962 - For {},[],(): their length.
962 - For {},[],(): their length.
963
963
964 - For numpy and Numeric arrays, a summary with shape, number of
964 - For numpy and Numeric arrays, a summary with shape, number of
965 elements, typecode and size in memory.
965 elements, typecode and size in memory.
966
966
967 - Everything else: a string representation, snipping their middle if
967 - Everything else: a string representation, snipping their middle if
968 too long."""
968 too long."""
969
969
970 varnames = self.magic_who_ls(parameter_s)
970 varnames = self.magic_who_ls(parameter_s)
971 if not varnames:
971 if not varnames:
972 if parameter_s:
972 if parameter_s:
973 print 'No variables match your requested type.'
973 print 'No variables match your requested type.'
974 else:
974 else:
975 print 'Interactive namespace is empty.'
975 print 'Interactive namespace is empty.'
976 return
976 return
977
977
978 # if we have variables, move on...
978 # if we have variables, move on...
979
979
980 # for these types, show len() instead of data:
980 # for these types, show len() instead of data:
981 seq_types = [types.DictType,types.ListType,types.TupleType]
981 seq_types = [types.DictType,types.ListType,types.TupleType]
982
982
983 # for numpy/Numeric arrays, display summary info
983 # for numpy/Numeric arrays, display summary info
984 try:
984 try:
985 import numpy
985 import numpy
986 except ImportError:
986 except ImportError:
987 ndarray_type = None
987 ndarray_type = None
988 else:
988 else:
989 ndarray_type = numpy.ndarray.__name__
989 ndarray_type = numpy.ndarray.__name__
990 try:
990 try:
991 import Numeric
991 import Numeric
992 except ImportError:
992 except ImportError:
993 array_type = None
993 array_type = None
994 else:
994 else:
995 array_type = Numeric.ArrayType.__name__
995 array_type = Numeric.ArrayType.__name__
996
996
997 # Find all variable names and types so we can figure out column sizes
997 # Find all variable names and types so we can figure out column sizes
998 def get_vars(i):
998 def get_vars(i):
999 return self.shell.user_ns[i]
999 return self.shell.user_ns[i]
1000
1000
1001 # some types are well known and can be shorter
1001 # some types are well known and can be shorter
1002 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1002 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1003 def type_name(v):
1003 def type_name(v):
1004 tn = type(v).__name__
1004 tn = type(v).__name__
1005 return abbrevs.get(tn,tn)
1005 return abbrevs.get(tn,tn)
1006
1006
1007 varlist = map(get_vars,varnames)
1007 varlist = map(get_vars,varnames)
1008
1008
1009 typelist = []
1009 typelist = []
1010 for vv in varlist:
1010 for vv in varlist:
1011 tt = type_name(vv)
1011 tt = type_name(vv)
1012
1012
1013 if tt=='instance':
1013 if tt=='instance':
1014 typelist.append( abbrevs.get(str(vv.__class__),
1014 typelist.append( abbrevs.get(str(vv.__class__),
1015 str(vv.__class__)))
1015 str(vv.__class__)))
1016 else:
1016 else:
1017 typelist.append(tt)
1017 typelist.append(tt)
1018
1018
1019 # column labels and # of spaces as separator
1019 # column labels and # of spaces as separator
1020 varlabel = 'Variable'
1020 varlabel = 'Variable'
1021 typelabel = 'Type'
1021 typelabel = 'Type'
1022 datalabel = 'Data/Info'
1022 datalabel = 'Data/Info'
1023 colsep = 3
1023 colsep = 3
1024 # variable format strings
1024 # variable format strings
1025 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1025 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1026 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1026 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1027 aformat = "%s: %s elems, type `%s`, %s bytes"
1027 aformat = "%s: %s elems, type `%s`, %s bytes"
1028 # find the size of the columns to format the output nicely
1028 # find the size of the columns to format the output nicely
1029 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1029 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1030 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1030 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1031 # table header
1031 # table header
1032 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1032 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1033 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1033 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1034 # and the table itself
1034 # and the table itself
1035 kb = 1024
1035 kb = 1024
1036 Mb = 1048576 # kb**2
1036 Mb = 1048576 # kb**2
1037 for vname,var,vtype in zip(varnames,varlist,typelist):
1037 for vname,var,vtype in zip(varnames,varlist,typelist):
1038 print itpl(vformat),
1038 print itpl(vformat),
1039 if vtype in seq_types:
1039 if vtype in seq_types:
1040 print len(var)
1040 print len(var)
1041 elif vtype in [array_type,ndarray_type]:
1041 elif vtype in [array_type,ndarray_type]:
1042 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1042 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1043 if vtype==ndarray_type:
1043 if vtype==ndarray_type:
1044 # numpy
1044 # numpy
1045 vsize = var.size
1045 vsize = var.size
1046 vbytes = vsize*var.itemsize
1046 vbytes = vsize*var.itemsize
1047 vdtype = var.dtype
1047 vdtype = var.dtype
1048 else:
1048 else:
1049 # Numeric
1049 # Numeric
1050 vsize = Numeric.size(var)
1050 vsize = Numeric.size(var)
1051 vbytes = vsize*var.itemsize()
1051 vbytes = vsize*var.itemsize()
1052 vdtype = var.typecode()
1052 vdtype = var.typecode()
1053
1053
1054 if vbytes < 100000:
1054 if vbytes < 100000:
1055 print aformat % (vshape,vsize,vdtype,vbytes)
1055 print aformat % (vshape,vsize,vdtype,vbytes)
1056 else:
1056 else:
1057 print aformat % (vshape,vsize,vdtype,vbytes),
1057 print aformat % (vshape,vsize,vdtype,vbytes),
1058 if vbytes < Mb:
1058 if vbytes < Mb:
1059 print '(%s kb)' % (vbytes/kb,)
1059 print '(%s kb)' % (vbytes/kb,)
1060 else:
1060 else:
1061 print '(%s Mb)' % (vbytes/Mb,)
1061 print '(%s Mb)' % (vbytes/Mb,)
1062 else:
1062 else:
1063 try:
1063 try:
1064 vstr = str(var)
1064 vstr = str(var)
1065 except UnicodeEncodeError:
1065 except UnicodeEncodeError:
1066 vstr = unicode(var).encode(sys.getdefaultencoding(),
1066 vstr = unicode(var).encode(sys.getdefaultencoding(),
1067 'backslashreplace')
1067 'backslashreplace')
1068 vstr = vstr.replace('\n','\\n')
1068 vstr = vstr.replace('\n','\\n')
1069 if len(vstr) < 50:
1069 if len(vstr) < 50:
1070 print vstr
1070 print vstr
1071 else:
1071 else:
1072 printpl(vfmt_short)
1072 printpl(vfmt_short)
1073
1073
1074 def magic_reset(self, parameter_s=''):
1074 def magic_reset(self, parameter_s=''):
1075 """Resets the namespace by removing all names defined by the user.
1075 """Resets the namespace by removing all names defined by the user.
1076
1076
1077 Input/Output history are left around in case you need them.
1077 Input/Output history are left around in case you need them.
1078
1078
1079 Parameters
1079 Parameters
1080 ----------
1080 ----------
1081 -y : force reset without asking for confirmation.
1081 -y : force reset without asking for confirmation.
1082
1082
1083 Examples
1083 Examples
1084 --------
1084 --------
1085 In [6]: a = 1
1085 In [6]: a = 1
1086
1086
1087 In [7]: a
1087 In [7]: a
1088 Out[7]: 1
1088 Out[7]: 1
1089
1089
1090 In [8]: 'a' in _ip.user_ns
1090 In [8]: 'a' in _ip.user_ns
1091 Out[8]: True
1091 Out[8]: True
1092
1092
1093 In [9]: %reset -f
1093 In [9]: %reset -f
1094
1094
1095 In [10]: 'a' in _ip.user_ns
1095 In [10]: 'a' in _ip.user_ns
1096 Out[10]: False
1096 Out[10]: False
1097 """
1097 """
1098
1098
1099 if parameter_s == '-f':
1099 if parameter_s == '-f':
1100 ans = True
1100 ans = True
1101 else:
1101 else:
1102 ans = self.shell.ask_yes_no(
1102 ans = self.shell.ask_yes_no(
1103 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1103 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1104 if not ans:
1104 if not ans:
1105 print 'Nothing done.'
1105 print 'Nothing done.'
1106 return
1106 return
1107 user_ns = self.shell.user_ns
1107 user_ns = self.shell.user_ns
1108 for i in self.magic_who_ls():
1108 for i in self.magic_who_ls():
1109 del(user_ns[i])
1109 del(user_ns[i])
1110
1110
1111 # Also flush the private list of module references kept for script
1111 # Also flush the private list of module references kept for script
1112 # execution protection
1112 # execution protection
1113 self.shell.clear_main_mod_cache()
1113 self.shell.clear_main_mod_cache()
1114
1114
1115 def magic_reset_selective(self, parameter_s=''):
1115 def magic_reset_selective(self, parameter_s=''):
1116 """Resets the namespace by removing names defined by the user.
1116 """Resets the namespace by removing names defined by the user.
1117
1117
1118 Input/Output history are left around in case you need them.
1118 Input/Output history are left around in case you need them.
1119
1119
1120 %reset_selective [-f] regex
1120 %reset_selective [-f] regex
1121
1121
1122 No action is taken if regex is not included
1122 No action is taken if regex is not included
1123
1123
1124 Options
1124 Options
1125 -f : force reset without asking for confirmation.
1125 -f : force reset without asking for confirmation.
1126
1126
1127 Examples
1127 Examples
1128 --------
1128 --------
1129
1129
1130 We first fully reset the namespace so your output looks identical to
1130 We first fully reset the namespace so your output looks identical to
1131 this example for pedagogical reasons; in practice you do not need a
1131 this example for pedagogical reasons; in practice you do not need a
1132 full reset.
1132 full reset.
1133
1133
1134 In [1]: %reset -f
1134 In [1]: %reset -f
1135
1135
1136 Now, with a clean namespace we can make a few variables and use
1136 Now, with a clean namespace we can make a few variables and use
1137 %reset_selective to only delete names that match our regexp:
1137 %reset_selective to only delete names that match our regexp:
1138
1138
1139 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1139 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1140
1140
1141 In [3]: who_ls
1141 In [3]: who_ls
1142 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1142 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1143
1143
1144 In [4]: %reset_selective -f b[2-3]m
1144 In [4]: %reset_selective -f b[2-3]m
1145
1145
1146 In [5]: who_ls
1146 In [5]: who_ls
1147 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1147 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1148
1148
1149 In [6]: %reset_selective -f d
1149 In [6]: %reset_selective -f d
1150
1150
1151 In [7]: who_ls
1151 In [7]: who_ls
1152 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1152 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1153
1153
1154 In [8]: %reset_selective -f c
1154 In [8]: %reset_selective -f c
1155
1155
1156 In [9]: who_ls
1156 In [9]: who_ls
1157 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1157 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1158
1158
1159 In [10]: %reset_selective -f b
1159 In [10]: %reset_selective -f b
1160
1160
1161 In [11]: who_ls
1161 In [11]: who_ls
1162 Out[11]: ['a']
1162 Out[11]: ['a']
1163 """
1163 """
1164
1164
1165 opts, regex = self.parse_options(parameter_s,'f')
1165 opts, regex = self.parse_options(parameter_s,'f')
1166
1166
1167 if opts.has_key('f'):
1167 if opts.has_key('f'):
1168 ans = True
1168 ans = True
1169 else:
1169 else:
1170 ans = self.shell.ask_yes_no(
1170 ans = self.shell.ask_yes_no(
1171 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1171 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1172 if not ans:
1172 if not ans:
1173 print 'Nothing done.'
1173 print 'Nothing done.'
1174 return
1174 return
1175 user_ns = self.shell.user_ns
1175 user_ns = self.shell.user_ns
1176 if not regex:
1176 if not regex:
1177 print 'No regex pattern specified. Nothing done.'
1177 print 'No regex pattern specified. Nothing done.'
1178 return
1178 return
1179 else:
1179 else:
1180 try:
1180 try:
1181 m = re.compile(regex)
1181 m = re.compile(regex)
1182 except TypeError:
1182 except TypeError:
1183 raise TypeError('regex must be a string or compiled pattern')
1183 raise TypeError('regex must be a string or compiled pattern')
1184 for i in self.magic_who_ls():
1184 for i in self.magic_who_ls():
1185 if m.search(i):
1185 if m.search(i):
1186 del(user_ns[i])
1186 del(user_ns[i])
1187
1187
1188 def magic_logstart(self,parameter_s=''):
1188 def magic_logstart(self,parameter_s=''):
1189 """Start logging anywhere in a session.
1189 """Start logging anywhere in a session.
1190
1190
1191 %logstart [-o|-r|-t] [log_name [log_mode]]
1191 %logstart [-o|-r|-t] [log_name [log_mode]]
1192
1192
1193 If no name is given, it defaults to a file named 'ipython_log.py' in your
1193 If no name is given, it defaults to a file named 'ipython_log.py' in your
1194 current directory, in 'rotate' mode (see below).
1194 current directory, in 'rotate' mode (see below).
1195
1195
1196 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1196 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1197 history up to that point and then continues logging.
1197 history up to that point and then continues logging.
1198
1198
1199 %logstart takes a second optional parameter: logging mode. This can be one
1199 %logstart takes a second optional parameter: logging mode. This can be one
1200 of (note that the modes are given unquoted):\\
1200 of (note that the modes are given unquoted):\\
1201 append: well, that says it.\\
1201 append: well, that says it.\\
1202 backup: rename (if exists) to name~ and start name.\\
1202 backup: rename (if exists) to name~ and start name.\\
1203 global: single logfile in your home dir, appended to.\\
1203 global: single logfile in your home dir, appended to.\\
1204 over : overwrite existing log.\\
1204 over : overwrite existing log.\\
1205 rotate: create rotating logs name.1~, name.2~, etc.
1205 rotate: create rotating logs name.1~, name.2~, etc.
1206
1206
1207 Options:
1207 Options:
1208
1208
1209 -o: log also IPython's output. In this mode, all commands which
1209 -o: log also IPython's output. In this mode, all commands which
1210 generate an Out[NN] prompt are recorded to the logfile, right after
1210 generate an Out[NN] prompt are recorded to the logfile, right after
1211 their corresponding input line. The output lines are always
1211 their corresponding input line. The output lines are always
1212 prepended with a '#[Out]# ' marker, so that the log remains valid
1212 prepended with a '#[Out]# ' marker, so that the log remains valid
1213 Python code.
1213 Python code.
1214
1214
1215 Since this marker is always the same, filtering only the output from
1215 Since this marker is always the same, filtering only the output from
1216 a log is very easy, using for example a simple awk call:
1216 a log is very easy, using for example a simple awk call:
1217
1217
1218 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1218 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1219
1219
1220 -r: log 'raw' input. Normally, IPython's logs contain the processed
1220 -r: log 'raw' input. Normally, IPython's logs contain the processed
1221 input, so that user lines are logged in their final form, converted
1221 input, so that user lines are logged in their final form, converted
1222 into valid Python. For example, %Exit is logged as
1222 into valid Python. For example, %Exit is logged as
1223 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1223 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1224 exactly as typed, with no transformations applied.
1224 exactly as typed, with no transformations applied.
1225
1225
1226 -t: put timestamps before each input line logged (these are put in
1226 -t: put timestamps before each input line logged (these are put in
1227 comments)."""
1227 comments)."""
1228
1228
1229 opts,par = self.parse_options(parameter_s,'ort')
1229 opts,par = self.parse_options(parameter_s,'ort')
1230 log_output = 'o' in opts
1230 log_output = 'o' in opts
1231 log_raw_input = 'r' in opts
1231 log_raw_input = 'r' in opts
1232 timestamp = 't' in opts
1232 timestamp = 't' in opts
1233
1233
1234 logger = self.shell.logger
1234 logger = self.shell.logger
1235
1235
1236 # if no args are given, the defaults set in the logger constructor by
1236 # if no args are given, the defaults set in the logger constructor by
1237 # ipytohn remain valid
1237 # ipytohn remain valid
1238 if par:
1238 if par:
1239 try:
1239 try:
1240 logfname,logmode = par.split()
1240 logfname,logmode = par.split()
1241 except:
1241 except:
1242 logfname = par
1242 logfname = par
1243 logmode = 'backup'
1243 logmode = 'backup'
1244 else:
1244 else:
1245 logfname = logger.logfname
1245 logfname = logger.logfname
1246 logmode = logger.logmode
1246 logmode = logger.logmode
1247 # put logfname into rc struct as if it had been called on the command
1247 # put logfname into rc struct as if it had been called on the command
1248 # line, so it ends up saved in the log header Save it in case we need
1248 # line, so it ends up saved in the log header Save it in case we need
1249 # to restore it...
1249 # to restore it...
1250 old_logfile = self.shell.logfile
1250 old_logfile = self.shell.logfile
1251 if logfname:
1251 if logfname:
1252 logfname = os.path.expanduser(logfname)
1252 logfname = os.path.expanduser(logfname)
1253 self.shell.logfile = logfname
1253 self.shell.logfile = logfname
1254
1254
1255 loghead = '# IPython log file\n\n'
1255 loghead = '# IPython log file\n\n'
1256 try:
1256 try:
1257 started = logger.logstart(logfname,loghead,logmode,
1257 started = logger.logstart(logfname,loghead,logmode,
1258 log_output,timestamp,log_raw_input)
1258 log_output,timestamp,log_raw_input)
1259 except:
1259 except:
1260 self.shell.logfile = old_logfile
1260 self.shell.logfile = old_logfile
1261 warn("Couldn't start log: %s" % sys.exc_info()[1])
1261 warn("Couldn't start log: %s" % sys.exc_info()[1])
1262 else:
1262 else:
1263 # log input history up to this point, optionally interleaving
1263 # log input history up to this point, optionally interleaving
1264 # output if requested
1264 # output if requested
1265
1265
1266 if timestamp:
1266 if timestamp:
1267 # disable timestamping for the previous history, since we've
1267 # disable timestamping for the previous history, since we've
1268 # lost those already (no time machine here).
1268 # lost those already (no time machine here).
1269 logger.timestamp = False
1269 logger.timestamp = False
1270
1270
1271 if log_raw_input:
1271 if log_raw_input:
1272 input_hist = self.shell.input_hist_raw
1272 input_hist = self.shell.input_hist_raw
1273 else:
1273 else:
1274 input_hist = self.shell.input_hist
1274 input_hist = self.shell.input_hist
1275
1275
1276 if log_output:
1276 if log_output:
1277 log_write = logger.log_write
1277 log_write = logger.log_write
1278 output_hist = self.shell.output_hist
1278 output_hist = self.shell.output_hist
1279 for n in range(1,len(input_hist)-1):
1279 for n in range(1,len(input_hist)-1):
1280 log_write(input_hist[n].rstrip())
1280 log_write(input_hist[n].rstrip())
1281 if n in output_hist:
1281 if n in output_hist:
1282 log_write(repr(output_hist[n]),'output')
1282 log_write(repr(output_hist[n]),'output')
1283 else:
1283 else:
1284 logger.log_write(input_hist[1:])
1284 logger.log_write(input_hist[1:])
1285 if timestamp:
1285 if timestamp:
1286 # re-enable timestamping
1286 # re-enable timestamping
1287 logger.timestamp = True
1287 logger.timestamp = True
1288
1288
1289 print ('Activating auto-logging. '
1289 print ('Activating auto-logging. '
1290 'Current session state plus future input saved.')
1290 'Current session state plus future input saved.')
1291 logger.logstate()
1291 logger.logstate()
1292
1292
1293 def magic_logstop(self,parameter_s=''):
1293 def magic_logstop(self,parameter_s=''):
1294 """Fully stop logging and close log file.
1294 """Fully stop logging and close log file.
1295
1295
1296 In order to start logging again, a new %logstart call needs to be made,
1296 In order to start logging again, a new %logstart call needs to be made,
1297 possibly (though not necessarily) with a new filename, mode and other
1297 possibly (though not necessarily) with a new filename, mode and other
1298 options."""
1298 options."""
1299 self.logger.logstop()
1299 self.logger.logstop()
1300
1300
1301 def magic_logoff(self,parameter_s=''):
1301 def magic_logoff(self,parameter_s=''):
1302 """Temporarily stop logging.
1302 """Temporarily stop logging.
1303
1303
1304 You must have previously started logging."""
1304 You must have previously started logging."""
1305 self.shell.logger.switch_log(0)
1305 self.shell.logger.switch_log(0)
1306
1306
1307 def magic_logon(self,parameter_s=''):
1307 def magic_logon(self,parameter_s=''):
1308 """Restart logging.
1308 """Restart logging.
1309
1309
1310 This function is for restarting logging which you've temporarily
1310 This function is for restarting logging which you've temporarily
1311 stopped with %logoff. For starting logging for the first time, you
1311 stopped with %logoff. For starting logging for the first time, you
1312 must use the %logstart function, which allows you to specify an
1312 must use the %logstart function, which allows you to specify an
1313 optional log filename."""
1313 optional log filename."""
1314
1314
1315 self.shell.logger.switch_log(1)
1315 self.shell.logger.switch_log(1)
1316
1316
1317 def magic_logstate(self,parameter_s=''):
1317 def magic_logstate(self,parameter_s=''):
1318 """Print the status of the logging system."""
1318 """Print the status of the logging system."""
1319
1319
1320 self.shell.logger.logstate()
1320 self.shell.logger.logstate()
1321
1321
1322 def magic_pdb(self, parameter_s=''):
1322 def magic_pdb(self, parameter_s=''):
1323 """Control the automatic calling of the pdb interactive debugger.
1323 """Control the automatic calling of the pdb interactive debugger.
1324
1324
1325 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1325 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1326 argument it works as a toggle.
1326 argument it works as a toggle.
1327
1327
1328 When an exception is triggered, IPython can optionally call the
1328 When an exception is triggered, IPython can optionally call the
1329 interactive pdb debugger after the traceback printout. %pdb toggles
1329 interactive pdb debugger after the traceback printout. %pdb toggles
1330 this feature on and off.
1330 this feature on and off.
1331
1331
1332 The initial state of this feature is set in your ipythonrc
1332 The initial state of this feature is set in your ipythonrc
1333 configuration file (the variable is called 'pdb').
1333 configuration file (the variable is called 'pdb').
1334
1334
1335 If you want to just activate the debugger AFTER an exception has fired,
1335 If you want to just activate the debugger AFTER an exception has fired,
1336 without having to type '%pdb on' and rerunning your code, you can use
1336 without having to type '%pdb on' and rerunning your code, you can use
1337 the %debug magic."""
1337 the %debug magic."""
1338
1338
1339 par = parameter_s.strip().lower()
1339 par = parameter_s.strip().lower()
1340
1340
1341 if par:
1341 if par:
1342 try:
1342 try:
1343 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1343 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1344 except KeyError:
1344 except KeyError:
1345 print ('Incorrect argument. Use on/1, off/0, '
1345 print ('Incorrect argument. Use on/1, off/0, '
1346 'or nothing for a toggle.')
1346 'or nothing for a toggle.')
1347 return
1347 return
1348 else:
1348 else:
1349 # toggle
1349 # toggle
1350 new_pdb = not self.shell.call_pdb
1350 new_pdb = not self.shell.call_pdb
1351
1351
1352 # set on the shell
1352 # set on the shell
1353 self.shell.call_pdb = new_pdb
1353 self.shell.call_pdb = new_pdb
1354 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1354 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1355
1355
1356 def magic_debug(self, parameter_s=''):
1356 def magic_debug(self, parameter_s=''):
1357 """Activate the interactive debugger in post-mortem mode.
1357 """Activate the interactive debugger in post-mortem mode.
1358
1358
1359 If an exception has just occurred, this lets you inspect its stack
1359 If an exception has just occurred, this lets you inspect its stack
1360 frames interactively. Note that this will always work only on the last
1360 frames interactively. Note that this will always work only on the last
1361 traceback that occurred, so you must call this quickly after an
1361 traceback that occurred, so you must call this quickly after an
1362 exception that you wish to inspect has fired, because if another one
1362 exception that you wish to inspect has fired, because if another one
1363 occurs, it clobbers the previous one.
1363 occurs, it clobbers the previous one.
1364
1364
1365 If you want IPython to automatically do this on every exception, see
1365 If you want IPython to automatically do this on every exception, see
1366 the %pdb magic for more details.
1366 the %pdb magic for more details.
1367 """
1367 """
1368 self.shell.debugger(force=True)
1368 self.shell.debugger(force=True)
1369
1369
1370 @testdec.skip_doctest
1370 @testdec.skip_doctest
1371 def magic_prun(self, parameter_s ='',user_mode=1,
1371 def magic_prun(self, parameter_s ='',user_mode=1,
1372 opts=None,arg_lst=None,prog_ns=None):
1372 opts=None,arg_lst=None,prog_ns=None):
1373
1373
1374 """Run a statement through the python code profiler.
1374 """Run a statement through the python code profiler.
1375
1375
1376 Usage:
1376 Usage:
1377 %prun [options] statement
1377 %prun [options] statement
1378
1378
1379 The given statement (which doesn't require quote marks) is run via the
1379 The given statement (which doesn't require quote marks) is run via the
1380 python profiler in a manner similar to the profile.run() function.
1380 python profiler in a manner similar to the profile.run() function.
1381 Namespaces are internally managed to work correctly; profile.run
1381 Namespaces are internally managed to work correctly; profile.run
1382 cannot be used in IPython because it makes certain assumptions about
1382 cannot be used in IPython because it makes certain assumptions about
1383 namespaces which do not hold under IPython.
1383 namespaces which do not hold under IPython.
1384
1384
1385 Options:
1385 Options:
1386
1386
1387 -l <limit>: you can place restrictions on what or how much of the
1387 -l <limit>: you can place restrictions on what or how much of the
1388 profile gets printed. The limit value can be:
1388 profile gets printed. The limit value can be:
1389
1389
1390 * A string: only information for function names containing this string
1390 * A string: only information for function names containing this string
1391 is printed.
1391 is printed.
1392
1392
1393 * An integer: only these many lines are printed.
1393 * An integer: only these many lines are printed.
1394
1394
1395 * A float (between 0 and 1): this fraction of the report is printed
1395 * A float (between 0 and 1): this fraction of the report is printed
1396 (for example, use a limit of 0.4 to see the topmost 40% only).
1396 (for example, use a limit of 0.4 to see the topmost 40% only).
1397
1397
1398 You can combine several limits with repeated use of the option. For
1398 You can combine several limits with repeated use of the option. For
1399 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1399 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1400 information about class constructors.
1400 information about class constructors.
1401
1401
1402 -r: return the pstats.Stats object generated by the profiling. This
1402 -r: return the pstats.Stats object generated by the profiling. This
1403 object has all the information about the profile in it, and you can
1403 object has all the information about the profile in it, and you can
1404 later use it for further analysis or in other functions.
1404 later use it for further analysis or in other functions.
1405
1405
1406 -s <key>: sort profile by given key. You can provide more than one key
1406 -s <key>: sort profile by given key. You can provide more than one key
1407 by using the option several times: '-s key1 -s key2 -s key3...'. The
1407 by using the option several times: '-s key1 -s key2 -s key3...'. The
1408 default sorting key is 'time'.
1408 default sorting key is 'time'.
1409
1409
1410 The following is copied verbatim from the profile documentation
1410 The following is copied verbatim from the profile documentation
1411 referenced below:
1411 referenced below:
1412
1412
1413 When more than one key is provided, additional keys are used as
1413 When more than one key is provided, additional keys are used as
1414 secondary criteria when the there is equality in all keys selected
1414 secondary criteria when the there is equality in all keys selected
1415 before them.
1415 before them.
1416
1416
1417 Abbreviations can be used for any key names, as long as the
1417 Abbreviations can be used for any key names, as long as the
1418 abbreviation is unambiguous. The following are the keys currently
1418 abbreviation is unambiguous. The following are the keys currently
1419 defined:
1419 defined:
1420
1420
1421 Valid Arg Meaning
1421 Valid Arg Meaning
1422 "calls" call count
1422 "calls" call count
1423 "cumulative" cumulative time
1423 "cumulative" cumulative time
1424 "file" file name
1424 "file" file name
1425 "module" file name
1425 "module" file name
1426 "pcalls" primitive call count
1426 "pcalls" primitive call count
1427 "line" line number
1427 "line" line number
1428 "name" function name
1428 "name" function name
1429 "nfl" name/file/line
1429 "nfl" name/file/line
1430 "stdname" standard name
1430 "stdname" standard name
1431 "time" internal time
1431 "time" internal time
1432
1432
1433 Note that all sorts on statistics are in descending order (placing
1433 Note that all sorts on statistics are in descending order (placing
1434 most time consuming items first), where as name, file, and line number
1434 most time consuming items first), where as name, file, and line number
1435 searches are in ascending order (i.e., alphabetical). The subtle
1435 searches are in ascending order (i.e., alphabetical). The subtle
1436 distinction between "nfl" and "stdname" is that the standard name is a
1436 distinction between "nfl" and "stdname" is that the standard name is a
1437 sort of the name as printed, which means that the embedded line
1437 sort of the name as printed, which means that the embedded line
1438 numbers get compared in an odd way. For example, lines 3, 20, and 40
1438 numbers get compared in an odd way. For example, lines 3, 20, and 40
1439 would (if the file names were the same) appear in the string order
1439 would (if the file names were the same) appear in the string order
1440 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1440 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1441 line numbers. In fact, sort_stats("nfl") is the same as
1441 line numbers. In fact, sort_stats("nfl") is the same as
1442 sort_stats("name", "file", "line").
1442 sort_stats("name", "file", "line").
1443
1443
1444 -T <filename>: save profile results as shown on screen to a text
1444 -T <filename>: save profile results as shown on screen to a text
1445 file. The profile is still shown on screen.
1445 file. The profile is still shown on screen.
1446
1446
1447 -D <filename>: save (via dump_stats) profile statistics to given
1447 -D <filename>: save (via dump_stats) profile statistics to given
1448 filename. This data is in a format understod by the pstats module, and
1448 filename. This data is in a format understod by the pstats module, and
1449 is generated by a call to the dump_stats() method of profile
1449 is generated by a call to the dump_stats() method of profile
1450 objects. The profile is still shown on screen.
1450 objects. The profile is still shown on screen.
1451
1451
1452 If you want to run complete programs under the profiler's control, use
1452 If you want to run complete programs under the profiler's control, use
1453 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1453 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1454 contains profiler specific options as described here.
1454 contains profiler specific options as described here.
1455
1455
1456 You can read the complete documentation for the profile module with::
1456 You can read the complete documentation for the profile module with::
1457
1457
1458 In [1]: import profile; profile.help()
1458 In [1]: import profile; profile.help()
1459 """
1459 """
1460
1460
1461 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1461 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1462 # protect user quote marks
1462 # protect user quote marks
1463 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1463 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1464
1464
1465 if user_mode: # regular user call
1465 if user_mode: # regular user call
1466 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1466 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1467 list_all=1)
1467 list_all=1)
1468 namespace = self.shell.user_ns
1468 namespace = self.shell.user_ns
1469 else: # called to run a program by %run -p
1469 else: # called to run a program by %run -p
1470 try:
1470 try:
1471 filename = get_py_filename(arg_lst[0])
1471 filename = get_py_filename(arg_lst[0])
1472 except IOError,msg:
1472 except IOError,msg:
1473 error(msg)
1473 error(msg)
1474 return
1474 return
1475
1475
1476 arg_str = 'execfile(filename,prog_ns)'
1476 arg_str = 'execfile(filename,prog_ns)'
1477 namespace = locals()
1477 namespace = locals()
1478
1478
1479 opts.merge(opts_def)
1479 opts.merge(opts_def)
1480
1480
1481 prof = profile.Profile()
1481 prof = profile.Profile()
1482 try:
1482 try:
1483 prof = prof.runctx(arg_str,namespace,namespace)
1483 prof = prof.runctx(arg_str,namespace,namespace)
1484 sys_exit = ''
1484 sys_exit = ''
1485 except SystemExit:
1485 except SystemExit:
1486 sys_exit = """*** SystemExit exception caught in code being profiled."""
1486 sys_exit = """*** SystemExit exception caught in code being profiled."""
1487
1487
1488 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1488 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1489
1489
1490 lims = opts.l
1490 lims = opts.l
1491 if lims:
1491 if lims:
1492 lims = [] # rebuild lims with ints/floats/strings
1492 lims = [] # rebuild lims with ints/floats/strings
1493 for lim in opts.l:
1493 for lim in opts.l:
1494 try:
1494 try:
1495 lims.append(int(lim))
1495 lims.append(int(lim))
1496 except ValueError:
1496 except ValueError:
1497 try:
1497 try:
1498 lims.append(float(lim))
1498 lims.append(float(lim))
1499 except ValueError:
1499 except ValueError:
1500 lims.append(lim)
1500 lims.append(lim)
1501
1501
1502 # Trap output.
1502 # Trap output.
1503 stdout_trap = StringIO()
1503 stdout_trap = StringIO()
1504
1504
1505 if hasattr(stats,'stream'):
1505 if hasattr(stats,'stream'):
1506 # In newer versions of python, the stats object has a 'stream'
1506 # In newer versions of python, the stats object has a 'stream'
1507 # attribute to write into.
1507 # attribute to write into.
1508 stats.stream = stdout_trap
1508 stats.stream = stdout_trap
1509 stats.print_stats(*lims)
1509 stats.print_stats(*lims)
1510 else:
1510 else:
1511 # For older versions, we manually redirect stdout during printing
1511 # For older versions, we manually redirect stdout during printing
1512 sys_stdout = sys.stdout
1512 sys_stdout = sys.stdout
1513 try:
1513 try:
1514 sys.stdout = stdout_trap
1514 sys.stdout = stdout_trap
1515 stats.print_stats(*lims)
1515 stats.print_stats(*lims)
1516 finally:
1516 finally:
1517 sys.stdout = sys_stdout
1517 sys.stdout = sys_stdout
1518
1518
1519 output = stdout_trap.getvalue()
1519 output = stdout_trap.getvalue()
1520 output = output.rstrip()
1520 output = output.rstrip()
1521
1521
1522 page(output,screen_lines=self.shell.usable_screen_length)
1522 page(output,screen_lines=self.shell.usable_screen_length)
1523 print sys_exit,
1523 print sys_exit,
1524
1524
1525 dump_file = opts.D[0]
1525 dump_file = opts.D[0]
1526 text_file = opts.T[0]
1526 text_file = opts.T[0]
1527 if dump_file:
1527 if dump_file:
1528 prof.dump_stats(dump_file)
1528 prof.dump_stats(dump_file)
1529 print '\n*** Profile stats marshalled to file',\
1529 print '\n*** Profile stats marshalled to file',\
1530 `dump_file`+'.',sys_exit
1530 `dump_file`+'.',sys_exit
1531 if text_file:
1531 if text_file:
1532 pfile = file(text_file,'w')
1532 pfile = file(text_file,'w')
1533 pfile.write(output)
1533 pfile.write(output)
1534 pfile.close()
1534 pfile.close()
1535 print '\n*** Profile printout saved to text file',\
1535 print '\n*** Profile printout saved to text file',\
1536 `text_file`+'.',sys_exit
1536 `text_file`+'.',sys_exit
1537
1537
1538 if opts.has_key('r'):
1538 if opts.has_key('r'):
1539 return stats
1539 return stats
1540 else:
1540 else:
1541 return None
1541 return None
1542
1542
1543 @testdec.skip_doctest
1543 @testdec.skip_doctest
1544 def magic_run(self, parameter_s ='',runner=None,
1544 def magic_run(self, parameter_s ='',runner=None,
1545 file_finder=get_py_filename):
1545 file_finder=get_py_filename):
1546 """Run the named file inside IPython as a program.
1546 """Run the named file inside IPython as a program.
1547
1547
1548 Usage:\\
1548 Usage:\\
1549 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1549 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1550
1550
1551 Parameters after the filename are passed as command-line arguments to
1551 Parameters after the filename are passed as command-line arguments to
1552 the program (put in sys.argv). Then, control returns to IPython's
1552 the program (put in sys.argv). Then, control returns to IPython's
1553 prompt.
1553 prompt.
1554
1554
1555 This is similar to running at a system prompt:\\
1555 This is similar to running at a system prompt:\\
1556 $ python file args\\
1556 $ python file args\\
1557 but with the advantage of giving you IPython's tracebacks, and of
1557 but with the advantage of giving you IPython's tracebacks, and of
1558 loading all variables into your interactive namespace for further use
1558 loading all variables into your interactive namespace for further use
1559 (unless -p is used, see below).
1559 (unless -p is used, see below).
1560
1560
1561 The file is executed in a namespace initially consisting only of
1561 The file is executed in a namespace initially consisting only of
1562 __name__=='__main__' and sys.argv constructed as indicated. It thus
1562 __name__=='__main__' and sys.argv constructed as indicated. It thus
1563 sees its environment as if it were being run as a stand-alone program
1563 sees its environment as if it were being run as a stand-alone program
1564 (except for sharing global objects such as previously imported
1564 (except for sharing global objects such as previously imported
1565 modules). But after execution, the IPython interactive namespace gets
1565 modules). But after execution, the IPython interactive namespace gets
1566 updated with all variables defined in the program (except for __name__
1566 updated with all variables defined in the program (except for __name__
1567 and sys.argv). This allows for very convenient loading of code for
1567 and sys.argv). This allows for very convenient loading of code for
1568 interactive work, while giving each program a 'clean sheet' to run in.
1568 interactive work, while giving each program a 'clean sheet' to run in.
1569
1569
1570 Options:
1570 Options:
1571
1571
1572 -n: __name__ is NOT set to '__main__', but to the running file's name
1572 -n: __name__ is NOT set to '__main__', but to the running file's name
1573 without extension (as python does under import). This allows running
1573 without extension (as python does under import). This allows running
1574 scripts and reloading the definitions in them without calling code
1574 scripts and reloading the definitions in them without calling code
1575 protected by an ' if __name__ == "__main__" ' clause.
1575 protected by an ' if __name__ == "__main__" ' clause.
1576
1576
1577 -i: run the file in IPython's namespace instead of an empty one. This
1577 -i: run the file in IPython's namespace instead of an empty one. This
1578 is useful if you are experimenting with code written in a text editor
1578 is useful if you are experimenting with code written in a text editor
1579 which depends on variables defined interactively.
1579 which depends on variables defined interactively.
1580
1580
1581 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1581 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1582 being run. This is particularly useful if IPython is being used to
1582 being run. This is particularly useful if IPython is being used to
1583 run unittests, which always exit with a sys.exit() call. In such
1583 run unittests, which always exit with a sys.exit() call. In such
1584 cases you are interested in the output of the test results, not in
1584 cases you are interested in the output of the test results, not in
1585 seeing a traceback of the unittest module.
1585 seeing a traceback of the unittest module.
1586
1586
1587 -t: print timing information at the end of the run. IPython will give
1587 -t: print timing information at the end of the run. IPython will give
1588 you an estimated CPU time consumption for your script, which under
1588 you an estimated CPU time consumption for your script, which under
1589 Unix uses the resource module to avoid the wraparound problems of
1589 Unix uses the resource module to avoid the wraparound problems of
1590 time.clock(). Under Unix, an estimate of time spent on system tasks
1590 time.clock(). Under Unix, an estimate of time spent on system tasks
1591 is also given (for Windows platforms this is reported as 0.0).
1591 is also given (for Windows platforms this is reported as 0.0).
1592
1592
1593 If -t is given, an additional -N<N> option can be given, where <N>
1593 If -t is given, an additional -N<N> option can be given, where <N>
1594 must be an integer indicating how many times you want the script to
1594 must be an integer indicating how many times you want the script to
1595 run. The final timing report will include total and per run results.
1595 run. The final timing report will include total and per run results.
1596
1596
1597 For example (testing the script uniq_stable.py):
1597 For example (testing the script uniq_stable.py):
1598
1598
1599 In [1]: run -t uniq_stable
1599 In [1]: run -t uniq_stable
1600
1600
1601 IPython CPU timings (estimated):\\
1601 IPython CPU timings (estimated):\\
1602 User : 0.19597 s.\\
1602 User : 0.19597 s.\\
1603 System: 0.0 s.\\
1603 System: 0.0 s.\\
1604
1604
1605 In [2]: run -t -N5 uniq_stable
1605 In [2]: run -t -N5 uniq_stable
1606
1606
1607 IPython CPU timings (estimated):\\
1607 IPython CPU timings (estimated):\\
1608 Total runs performed: 5\\
1608 Total runs performed: 5\\
1609 Times : Total Per run\\
1609 Times : Total Per run\\
1610 User : 0.910862 s, 0.1821724 s.\\
1610 User : 0.910862 s, 0.1821724 s.\\
1611 System: 0.0 s, 0.0 s.
1611 System: 0.0 s, 0.0 s.
1612
1612
1613 -d: run your program under the control of pdb, the Python debugger.
1613 -d: run your program under the control of pdb, the Python debugger.
1614 This allows you to execute your program step by step, watch variables,
1614 This allows you to execute your program step by step, watch variables,
1615 etc. Internally, what IPython does is similar to calling:
1615 etc. Internally, what IPython does is similar to calling:
1616
1616
1617 pdb.run('execfile("YOURFILENAME")')
1617 pdb.run('execfile("YOURFILENAME")')
1618
1618
1619 with a breakpoint set on line 1 of your file. You can change the line
1619 with a breakpoint set on line 1 of your file. You can change the line
1620 number for this automatic breakpoint to be <N> by using the -bN option
1620 number for this automatic breakpoint to be <N> by using the -bN option
1621 (where N must be an integer). For example:
1621 (where N must be an integer). For example:
1622
1622
1623 %run -d -b40 myscript
1623 %run -d -b40 myscript
1624
1624
1625 will set the first breakpoint at line 40 in myscript.py. Note that
1625 will set the first breakpoint at line 40 in myscript.py. Note that
1626 the first breakpoint must be set on a line which actually does
1626 the first breakpoint must be set on a line which actually does
1627 something (not a comment or docstring) for it to stop execution.
1627 something (not a comment or docstring) for it to stop execution.
1628
1628
1629 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1629 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1630 first enter 'c' (without qoutes) to start execution up to the first
1630 first enter 'c' (without qoutes) to start execution up to the first
1631 breakpoint.
1631 breakpoint.
1632
1632
1633 Entering 'help' gives information about the use of the debugger. You
1633 Entering 'help' gives information about the use of the debugger. You
1634 can easily see pdb's full documentation with "import pdb;pdb.help()"
1634 can easily see pdb's full documentation with "import pdb;pdb.help()"
1635 at a prompt.
1635 at a prompt.
1636
1636
1637 -p: run program under the control of the Python profiler module (which
1637 -p: run program under the control of the Python profiler module (which
1638 prints a detailed report of execution times, function calls, etc).
1638 prints a detailed report of execution times, function calls, etc).
1639
1639
1640 You can pass other options after -p which affect the behavior of the
1640 You can pass other options after -p which affect the behavior of the
1641 profiler itself. See the docs for %prun for details.
1641 profiler itself. See the docs for %prun for details.
1642
1642
1643 In this mode, the program's variables do NOT propagate back to the
1643 In this mode, the program's variables do NOT propagate back to the
1644 IPython interactive namespace (because they remain in the namespace
1644 IPython interactive namespace (because they remain in the namespace
1645 where the profiler executes them).
1645 where the profiler executes them).
1646
1646
1647 Internally this triggers a call to %prun, see its documentation for
1647 Internally this triggers a call to %prun, see its documentation for
1648 details on the options available specifically for profiling.
1648 details on the options available specifically for profiling.
1649
1649
1650 There is one special usage for which the text above doesn't apply:
1650 There is one special usage for which the text above doesn't apply:
1651 if the filename ends with .ipy, the file is run as ipython script,
1651 if the filename ends with .ipy, the file is run as ipython script,
1652 just as if the commands were written on IPython prompt.
1652 just as if the commands were written on IPython prompt.
1653 """
1653 """
1654
1654
1655 # get arguments and set sys.argv for program to be run.
1655 # get arguments and set sys.argv for program to be run.
1656 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1656 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1657 mode='list',list_all=1)
1657 mode='list',list_all=1)
1658
1658
1659 try:
1659 try:
1660 filename = file_finder(arg_lst[0])
1660 filename = file_finder(arg_lst[0])
1661 except IndexError:
1661 except IndexError:
1662 warn('you must provide at least a filename.')
1662 warn('you must provide at least a filename.')
1663 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1663 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1664 return
1664 return
1665 except IOError,msg:
1665 except IOError,msg:
1666 error(msg)
1666 error(msg)
1667 return
1667 return
1668
1668
1669 if filename.lower().endswith('.ipy'):
1669 if filename.lower().endswith('.ipy'):
1670 self.shell.safe_execfile_ipy(filename)
1670 self.shell.safe_execfile_ipy(filename)
1671 return
1671 return
1672
1672
1673 # Control the response to exit() calls made by the script being run
1673 # Control the response to exit() calls made by the script being run
1674 exit_ignore = opts.has_key('e')
1674 exit_ignore = opts.has_key('e')
1675
1675
1676 # Make sure that the running script gets a proper sys.argv as if it
1676 # Make sure that the running script gets a proper sys.argv as if it
1677 # were run from a system shell.
1677 # were run from a system shell.
1678 save_argv = sys.argv # save it for later restoring
1678 save_argv = sys.argv # save it for later restoring
1679 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1679 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1680
1680
1681 if opts.has_key('i'):
1681 if opts.has_key('i'):
1682 # Run in user's interactive namespace
1682 # Run in user's interactive namespace
1683 prog_ns = self.shell.user_ns
1683 prog_ns = self.shell.user_ns
1684 __name__save = self.shell.user_ns['__name__']
1684 __name__save = self.shell.user_ns['__name__']
1685 prog_ns['__name__'] = '__main__'
1685 prog_ns['__name__'] = '__main__'
1686 main_mod = self.shell.new_main_mod(prog_ns)
1686 main_mod = self.shell.new_main_mod(prog_ns)
1687 else:
1687 else:
1688 # Run in a fresh, empty namespace
1688 # Run in a fresh, empty namespace
1689 if opts.has_key('n'):
1689 if opts.has_key('n'):
1690 name = os.path.splitext(os.path.basename(filename))[0]
1690 name = os.path.splitext(os.path.basename(filename))[0]
1691 else:
1691 else:
1692 name = '__main__'
1692 name = '__main__'
1693
1693
1694 main_mod = self.shell.new_main_mod()
1694 main_mod = self.shell.new_main_mod()
1695 prog_ns = main_mod.__dict__
1695 prog_ns = main_mod.__dict__
1696 prog_ns['__name__'] = name
1696 prog_ns['__name__'] = name
1697
1697
1698 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1698 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1699 # set the __file__ global in the script's namespace
1699 # set the __file__ global in the script's namespace
1700 prog_ns['__file__'] = filename
1700 prog_ns['__file__'] = filename
1701
1701
1702 # pickle fix. See iplib for an explanation. But we need to make sure
1702 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1703 # that, if we overwrite __main__, we replace it at the end
1703 # that, if we overwrite __main__, we replace it at the end
1704 main_mod_name = prog_ns['__name__']
1704 main_mod_name = prog_ns['__name__']
1705
1705
1706 if main_mod_name == '__main__':
1706 if main_mod_name == '__main__':
1707 restore_main = sys.modules['__main__']
1707 restore_main = sys.modules['__main__']
1708 else:
1708 else:
1709 restore_main = False
1709 restore_main = False
1710
1710
1711 # This needs to be undone at the end to prevent holding references to
1711 # This needs to be undone at the end to prevent holding references to
1712 # every single object ever created.
1712 # every single object ever created.
1713 sys.modules[main_mod_name] = main_mod
1713 sys.modules[main_mod_name] = main_mod
1714
1714
1715 stats = None
1715 stats = None
1716 try:
1716 try:
1717 self.shell.savehist()
1717 self.shell.savehist()
1718
1718
1719 if opts.has_key('p'):
1719 if opts.has_key('p'):
1720 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1720 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1721 else:
1721 else:
1722 if opts.has_key('d'):
1722 if opts.has_key('d'):
1723 deb = debugger.Pdb(self.shell.colors)
1723 deb = debugger.Pdb(self.shell.colors)
1724 # reset Breakpoint state, which is moronically kept
1724 # reset Breakpoint state, which is moronically kept
1725 # in a class
1725 # in a class
1726 bdb.Breakpoint.next = 1
1726 bdb.Breakpoint.next = 1
1727 bdb.Breakpoint.bplist = {}
1727 bdb.Breakpoint.bplist = {}
1728 bdb.Breakpoint.bpbynumber = [None]
1728 bdb.Breakpoint.bpbynumber = [None]
1729 # Set an initial breakpoint to stop execution
1729 # Set an initial breakpoint to stop execution
1730 maxtries = 10
1730 maxtries = 10
1731 bp = int(opts.get('b',[1])[0])
1731 bp = int(opts.get('b',[1])[0])
1732 checkline = deb.checkline(filename,bp)
1732 checkline = deb.checkline(filename,bp)
1733 if not checkline:
1733 if not checkline:
1734 for bp in range(bp+1,bp+maxtries+1):
1734 for bp in range(bp+1,bp+maxtries+1):
1735 if deb.checkline(filename,bp):
1735 if deb.checkline(filename,bp):
1736 break
1736 break
1737 else:
1737 else:
1738 msg = ("\nI failed to find a valid line to set "
1738 msg = ("\nI failed to find a valid line to set "
1739 "a breakpoint\n"
1739 "a breakpoint\n"
1740 "after trying up to line: %s.\n"
1740 "after trying up to line: %s.\n"
1741 "Please set a valid breakpoint manually "
1741 "Please set a valid breakpoint manually "
1742 "with the -b option." % bp)
1742 "with the -b option." % bp)
1743 error(msg)
1743 error(msg)
1744 return
1744 return
1745 # if we find a good linenumber, set the breakpoint
1745 # if we find a good linenumber, set the breakpoint
1746 deb.do_break('%s:%s' % (filename,bp))
1746 deb.do_break('%s:%s' % (filename,bp))
1747 # Start file run
1747 # Start file run
1748 print "NOTE: Enter 'c' at the",
1748 print "NOTE: Enter 'c' at the",
1749 print "%s prompt to start your script." % deb.prompt
1749 print "%s prompt to start your script." % deb.prompt
1750 try:
1750 try:
1751 deb.run('execfile("%s")' % filename,prog_ns)
1751 deb.run('execfile("%s")' % filename,prog_ns)
1752
1752
1753 except:
1753 except:
1754 etype, value, tb = sys.exc_info()
1754 etype, value, tb = sys.exc_info()
1755 # Skip three frames in the traceback: the %run one,
1755 # Skip three frames in the traceback: the %run one,
1756 # one inside bdb.py, and the command-line typed by the
1756 # one inside bdb.py, and the command-line typed by the
1757 # user (run by exec in pdb itself).
1757 # user (run by exec in pdb itself).
1758 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1758 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1759 else:
1759 else:
1760 if runner is None:
1760 if runner is None:
1761 runner = self.shell.safe_execfile
1761 runner = self.shell.safe_execfile
1762 if opts.has_key('t'):
1762 if opts.has_key('t'):
1763 # timed execution
1763 # timed execution
1764 try:
1764 try:
1765 nruns = int(opts['N'][0])
1765 nruns = int(opts['N'][0])
1766 if nruns < 1:
1766 if nruns < 1:
1767 error('Number of runs must be >=1')
1767 error('Number of runs must be >=1')
1768 return
1768 return
1769 except (KeyError):
1769 except (KeyError):
1770 nruns = 1
1770 nruns = 1
1771 if nruns == 1:
1771 if nruns == 1:
1772 t0 = clock2()
1772 t0 = clock2()
1773 runner(filename,prog_ns,prog_ns,
1773 runner(filename,prog_ns,prog_ns,
1774 exit_ignore=exit_ignore)
1774 exit_ignore=exit_ignore)
1775 t1 = clock2()
1775 t1 = clock2()
1776 t_usr = t1[0]-t0[0]
1776 t_usr = t1[0]-t0[0]
1777 t_sys = t1[1]-t0[1]
1777 t_sys = t1[1]-t0[1]
1778 print "\nIPython CPU timings (estimated):"
1778 print "\nIPython CPU timings (estimated):"
1779 print " User : %10s s." % t_usr
1779 print " User : %10s s." % t_usr
1780 print " System: %10s s." % t_sys
1780 print " System: %10s s." % t_sys
1781 else:
1781 else:
1782 runs = range(nruns)
1782 runs = range(nruns)
1783 t0 = clock2()
1783 t0 = clock2()
1784 for nr in runs:
1784 for nr in runs:
1785 runner(filename,prog_ns,prog_ns,
1785 runner(filename,prog_ns,prog_ns,
1786 exit_ignore=exit_ignore)
1786 exit_ignore=exit_ignore)
1787 t1 = clock2()
1787 t1 = clock2()
1788 t_usr = t1[0]-t0[0]
1788 t_usr = t1[0]-t0[0]
1789 t_sys = t1[1]-t0[1]
1789 t_sys = t1[1]-t0[1]
1790 print "\nIPython CPU timings (estimated):"
1790 print "\nIPython CPU timings (estimated):"
1791 print "Total runs performed:",nruns
1791 print "Total runs performed:",nruns
1792 print " Times : %10s %10s" % ('Total','Per run')
1792 print " Times : %10s %10s" % ('Total','Per run')
1793 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1793 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1794 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1794 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1795
1795
1796 else:
1796 else:
1797 # regular execution
1797 # regular execution
1798 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1798 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1799
1799
1800 if opts.has_key('i'):
1800 if opts.has_key('i'):
1801 self.shell.user_ns['__name__'] = __name__save
1801 self.shell.user_ns['__name__'] = __name__save
1802 else:
1802 else:
1803 # The shell MUST hold a reference to prog_ns so after %run
1803 # The shell MUST hold a reference to prog_ns so after %run
1804 # exits, the python deletion mechanism doesn't zero it out
1804 # exits, the python deletion mechanism doesn't zero it out
1805 # (leaving dangling references).
1805 # (leaving dangling references).
1806 self.shell.cache_main_mod(prog_ns,filename)
1806 self.shell.cache_main_mod(prog_ns,filename)
1807 # update IPython interactive namespace
1807 # update IPython interactive namespace
1808
1808
1809 # Some forms of read errors on the file may mean the
1809 # Some forms of read errors on the file may mean the
1810 # __name__ key was never set; using pop we don't have to
1810 # __name__ key was never set; using pop we don't have to
1811 # worry about a possible KeyError.
1811 # worry about a possible KeyError.
1812 prog_ns.pop('__name__', None)
1812 prog_ns.pop('__name__', None)
1813
1813
1814 self.shell.user_ns.update(prog_ns)
1814 self.shell.user_ns.update(prog_ns)
1815 finally:
1815 finally:
1816 # It's a bit of a mystery why, but __builtins__ can change from
1816 # It's a bit of a mystery why, but __builtins__ can change from
1817 # being a module to becoming a dict missing some key data after
1817 # being a module to becoming a dict missing some key data after
1818 # %run. As best I can see, this is NOT something IPython is doing
1818 # %run. As best I can see, this is NOT something IPython is doing
1819 # at all, and similar problems have been reported before:
1819 # at all, and similar problems have been reported before:
1820 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1820 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1821 # Since this seems to be done by the interpreter itself, the best
1821 # Since this seems to be done by the interpreter itself, the best
1822 # we can do is to at least restore __builtins__ for the user on
1822 # we can do is to at least restore __builtins__ for the user on
1823 # exit.
1823 # exit.
1824 self.shell.user_ns['__builtins__'] = __builtin__
1824 self.shell.user_ns['__builtins__'] = __builtin__
1825
1825
1826 # Ensure key global structures are restored
1826 # Ensure key global structures are restored
1827 sys.argv = save_argv
1827 sys.argv = save_argv
1828 if restore_main:
1828 if restore_main:
1829 sys.modules['__main__'] = restore_main
1829 sys.modules['__main__'] = restore_main
1830 else:
1830 else:
1831 # Remove from sys.modules the reference to main_mod we'd
1831 # Remove from sys.modules the reference to main_mod we'd
1832 # added. Otherwise it will trap references to objects
1832 # added. Otherwise it will trap references to objects
1833 # contained therein.
1833 # contained therein.
1834 del sys.modules[main_mod_name]
1834 del sys.modules[main_mod_name]
1835
1835
1836 self.shell.reloadhist()
1836 self.shell.reloadhist()
1837
1837
1838 return stats
1838 return stats
1839
1839
1840 @testdec.skip_doctest
1840 @testdec.skip_doctest
1841 def magic_timeit(self, parameter_s =''):
1841 def magic_timeit(self, parameter_s =''):
1842 """Time execution of a Python statement or expression
1842 """Time execution of a Python statement or expression
1843
1843
1844 Usage:\\
1844 Usage:\\
1845 %timeit [-n<N> -r<R> [-t|-c]] statement
1845 %timeit [-n<N> -r<R> [-t|-c]] statement
1846
1846
1847 Time execution of a Python statement or expression using the timeit
1847 Time execution of a Python statement or expression using the timeit
1848 module.
1848 module.
1849
1849
1850 Options:
1850 Options:
1851 -n<N>: execute the given statement <N> times in a loop. If this value
1851 -n<N>: execute the given statement <N> times in a loop. If this value
1852 is not given, a fitting value is chosen.
1852 is not given, a fitting value is chosen.
1853
1853
1854 -r<R>: repeat the loop iteration <R> times and take the best result.
1854 -r<R>: repeat the loop iteration <R> times and take the best result.
1855 Default: 3
1855 Default: 3
1856
1856
1857 -t: use time.time to measure the time, which is the default on Unix.
1857 -t: use time.time to measure the time, which is the default on Unix.
1858 This function measures wall time.
1858 This function measures wall time.
1859
1859
1860 -c: use time.clock to measure the time, which is the default on
1860 -c: use time.clock to measure the time, which is the default on
1861 Windows and measures wall time. On Unix, resource.getrusage is used
1861 Windows and measures wall time. On Unix, resource.getrusage is used
1862 instead and returns the CPU user time.
1862 instead and returns the CPU user time.
1863
1863
1864 -p<P>: use a precision of <P> digits to display the timing result.
1864 -p<P>: use a precision of <P> digits to display the timing result.
1865 Default: 3
1865 Default: 3
1866
1866
1867
1867
1868 Examples:
1868 Examples:
1869
1869
1870 In [1]: %timeit pass
1870 In [1]: %timeit pass
1871 10000000 loops, best of 3: 53.3 ns per loop
1871 10000000 loops, best of 3: 53.3 ns per loop
1872
1872
1873 In [2]: u = None
1873 In [2]: u = None
1874
1874
1875 In [3]: %timeit u is None
1875 In [3]: %timeit u is None
1876 10000000 loops, best of 3: 184 ns per loop
1876 10000000 loops, best of 3: 184 ns per loop
1877
1877
1878 In [4]: %timeit -r 4 u == None
1878 In [4]: %timeit -r 4 u == None
1879 1000000 loops, best of 4: 242 ns per loop
1879 1000000 loops, best of 4: 242 ns per loop
1880
1880
1881 In [5]: import time
1881 In [5]: import time
1882
1882
1883 In [6]: %timeit -n1 time.sleep(2)
1883 In [6]: %timeit -n1 time.sleep(2)
1884 1 loops, best of 3: 2 s per loop
1884 1 loops, best of 3: 2 s per loop
1885
1885
1886
1886
1887 The times reported by %timeit will be slightly higher than those
1887 The times reported by %timeit will be slightly higher than those
1888 reported by the timeit.py script when variables are accessed. This is
1888 reported by the timeit.py script when variables are accessed. This is
1889 due to the fact that %timeit executes the statement in the namespace
1889 due to the fact that %timeit executes the statement in the namespace
1890 of the shell, compared with timeit.py, which uses a single setup
1890 of the shell, compared with timeit.py, which uses a single setup
1891 statement to import function or create variables. Generally, the bias
1891 statement to import function or create variables. Generally, the bias
1892 does not matter as long as results from timeit.py are not mixed with
1892 does not matter as long as results from timeit.py are not mixed with
1893 those from %timeit."""
1893 those from %timeit."""
1894
1894
1895 import timeit
1895 import timeit
1896 import math
1896 import math
1897
1897
1898 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1898 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1899 # certain terminals. Until we figure out a robust way of
1899 # certain terminals. Until we figure out a robust way of
1900 # auto-detecting if the terminal can deal with it, use plain 'us' for
1900 # auto-detecting if the terminal can deal with it, use plain 'us' for
1901 # microseconds. I am really NOT happy about disabling the proper
1901 # microseconds. I am really NOT happy about disabling the proper
1902 # 'micro' prefix, but crashing is worse... If anyone knows what the
1902 # 'micro' prefix, but crashing is worse... If anyone knows what the
1903 # right solution for this is, I'm all ears...
1903 # right solution for this is, I'm all ears...
1904 #
1904 #
1905 # Note: using
1905 # Note: using
1906 #
1906 #
1907 # s = u'\xb5'
1907 # s = u'\xb5'
1908 # s.encode(sys.getdefaultencoding())
1908 # s.encode(sys.getdefaultencoding())
1909 #
1909 #
1910 # is not sufficient, as I've seen terminals where that fails but
1910 # is not sufficient, as I've seen terminals where that fails but
1911 # print s
1911 # print s
1912 #
1912 #
1913 # succeeds
1913 # succeeds
1914 #
1914 #
1915 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1915 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1916
1916
1917 #units = [u"s", u"ms",u'\xb5',"ns"]
1917 #units = [u"s", u"ms",u'\xb5',"ns"]
1918 units = [u"s", u"ms",u'us',"ns"]
1918 units = [u"s", u"ms",u'us',"ns"]
1919
1919
1920 scaling = [1, 1e3, 1e6, 1e9]
1920 scaling = [1, 1e3, 1e6, 1e9]
1921
1921
1922 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1922 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1923 posix=False)
1923 posix=False)
1924 if stmt == "":
1924 if stmt == "":
1925 return
1925 return
1926 timefunc = timeit.default_timer
1926 timefunc = timeit.default_timer
1927 number = int(getattr(opts, "n", 0))
1927 number = int(getattr(opts, "n", 0))
1928 repeat = int(getattr(opts, "r", timeit.default_repeat))
1928 repeat = int(getattr(opts, "r", timeit.default_repeat))
1929 precision = int(getattr(opts, "p", 3))
1929 precision = int(getattr(opts, "p", 3))
1930 if hasattr(opts, "t"):
1930 if hasattr(opts, "t"):
1931 timefunc = time.time
1931 timefunc = time.time
1932 if hasattr(opts, "c"):
1932 if hasattr(opts, "c"):
1933 timefunc = clock
1933 timefunc = clock
1934
1934
1935 timer = timeit.Timer(timer=timefunc)
1935 timer = timeit.Timer(timer=timefunc)
1936 # this code has tight coupling to the inner workings of timeit.Timer,
1936 # this code has tight coupling to the inner workings of timeit.Timer,
1937 # but is there a better way to achieve that the code stmt has access
1937 # but is there a better way to achieve that the code stmt has access
1938 # to the shell namespace?
1938 # to the shell namespace?
1939
1939
1940 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1940 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1941 'setup': "pass"}
1941 'setup': "pass"}
1942 # Track compilation time so it can be reported if too long
1942 # Track compilation time so it can be reported if too long
1943 # Minimum time above which compilation time will be reported
1943 # Minimum time above which compilation time will be reported
1944 tc_min = 0.1
1944 tc_min = 0.1
1945
1945
1946 t0 = clock()
1946 t0 = clock()
1947 code = compile(src, "<magic-timeit>", "exec")
1947 code = compile(src, "<magic-timeit>", "exec")
1948 tc = clock()-t0
1948 tc = clock()-t0
1949
1949
1950 ns = {}
1950 ns = {}
1951 exec code in self.shell.user_ns, ns
1951 exec code in self.shell.user_ns, ns
1952 timer.inner = ns["inner"]
1952 timer.inner = ns["inner"]
1953
1953
1954 if number == 0:
1954 if number == 0:
1955 # determine number so that 0.2 <= total time < 2.0
1955 # determine number so that 0.2 <= total time < 2.0
1956 number = 1
1956 number = 1
1957 for i in range(1, 10):
1957 for i in range(1, 10):
1958 if timer.timeit(number) >= 0.2:
1958 if timer.timeit(number) >= 0.2:
1959 break
1959 break
1960 number *= 10
1960 number *= 10
1961
1961
1962 best = min(timer.repeat(repeat, number)) / number
1962 best = min(timer.repeat(repeat, number)) / number
1963
1963
1964 if best > 0.0 and best < 1000.0:
1964 if best > 0.0 and best < 1000.0:
1965 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1965 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1966 elif best >= 1000.0:
1966 elif best >= 1000.0:
1967 order = 0
1967 order = 0
1968 else:
1968 else:
1969 order = 3
1969 order = 3
1970 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1970 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1971 precision,
1971 precision,
1972 best * scaling[order],
1972 best * scaling[order],
1973 units[order])
1973 units[order])
1974 if tc > tc_min:
1974 if tc > tc_min:
1975 print "Compiler time: %.2f s" % tc
1975 print "Compiler time: %.2f s" % tc
1976
1976
1977 @testdec.skip_doctest
1977 @testdec.skip_doctest
1978 def magic_time(self,parameter_s = ''):
1978 def magic_time(self,parameter_s = ''):
1979 """Time execution of a Python statement or expression.
1979 """Time execution of a Python statement or expression.
1980
1980
1981 The CPU and wall clock times are printed, and the value of the
1981 The CPU and wall clock times are printed, and the value of the
1982 expression (if any) is returned. Note that under Win32, system time
1982 expression (if any) is returned. Note that under Win32, system time
1983 is always reported as 0, since it can not be measured.
1983 is always reported as 0, since it can not be measured.
1984
1984
1985 This function provides very basic timing functionality. In Python
1985 This function provides very basic timing functionality. In Python
1986 2.3, the timeit module offers more control and sophistication, so this
1986 2.3, the timeit module offers more control and sophistication, so this
1987 could be rewritten to use it (patches welcome).
1987 could be rewritten to use it (patches welcome).
1988
1988
1989 Some examples:
1989 Some examples:
1990
1990
1991 In [1]: time 2**128
1991 In [1]: time 2**128
1992 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1992 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1993 Wall time: 0.00
1993 Wall time: 0.00
1994 Out[1]: 340282366920938463463374607431768211456L
1994 Out[1]: 340282366920938463463374607431768211456L
1995
1995
1996 In [2]: n = 1000000
1996 In [2]: n = 1000000
1997
1997
1998 In [3]: time sum(range(n))
1998 In [3]: time sum(range(n))
1999 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1999 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2000 Wall time: 1.37
2000 Wall time: 1.37
2001 Out[3]: 499999500000L
2001 Out[3]: 499999500000L
2002
2002
2003 In [4]: time print 'hello world'
2003 In [4]: time print 'hello world'
2004 hello world
2004 hello world
2005 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2005 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2006 Wall time: 0.00
2006 Wall time: 0.00
2007
2007
2008 Note that the time needed by Python to compile the given expression
2008 Note that the time needed by Python to compile the given expression
2009 will be reported if it is more than 0.1s. In this example, the
2009 will be reported if it is more than 0.1s. In this example, the
2010 actual exponentiation is done by Python at compilation time, so while
2010 actual exponentiation is done by Python at compilation time, so while
2011 the expression can take a noticeable amount of time to compute, that
2011 the expression can take a noticeable amount of time to compute, that
2012 time is purely due to the compilation:
2012 time is purely due to the compilation:
2013
2013
2014 In [5]: time 3**9999;
2014 In [5]: time 3**9999;
2015 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2015 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2016 Wall time: 0.00 s
2016 Wall time: 0.00 s
2017
2017
2018 In [6]: time 3**999999;
2018 In [6]: time 3**999999;
2019 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2019 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2020 Wall time: 0.00 s
2020 Wall time: 0.00 s
2021 Compiler : 0.78 s
2021 Compiler : 0.78 s
2022 """
2022 """
2023
2023
2024 # fail immediately if the given expression can't be compiled
2024 # fail immediately if the given expression can't be compiled
2025
2025
2026 expr = self.shell.prefilter(parameter_s,False)
2026 expr = self.shell.prefilter(parameter_s,False)
2027
2027
2028 # Minimum time above which compilation time will be reported
2028 # Minimum time above which compilation time will be reported
2029 tc_min = 0.1
2029 tc_min = 0.1
2030
2030
2031 try:
2031 try:
2032 mode = 'eval'
2032 mode = 'eval'
2033 t0 = clock()
2033 t0 = clock()
2034 code = compile(expr,'<timed eval>',mode)
2034 code = compile(expr,'<timed eval>',mode)
2035 tc = clock()-t0
2035 tc = clock()-t0
2036 except SyntaxError:
2036 except SyntaxError:
2037 mode = 'exec'
2037 mode = 'exec'
2038 t0 = clock()
2038 t0 = clock()
2039 code = compile(expr,'<timed exec>',mode)
2039 code = compile(expr,'<timed exec>',mode)
2040 tc = clock()-t0
2040 tc = clock()-t0
2041 # skew measurement as little as possible
2041 # skew measurement as little as possible
2042 glob = self.shell.user_ns
2042 glob = self.shell.user_ns
2043 clk = clock2
2043 clk = clock2
2044 wtime = time.time
2044 wtime = time.time
2045 # time execution
2045 # time execution
2046 wall_st = wtime()
2046 wall_st = wtime()
2047 if mode=='eval':
2047 if mode=='eval':
2048 st = clk()
2048 st = clk()
2049 out = eval(code,glob)
2049 out = eval(code,glob)
2050 end = clk()
2050 end = clk()
2051 else:
2051 else:
2052 st = clk()
2052 st = clk()
2053 exec code in glob
2053 exec code in glob
2054 end = clk()
2054 end = clk()
2055 out = None
2055 out = None
2056 wall_end = wtime()
2056 wall_end = wtime()
2057 # Compute actual times and report
2057 # Compute actual times and report
2058 wall_time = wall_end-wall_st
2058 wall_time = wall_end-wall_st
2059 cpu_user = end[0]-st[0]
2059 cpu_user = end[0]-st[0]
2060 cpu_sys = end[1]-st[1]
2060 cpu_sys = end[1]-st[1]
2061 cpu_tot = cpu_user+cpu_sys
2061 cpu_tot = cpu_user+cpu_sys
2062 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2062 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2063 (cpu_user,cpu_sys,cpu_tot)
2063 (cpu_user,cpu_sys,cpu_tot)
2064 print "Wall time: %.2f s" % wall_time
2064 print "Wall time: %.2f s" % wall_time
2065 if tc > tc_min:
2065 if tc > tc_min:
2066 print "Compiler : %.2f s" % tc
2066 print "Compiler : %.2f s" % tc
2067 return out
2067 return out
2068
2068
2069 @testdec.skip_doctest
2069 @testdec.skip_doctest
2070 def magic_macro(self,parameter_s = ''):
2070 def magic_macro(self,parameter_s = ''):
2071 """Define a set of input lines as a macro for future re-execution.
2071 """Define a set of input lines as a macro for future re-execution.
2072
2072
2073 Usage:\\
2073 Usage:\\
2074 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2074 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2075
2075
2076 Options:
2076 Options:
2077
2077
2078 -r: use 'raw' input. By default, the 'processed' history is used,
2078 -r: use 'raw' input. By default, the 'processed' history is used,
2079 so that magics are loaded in their transformed version to valid
2079 so that magics are loaded in their transformed version to valid
2080 Python. If this option is given, the raw input as typed as the
2080 Python. If this option is given, the raw input as typed as the
2081 command line is used instead.
2081 command line is used instead.
2082
2082
2083 This will define a global variable called `name` which is a string
2083 This will define a global variable called `name` which is a string
2084 made of joining the slices and lines you specify (n1,n2,... numbers
2084 made of joining the slices and lines you specify (n1,n2,... numbers
2085 above) from your input history into a single string. This variable
2085 above) from your input history into a single string. This variable
2086 acts like an automatic function which re-executes those lines as if
2086 acts like an automatic function which re-executes those lines as if
2087 you had typed them. You just type 'name' at the prompt and the code
2087 you had typed them. You just type 'name' at the prompt and the code
2088 executes.
2088 executes.
2089
2089
2090 The notation for indicating number ranges is: n1-n2 means 'use line
2090 The notation for indicating number ranges is: n1-n2 means 'use line
2091 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2091 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2092 using the lines numbered 5,6 and 7.
2092 using the lines numbered 5,6 and 7.
2093
2093
2094 Note: as a 'hidden' feature, you can also use traditional python slice
2094 Note: as a 'hidden' feature, you can also use traditional python slice
2095 notation, where N:M means numbers N through M-1.
2095 notation, where N:M means numbers N through M-1.
2096
2096
2097 For example, if your history contains (%hist prints it):
2097 For example, if your history contains (%hist prints it):
2098
2098
2099 44: x=1
2099 44: x=1
2100 45: y=3
2100 45: y=3
2101 46: z=x+y
2101 46: z=x+y
2102 47: print x
2102 47: print x
2103 48: a=5
2103 48: a=5
2104 49: print 'x',x,'y',y
2104 49: print 'x',x,'y',y
2105
2105
2106 you can create a macro with lines 44 through 47 (included) and line 49
2106 you can create a macro with lines 44 through 47 (included) and line 49
2107 called my_macro with:
2107 called my_macro with:
2108
2108
2109 In [55]: %macro my_macro 44-47 49
2109 In [55]: %macro my_macro 44-47 49
2110
2110
2111 Now, typing `my_macro` (without quotes) will re-execute all this code
2111 Now, typing `my_macro` (without quotes) will re-execute all this code
2112 in one pass.
2112 in one pass.
2113
2113
2114 You don't need to give the line-numbers in order, and any given line
2114 You don't need to give the line-numbers in order, and any given line
2115 number can appear multiple times. You can assemble macros with any
2115 number can appear multiple times. You can assemble macros with any
2116 lines from your input history in any order.
2116 lines from your input history in any order.
2117
2117
2118 The macro is a simple object which holds its value in an attribute,
2118 The macro is a simple object which holds its value in an attribute,
2119 but IPython's display system checks for macros and executes them as
2119 but IPython's display system checks for macros and executes them as
2120 code instead of printing them when you type their name.
2120 code instead of printing them when you type their name.
2121
2121
2122 You can view a macro's contents by explicitly printing it with:
2122 You can view a macro's contents by explicitly printing it with:
2123
2123
2124 'print macro_name'.
2124 'print macro_name'.
2125
2125
2126 For one-off cases which DON'T contain magic function calls in them you
2126 For one-off cases which DON'T contain magic function calls in them you
2127 can obtain similar results by explicitly executing slices from your
2127 can obtain similar results by explicitly executing slices from your
2128 input history with:
2128 input history with:
2129
2129
2130 In [60]: exec In[44:48]+In[49]"""
2130 In [60]: exec In[44:48]+In[49]"""
2131
2131
2132 opts,args = self.parse_options(parameter_s,'r',mode='list')
2132 opts,args = self.parse_options(parameter_s,'r',mode='list')
2133 if not args:
2133 if not args:
2134 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2134 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2135 macs.sort()
2135 macs.sort()
2136 return macs
2136 return macs
2137 if len(args) == 1:
2137 if len(args) == 1:
2138 raise UsageError(
2138 raise UsageError(
2139 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2139 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2140 name,ranges = args[0], args[1:]
2140 name,ranges = args[0], args[1:]
2141
2141
2142 #print 'rng',ranges # dbg
2142 #print 'rng',ranges # dbg
2143 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2143 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2144 macro = Macro(lines)
2144 macro = Macro(lines)
2145 self.shell.define_macro(name, macro)
2145 self.shell.define_macro(name, macro)
2146 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2146 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2147 print 'Macro contents:'
2147 print 'Macro contents:'
2148 print macro,
2148 print macro,
2149
2149
2150 def magic_save(self,parameter_s = ''):
2150 def magic_save(self,parameter_s = ''):
2151 """Save a set of lines to a given filename.
2151 """Save a set of lines to a given filename.
2152
2152
2153 Usage:\\
2153 Usage:\\
2154 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2154 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2155
2155
2156 Options:
2156 Options:
2157
2157
2158 -r: use 'raw' input. By default, the 'processed' history is used,
2158 -r: use 'raw' input. By default, the 'processed' history is used,
2159 so that magics are loaded in their transformed version to valid
2159 so that magics are loaded in their transformed version to valid
2160 Python. If this option is given, the raw input as typed as the
2160 Python. If this option is given, the raw input as typed as the
2161 command line is used instead.
2161 command line is used instead.
2162
2162
2163 This function uses the same syntax as %macro for line extraction, but
2163 This function uses the same syntax as %macro for line extraction, but
2164 instead of creating a macro it saves the resulting string to the
2164 instead of creating a macro it saves the resulting string to the
2165 filename you specify.
2165 filename you specify.
2166
2166
2167 It adds a '.py' extension to the file if you don't do so yourself, and
2167 It adds a '.py' extension to the file if you don't do so yourself, and
2168 it asks for confirmation before overwriting existing files."""
2168 it asks for confirmation before overwriting existing files."""
2169
2169
2170 opts,args = self.parse_options(parameter_s,'r',mode='list')
2170 opts,args = self.parse_options(parameter_s,'r',mode='list')
2171 fname,ranges = args[0], args[1:]
2171 fname,ranges = args[0], args[1:]
2172 if not fname.endswith('.py'):
2172 if not fname.endswith('.py'):
2173 fname += '.py'
2173 fname += '.py'
2174 if os.path.isfile(fname):
2174 if os.path.isfile(fname):
2175 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2175 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2176 if ans.lower() not in ['y','yes']:
2176 if ans.lower() not in ['y','yes']:
2177 print 'Operation cancelled.'
2177 print 'Operation cancelled.'
2178 return
2178 return
2179 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2179 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2180 f = file(fname,'w')
2180 f = file(fname,'w')
2181 f.write(cmds)
2181 f.write(cmds)
2182 f.close()
2182 f.close()
2183 print 'The following commands were written to file `%s`:' % fname
2183 print 'The following commands were written to file `%s`:' % fname
2184 print cmds
2184 print cmds
2185
2185
2186 def _edit_macro(self,mname,macro):
2186 def _edit_macro(self,mname,macro):
2187 """open an editor with the macro data in a file"""
2187 """open an editor with the macro data in a file"""
2188 filename = self.shell.mktempfile(macro.value)
2188 filename = self.shell.mktempfile(macro.value)
2189 self.shell.hooks.editor(filename)
2189 self.shell.hooks.editor(filename)
2190
2190
2191 # and make a new macro object, to replace the old one
2191 # and make a new macro object, to replace the old one
2192 mfile = open(filename)
2192 mfile = open(filename)
2193 mvalue = mfile.read()
2193 mvalue = mfile.read()
2194 mfile.close()
2194 mfile.close()
2195 self.shell.user_ns[mname] = Macro(mvalue)
2195 self.shell.user_ns[mname] = Macro(mvalue)
2196
2196
2197 def magic_ed(self,parameter_s=''):
2197 def magic_ed(self,parameter_s=''):
2198 """Alias to %edit."""
2198 """Alias to %edit."""
2199 return self.magic_edit(parameter_s)
2199 return self.magic_edit(parameter_s)
2200
2200
2201 @testdec.skip_doctest
2201 @testdec.skip_doctest
2202 def magic_edit(self,parameter_s='',last_call=['','']):
2202 def magic_edit(self,parameter_s='',last_call=['','']):
2203 """Bring up an editor and execute the resulting code.
2203 """Bring up an editor and execute the resulting code.
2204
2204
2205 Usage:
2205 Usage:
2206 %edit [options] [args]
2206 %edit [options] [args]
2207
2207
2208 %edit runs IPython's editor hook. The default version of this hook is
2208 %edit runs IPython's editor hook. The default version of this hook is
2209 set to call the __IPYTHON__.rc.editor command. This is read from your
2209 set to call the __IPYTHON__.rc.editor command. This is read from your
2210 environment variable $EDITOR. If this isn't found, it will default to
2210 environment variable $EDITOR. If this isn't found, it will default to
2211 vi under Linux/Unix and to notepad under Windows. See the end of this
2211 vi under Linux/Unix and to notepad under Windows. See the end of this
2212 docstring for how to change the editor hook.
2212 docstring for how to change the editor hook.
2213
2213
2214 You can also set the value of this editor via the command line option
2214 You can also set the value of this editor via the command line option
2215 '-editor' or in your ipythonrc file. This is useful if you wish to use
2215 '-editor' or in your ipythonrc file. This is useful if you wish to use
2216 specifically for IPython an editor different from your typical default
2216 specifically for IPython an editor different from your typical default
2217 (and for Windows users who typically don't set environment variables).
2217 (and for Windows users who typically don't set environment variables).
2218
2218
2219 This command allows you to conveniently edit multi-line code right in
2219 This command allows you to conveniently edit multi-line code right in
2220 your IPython session.
2220 your IPython session.
2221
2221
2222 If called without arguments, %edit opens up an empty editor with a
2222 If called without arguments, %edit opens up an empty editor with a
2223 temporary file and will execute the contents of this file when you
2223 temporary file and will execute the contents of this file when you
2224 close it (don't forget to save it!).
2224 close it (don't forget to save it!).
2225
2225
2226
2226
2227 Options:
2227 Options:
2228
2228
2229 -n <number>: open the editor at a specified line number. By default,
2229 -n <number>: open the editor at a specified line number. By default,
2230 the IPython editor hook uses the unix syntax 'editor +N filename', but
2230 the IPython editor hook uses the unix syntax 'editor +N filename', but
2231 you can configure this by providing your own modified hook if your
2231 you can configure this by providing your own modified hook if your
2232 favorite editor supports line-number specifications with a different
2232 favorite editor supports line-number specifications with a different
2233 syntax.
2233 syntax.
2234
2234
2235 -p: this will call the editor with the same data as the previous time
2235 -p: this will call the editor with the same data as the previous time
2236 it was used, regardless of how long ago (in your current session) it
2236 it was used, regardless of how long ago (in your current session) it
2237 was.
2237 was.
2238
2238
2239 -r: use 'raw' input. This option only applies to input taken from the
2239 -r: use 'raw' input. This option only applies to input taken from the
2240 user's history. By default, the 'processed' history is used, so that
2240 user's history. By default, the 'processed' history is used, so that
2241 magics are loaded in their transformed version to valid Python. If
2241 magics are loaded in their transformed version to valid Python. If
2242 this option is given, the raw input as typed as the command line is
2242 this option is given, the raw input as typed as the command line is
2243 used instead. When you exit the editor, it will be executed by
2243 used instead. When you exit the editor, it will be executed by
2244 IPython's own processor.
2244 IPython's own processor.
2245
2245
2246 -x: do not execute the edited code immediately upon exit. This is
2246 -x: do not execute the edited code immediately upon exit. This is
2247 mainly useful if you are editing programs which need to be called with
2247 mainly useful if you are editing programs which need to be called with
2248 command line arguments, which you can then do using %run.
2248 command line arguments, which you can then do using %run.
2249
2249
2250
2250
2251 Arguments:
2251 Arguments:
2252
2252
2253 If arguments are given, the following possibilites exist:
2253 If arguments are given, the following possibilites exist:
2254
2254
2255 - The arguments are numbers or pairs of colon-separated numbers (like
2255 - The arguments are numbers or pairs of colon-separated numbers (like
2256 1 4:8 9). These are interpreted as lines of previous input to be
2256 1 4:8 9). These are interpreted as lines of previous input to be
2257 loaded into the editor. The syntax is the same of the %macro command.
2257 loaded into the editor. The syntax is the same of the %macro command.
2258
2258
2259 - If the argument doesn't start with a number, it is evaluated as a
2259 - If the argument doesn't start with a number, it is evaluated as a
2260 variable and its contents loaded into the editor. You can thus edit
2260 variable and its contents loaded into the editor. You can thus edit
2261 any string which contains python code (including the result of
2261 any string which contains python code (including the result of
2262 previous edits).
2262 previous edits).
2263
2263
2264 - If the argument is the name of an object (other than a string),
2264 - If the argument is the name of an object (other than a string),
2265 IPython will try to locate the file where it was defined and open the
2265 IPython will try to locate the file where it was defined and open the
2266 editor at the point where it is defined. You can use `%edit function`
2266 editor at the point where it is defined. You can use `%edit function`
2267 to load an editor exactly at the point where 'function' is defined,
2267 to load an editor exactly at the point where 'function' is defined,
2268 edit it and have the file be executed automatically.
2268 edit it and have the file be executed automatically.
2269
2269
2270 If the object is a macro (see %macro for details), this opens up your
2270 If the object is a macro (see %macro for details), this opens up your
2271 specified editor with a temporary file containing the macro's data.
2271 specified editor with a temporary file containing the macro's data.
2272 Upon exit, the macro is reloaded with the contents of the file.
2272 Upon exit, the macro is reloaded with the contents of the file.
2273
2273
2274 Note: opening at an exact line is only supported under Unix, and some
2274 Note: opening at an exact line is only supported under Unix, and some
2275 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2275 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2276 '+NUMBER' parameter necessary for this feature. Good editors like
2276 '+NUMBER' parameter necessary for this feature. Good editors like
2277 (X)Emacs, vi, jed, pico and joe all do.
2277 (X)Emacs, vi, jed, pico and joe all do.
2278
2278
2279 - If the argument is not found as a variable, IPython will look for a
2279 - If the argument is not found as a variable, IPython will look for a
2280 file with that name (adding .py if necessary) and load it into the
2280 file with that name (adding .py if necessary) and load it into the
2281 editor. It will execute its contents with execfile() when you exit,
2281 editor. It will execute its contents with execfile() when you exit,
2282 loading any code in the file into your interactive namespace.
2282 loading any code in the file into your interactive namespace.
2283
2283
2284 After executing your code, %edit will return as output the code you
2284 After executing your code, %edit will return as output the code you
2285 typed in the editor (except when it was an existing file). This way
2285 typed in the editor (except when it was an existing file). This way
2286 you can reload the code in further invocations of %edit as a variable,
2286 you can reload the code in further invocations of %edit as a variable,
2287 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2287 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2288 the output.
2288 the output.
2289
2289
2290 Note that %edit is also available through the alias %ed.
2290 Note that %edit is also available through the alias %ed.
2291
2291
2292 This is an example of creating a simple function inside the editor and
2292 This is an example of creating a simple function inside the editor and
2293 then modifying it. First, start up the editor:
2293 then modifying it. First, start up the editor:
2294
2294
2295 In [1]: ed
2295 In [1]: ed
2296 Editing... done. Executing edited code...
2296 Editing... done. Executing edited code...
2297 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2297 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2298
2298
2299 We can then call the function foo():
2299 We can then call the function foo():
2300
2300
2301 In [2]: foo()
2301 In [2]: foo()
2302 foo() was defined in an editing session
2302 foo() was defined in an editing session
2303
2303
2304 Now we edit foo. IPython automatically loads the editor with the
2304 Now we edit foo. IPython automatically loads the editor with the
2305 (temporary) file where foo() was previously defined:
2305 (temporary) file where foo() was previously defined:
2306
2306
2307 In [3]: ed foo
2307 In [3]: ed foo
2308 Editing... done. Executing edited code...
2308 Editing... done. Executing edited code...
2309
2309
2310 And if we call foo() again we get the modified version:
2310 And if we call foo() again we get the modified version:
2311
2311
2312 In [4]: foo()
2312 In [4]: foo()
2313 foo() has now been changed!
2313 foo() has now been changed!
2314
2314
2315 Here is an example of how to edit a code snippet successive
2315 Here is an example of how to edit a code snippet successive
2316 times. First we call the editor:
2316 times. First we call the editor:
2317
2317
2318 In [5]: ed
2318 In [5]: ed
2319 Editing... done. Executing edited code...
2319 Editing... done. Executing edited code...
2320 hello
2320 hello
2321 Out[5]: "print 'hello'n"
2321 Out[5]: "print 'hello'n"
2322
2322
2323 Now we call it again with the previous output (stored in _):
2323 Now we call it again with the previous output (stored in _):
2324
2324
2325 In [6]: ed _
2325 In [6]: ed _
2326 Editing... done. Executing edited code...
2326 Editing... done. Executing edited code...
2327 hello world
2327 hello world
2328 Out[6]: "print 'hello world'n"
2328 Out[6]: "print 'hello world'n"
2329
2329
2330 Now we call it with the output #8 (stored in _8, also as Out[8]):
2330 Now we call it with the output #8 (stored in _8, also as Out[8]):
2331
2331
2332 In [7]: ed _8
2332 In [7]: ed _8
2333 Editing... done. Executing edited code...
2333 Editing... done. Executing edited code...
2334 hello again
2334 hello again
2335 Out[7]: "print 'hello again'n"
2335 Out[7]: "print 'hello again'n"
2336
2336
2337
2337
2338 Changing the default editor hook:
2338 Changing the default editor hook:
2339
2339
2340 If you wish to write your own editor hook, you can put it in a
2340 If you wish to write your own editor hook, you can put it in a
2341 configuration file which you load at startup time. The default hook
2341 configuration file which you load at startup time. The default hook
2342 is defined in the IPython.core.hooks module, and you can use that as a
2342 is defined in the IPython.core.hooks module, and you can use that as a
2343 starting example for further modifications. That file also has
2343 starting example for further modifications. That file also has
2344 general instructions on how to set a new hook for use once you've
2344 general instructions on how to set a new hook for use once you've
2345 defined it."""
2345 defined it."""
2346
2346
2347 # FIXME: This function has become a convoluted mess. It needs a
2347 # FIXME: This function has become a convoluted mess. It needs a
2348 # ground-up rewrite with clean, simple logic.
2348 # ground-up rewrite with clean, simple logic.
2349
2349
2350 def make_filename(arg):
2350 def make_filename(arg):
2351 "Make a filename from the given args"
2351 "Make a filename from the given args"
2352 try:
2352 try:
2353 filename = get_py_filename(arg)
2353 filename = get_py_filename(arg)
2354 except IOError:
2354 except IOError:
2355 if args.endswith('.py'):
2355 if args.endswith('.py'):
2356 filename = arg
2356 filename = arg
2357 else:
2357 else:
2358 filename = None
2358 filename = None
2359 return filename
2359 return filename
2360
2360
2361 # custom exceptions
2361 # custom exceptions
2362 class DataIsObject(Exception): pass
2362 class DataIsObject(Exception): pass
2363
2363
2364 opts,args = self.parse_options(parameter_s,'prxn:')
2364 opts,args = self.parse_options(parameter_s,'prxn:')
2365 # Set a few locals from the options for convenience:
2365 # Set a few locals from the options for convenience:
2366 opts_p = opts.has_key('p')
2366 opts_p = opts.has_key('p')
2367 opts_r = opts.has_key('r')
2367 opts_r = opts.has_key('r')
2368
2368
2369 # Default line number value
2369 # Default line number value
2370 lineno = opts.get('n',None)
2370 lineno = opts.get('n',None)
2371
2371
2372 if opts_p:
2372 if opts_p:
2373 args = '_%s' % last_call[0]
2373 args = '_%s' % last_call[0]
2374 if not self.shell.user_ns.has_key(args):
2374 if not self.shell.user_ns.has_key(args):
2375 args = last_call[1]
2375 args = last_call[1]
2376
2376
2377 # use last_call to remember the state of the previous call, but don't
2377 # use last_call to remember the state of the previous call, but don't
2378 # let it be clobbered by successive '-p' calls.
2378 # let it be clobbered by successive '-p' calls.
2379 try:
2379 try:
2380 last_call[0] = self.shell.outputcache.prompt_count
2380 last_call[0] = self.shell.outputcache.prompt_count
2381 if not opts_p:
2381 if not opts_p:
2382 last_call[1] = parameter_s
2382 last_call[1] = parameter_s
2383 except:
2383 except:
2384 pass
2384 pass
2385
2385
2386 # by default this is done with temp files, except when the given
2386 # by default this is done with temp files, except when the given
2387 # arg is a filename
2387 # arg is a filename
2388 use_temp = 1
2388 use_temp = 1
2389
2389
2390 if re.match(r'\d',args):
2390 if re.match(r'\d',args):
2391 # Mode where user specifies ranges of lines, like in %macro.
2391 # Mode where user specifies ranges of lines, like in %macro.
2392 # This means that you can't edit files whose names begin with
2392 # This means that you can't edit files whose names begin with
2393 # numbers this way. Tough.
2393 # numbers this way. Tough.
2394 ranges = args.split()
2394 ranges = args.split()
2395 data = ''.join(self.extract_input_slices(ranges,opts_r))
2395 data = ''.join(self.extract_input_slices(ranges,opts_r))
2396 elif args.endswith('.py'):
2396 elif args.endswith('.py'):
2397 filename = make_filename(args)
2397 filename = make_filename(args)
2398 data = ''
2398 data = ''
2399 use_temp = 0
2399 use_temp = 0
2400 elif args:
2400 elif args:
2401 try:
2401 try:
2402 # Load the parameter given as a variable. If not a string,
2402 # Load the parameter given as a variable. If not a string,
2403 # process it as an object instead (below)
2403 # process it as an object instead (below)
2404
2404
2405 #print '*** args',args,'type',type(args) # dbg
2405 #print '*** args',args,'type',type(args) # dbg
2406 data = eval(args,self.shell.user_ns)
2406 data = eval(args,self.shell.user_ns)
2407 if not type(data) in StringTypes:
2407 if not type(data) in StringTypes:
2408 raise DataIsObject
2408 raise DataIsObject
2409
2409
2410 except (NameError,SyntaxError):
2410 except (NameError,SyntaxError):
2411 # given argument is not a variable, try as a filename
2411 # given argument is not a variable, try as a filename
2412 filename = make_filename(args)
2412 filename = make_filename(args)
2413 if filename is None:
2413 if filename is None:
2414 warn("Argument given (%s) can't be found as a variable "
2414 warn("Argument given (%s) can't be found as a variable "
2415 "or as a filename." % args)
2415 "or as a filename." % args)
2416 return
2416 return
2417
2417
2418 data = ''
2418 data = ''
2419 use_temp = 0
2419 use_temp = 0
2420 except DataIsObject:
2420 except DataIsObject:
2421
2421
2422 # macros have a special edit function
2422 # macros have a special edit function
2423 if isinstance(data,Macro):
2423 if isinstance(data,Macro):
2424 self._edit_macro(args,data)
2424 self._edit_macro(args,data)
2425 return
2425 return
2426
2426
2427 # For objects, try to edit the file where they are defined
2427 # For objects, try to edit the file where they are defined
2428 try:
2428 try:
2429 filename = inspect.getabsfile(data)
2429 filename = inspect.getabsfile(data)
2430 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2430 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2431 # class created by %edit? Try to find source
2431 # class created by %edit? Try to find source
2432 # by looking for method definitions instead, the
2432 # by looking for method definitions instead, the
2433 # __module__ in those classes is FakeModule.
2433 # __module__ in those classes is FakeModule.
2434 attrs = [getattr(data, aname) for aname in dir(data)]
2434 attrs = [getattr(data, aname) for aname in dir(data)]
2435 for attr in attrs:
2435 for attr in attrs:
2436 if not inspect.ismethod(attr):
2436 if not inspect.ismethod(attr):
2437 continue
2437 continue
2438 filename = inspect.getabsfile(attr)
2438 filename = inspect.getabsfile(attr)
2439 if filename and 'fakemodule' not in filename.lower():
2439 if filename and 'fakemodule' not in filename.lower():
2440 # change the attribute to be the edit target instead
2440 # change the attribute to be the edit target instead
2441 data = attr
2441 data = attr
2442 break
2442 break
2443
2443
2444 datafile = 1
2444 datafile = 1
2445 except TypeError:
2445 except TypeError:
2446 filename = make_filename(args)
2446 filename = make_filename(args)
2447 datafile = 1
2447 datafile = 1
2448 warn('Could not find file where `%s` is defined.\n'
2448 warn('Could not find file where `%s` is defined.\n'
2449 'Opening a file named `%s`' % (args,filename))
2449 'Opening a file named `%s`' % (args,filename))
2450 # Now, make sure we can actually read the source (if it was in
2450 # Now, make sure we can actually read the source (if it was in
2451 # a temp file it's gone by now).
2451 # a temp file it's gone by now).
2452 if datafile:
2452 if datafile:
2453 try:
2453 try:
2454 if lineno is None:
2454 if lineno is None:
2455 lineno = inspect.getsourcelines(data)[1]
2455 lineno = inspect.getsourcelines(data)[1]
2456 except IOError:
2456 except IOError:
2457 filename = make_filename(args)
2457 filename = make_filename(args)
2458 if filename is None:
2458 if filename is None:
2459 warn('The file `%s` where `%s` was defined cannot '
2459 warn('The file `%s` where `%s` was defined cannot '
2460 'be read.' % (filename,data))
2460 'be read.' % (filename,data))
2461 return
2461 return
2462 use_temp = 0
2462 use_temp = 0
2463 else:
2463 else:
2464 data = ''
2464 data = ''
2465
2465
2466 if use_temp:
2466 if use_temp:
2467 filename = self.shell.mktempfile(data)
2467 filename = self.shell.mktempfile(data)
2468 print 'IPython will make a temporary file named:',filename
2468 print 'IPython will make a temporary file named:',filename
2469
2469
2470 # do actual editing here
2470 # do actual editing here
2471 print 'Editing...',
2471 print 'Editing...',
2472 sys.stdout.flush()
2472 sys.stdout.flush()
2473 try:
2473 try:
2474 # Quote filenames that may have spaces in them
2474 # Quote filenames that may have spaces in them
2475 if ' ' in filename:
2475 if ' ' in filename:
2476 filename = "%s" % filename
2476 filename = "%s" % filename
2477 self.shell.hooks.editor(filename,lineno)
2477 self.shell.hooks.editor(filename,lineno)
2478 except TryNext:
2478 except TryNext:
2479 warn('Could not open editor')
2479 warn('Could not open editor')
2480 return
2480 return
2481
2481
2482 # XXX TODO: should this be generalized for all string vars?
2482 # XXX TODO: should this be generalized for all string vars?
2483 # For now, this is special-cased to blocks created by cpaste
2483 # For now, this is special-cased to blocks created by cpaste
2484 if args.strip() == 'pasted_block':
2484 if args.strip() == 'pasted_block':
2485 self.shell.user_ns['pasted_block'] = file_read(filename)
2485 self.shell.user_ns['pasted_block'] = file_read(filename)
2486
2486
2487 if opts.has_key('x'): # -x prevents actual execution
2487 if opts.has_key('x'): # -x prevents actual execution
2488 print
2488 print
2489 else:
2489 else:
2490 print 'done. Executing edited code...'
2490 print 'done. Executing edited code...'
2491 if opts_r:
2491 if opts_r:
2492 self.shell.runlines(file_read(filename))
2492 self.shell.runlines(file_read(filename))
2493 else:
2493 else:
2494 self.shell.safe_execfile(filename,self.shell.user_ns,
2494 self.shell.safe_execfile(filename,self.shell.user_ns,
2495 self.shell.user_ns)
2495 self.shell.user_ns)
2496
2496
2497
2497
2498 if use_temp:
2498 if use_temp:
2499 try:
2499 try:
2500 return open(filename).read()
2500 return open(filename).read()
2501 except IOError,msg:
2501 except IOError,msg:
2502 if msg.filename == filename:
2502 if msg.filename == filename:
2503 warn('File not found. Did you forget to save?')
2503 warn('File not found. Did you forget to save?')
2504 return
2504 return
2505 else:
2505 else:
2506 self.shell.showtraceback()
2506 self.shell.showtraceback()
2507
2507
2508 def magic_xmode(self,parameter_s = ''):
2508 def magic_xmode(self,parameter_s = ''):
2509 """Switch modes for the exception handlers.
2509 """Switch modes for the exception handlers.
2510
2510
2511 Valid modes: Plain, Context and Verbose.
2511 Valid modes: Plain, Context and Verbose.
2512
2512
2513 If called without arguments, acts as a toggle."""
2513 If called without arguments, acts as a toggle."""
2514
2514
2515 def xmode_switch_err(name):
2515 def xmode_switch_err(name):
2516 warn('Error changing %s exception modes.\n%s' %
2516 warn('Error changing %s exception modes.\n%s' %
2517 (name,sys.exc_info()[1]))
2517 (name,sys.exc_info()[1]))
2518
2518
2519 shell = self.shell
2519 shell = self.shell
2520 new_mode = parameter_s.strip().capitalize()
2520 new_mode = parameter_s.strip().capitalize()
2521 try:
2521 try:
2522 shell.InteractiveTB.set_mode(mode=new_mode)
2522 shell.InteractiveTB.set_mode(mode=new_mode)
2523 print 'Exception reporting mode:',shell.InteractiveTB.mode
2523 print 'Exception reporting mode:',shell.InteractiveTB.mode
2524 except:
2524 except:
2525 xmode_switch_err('user')
2525 xmode_switch_err('user')
2526
2526
2527 # threaded shells use a special handler in sys.excepthook
2527 # threaded shells use a special handler in sys.excepthook
2528 if shell.isthreaded:
2528 if shell.isthreaded:
2529 try:
2529 try:
2530 shell.sys_excepthook.set_mode(mode=new_mode)
2530 shell.sys_excepthook.set_mode(mode=new_mode)
2531 except:
2531 except:
2532 xmode_switch_err('threaded')
2532 xmode_switch_err('threaded')
2533
2533
2534 def magic_colors(self,parameter_s = ''):
2534 def magic_colors(self,parameter_s = ''):
2535 """Switch color scheme for prompts, info system and exception handlers.
2535 """Switch color scheme for prompts, info system and exception handlers.
2536
2536
2537 Currently implemented schemes: NoColor, Linux, LightBG.
2537 Currently implemented schemes: NoColor, Linux, LightBG.
2538
2538
2539 Color scheme names are not case-sensitive."""
2539 Color scheme names are not case-sensitive."""
2540
2540
2541 def color_switch_err(name):
2541 def color_switch_err(name):
2542 warn('Error changing %s color schemes.\n%s' %
2542 warn('Error changing %s color schemes.\n%s' %
2543 (name,sys.exc_info()[1]))
2543 (name,sys.exc_info()[1]))
2544
2544
2545
2545
2546 new_scheme = parameter_s.strip()
2546 new_scheme = parameter_s.strip()
2547 if not new_scheme:
2547 if not new_scheme:
2548 raise UsageError(
2548 raise UsageError(
2549 "%colors: you must specify a color scheme. See '%colors?'")
2549 "%colors: you must specify a color scheme. See '%colors?'")
2550 return
2550 return
2551 # local shortcut
2551 # local shortcut
2552 shell = self.shell
2552 shell = self.shell
2553
2553
2554 import IPython.utils.rlineimpl as readline
2554 import IPython.utils.rlineimpl as readline
2555
2555
2556 if not readline.have_readline and sys.platform == "win32":
2556 if not readline.have_readline and sys.platform == "win32":
2557 msg = """\
2557 msg = """\
2558 Proper color support under MS Windows requires the pyreadline library.
2558 Proper color support under MS Windows requires the pyreadline library.
2559 You can find it at:
2559 You can find it at:
2560 http://ipython.scipy.org/moin/PyReadline/Intro
2560 http://ipython.scipy.org/moin/PyReadline/Intro
2561 Gary's readline needs the ctypes module, from:
2561 Gary's readline needs the ctypes module, from:
2562 http://starship.python.net/crew/theller/ctypes
2562 http://starship.python.net/crew/theller/ctypes
2563 (Note that ctypes is already part of Python versions 2.5 and newer).
2563 (Note that ctypes is already part of Python versions 2.5 and newer).
2564
2564
2565 Defaulting color scheme to 'NoColor'"""
2565 Defaulting color scheme to 'NoColor'"""
2566 new_scheme = 'NoColor'
2566 new_scheme = 'NoColor'
2567 warn(msg)
2567 warn(msg)
2568
2568
2569 # readline option is 0
2569 # readline option is 0
2570 if not shell.has_readline:
2570 if not shell.has_readline:
2571 new_scheme = 'NoColor'
2571 new_scheme = 'NoColor'
2572
2572
2573 # Set prompt colors
2573 # Set prompt colors
2574 try:
2574 try:
2575 shell.outputcache.set_colors(new_scheme)
2575 shell.outputcache.set_colors(new_scheme)
2576 except:
2576 except:
2577 color_switch_err('prompt')
2577 color_switch_err('prompt')
2578 else:
2578 else:
2579 shell.colors = \
2579 shell.colors = \
2580 shell.outputcache.color_table.active_scheme_name
2580 shell.outputcache.color_table.active_scheme_name
2581 # Set exception colors
2581 # Set exception colors
2582 try:
2582 try:
2583 shell.InteractiveTB.set_colors(scheme = new_scheme)
2583 shell.InteractiveTB.set_colors(scheme = new_scheme)
2584 shell.SyntaxTB.set_colors(scheme = new_scheme)
2584 shell.SyntaxTB.set_colors(scheme = new_scheme)
2585 except:
2585 except:
2586 color_switch_err('exception')
2586 color_switch_err('exception')
2587
2587
2588 # threaded shells use a verbose traceback in sys.excepthook
2588 # threaded shells use a verbose traceback in sys.excepthook
2589 if shell.isthreaded:
2589 if shell.isthreaded:
2590 try:
2590 try:
2591 shell.sys_excepthook.set_colors(scheme=new_scheme)
2591 shell.sys_excepthook.set_colors(scheme=new_scheme)
2592 except:
2592 except:
2593 color_switch_err('system exception handler')
2593 color_switch_err('system exception handler')
2594
2594
2595 # Set info (for 'object?') colors
2595 # Set info (for 'object?') colors
2596 if shell.color_info:
2596 if shell.color_info:
2597 try:
2597 try:
2598 shell.inspector.set_active_scheme(new_scheme)
2598 shell.inspector.set_active_scheme(new_scheme)
2599 except:
2599 except:
2600 color_switch_err('object inspector')
2600 color_switch_err('object inspector')
2601 else:
2601 else:
2602 shell.inspector.set_active_scheme('NoColor')
2602 shell.inspector.set_active_scheme('NoColor')
2603
2603
2604 def magic_color_info(self,parameter_s = ''):
2604 def magic_color_info(self,parameter_s = ''):
2605 """Toggle color_info.
2605 """Toggle color_info.
2606
2606
2607 The color_info configuration parameter controls whether colors are
2607 The color_info configuration parameter controls whether colors are
2608 used for displaying object details (by things like %psource, %pfile or
2608 used for displaying object details (by things like %psource, %pfile or
2609 the '?' system). This function toggles this value with each call.
2609 the '?' system). This function toggles this value with each call.
2610
2610
2611 Note that unless you have a fairly recent pager (less works better
2611 Note that unless you have a fairly recent pager (less works better
2612 than more) in your system, using colored object information displays
2612 than more) in your system, using colored object information displays
2613 will not work properly. Test it and see."""
2613 will not work properly. Test it and see."""
2614
2614
2615 self.shell.color_info = not self.shell.color_info
2615 self.shell.color_info = not self.shell.color_info
2616 self.magic_colors(self.shell.colors)
2616 self.magic_colors(self.shell.colors)
2617 print 'Object introspection functions have now coloring:',
2617 print 'Object introspection functions have now coloring:',
2618 print ['OFF','ON'][int(self.shell.color_info)]
2618 print ['OFF','ON'][int(self.shell.color_info)]
2619
2619
2620 def magic_Pprint(self, parameter_s=''):
2620 def magic_Pprint(self, parameter_s=''):
2621 """Toggle pretty printing on/off."""
2621 """Toggle pretty printing on/off."""
2622
2622
2623 self.shell.pprint = 1 - self.shell.pprint
2623 self.shell.pprint = 1 - self.shell.pprint
2624 print 'Pretty printing has been turned', \
2624 print 'Pretty printing has been turned', \
2625 ['OFF','ON'][self.shell.pprint]
2625 ['OFF','ON'][self.shell.pprint]
2626
2626
2627 def magic_Exit(self, parameter_s=''):
2627 def magic_Exit(self, parameter_s=''):
2628 """Exit IPython without confirmation."""
2628 """Exit IPython without confirmation."""
2629
2629
2630 self.shell.ask_exit()
2630 self.shell.ask_exit()
2631
2631
2632 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2632 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2633 magic_exit = magic_quit = magic_Quit = magic_Exit
2633 magic_exit = magic_quit = magic_Quit = magic_Exit
2634
2634
2635 #......................................................................
2635 #......................................................................
2636 # Functions to implement unix shell-type things
2636 # Functions to implement unix shell-type things
2637
2637
2638 @testdec.skip_doctest
2638 @testdec.skip_doctest
2639 def magic_alias(self, parameter_s = ''):
2639 def magic_alias(self, parameter_s = ''):
2640 """Define an alias for a system command.
2640 """Define an alias for a system command.
2641
2641
2642 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2642 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2643
2643
2644 Then, typing 'alias_name params' will execute the system command 'cmd
2644 Then, typing 'alias_name params' will execute the system command 'cmd
2645 params' (from your underlying operating system).
2645 params' (from your underlying operating system).
2646
2646
2647 Aliases have lower precedence than magic functions and Python normal
2647 Aliases have lower precedence than magic functions and Python normal
2648 variables, so if 'foo' is both a Python variable and an alias, the
2648 variables, so if 'foo' is both a Python variable and an alias, the
2649 alias can not be executed until 'del foo' removes the Python variable.
2649 alias can not be executed until 'del foo' removes the Python variable.
2650
2650
2651 You can use the %l specifier in an alias definition to represent the
2651 You can use the %l specifier in an alias definition to represent the
2652 whole line when the alias is called. For example:
2652 whole line when the alias is called. For example:
2653
2653
2654 In [2]: alias all echo "Input in brackets: <%l>"
2654 In [2]: alias all echo "Input in brackets: <%l>"
2655 In [3]: all hello world
2655 In [3]: all hello world
2656 Input in brackets: <hello world>
2656 Input in brackets: <hello world>
2657
2657
2658 You can also define aliases with parameters using %s specifiers (one
2658 You can also define aliases with parameters using %s specifiers (one
2659 per parameter):
2659 per parameter):
2660
2660
2661 In [1]: alias parts echo first %s second %s
2661 In [1]: alias parts echo first %s second %s
2662 In [2]: %parts A B
2662 In [2]: %parts A B
2663 first A second B
2663 first A second B
2664 In [3]: %parts A
2664 In [3]: %parts A
2665 Incorrect number of arguments: 2 expected.
2665 Incorrect number of arguments: 2 expected.
2666 parts is an alias to: 'echo first %s second %s'
2666 parts is an alias to: 'echo first %s second %s'
2667
2667
2668 Note that %l and %s are mutually exclusive. You can only use one or
2668 Note that %l and %s are mutually exclusive. You can only use one or
2669 the other in your aliases.
2669 the other in your aliases.
2670
2670
2671 Aliases expand Python variables just like system calls using ! or !!
2671 Aliases expand Python variables just like system calls using ! or !!
2672 do: all expressions prefixed with '$' get expanded. For details of
2672 do: all expressions prefixed with '$' get expanded. For details of
2673 the semantic rules, see PEP-215:
2673 the semantic rules, see PEP-215:
2674 http://www.python.org/peps/pep-0215.html. This is the library used by
2674 http://www.python.org/peps/pep-0215.html. This is the library used by
2675 IPython for variable expansion. If you want to access a true shell
2675 IPython for variable expansion. If you want to access a true shell
2676 variable, an extra $ is necessary to prevent its expansion by IPython:
2676 variable, an extra $ is necessary to prevent its expansion by IPython:
2677
2677
2678 In [6]: alias show echo
2678 In [6]: alias show echo
2679 In [7]: PATH='A Python string'
2679 In [7]: PATH='A Python string'
2680 In [8]: show $PATH
2680 In [8]: show $PATH
2681 A Python string
2681 A Python string
2682 In [9]: show $$PATH
2682 In [9]: show $$PATH
2683 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2683 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2684
2684
2685 You can use the alias facility to acess all of $PATH. See the %rehash
2685 You can use the alias facility to acess all of $PATH. See the %rehash
2686 and %rehashx functions, which automatically create aliases for the
2686 and %rehashx functions, which automatically create aliases for the
2687 contents of your $PATH.
2687 contents of your $PATH.
2688
2688
2689 If called with no parameters, %alias prints the current alias table."""
2689 If called with no parameters, %alias prints the current alias table."""
2690
2690
2691 par = parameter_s.strip()
2691 par = parameter_s.strip()
2692 if not par:
2692 if not par:
2693 stored = self.db.get('stored_aliases', {} )
2693 stored = self.db.get('stored_aliases', {} )
2694 aliases = sorted(self.shell.alias_manager.aliases)
2694 aliases = sorted(self.shell.alias_manager.aliases)
2695 # for k, v in stored:
2695 # for k, v in stored:
2696 # atab.append(k, v[0])
2696 # atab.append(k, v[0])
2697
2697
2698 print "Total number of aliases:", len(aliases)
2698 print "Total number of aliases:", len(aliases)
2699 return aliases
2699 return aliases
2700
2700
2701 # Now try to define a new one
2701 # Now try to define a new one
2702 try:
2702 try:
2703 alias,cmd = par.split(None, 1)
2703 alias,cmd = par.split(None, 1)
2704 except:
2704 except:
2705 print oinspect.getdoc(self.magic_alias)
2705 print oinspect.getdoc(self.magic_alias)
2706 else:
2706 else:
2707 self.shell.alias_manager.soft_define_alias(alias, cmd)
2707 self.shell.alias_manager.soft_define_alias(alias, cmd)
2708 # end magic_alias
2708 # end magic_alias
2709
2709
2710 def magic_unalias(self, parameter_s = ''):
2710 def magic_unalias(self, parameter_s = ''):
2711 """Remove an alias"""
2711 """Remove an alias"""
2712
2712
2713 aname = parameter_s.strip()
2713 aname = parameter_s.strip()
2714 self.shell.alias_manager.undefine_alias(aname)
2714 self.shell.alias_manager.undefine_alias(aname)
2715 stored = self.db.get('stored_aliases', {} )
2715 stored = self.db.get('stored_aliases', {} )
2716 if aname in stored:
2716 if aname in stored:
2717 print "Removing %stored alias",aname
2717 print "Removing %stored alias",aname
2718 del stored[aname]
2718 del stored[aname]
2719 self.db['stored_aliases'] = stored
2719 self.db['stored_aliases'] = stored
2720
2720
2721
2721
2722 def magic_rehashx(self, parameter_s = ''):
2722 def magic_rehashx(self, parameter_s = ''):
2723 """Update the alias table with all executable files in $PATH.
2723 """Update the alias table with all executable files in $PATH.
2724
2724
2725 This version explicitly checks that every entry in $PATH is a file
2725 This version explicitly checks that every entry in $PATH is a file
2726 with execute access (os.X_OK), so it is much slower than %rehash.
2726 with execute access (os.X_OK), so it is much slower than %rehash.
2727
2727
2728 Under Windows, it checks executability as a match agains a
2728 Under Windows, it checks executability as a match agains a
2729 '|'-separated string of extensions, stored in the IPython config
2729 '|'-separated string of extensions, stored in the IPython config
2730 variable win_exec_ext. This defaults to 'exe|com|bat'.
2730 variable win_exec_ext. This defaults to 'exe|com|bat'.
2731
2731
2732 This function also resets the root module cache of module completer,
2732 This function also resets the root module cache of module completer,
2733 used on slow filesystems.
2733 used on slow filesystems.
2734 """
2734 """
2735 from IPython.core.alias import InvalidAliasError
2735 from IPython.core.alias import InvalidAliasError
2736
2736
2737 # for the benefit of module completer in ipy_completers.py
2737 # for the benefit of module completer in ipy_completers.py
2738 del self.db['rootmodules']
2738 del self.db['rootmodules']
2739
2739
2740 path = [os.path.abspath(os.path.expanduser(p)) for p in
2740 path = [os.path.abspath(os.path.expanduser(p)) for p in
2741 os.environ.get('PATH','').split(os.pathsep)]
2741 os.environ.get('PATH','').split(os.pathsep)]
2742 path = filter(os.path.isdir,path)
2742 path = filter(os.path.isdir,path)
2743
2743
2744 syscmdlist = []
2744 syscmdlist = []
2745 # Now define isexec in a cross platform manner.
2745 # Now define isexec in a cross platform manner.
2746 if os.name == 'posix':
2746 if os.name == 'posix':
2747 isexec = lambda fname:os.path.isfile(fname) and \
2747 isexec = lambda fname:os.path.isfile(fname) and \
2748 os.access(fname,os.X_OK)
2748 os.access(fname,os.X_OK)
2749 else:
2749 else:
2750 try:
2750 try:
2751 winext = os.environ['pathext'].replace(';','|').replace('.','')
2751 winext = os.environ['pathext'].replace(';','|').replace('.','')
2752 except KeyError:
2752 except KeyError:
2753 winext = 'exe|com|bat|py'
2753 winext = 'exe|com|bat|py'
2754 if 'py' not in winext:
2754 if 'py' not in winext:
2755 winext += '|py'
2755 winext += '|py'
2756 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2756 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2757 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2757 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2758 savedir = os.getcwd()
2758 savedir = os.getcwd()
2759
2759
2760 # Now walk the paths looking for executables to alias.
2760 # Now walk the paths looking for executables to alias.
2761 try:
2761 try:
2762 # write the whole loop for posix/Windows so we don't have an if in
2762 # write the whole loop for posix/Windows so we don't have an if in
2763 # the innermost part
2763 # the innermost part
2764 if os.name == 'posix':
2764 if os.name == 'posix':
2765 for pdir in path:
2765 for pdir in path:
2766 os.chdir(pdir)
2766 os.chdir(pdir)
2767 for ff in os.listdir(pdir):
2767 for ff in os.listdir(pdir):
2768 if isexec(ff):
2768 if isexec(ff):
2769 try:
2769 try:
2770 # Removes dots from the name since ipython
2770 # Removes dots from the name since ipython
2771 # will assume names with dots to be python.
2771 # will assume names with dots to be python.
2772 self.shell.alias_manager.define_alias(
2772 self.shell.alias_manager.define_alias(
2773 ff.replace('.',''), ff)
2773 ff.replace('.',''), ff)
2774 except InvalidAliasError:
2774 except InvalidAliasError:
2775 pass
2775 pass
2776 else:
2776 else:
2777 syscmdlist.append(ff)
2777 syscmdlist.append(ff)
2778 else:
2778 else:
2779 no_alias = self.shell.alias_manager.no_alias
2779 no_alias = self.shell.alias_manager.no_alias
2780 for pdir in path:
2780 for pdir in path:
2781 os.chdir(pdir)
2781 os.chdir(pdir)
2782 for ff in os.listdir(pdir):
2782 for ff in os.listdir(pdir):
2783 base, ext = os.path.splitext(ff)
2783 base, ext = os.path.splitext(ff)
2784 if isexec(ff) and base.lower() not in no_alias:
2784 if isexec(ff) and base.lower() not in no_alias:
2785 if ext.lower() == '.exe':
2785 if ext.lower() == '.exe':
2786 ff = base
2786 ff = base
2787 try:
2787 try:
2788 # Removes dots from the name since ipython
2788 # Removes dots from the name since ipython
2789 # will assume names with dots to be python.
2789 # will assume names with dots to be python.
2790 self.shell.alias_manager.define_alias(
2790 self.shell.alias_manager.define_alias(
2791 base.lower().replace('.',''), ff)
2791 base.lower().replace('.',''), ff)
2792 except InvalidAliasError:
2792 except InvalidAliasError:
2793 pass
2793 pass
2794 syscmdlist.append(ff)
2794 syscmdlist.append(ff)
2795 db = self.db
2795 db = self.db
2796 db['syscmdlist'] = syscmdlist
2796 db['syscmdlist'] = syscmdlist
2797 finally:
2797 finally:
2798 os.chdir(savedir)
2798 os.chdir(savedir)
2799
2799
2800 def magic_pwd(self, parameter_s = ''):
2800 def magic_pwd(self, parameter_s = ''):
2801 """Return the current working directory path."""
2801 """Return the current working directory path."""
2802 return os.getcwd()
2802 return os.getcwd()
2803
2803
2804 def magic_cd(self, parameter_s=''):
2804 def magic_cd(self, parameter_s=''):
2805 """Change the current working directory.
2805 """Change the current working directory.
2806
2806
2807 This command automatically maintains an internal list of directories
2807 This command automatically maintains an internal list of directories
2808 you visit during your IPython session, in the variable _dh. The
2808 you visit during your IPython session, in the variable _dh. The
2809 command %dhist shows this history nicely formatted. You can also
2809 command %dhist shows this history nicely formatted. You can also
2810 do 'cd -<tab>' to see directory history conveniently.
2810 do 'cd -<tab>' to see directory history conveniently.
2811
2811
2812 Usage:
2812 Usage:
2813
2813
2814 cd 'dir': changes to directory 'dir'.
2814 cd 'dir': changes to directory 'dir'.
2815
2815
2816 cd -: changes to the last visited directory.
2816 cd -: changes to the last visited directory.
2817
2817
2818 cd -<n>: changes to the n-th directory in the directory history.
2818 cd -<n>: changes to the n-th directory in the directory history.
2819
2819
2820 cd --foo: change to directory that matches 'foo' in history
2820 cd --foo: change to directory that matches 'foo' in history
2821
2821
2822 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2822 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2823 (note: cd <bookmark_name> is enough if there is no
2823 (note: cd <bookmark_name> is enough if there is no
2824 directory <bookmark_name>, but a bookmark with the name exists.)
2824 directory <bookmark_name>, but a bookmark with the name exists.)
2825 'cd -b <tab>' allows you to tab-complete bookmark names.
2825 'cd -b <tab>' allows you to tab-complete bookmark names.
2826
2826
2827 Options:
2827 Options:
2828
2828
2829 -q: quiet. Do not print the working directory after the cd command is
2829 -q: quiet. Do not print the working directory after the cd command is
2830 executed. By default IPython's cd command does print this directory,
2830 executed. By default IPython's cd command does print this directory,
2831 since the default prompts do not display path information.
2831 since the default prompts do not display path information.
2832
2832
2833 Note that !cd doesn't work for this purpose because the shell where
2833 Note that !cd doesn't work for this purpose because the shell where
2834 !command runs is immediately discarded after executing 'command'."""
2834 !command runs is immediately discarded after executing 'command'."""
2835
2835
2836 parameter_s = parameter_s.strip()
2836 parameter_s = parameter_s.strip()
2837 #bkms = self.shell.persist.get("bookmarks",{})
2837 #bkms = self.shell.persist.get("bookmarks",{})
2838
2838
2839 oldcwd = os.getcwd()
2839 oldcwd = os.getcwd()
2840 numcd = re.match(r'(-)(\d+)$',parameter_s)
2840 numcd = re.match(r'(-)(\d+)$',parameter_s)
2841 # jump in directory history by number
2841 # jump in directory history by number
2842 if numcd:
2842 if numcd:
2843 nn = int(numcd.group(2))
2843 nn = int(numcd.group(2))
2844 try:
2844 try:
2845 ps = self.shell.user_ns['_dh'][nn]
2845 ps = self.shell.user_ns['_dh'][nn]
2846 except IndexError:
2846 except IndexError:
2847 print 'The requested directory does not exist in history.'
2847 print 'The requested directory does not exist in history.'
2848 return
2848 return
2849 else:
2849 else:
2850 opts = {}
2850 opts = {}
2851 elif parameter_s.startswith('--'):
2851 elif parameter_s.startswith('--'):
2852 ps = None
2852 ps = None
2853 fallback = None
2853 fallback = None
2854 pat = parameter_s[2:]
2854 pat = parameter_s[2:]
2855 dh = self.shell.user_ns['_dh']
2855 dh = self.shell.user_ns['_dh']
2856 # first search only by basename (last component)
2856 # first search only by basename (last component)
2857 for ent in reversed(dh):
2857 for ent in reversed(dh):
2858 if pat in os.path.basename(ent) and os.path.isdir(ent):
2858 if pat in os.path.basename(ent) and os.path.isdir(ent):
2859 ps = ent
2859 ps = ent
2860 break
2860 break
2861
2861
2862 if fallback is None and pat in ent and os.path.isdir(ent):
2862 if fallback is None and pat in ent and os.path.isdir(ent):
2863 fallback = ent
2863 fallback = ent
2864
2864
2865 # if we have no last part match, pick the first full path match
2865 # if we have no last part match, pick the first full path match
2866 if ps is None:
2866 if ps is None:
2867 ps = fallback
2867 ps = fallback
2868
2868
2869 if ps is None:
2869 if ps is None:
2870 print "No matching entry in directory history"
2870 print "No matching entry in directory history"
2871 return
2871 return
2872 else:
2872 else:
2873 opts = {}
2873 opts = {}
2874
2874
2875
2875
2876 else:
2876 else:
2877 #turn all non-space-escaping backslashes to slashes,
2877 #turn all non-space-escaping backslashes to slashes,
2878 # for c:\windows\directory\names\
2878 # for c:\windows\directory\names\
2879 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2879 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2880 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2880 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2881 # jump to previous
2881 # jump to previous
2882 if ps == '-':
2882 if ps == '-':
2883 try:
2883 try:
2884 ps = self.shell.user_ns['_dh'][-2]
2884 ps = self.shell.user_ns['_dh'][-2]
2885 except IndexError:
2885 except IndexError:
2886 raise UsageError('%cd -: No previous directory to change to.')
2886 raise UsageError('%cd -: No previous directory to change to.')
2887 # jump to bookmark if needed
2887 # jump to bookmark if needed
2888 else:
2888 else:
2889 if not os.path.isdir(ps) or opts.has_key('b'):
2889 if not os.path.isdir(ps) or opts.has_key('b'):
2890 bkms = self.db.get('bookmarks', {})
2890 bkms = self.db.get('bookmarks', {})
2891
2891
2892 if bkms.has_key(ps):
2892 if bkms.has_key(ps):
2893 target = bkms[ps]
2893 target = bkms[ps]
2894 print '(bookmark:%s) -> %s' % (ps,target)
2894 print '(bookmark:%s) -> %s' % (ps,target)
2895 ps = target
2895 ps = target
2896 else:
2896 else:
2897 if opts.has_key('b'):
2897 if opts.has_key('b'):
2898 raise UsageError("Bookmark '%s' not found. "
2898 raise UsageError("Bookmark '%s' not found. "
2899 "Use '%%bookmark -l' to see your bookmarks." % ps)
2899 "Use '%%bookmark -l' to see your bookmarks." % ps)
2900
2900
2901 # at this point ps should point to the target dir
2901 # at this point ps should point to the target dir
2902 if ps:
2902 if ps:
2903 try:
2903 try:
2904 os.chdir(os.path.expanduser(ps))
2904 os.chdir(os.path.expanduser(ps))
2905 if self.shell.term_title:
2905 if self.shell.term_title:
2906 set_term_title('IPython: ' + abbrev_cwd())
2906 set_term_title('IPython: ' + abbrev_cwd())
2907 except OSError:
2907 except OSError:
2908 print sys.exc_info()[1]
2908 print sys.exc_info()[1]
2909 else:
2909 else:
2910 cwd = os.getcwd()
2910 cwd = os.getcwd()
2911 dhist = self.shell.user_ns['_dh']
2911 dhist = self.shell.user_ns['_dh']
2912 if oldcwd != cwd:
2912 if oldcwd != cwd:
2913 dhist.append(cwd)
2913 dhist.append(cwd)
2914 self.db['dhist'] = compress_dhist(dhist)[-100:]
2914 self.db['dhist'] = compress_dhist(dhist)[-100:]
2915
2915
2916 else:
2916 else:
2917 os.chdir(self.shell.home_dir)
2917 os.chdir(self.shell.home_dir)
2918 if self.shell.term_title:
2918 if self.shell.term_title:
2919 set_term_title('IPython: ' + '~')
2919 set_term_title('IPython: ' + '~')
2920 cwd = os.getcwd()
2920 cwd = os.getcwd()
2921 dhist = self.shell.user_ns['_dh']
2921 dhist = self.shell.user_ns['_dh']
2922
2922
2923 if oldcwd != cwd:
2923 if oldcwd != cwd:
2924 dhist.append(cwd)
2924 dhist.append(cwd)
2925 self.db['dhist'] = compress_dhist(dhist)[-100:]
2925 self.db['dhist'] = compress_dhist(dhist)[-100:]
2926 if not 'q' in opts and self.shell.user_ns['_dh']:
2926 if not 'q' in opts and self.shell.user_ns['_dh']:
2927 print self.shell.user_ns['_dh'][-1]
2927 print self.shell.user_ns['_dh'][-1]
2928
2928
2929
2929
2930 def magic_env(self, parameter_s=''):
2930 def magic_env(self, parameter_s=''):
2931 """List environment variables."""
2931 """List environment variables."""
2932
2932
2933 return os.environ.data
2933 return os.environ.data
2934
2934
2935 def magic_pushd(self, parameter_s=''):
2935 def magic_pushd(self, parameter_s=''):
2936 """Place the current dir on stack and change directory.
2936 """Place the current dir on stack and change directory.
2937
2937
2938 Usage:\\
2938 Usage:\\
2939 %pushd ['dirname']
2939 %pushd ['dirname']
2940 """
2940 """
2941
2941
2942 dir_s = self.shell.dir_stack
2942 dir_s = self.shell.dir_stack
2943 tgt = os.path.expanduser(parameter_s)
2943 tgt = os.path.expanduser(parameter_s)
2944 cwd = os.getcwd().replace(self.home_dir,'~')
2944 cwd = os.getcwd().replace(self.home_dir,'~')
2945 if tgt:
2945 if tgt:
2946 self.magic_cd(parameter_s)
2946 self.magic_cd(parameter_s)
2947 dir_s.insert(0,cwd)
2947 dir_s.insert(0,cwd)
2948 return self.magic_dirs()
2948 return self.magic_dirs()
2949
2949
2950 def magic_popd(self, parameter_s=''):
2950 def magic_popd(self, parameter_s=''):
2951 """Change to directory popped off the top of the stack.
2951 """Change to directory popped off the top of the stack.
2952 """
2952 """
2953 if not self.shell.dir_stack:
2953 if not self.shell.dir_stack:
2954 raise UsageError("%popd on empty stack")
2954 raise UsageError("%popd on empty stack")
2955 top = self.shell.dir_stack.pop(0)
2955 top = self.shell.dir_stack.pop(0)
2956 self.magic_cd(top)
2956 self.magic_cd(top)
2957 print "popd ->",top
2957 print "popd ->",top
2958
2958
2959 def magic_dirs(self, parameter_s=''):
2959 def magic_dirs(self, parameter_s=''):
2960 """Return the current directory stack."""
2960 """Return the current directory stack."""
2961
2961
2962 return self.shell.dir_stack
2962 return self.shell.dir_stack
2963
2963
2964 def magic_dhist(self, parameter_s=''):
2964 def magic_dhist(self, parameter_s=''):
2965 """Print your history of visited directories.
2965 """Print your history of visited directories.
2966
2966
2967 %dhist -> print full history\\
2967 %dhist -> print full history\\
2968 %dhist n -> print last n entries only\\
2968 %dhist n -> print last n entries only\\
2969 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2969 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2970
2970
2971 This history is automatically maintained by the %cd command, and
2971 This history is automatically maintained by the %cd command, and
2972 always available as the global list variable _dh. You can use %cd -<n>
2972 always available as the global list variable _dh. You can use %cd -<n>
2973 to go to directory number <n>.
2973 to go to directory number <n>.
2974
2974
2975 Note that most of time, you should view directory history by entering
2975 Note that most of time, you should view directory history by entering
2976 cd -<TAB>.
2976 cd -<TAB>.
2977
2977
2978 """
2978 """
2979
2979
2980 dh = self.shell.user_ns['_dh']
2980 dh = self.shell.user_ns['_dh']
2981 if parameter_s:
2981 if parameter_s:
2982 try:
2982 try:
2983 args = map(int,parameter_s.split())
2983 args = map(int,parameter_s.split())
2984 except:
2984 except:
2985 self.arg_err(Magic.magic_dhist)
2985 self.arg_err(Magic.magic_dhist)
2986 return
2986 return
2987 if len(args) == 1:
2987 if len(args) == 1:
2988 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2988 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2989 elif len(args) == 2:
2989 elif len(args) == 2:
2990 ini,fin = args
2990 ini,fin = args
2991 else:
2991 else:
2992 self.arg_err(Magic.magic_dhist)
2992 self.arg_err(Magic.magic_dhist)
2993 return
2993 return
2994 else:
2994 else:
2995 ini,fin = 0,len(dh)
2995 ini,fin = 0,len(dh)
2996 nlprint(dh,
2996 nlprint(dh,
2997 header = 'Directory history (kept in _dh)',
2997 header = 'Directory history (kept in _dh)',
2998 start=ini,stop=fin)
2998 start=ini,stop=fin)
2999
2999
3000 @testdec.skip_doctest
3000 @testdec.skip_doctest
3001 def magic_sc(self, parameter_s=''):
3001 def magic_sc(self, parameter_s=''):
3002 """Shell capture - execute a shell command and capture its output.
3002 """Shell capture - execute a shell command and capture its output.
3003
3003
3004 DEPRECATED. Suboptimal, retained for backwards compatibility.
3004 DEPRECATED. Suboptimal, retained for backwards compatibility.
3005
3005
3006 You should use the form 'var = !command' instead. Example:
3006 You should use the form 'var = !command' instead. Example:
3007
3007
3008 "%sc -l myfiles = ls ~" should now be written as
3008 "%sc -l myfiles = ls ~" should now be written as
3009
3009
3010 "myfiles = !ls ~"
3010 "myfiles = !ls ~"
3011
3011
3012 myfiles.s, myfiles.l and myfiles.n still apply as documented
3012 myfiles.s, myfiles.l and myfiles.n still apply as documented
3013 below.
3013 below.
3014
3014
3015 --
3015 --
3016 %sc [options] varname=command
3016 %sc [options] varname=command
3017
3017
3018 IPython will run the given command using commands.getoutput(), and
3018 IPython will run the given command using commands.getoutput(), and
3019 will then update the user's interactive namespace with a variable
3019 will then update the user's interactive namespace with a variable
3020 called varname, containing the value of the call. Your command can
3020 called varname, containing the value of the call. Your command can
3021 contain shell wildcards, pipes, etc.
3021 contain shell wildcards, pipes, etc.
3022
3022
3023 The '=' sign in the syntax is mandatory, and the variable name you
3023 The '=' sign in the syntax is mandatory, and the variable name you
3024 supply must follow Python's standard conventions for valid names.
3024 supply must follow Python's standard conventions for valid names.
3025
3025
3026 (A special format without variable name exists for internal use)
3026 (A special format without variable name exists for internal use)
3027
3027
3028 Options:
3028 Options:
3029
3029
3030 -l: list output. Split the output on newlines into a list before
3030 -l: list output. Split the output on newlines into a list before
3031 assigning it to the given variable. By default the output is stored
3031 assigning it to the given variable. By default the output is stored
3032 as a single string.
3032 as a single string.
3033
3033
3034 -v: verbose. Print the contents of the variable.
3034 -v: verbose. Print the contents of the variable.
3035
3035
3036 In most cases you should not need to split as a list, because the
3036 In most cases you should not need to split as a list, because the
3037 returned value is a special type of string which can automatically
3037 returned value is a special type of string which can automatically
3038 provide its contents either as a list (split on newlines) or as a
3038 provide its contents either as a list (split on newlines) or as a
3039 space-separated string. These are convenient, respectively, either
3039 space-separated string. These are convenient, respectively, either
3040 for sequential processing or to be passed to a shell command.
3040 for sequential processing or to be passed to a shell command.
3041
3041
3042 For example:
3042 For example:
3043
3043
3044 # all-random
3044 # all-random
3045
3045
3046 # Capture into variable a
3046 # Capture into variable a
3047 In [1]: sc a=ls *py
3047 In [1]: sc a=ls *py
3048
3048
3049 # a is a string with embedded newlines
3049 # a is a string with embedded newlines
3050 In [2]: a
3050 In [2]: a
3051 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3051 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3052
3052
3053 # which can be seen as a list:
3053 # which can be seen as a list:
3054 In [3]: a.l
3054 In [3]: a.l
3055 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3055 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3056
3056
3057 # or as a whitespace-separated string:
3057 # or as a whitespace-separated string:
3058 In [4]: a.s
3058 In [4]: a.s
3059 Out[4]: 'setup.py win32_manual_post_install.py'
3059 Out[4]: 'setup.py win32_manual_post_install.py'
3060
3060
3061 # a.s is useful to pass as a single command line:
3061 # a.s is useful to pass as a single command line:
3062 In [5]: !wc -l $a.s
3062 In [5]: !wc -l $a.s
3063 146 setup.py
3063 146 setup.py
3064 130 win32_manual_post_install.py
3064 130 win32_manual_post_install.py
3065 276 total
3065 276 total
3066
3066
3067 # while the list form is useful to loop over:
3067 # while the list form is useful to loop over:
3068 In [6]: for f in a.l:
3068 In [6]: for f in a.l:
3069 ...: !wc -l $f
3069 ...: !wc -l $f
3070 ...:
3070 ...:
3071 146 setup.py
3071 146 setup.py
3072 130 win32_manual_post_install.py
3072 130 win32_manual_post_install.py
3073
3073
3074 Similiarly, the lists returned by the -l option are also special, in
3074 Similiarly, the lists returned by the -l option are also special, in
3075 the sense that you can equally invoke the .s attribute on them to
3075 the sense that you can equally invoke the .s attribute on them to
3076 automatically get a whitespace-separated string from their contents:
3076 automatically get a whitespace-separated string from their contents:
3077
3077
3078 In [7]: sc -l b=ls *py
3078 In [7]: sc -l b=ls *py
3079
3079
3080 In [8]: b
3080 In [8]: b
3081 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3081 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3082
3082
3083 In [9]: b.s
3083 In [9]: b.s
3084 Out[9]: 'setup.py win32_manual_post_install.py'
3084 Out[9]: 'setup.py win32_manual_post_install.py'
3085
3085
3086 In summary, both the lists and strings used for ouptut capture have
3086 In summary, both the lists and strings used for ouptut capture have
3087 the following special attributes:
3087 the following special attributes:
3088
3088
3089 .l (or .list) : value as list.
3089 .l (or .list) : value as list.
3090 .n (or .nlstr): value as newline-separated string.
3090 .n (or .nlstr): value as newline-separated string.
3091 .s (or .spstr): value as space-separated string.
3091 .s (or .spstr): value as space-separated string.
3092 """
3092 """
3093
3093
3094 opts,args = self.parse_options(parameter_s,'lv')
3094 opts,args = self.parse_options(parameter_s,'lv')
3095 # Try to get a variable name and command to run
3095 # Try to get a variable name and command to run
3096 try:
3096 try:
3097 # the variable name must be obtained from the parse_options
3097 # the variable name must be obtained from the parse_options
3098 # output, which uses shlex.split to strip options out.
3098 # output, which uses shlex.split to strip options out.
3099 var,_ = args.split('=',1)
3099 var,_ = args.split('=',1)
3100 var = var.strip()
3100 var = var.strip()
3101 # But the the command has to be extracted from the original input
3101 # But the the command has to be extracted from the original input
3102 # parameter_s, not on what parse_options returns, to avoid the
3102 # parameter_s, not on what parse_options returns, to avoid the
3103 # quote stripping which shlex.split performs on it.
3103 # quote stripping which shlex.split performs on it.
3104 _,cmd = parameter_s.split('=',1)
3104 _,cmd = parameter_s.split('=',1)
3105 except ValueError:
3105 except ValueError:
3106 var,cmd = '',''
3106 var,cmd = '',''
3107 # If all looks ok, proceed
3107 # If all looks ok, proceed
3108 out,err = self.shell.getoutputerror(cmd)
3108 out,err = self.shell.getoutputerror(cmd)
3109 if err:
3109 if err:
3110 print >> Term.cerr,err
3110 print >> Term.cerr,err
3111 if opts.has_key('l'):
3111 if opts.has_key('l'):
3112 out = SList(out.split('\n'))
3112 out = SList(out.split('\n'))
3113 else:
3113 else:
3114 out = LSString(out)
3114 out = LSString(out)
3115 if opts.has_key('v'):
3115 if opts.has_key('v'):
3116 print '%s ==\n%s' % (var,pformat(out))
3116 print '%s ==\n%s' % (var,pformat(out))
3117 if var:
3117 if var:
3118 self.shell.user_ns.update({var:out})
3118 self.shell.user_ns.update({var:out})
3119 else:
3119 else:
3120 return out
3120 return out
3121
3121
3122 def magic_sx(self, parameter_s=''):
3122 def magic_sx(self, parameter_s=''):
3123 """Shell execute - run a shell command and capture its output.
3123 """Shell execute - run a shell command and capture its output.
3124
3124
3125 %sx command
3125 %sx command
3126
3126
3127 IPython will run the given command using commands.getoutput(), and
3127 IPython will run the given command using commands.getoutput(), and
3128 return the result formatted as a list (split on '\\n'). Since the
3128 return the result formatted as a list (split on '\\n'). Since the
3129 output is _returned_, it will be stored in ipython's regular output
3129 output is _returned_, it will be stored in ipython's regular output
3130 cache Out[N] and in the '_N' automatic variables.
3130 cache Out[N] and in the '_N' automatic variables.
3131
3131
3132 Notes:
3132 Notes:
3133
3133
3134 1) If an input line begins with '!!', then %sx is automatically
3134 1) If an input line begins with '!!', then %sx is automatically
3135 invoked. That is, while:
3135 invoked. That is, while:
3136 !ls
3136 !ls
3137 causes ipython to simply issue system('ls'), typing
3137 causes ipython to simply issue system('ls'), typing
3138 !!ls
3138 !!ls
3139 is a shorthand equivalent to:
3139 is a shorthand equivalent to:
3140 %sx ls
3140 %sx ls
3141
3141
3142 2) %sx differs from %sc in that %sx automatically splits into a list,
3142 2) %sx differs from %sc in that %sx automatically splits into a list,
3143 like '%sc -l'. The reason for this is to make it as easy as possible
3143 like '%sc -l'. The reason for this is to make it as easy as possible
3144 to process line-oriented shell output via further python commands.
3144 to process line-oriented shell output via further python commands.
3145 %sc is meant to provide much finer control, but requires more
3145 %sc is meant to provide much finer control, but requires more
3146 typing.
3146 typing.
3147
3147
3148 3) Just like %sc -l, this is a list with special attributes:
3148 3) Just like %sc -l, this is a list with special attributes:
3149
3149
3150 .l (or .list) : value as list.
3150 .l (or .list) : value as list.
3151 .n (or .nlstr): value as newline-separated string.
3151 .n (or .nlstr): value as newline-separated string.
3152 .s (or .spstr): value as whitespace-separated string.
3152 .s (or .spstr): value as whitespace-separated string.
3153
3153
3154 This is very useful when trying to use such lists as arguments to
3154 This is very useful when trying to use such lists as arguments to
3155 system commands."""
3155 system commands."""
3156
3156
3157 if parameter_s:
3157 if parameter_s:
3158 out,err = self.shell.getoutputerror(parameter_s)
3158 out,err = self.shell.getoutputerror(parameter_s)
3159 if err:
3159 if err:
3160 print >> Term.cerr,err
3160 print >> Term.cerr,err
3161 return SList(out.split('\n'))
3161 return SList(out.split('\n'))
3162
3162
3163 def magic_bg(self, parameter_s=''):
3163 def magic_bg(self, parameter_s=''):
3164 """Run a job in the background, in a separate thread.
3164 """Run a job in the background, in a separate thread.
3165
3165
3166 For example,
3166 For example,
3167
3167
3168 %bg myfunc(x,y,z=1)
3168 %bg myfunc(x,y,z=1)
3169
3169
3170 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3170 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3171 execution starts, a message will be printed indicating the job
3171 execution starts, a message will be printed indicating the job
3172 number. If your job number is 5, you can use
3172 number. If your job number is 5, you can use
3173
3173
3174 myvar = jobs.result(5) or myvar = jobs[5].result
3174 myvar = jobs.result(5) or myvar = jobs[5].result
3175
3175
3176 to assign this result to variable 'myvar'.
3176 to assign this result to variable 'myvar'.
3177
3177
3178 IPython has a job manager, accessible via the 'jobs' object. You can
3178 IPython has a job manager, accessible via the 'jobs' object. You can
3179 type jobs? to get more information about it, and use jobs.<TAB> to see
3179 type jobs? to get more information about it, and use jobs.<TAB> to see
3180 its attributes. All attributes not starting with an underscore are
3180 its attributes. All attributes not starting with an underscore are
3181 meant for public use.
3181 meant for public use.
3182
3182
3183 In particular, look at the jobs.new() method, which is used to create
3183 In particular, look at the jobs.new() method, which is used to create
3184 new jobs. This magic %bg function is just a convenience wrapper
3184 new jobs. This magic %bg function is just a convenience wrapper
3185 around jobs.new(), for expression-based jobs. If you want to create a
3185 around jobs.new(), for expression-based jobs. If you want to create a
3186 new job with an explicit function object and arguments, you must call
3186 new job with an explicit function object and arguments, you must call
3187 jobs.new() directly.
3187 jobs.new() directly.
3188
3188
3189 The jobs.new docstring also describes in detail several important
3189 The jobs.new docstring also describes in detail several important
3190 caveats associated with a thread-based model for background job
3190 caveats associated with a thread-based model for background job
3191 execution. Type jobs.new? for details.
3191 execution. Type jobs.new? for details.
3192
3192
3193 You can check the status of all jobs with jobs.status().
3193 You can check the status of all jobs with jobs.status().
3194
3194
3195 The jobs variable is set by IPython into the Python builtin namespace.
3195 The jobs variable is set by IPython into the Python builtin namespace.
3196 If you ever declare a variable named 'jobs', you will shadow this
3196 If you ever declare a variable named 'jobs', you will shadow this
3197 name. You can either delete your global jobs variable to regain
3197 name. You can either delete your global jobs variable to regain
3198 access to the job manager, or make a new name and assign it manually
3198 access to the job manager, or make a new name and assign it manually
3199 to the manager (stored in IPython's namespace). For example, to
3199 to the manager (stored in IPython's namespace). For example, to
3200 assign the job manager to the Jobs name, use:
3200 assign the job manager to the Jobs name, use:
3201
3201
3202 Jobs = __builtins__.jobs"""
3202 Jobs = __builtins__.jobs"""
3203
3203
3204 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3204 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3205
3205
3206 def magic_r(self, parameter_s=''):
3206 def magic_r(self, parameter_s=''):
3207 """Repeat previous input.
3207 """Repeat previous input.
3208
3208
3209 Note: Consider using the more powerfull %rep instead!
3209 Note: Consider using the more powerfull %rep instead!
3210
3210
3211 If given an argument, repeats the previous command which starts with
3211 If given an argument, repeats the previous command which starts with
3212 the same string, otherwise it just repeats the previous input.
3212 the same string, otherwise it just repeats the previous input.
3213
3213
3214 Shell escaped commands (with ! as first character) are not recognized
3214 Shell escaped commands (with ! as first character) are not recognized
3215 by this system, only pure python code and magic commands.
3215 by this system, only pure python code and magic commands.
3216 """
3216 """
3217
3217
3218 start = parameter_s.strip()
3218 start = parameter_s.strip()
3219 esc_magic = ESC_MAGIC
3219 esc_magic = ESC_MAGIC
3220 # Identify magic commands even if automagic is on (which means
3220 # Identify magic commands even if automagic is on (which means
3221 # the in-memory version is different from that typed by the user).
3221 # the in-memory version is different from that typed by the user).
3222 if self.shell.automagic:
3222 if self.shell.automagic:
3223 start_magic = esc_magic+start
3223 start_magic = esc_magic+start
3224 else:
3224 else:
3225 start_magic = start
3225 start_magic = start
3226 # Look through the input history in reverse
3226 # Look through the input history in reverse
3227 for n in range(len(self.shell.input_hist)-2,0,-1):
3227 for n in range(len(self.shell.input_hist)-2,0,-1):
3228 input = self.shell.input_hist[n]
3228 input = self.shell.input_hist[n]
3229 # skip plain 'r' lines so we don't recurse to infinity
3229 # skip plain 'r' lines so we don't recurse to infinity
3230 if input != '_ip.magic("r")\n' and \
3230 if input != '_ip.magic("r")\n' and \
3231 (input.startswith(start) or input.startswith(start_magic)):
3231 (input.startswith(start) or input.startswith(start_magic)):
3232 #print 'match',`input` # dbg
3232 #print 'match',`input` # dbg
3233 print 'Executing:',input,
3233 print 'Executing:',input,
3234 self.shell.runlines(input)
3234 self.shell.runlines(input)
3235 return
3235 return
3236 print 'No previous input matching `%s` found.' % start
3236 print 'No previous input matching `%s` found.' % start
3237
3237
3238
3238
3239 def magic_bookmark(self, parameter_s=''):
3239 def magic_bookmark(self, parameter_s=''):
3240 """Manage IPython's bookmark system.
3240 """Manage IPython's bookmark system.
3241
3241
3242 %bookmark <name> - set bookmark to current dir
3242 %bookmark <name> - set bookmark to current dir
3243 %bookmark <name> <dir> - set bookmark to <dir>
3243 %bookmark <name> <dir> - set bookmark to <dir>
3244 %bookmark -l - list all bookmarks
3244 %bookmark -l - list all bookmarks
3245 %bookmark -d <name> - remove bookmark
3245 %bookmark -d <name> - remove bookmark
3246 %bookmark -r - remove all bookmarks
3246 %bookmark -r - remove all bookmarks
3247
3247
3248 You can later on access a bookmarked folder with:
3248 You can later on access a bookmarked folder with:
3249 %cd -b <name>
3249 %cd -b <name>
3250 or simply '%cd <name>' if there is no directory called <name> AND
3250 or simply '%cd <name>' if there is no directory called <name> AND
3251 there is such a bookmark defined.
3251 there is such a bookmark defined.
3252
3252
3253 Your bookmarks persist through IPython sessions, but they are
3253 Your bookmarks persist through IPython sessions, but they are
3254 associated with each profile."""
3254 associated with each profile."""
3255
3255
3256 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3256 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3257 if len(args) > 2:
3257 if len(args) > 2:
3258 raise UsageError("%bookmark: too many arguments")
3258 raise UsageError("%bookmark: too many arguments")
3259
3259
3260 bkms = self.db.get('bookmarks',{})
3260 bkms = self.db.get('bookmarks',{})
3261
3261
3262 if opts.has_key('d'):
3262 if opts.has_key('d'):
3263 try:
3263 try:
3264 todel = args[0]
3264 todel = args[0]
3265 except IndexError:
3265 except IndexError:
3266 raise UsageError(
3266 raise UsageError(
3267 "%bookmark -d: must provide a bookmark to delete")
3267 "%bookmark -d: must provide a bookmark to delete")
3268 else:
3268 else:
3269 try:
3269 try:
3270 del bkms[todel]
3270 del bkms[todel]
3271 except KeyError:
3271 except KeyError:
3272 raise UsageError(
3272 raise UsageError(
3273 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3273 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3274
3274
3275 elif opts.has_key('r'):
3275 elif opts.has_key('r'):
3276 bkms = {}
3276 bkms = {}
3277 elif opts.has_key('l'):
3277 elif opts.has_key('l'):
3278 bks = bkms.keys()
3278 bks = bkms.keys()
3279 bks.sort()
3279 bks.sort()
3280 if bks:
3280 if bks:
3281 size = max(map(len,bks))
3281 size = max(map(len,bks))
3282 else:
3282 else:
3283 size = 0
3283 size = 0
3284 fmt = '%-'+str(size)+'s -> %s'
3284 fmt = '%-'+str(size)+'s -> %s'
3285 print 'Current bookmarks:'
3285 print 'Current bookmarks:'
3286 for bk in bks:
3286 for bk in bks:
3287 print fmt % (bk,bkms[bk])
3287 print fmt % (bk,bkms[bk])
3288 else:
3288 else:
3289 if not args:
3289 if not args:
3290 raise UsageError("%bookmark: You must specify the bookmark name")
3290 raise UsageError("%bookmark: You must specify the bookmark name")
3291 elif len(args)==1:
3291 elif len(args)==1:
3292 bkms[args[0]] = os.getcwd()
3292 bkms[args[0]] = os.getcwd()
3293 elif len(args)==2:
3293 elif len(args)==2:
3294 bkms[args[0]] = args[1]
3294 bkms[args[0]] = args[1]
3295 self.db['bookmarks'] = bkms
3295 self.db['bookmarks'] = bkms
3296
3296
3297 def magic_pycat(self, parameter_s=''):
3297 def magic_pycat(self, parameter_s=''):
3298 """Show a syntax-highlighted file through a pager.
3298 """Show a syntax-highlighted file through a pager.
3299
3299
3300 This magic is similar to the cat utility, but it will assume the file
3300 This magic is similar to the cat utility, but it will assume the file
3301 to be Python source and will show it with syntax highlighting. """
3301 to be Python source and will show it with syntax highlighting. """
3302
3302
3303 try:
3303 try:
3304 filename = get_py_filename(parameter_s)
3304 filename = get_py_filename(parameter_s)
3305 cont = file_read(filename)
3305 cont = file_read(filename)
3306 except IOError:
3306 except IOError:
3307 try:
3307 try:
3308 cont = eval(parameter_s,self.user_ns)
3308 cont = eval(parameter_s,self.user_ns)
3309 except NameError:
3309 except NameError:
3310 cont = None
3310 cont = None
3311 if cont is None:
3311 if cont is None:
3312 print "Error: no such file or variable"
3312 print "Error: no such file or variable"
3313 return
3313 return
3314
3314
3315 page(self.shell.pycolorize(cont),
3315 page(self.shell.pycolorize(cont),
3316 screen_lines=self.shell.usable_screen_length)
3316 screen_lines=self.shell.usable_screen_length)
3317
3317
3318 def _rerun_pasted(self):
3318 def _rerun_pasted(self):
3319 """ Rerun a previously pasted command.
3319 """ Rerun a previously pasted command.
3320 """
3320 """
3321 b = self.user_ns.get('pasted_block', None)
3321 b = self.user_ns.get('pasted_block', None)
3322 if b is None:
3322 if b is None:
3323 raise UsageError('No previous pasted block available')
3323 raise UsageError('No previous pasted block available')
3324 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3324 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3325 exec b in self.user_ns
3325 exec b in self.user_ns
3326
3326
3327 def _get_pasted_lines(self, sentinel):
3327 def _get_pasted_lines(self, sentinel):
3328 """ Yield pasted lines until the user enters the given sentinel value.
3328 """ Yield pasted lines until the user enters the given sentinel value.
3329 """
3329 """
3330 from IPython.core import iplib
3330 from IPython.core import interactiveshell
3331 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3331 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3332 while True:
3332 while True:
3333 l = iplib.raw_input_original(':')
3333 l = interactiveshell.raw_input_original(':')
3334 if l == sentinel:
3334 if l == sentinel:
3335 return
3335 return
3336 else:
3336 else:
3337 yield l
3337 yield l
3338
3338
3339 def _strip_pasted_lines_for_code(self, raw_lines):
3339 def _strip_pasted_lines_for_code(self, raw_lines):
3340 """ Strip non-code parts of a sequence of lines to return a block of
3340 """ Strip non-code parts of a sequence of lines to return a block of
3341 code.
3341 code.
3342 """
3342 """
3343 # Regular expressions that declare text we strip from the input:
3343 # Regular expressions that declare text we strip from the input:
3344 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3344 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3345 r'^\s*(\s?>)+', # Python input prompt
3345 r'^\s*(\s?>)+', # Python input prompt
3346 r'^\s*\.{3,}', # Continuation prompts
3346 r'^\s*\.{3,}', # Continuation prompts
3347 r'^\++',
3347 r'^\++',
3348 ]
3348 ]
3349
3349
3350 strip_from_start = map(re.compile,strip_re)
3350 strip_from_start = map(re.compile,strip_re)
3351
3351
3352 lines = []
3352 lines = []
3353 for l in raw_lines:
3353 for l in raw_lines:
3354 for pat in strip_from_start:
3354 for pat in strip_from_start:
3355 l = pat.sub('',l)
3355 l = pat.sub('',l)
3356 lines.append(l)
3356 lines.append(l)
3357
3357
3358 block = "\n".join(lines) + '\n'
3358 block = "\n".join(lines) + '\n'
3359 #print "block:\n",block
3359 #print "block:\n",block
3360 return block
3360 return block
3361
3361
3362 def _execute_block(self, block, par):
3362 def _execute_block(self, block, par):
3363 """ Execute a block, or store it in a variable, per the user's request.
3363 """ Execute a block, or store it in a variable, per the user's request.
3364 """
3364 """
3365 if not par:
3365 if not par:
3366 b = textwrap.dedent(block)
3366 b = textwrap.dedent(block)
3367 self.user_ns['pasted_block'] = b
3367 self.user_ns['pasted_block'] = b
3368 exec b in self.user_ns
3368 exec b in self.user_ns
3369 else:
3369 else:
3370 self.user_ns[par] = SList(block.splitlines())
3370 self.user_ns[par] = SList(block.splitlines())
3371 print "Block assigned to '%s'" % par
3371 print "Block assigned to '%s'" % par
3372
3372
3373 def magic_cpaste(self, parameter_s=''):
3373 def magic_cpaste(self, parameter_s=''):
3374 """Allows you to paste & execute a pre-formatted code block from clipboard.
3374 """Allows you to paste & execute a pre-formatted code block from clipboard.
3375
3375
3376 You must terminate the block with '--' (two minus-signs) alone on the
3376 You must terminate the block with '--' (two minus-signs) alone on the
3377 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3377 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3378 is the new sentinel for this operation)
3378 is the new sentinel for this operation)
3379
3379
3380 The block is dedented prior to execution to enable execution of method
3380 The block is dedented prior to execution to enable execution of method
3381 definitions. '>' and '+' characters at the beginning of a line are
3381 definitions. '>' and '+' characters at the beginning of a line are
3382 ignored, to allow pasting directly from e-mails, diff files and
3382 ignored, to allow pasting directly from e-mails, diff files and
3383 doctests (the '...' continuation prompt is also stripped). The
3383 doctests (the '...' continuation prompt is also stripped). The
3384 executed block is also assigned to variable named 'pasted_block' for
3384 executed block is also assigned to variable named 'pasted_block' for
3385 later editing with '%edit pasted_block'.
3385 later editing with '%edit pasted_block'.
3386
3386
3387 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3387 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3388 This assigns the pasted block to variable 'foo' as string, without
3388 This assigns the pasted block to variable 'foo' as string, without
3389 dedenting or executing it (preceding >>> and + is still stripped)
3389 dedenting or executing it (preceding >>> and + is still stripped)
3390
3390
3391 '%cpaste -r' re-executes the block previously entered by cpaste.
3391 '%cpaste -r' re-executes the block previously entered by cpaste.
3392
3392
3393 Do not be alarmed by garbled output on Windows (it's a readline bug).
3393 Do not be alarmed by garbled output on Windows (it's a readline bug).
3394 Just press enter and type -- (and press enter again) and the block
3394 Just press enter and type -- (and press enter again) and the block
3395 will be what was just pasted.
3395 will be what was just pasted.
3396
3396
3397 IPython statements (magics, shell escapes) are not supported (yet).
3397 IPython statements (magics, shell escapes) are not supported (yet).
3398
3398
3399 See also
3399 See also
3400 --------
3400 --------
3401 paste: automatically pull code from clipboard.
3401 paste: automatically pull code from clipboard.
3402 """
3402 """
3403
3403
3404 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3404 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3405 par = args.strip()
3405 par = args.strip()
3406 if opts.has_key('r'):
3406 if opts.has_key('r'):
3407 self._rerun_pasted()
3407 self._rerun_pasted()
3408 return
3408 return
3409
3409
3410 sentinel = opts.get('s','--')
3410 sentinel = opts.get('s','--')
3411
3411
3412 block = self._strip_pasted_lines_for_code(
3412 block = self._strip_pasted_lines_for_code(
3413 self._get_pasted_lines(sentinel))
3413 self._get_pasted_lines(sentinel))
3414
3414
3415 self._execute_block(block, par)
3415 self._execute_block(block, par)
3416
3416
3417 def magic_paste(self, parameter_s=''):
3417 def magic_paste(self, parameter_s=''):
3418 """Allows you to paste & execute a pre-formatted code block from clipboard.
3418 """Allows you to paste & execute a pre-formatted code block from clipboard.
3419
3419
3420 The text is pulled directly from the clipboard without user
3420 The text is pulled directly from the clipboard without user
3421 intervention and printed back on the screen before execution (unless
3421 intervention and printed back on the screen before execution (unless
3422 the -q flag is given to force quiet mode).
3422 the -q flag is given to force quiet mode).
3423
3423
3424 The block is dedented prior to execution to enable execution of method
3424 The block is dedented prior to execution to enable execution of method
3425 definitions. '>' and '+' characters at the beginning of a line are
3425 definitions. '>' and '+' characters at the beginning of a line are
3426 ignored, to allow pasting directly from e-mails, diff files and
3426 ignored, to allow pasting directly from e-mails, diff files and
3427 doctests (the '...' continuation prompt is also stripped). The
3427 doctests (the '...' continuation prompt is also stripped). The
3428 executed block is also assigned to variable named 'pasted_block' for
3428 executed block is also assigned to variable named 'pasted_block' for
3429 later editing with '%edit pasted_block'.
3429 later editing with '%edit pasted_block'.
3430
3430
3431 You can also pass a variable name as an argument, e.g. '%paste foo'.
3431 You can also pass a variable name as an argument, e.g. '%paste foo'.
3432 This assigns the pasted block to variable 'foo' as string, without
3432 This assigns the pasted block to variable 'foo' as string, without
3433 dedenting or executing it (preceding >>> and + is still stripped)
3433 dedenting or executing it (preceding >>> and + is still stripped)
3434
3434
3435 Options
3435 Options
3436 -------
3436 -------
3437
3437
3438 -r: re-executes the block previously entered by cpaste.
3438 -r: re-executes the block previously entered by cpaste.
3439
3439
3440 -q: quiet mode: do not echo the pasted text back to the terminal.
3440 -q: quiet mode: do not echo the pasted text back to the terminal.
3441
3441
3442 IPython statements (magics, shell escapes) are not supported (yet).
3442 IPython statements (magics, shell escapes) are not supported (yet).
3443
3443
3444 See also
3444 See also
3445 --------
3445 --------
3446 cpaste: manually paste code into terminal until you mark its end.
3446 cpaste: manually paste code into terminal until you mark its end.
3447 """
3447 """
3448 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3448 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3449 par = args.strip()
3449 par = args.strip()
3450 if opts.has_key('r'):
3450 if opts.has_key('r'):
3451 self._rerun_pasted()
3451 self._rerun_pasted()
3452 return
3452 return
3453
3453
3454 text = self.shell.hooks.clipboard_get()
3454 text = self.shell.hooks.clipboard_get()
3455 block = self._strip_pasted_lines_for_code(text.splitlines())
3455 block = self._strip_pasted_lines_for_code(text.splitlines())
3456
3456
3457 # By default, echo back to terminal unless quiet mode is requested
3457 # By default, echo back to terminal unless quiet mode is requested
3458 if not opts.has_key('q'):
3458 if not opts.has_key('q'):
3459 write = self.shell.write
3459 write = self.shell.write
3460 write(self.shell.pycolorize(block))
3460 write(self.shell.pycolorize(block))
3461 if not block.endswith('\n'):
3461 if not block.endswith('\n'):
3462 write('\n')
3462 write('\n')
3463 write("## -- End pasted text --\n")
3463 write("## -- End pasted text --\n")
3464
3464
3465 self._execute_block(block, par)
3465 self._execute_block(block, par)
3466
3466
3467 def magic_quickref(self,arg):
3467 def magic_quickref(self,arg):
3468 """ Show a quick reference sheet """
3468 """ Show a quick reference sheet """
3469 import IPython.core.usage
3469 import IPython.core.usage
3470 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3470 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3471
3471
3472 page(qr)
3472 page(qr)
3473
3473
3474 def magic_doctest_mode(self,parameter_s=''):
3474 def magic_doctest_mode(self,parameter_s=''):
3475 """Toggle doctest mode on and off.
3475 """Toggle doctest mode on and off.
3476
3476
3477 This mode allows you to toggle the prompt behavior between normal
3477 This mode allows you to toggle the prompt behavior between normal
3478 IPython prompts and ones that are as similar to the default IPython
3478 IPython prompts and ones that are as similar to the default IPython
3479 interpreter as possible.
3479 interpreter as possible.
3480
3480
3481 It also supports the pasting of code snippets that have leading '>>>'
3481 It also supports the pasting of code snippets that have leading '>>>'
3482 and '...' prompts in them. This means that you can paste doctests from
3482 and '...' prompts in them. This means that you can paste doctests from
3483 files or docstrings (even if they have leading whitespace), and the
3483 files or docstrings (even if they have leading whitespace), and the
3484 code will execute correctly. You can then use '%history -tn' to see
3484 code will execute correctly. You can then use '%history -tn' to see
3485 the translated history without line numbers; this will give you the
3485 the translated history without line numbers; this will give you the
3486 input after removal of all the leading prompts and whitespace, which
3486 input after removal of all the leading prompts and whitespace, which
3487 can be pasted back into an editor.
3487 can be pasted back into an editor.
3488
3488
3489 With these features, you can switch into this mode easily whenever you
3489 With these features, you can switch into this mode easily whenever you
3490 need to do testing and changes to doctests, without having to leave
3490 need to do testing and changes to doctests, without having to leave
3491 your existing IPython session.
3491 your existing IPython session.
3492 """
3492 """
3493
3493
3494 from IPython.utils.ipstruct import Struct
3494 from IPython.utils.ipstruct import Struct
3495
3495
3496 # Shorthands
3496 # Shorthands
3497 shell = self.shell
3497 shell = self.shell
3498 oc = shell.outputcache
3498 oc = shell.outputcache
3499 meta = shell.meta
3499 meta = shell.meta
3500 # dstore is a data store kept in the instance metadata bag to track any
3500 # dstore is a data store kept in the instance metadata bag to track any
3501 # changes we make, so we can undo them later.
3501 # changes we make, so we can undo them later.
3502 dstore = meta.setdefault('doctest_mode',Struct())
3502 dstore = meta.setdefault('doctest_mode',Struct())
3503 save_dstore = dstore.setdefault
3503 save_dstore = dstore.setdefault
3504
3504
3505 # save a few values we'll need to recover later
3505 # save a few values we'll need to recover later
3506 mode = save_dstore('mode',False)
3506 mode = save_dstore('mode',False)
3507 save_dstore('rc_pprint',shell.pprint)
3507 save_dstore('rc_pprint',shell.pprint)
3508 save_dstore('xmode',shell.InteractiveTB.mode)
3508 save_dstore('xmode',shell.InteractiveTB.mode)
3509 save_dstore('rc_separate_out',shell.separate_out)
3509 save_dstore('rc_separate_out',shell.separate_out)
3510 save_dstore('rc_separate_out2',shell.separate_out2)
3510 save_dstore('rc_separate_out2',shell.separate_out2)
3511 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3511 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3512 save_dstore('rc_separate_in',shell.separate_in)
3512 save_dstore('rc_separate_in',shell.separate_in)
3513
3513
3514 if mode == False:
3514 if mode == False:
3515 # turn on
3515 # turn on
3516 oc.prompt1.p_template = '>>> '
3516 oc.prompt1.p_template = '>>> '
3517 oc.prompt2.p_template = '... '
3517 oc.prompt2.p_template = '... '
3518 oc.prompt_out.p_template = ''
3518 oc.prompt_out.p_template = ''
3519
3519
3520 # Prompt separators like plain python
3520 # Prompt separators like plain python
3521 oc.input_sep = oc.prompt1.sep = ''
3521 oc.input_sep = oc.prompt1.sep = ''
3522 oc.output_sep = ''
3522 oc.output_sep = ''
3523 oc.output_sep2 = ''
3523 oc.output_sep2 = ''
3524
3524
3525 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3525 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3526 oc.prompt_out.pad_left = False
3526 oc.prompt_out.pad_left = False
3527
3527
3528 shell.pprint = False
3528 shell.pprint = False
3529
3529
3530 shell.magic_xmode('Plain')
3530 shell.magic_xmode('Plain')
3531
3531
3532 else:
3532 else:
3533 # turn off
3533 # turn off
3534 oc.prompt1.p_template = shell.prompt_in1
3534 oc.prompt1.p_template = shell.prompt_in1
3535 oc.prompt2.p_template = shell.prompt_in2
3535 oc.prompt2.p_template = shell.prompt_in2
3536 oc.prompt_out.p_template = shell.prompt_out
3536 oc.prompt_out.p_template = shell.prompt_out
3537
3537
3538 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3538 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3539
3539
3540 oc.output_sep = dstore.rc_separate_out
3540 oc.output_sep = dstore.rc_separate_out
3541 oc.output_sep2 = dstore.rc_separate_out2
3541 oc.output_sep2 = dstore.rc_separate_out2
3542
3542
3543 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3543 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3544 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3544 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3545
3545
3546 shell.pprint = dstore.rc_pprint
3546 shell.pprint = dstore.rc_pprint
3547
3547
3548 shell.magic_xmode(dstore.xmode)
3548 shell.magic_xmode(dstore.xmode)
3549
3549
3550 # Store new mode and inform
3550 # Store new mode and inform
3551 dstore.mode = bool(1-int(mode))
3551 dstore.mode = bool(1-int(mode))
3552 print 'Doctest mode is:',
3552 print 'Doctest mode is:',
3553 print ['OFF','ON'][dstore.mode]
3553 print ['OFF','ON'][dstore.mode]
3554
3554
3555 def magic_gui(self, parameter_s=''):
3555 def magic_gui(self, parameter_s=''):
3556 """Enable or disable IPython GUI event loop integration.
3556 """Enable or disable IPython GUI event loop integration.
3557
3557
3558 %gui [-a] [GUINAME]
3558 %gui [-a] [GUINAME]
3559
3559
3560 This magic replaces IPython's threaded shells that were activated
3560 This magic replaces IPython's threaded shells that were activated
3561 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3561 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3562 can now be enabled, disabled and swtiched at runtime and keyboard
3562 can now be enabled, disabled and swtiched at runtime and keyboard
3563 interrupts should work without any problems. The following toolkits
3563 interrupts should work without any problems. The following toolkits
3564 are supported: wxPython, PyQt4, PyGTK, and Tk::
3564 are supported: wxPython, PyQt4, PyGTK, and Tk::
3565
3565
3566 %gui wx # enable wxPython event loop integration
3566 %gui wx # enable wxPython event loop integration
3567 %gui qt4|qt # enable PyQt4 event loop integration
3567 %gui qt4|qt # enable PyQt4 event loop integration
3568 %gui gtk # enable PyGTK event loop integration
3568 %gui gtk # enable PyGTK event loop integration
3569 %gui tk # enable Tk event loop integration
3569 %gui tk # enable Tk event loop integration
3570 %gui # disable all event loop integration
3570 %gui # disable all event loop integration
3571
3571
3572 WARNING: after any of these has been called you can simply create
3572 WARNING: after any of these has been called you can simply create
3573 an application object, but DO NOT start the event loop yourself, as
3573 an application object, but DO NOT start the event loop yourself, as
3574 we have already handled that.
3574 we have already handled that.
3575
3575
3576 If you want us to create an appropriate application object add the
3576 If you want us to create an appropriate application object add the
3577 "-a" flag to your command::
3577 "-a" flag to your command::
3578
3578
3579 %gui -a wx
3579 %gui -a wx
3580
3580
3581 This is highly recommended for most users.
3581 This is highly recommended for most users.
3582 """
3582 """
3583 opts, arg = self.parse_options(parameter_s,'a')
3583 opts, arg = self.parse_options(parameter_s,'a')
3584 if arg=='': arg = None
3584 if arg=='': arg = None
3585 return enable_gui(arg, 'a' in opts)
3585 return enable_gui(arg, 'a' in opts)
3586
3586
3587 def magic_load_ext(self, module_str):
3587 def magic_load_ext(self, module_str):
3588 """Load an IPython extension by its module name."""
3588 """Load an IPython extension by its module name."""
3589 return self.extension_manager.load_extension(module_str)
3589 return self.extension_manager.load_extension(module_str)
3590
3590
3591 def magic_unload_ext(self, module_str):
3591 def magic_unload_ext(self, module_str):
3592 """Unload an IPython extension by its module name."""
3592 """Unload an IPython extension by its module name."""
3593 self.extension_manager.unload_extension(module_str)
3593 self.extension_manager.unload_extension(module_str)
3594
3594
3595 def magic_reload_ext(self, module_str):
3595 def magic_reload_ext(self, module_str):
3596 """Reload an IPython extension by its module name."""
3596 """Reload an IPython extension by its module name."""
3597 self.extension_manager.reload_extension(module_str)
3597 self.extension_manager.reload_extension(module_str)
3598
3598
3599 @testdec.skip_doctest
3599 @testdec.skip_doctest
3600 def magic_install_profiles(self, s):
3600 def magic_install_profiles(self, s):
3601 """Install the default IPython profiles into the .ipython dir.
3601 """Install the default IPython profiles into the .ipython dir.
3602
3602
3603 If the default profiles have already been installed, they will not
3603 If the default profiles have already been installed, they will not
3604 be overwritten. You can force overwriting them by using the ``-o``
3604 be overwritten. You can force overwriting them by using the ``-o``
3605 option::
3605 option::
3606
3606
3607 In [1]: %install_profiles -o
3607 In [1]: %install_profiles -o
3608 """
3608 """
3609 if '-o' in s:
3609 if '-o' in s:
3610 overwrite = True
3610 overwrite = True
3611 else:
3611 else:
3612 overwrite = False
3612 overwrite = False
3613 from IPython.config import profile
3613 from IPython.config import profile
3614 profile_dir = os.path.split(profile.__file__)[0]
3614 profile_dir = os.path.split(profile.__file__)[0]
3615 ipython_dir = self.ipython_dir
3615 ipython_dir = self.ipython_dir
3616 files = os.listdir(profile_dir)
3616 files = os.listdir(profile_dir)
3617
3617
3618 to_install = []
3618 to_install = []
3619 for f in files:
3619 for f in files:
3620 if f.startswith('ipython_config'):
3620 if f.startswith('ipython_config'):
3621 src = os.path.join(profile_dir, f)
3621 src = os.path.join(profile_dir, f)
3622 dst = os.path.join(ipython_dir, f)
3622 dst = os.path.join(ipython_dir, f)
3623 if (not os.path.isfile(dst)) or overwrite:
3623 if (not os.path.isfile(dst)) or overwrite:
3624 to_install.append((f, src, dst))
3624 to_install.append((f, src, dst))
3625 if len(to_install)>0:
3625 if len(to_install)>0:
3626 print "Installing profiles to: ", ipython_dir
3626 print "Installing profiles to: ", ipython_dir
3627 for (f, src, dst) in to_install:
3627 for (f, src, dst) in to_install:
3628 shutil.copy(src, dst)
3628 shutil.copy(src, dst)
3629 print " %s" % f
3629 print " %s" % f
3630
3630
3631 def magic_install_default_config(self, s):
3631 def magic_install_default_config(self, s):
3632 """Install IPython's default config file into the .ipython dir.
3632 """Install IPython's default config file into the .ipython dir.
3633
3633
3634 If the default config file (:file:`ipython_config.py`) is already
3634 If the default config file (:file:`ipython_config.py`) is already
3635 installed, it will not be overwritten. You can force overwriting
3635 installed, it will not be overwritten. You can force overwriting
3636 by using the ``-o`` option::
3636 by using the ``-o`` option::
3637
3637
3638 In [1]: %install_default_config
3638 In [1]: %install_default_config
3639 """
3639 """
3640 if '-o' in s:
3640 if '-o' in s:
3641 overwrite = True
3641 overwrite = True
3642 else:
3642 else:
3643 overwrite = False
3643 overwrite = False
3644 from IPython.config import default
3644 from IPython.config import default
3645 config_dir = os.path.split(default.__file__)[0]
3645 config_dir = os.path.split(default.__file__)[0]
3646 ipython_dir = self.ipython_dir
3646 ipython_dir = self.ipython_dir
3647 default_config_file_name = 'ipython_config.py'
3647 default_config_file_name = 'ipython_config.py'
3648 src = os.path.join(config_dir, default_config_file_name)
3648 src = os.path.join(config_dir, default_config_file_name)
3649 dst = os.path.join(ipython_dir, default_config_file_name)
3649 dst = os.path.join(ipython_dir, default_config_file_name)
3650 if (not os.path.isfile(dst)) or overwrite:
3650 if (not os.path.isfile(dst)) or overwrite:
3651 shutil.copy(src, dst)
3651 shutil.copy(src, dst)
3652 print "Installing default config file: %s" % dst
3652 print "Installing default config file: %s" % dst
3653
3653
3654 # Pylab support: simple wrappers that activate pylab, load gui input
3654 # Pylab support: simple wrappers that activate pylab, load gui input
3655 # handling and modify slightly %run
3655 # handling and modify slightly %run
3656
3656
3657 @testdec.skip_doctest
3657 @testdec.skip_doctest
3658 def _pylab_magic_run(self, parameter_s=''):
3658 def _pylab_magic_run(self, parameter_s=''):
3659 Magic.magic_run(self, parameter_s,
3659 Magic.magic_run(self, parameter_s,
3660 runner=mpl_runner(self.shell.safe_execfile))
3660 runner=mpl_runner(self.shell.safe_execfile))
3661
3661
3662 _pylab_magic_run.__doc__ = magic_run.__doc__
3662 _pylab_magic_run.__doc__ = magic_run.__doc__
3663
3663
3664 @testdec.skip_doctest
3664 @testdec.skip_doctest
3665 def magic_pylab(self, s):
3665 def magic_pylab(self, s):
3666 """Load numpy and matplotlib to work interactively.
3666 """Load numpy and matplotlib to work interactively.
3667
3667
3668 %pylab [GUINAME]
3668 %pylab [GUINAME]
3669
3669
3670 This function lets you activate pylab (matplotlib, numpy and
3670 This function lets you activate pylab (matplotlib, numpy and
3671 interactive support) at any point during an IPython session.
3671 interactive support) at any point during an IPython session.
3672
3672
3673 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3673 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3674 pylab and mlab, as well as all names from numpy and pylab.
3674 pylab and mlab, as well as all names from numpy and pylab.
3675
3675
3676 Parameters
3676 Parameters
3677 ----------
3677 ----------
3678 guiname : optional
3678 guiname : optional
3679 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3679 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3680 'tk'). If given, the corresponding Matplotlib backend is used,
3680 'tk'). If given, the corresponding Matplotlib backend is used,
3681 otherwise matplotlib's default (which you can override in your
3681 otherwise matplotlib's default (which you can override in your
3682 matplotlib config file) is used.
3682 matplotlib config file) is used.
3683
3683
3684 Examples
3684 Examples
3685 --------
3685 --------
3686 In this case, where the MPL default is TkAgg:
3686 In this case, where the MPL default is TkAgg:
3687 In [2]: %pylab
3687 In [2]: %pylab
3688
3688
3689 Welcome to pylab, a matplotlib-based Python environment.
3689 Welcome to pylab, a matplotlib-based Python environment.
3690 Backend in use: TkAgg
3690 Backend in use: TkAgg
3691 For more information, type 'help(pylab)'.
3691 For more information, type 'help(pylab)'.
3692
3692
3693 But you can explicitly request a different backend:
3693 But you can explicitly request a different backend:
3694 In [3]: %pylab qt
3694 In [3]: %pylab qt
3695
3695
3696 Welcome to pylab, a matplotlib-based Python environment.
3696 Welcome to pylab, a matplotlib-based Python environment.
3697 Backend in use: Qt4Agg
3697 Backend in use: Qt4Agg
3698 For more information, type 'help(pylab)'.
3698 For more information, type 'help(pylab)'.
3699 """
3699 """
3700 self.shell.enable_pylab(s)
3700 self.shell.enable_pylab(s)
3701
3701
3702 def magic_tb(self, s):
3702 def magic_tb(self, s):
3703 """Print the last traceback with the currently active exception mode.
3703 """Print the last traceback with the currently active exception mode.
3704
3704
3705 See %xmode for changing exception reporting modes."""
3705 See %xmode for changing exception reporting modes."""
3706 self.shell.showtraceback()
3706 self.shell.showtraceback()
3707
3707
3708 # end Magic
3708 # end Magic
@@ -1,1022 +1,1022 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Prefiltering components.
4 Prefiltering components.
5
5
6 Prefilters transform user input before it is exec'd by Python. These
6 Prefilters transform user input before it is exec'd by Python. These
7 transforms are used to implement additional syntax such as !ls and %magic.
7 transforms are used to implement additional syntax such as !ls and %magic.
8
8
9 Authors:
9 Authors:
10
10
11 * Brian Granger
11 * Brian Granger
12 * Fernando Perez
12 * Fernando Perez
13 * Dan Milstein
13 * Dan Milstein
14 * Ville Vainio
14 * Ville Vainio
15 """
15 """
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2009 The IPython Development Team
18 # Copyright (C) 2008-2009 The IPython Development Team
19 #
19 #
20 # Distributed under the terms of the BSD License. The full license is in
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
21 # the file COPYING, distributed as part of this software.
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Imports
25 # Imports
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 import __builtin__
28 import __builtin__
29 import codeop
29 import codeop
30 import re
30 import re
31
31
32 from IPython.core.alias import AliasManager
32 from IPython.core.alias import AliasManager
33 from IPython.core.autocall import IPyAutocall
33 from IPython.core.autocall import IPyAutocall
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core.splitinput import split_user_input
35 from IPython.core.splitinput import split_user_input
36 from IPython.core.page import page
36 from IPython.core.page import page
37
37
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 from IPython.utils.io import Term
39 from IPython.utils.io import Term
40 from IPython.utils.text import make_quoted_expr
40 from IPython.utils.text import make_quoted_expr
41 from IPython.utils.autoattr import auto_attr
41 from IPython.utils.autoattr import auto_attr
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Global utilities, errors and constants
44 # Global utilities, errors and constants
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 # Warning, these cannot be changed unless various regular expressions
47 # Warning, these cannot be changed unless various regular expressions
48 # are updated in a number of places. Not great, but at least we told you.
48 # are updated in a number of places. Not great, but at least we told you.
49 ESC_SHELL = '!'
49 ESC_SHELL = '!'
50 ESC_SH_CAP = '!!'
50 ESC_SH_CAP = '!!'
51 ESC_HELP = '?'
51 ESC_HELP = '?'
52 ESC_MAGIC = '%'
52 ESC_MAGIC = '%'
53 ESC_QUOTE = ','
53 ESC_QUOTE = ','
54 ESC_QUOTE2 = ';'
54 ESC_QUOTE2 = ';'
55 ESC_PAREN = '/'
55 ESC_PAREN = '/'
56
56
57
57
58 class PrefilterError(Exception):
58 class PrefilterError(Exception):
59 pass
59 pass
60
60
61
61
62 # RegExp to identify potential function names
62 # RegExp to identify potential function names
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
64
64
65 # RegExp to exclude strings with this start from autocalling. In
65 # RegExp to exclude strings with this start from autocalling. In
66 # particular, all binary operators should be excluded, so that if foo is
66 # particular, all binary operators should be excluded, so that if foo is
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
69 # routine explicitely does so, to catch direct calls and rebindings of
69 # routine explicitely does so, to catch direct calls and rebindings of
70 # existing names.
70 # existing names.
71
71
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
73 # it affects the rest of the group in square brackets.
73 # it affects the rest of the group in square brackets.
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
75 r'|^is |^not |^in |^and |^or ')
75 r'|^is |^not |^in |^and |^or ')
76
76
77 # try to catch also methods for stuff in lists/tuples/dicts: off
77 # try to catch also methods for stuff in lists/tuples/dicts: off
78 # (experimental). For this to work, the line_split regexp would need
78 # (experimental). For this to work, the line_split regexp would need
79 # to be modified so it wouldn't break things at '['. That line is
79 # to be modified so it wouldn't break things at '['. That line is
80 # nasty enough that I shouldn't change it until I can test it _well_.
80 # nasty enough that I shouldn't change it until I can test it _well_.
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
82
82
83
83
84 # Handler Check Utilities
84 # Handler Check Utilities
85 def is_shadowed(identifier, ip):
85 def is_shadowed(identifier, ip):
86 """Is the given identifier defined in one of the namespaces which shadow
86 """Is the given identifier defined in one of the namespaces which shadow
87 the alias and magic namespaces? Note that an identifier is different
87 the alias and magic namespaces? Note that an identifier is different
88 than ifun, because it can not contain a '.' character."""
88 than ifun, because it can not contain a '.' character."""
89 # This is much safer than calling ofind, which can change state
89 # This is much safer than calling ofind, which can change state
90 return (identifier in ip.user_ns \
90 return (identifier in ip.user_ns \
91 or identifier in ip.internal_ns \
91 or identifier in ip.internal_ns \
92 or identifier in ip.ns_table['builtin'])
92 or identifier in ip.ns_table['builtin'])
93
93
94
94
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96 # The LineInfo class used throughout
96 # The LineInfo class used throughout
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98
98
99
99
100 class LineInfo(object):
100 class LineInfo(object):
101 """A single line of input and associated info.
101 """A single line of input and associated info.
102
102
103 Includes the following as properties:
103 Includes the following as properties:
104
104
105 line
105 line
106 The original, raw line
106 The original, raw line
107
107
108 continue_prompt
108 continue_prompt
109 Is this line a continuation in a sequence of multiline input?
109 Is this line a continuation in a sequence of multiline input?
110
110
111 pre
111 pre
112 The initial esc character or whitespace.
112 The initial esc character or whitespace.
113
113
114 pre_char
114 pre_char
115 The escape character(s) in pre or the empty string if there isn't one.
115 The escape character(s) in pre or the empty string if there isn't one.
116 Note that '!!' is a possible value for pre_char. Otherwise it will
116 Note that '!!' is a possible value for pre_char. Otherwise it will
117 always be a single character.
117 always be a single character.
118
118
119 pre_whitespace
119 pre_whitespace
120 The leading whitespace from pre if it exists. If there is a pre_char,
120 The leading whitespace from pre if it exists. If there is a pre_char,
121 this is just ''.
121 this is just ''.
122
122
123 ifun
123 ifun
124 The 'function part', which is basically the maximal initial sequence
124 The 'function part', which is basically the maximal initial sequence
125 of valid python identifiers and the '.' character. This is what is
125 of valid python identifiers and the '.' character. This is what is
126 checked for alias and magic transformations, used for auto-calling,
126 checked for alias and magic transformations, used for auto-calling,
127 etc.
127 etc.
128
128
129 the_rest
129 the_rest
130 Everything else on the line.
130 Everything else on the line.
131 """
131 """
132 def __init__(self, line, continue_prompt):
132 def __init__(self, line, continue_prompt):
133 self.line = line
133 self.line = line
134 self.continue_prompt = continue_prompt
134 self.continue_prompt = continue_prompt
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
136
136
137 self.pre_char = self.pre.strip()
137 self.pre_char = self.pre.strip()
138 if self.pre_char:
138 if self.pre_char:
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
140 else:
140 else:
141 self.pre_whitespace = self.pre
141 self.pre_whitespace = self.pre
142
142
143 self._oinfo = None
143 self._oinfo = None
144
144
145 def ofind(self, ip):
145 def ofind(self, ip):
146 """Do a full, attribute-walking lookup of the ifun in the various
146 """Do a full, attribute-walking lookup of the ifun in the various
147 namespaces for the given IPython InteractiveShell instance.
147 namespaces for the given IPython InteractiveShell instance.
148
148
149 Return a dict with keys: found,obj,ospace,ismagic
149 Return a dict with keys: found,obj,ospace,ismagic
150
150
151 Note: can cause state changes because of calling getattr, but should
151 Note: can cause state changes because of calling getattr, but should
152 only be run if autocall is on and if the line hasn't matched any
152 only be run if autocall is on and if the line hasn't matched any
153 other, less dangerous handlers.
153 other, less dangerous handlers.
154
154
155 Does cache the results of the call, so can be called multiple times
155 Does cache the results of the call, so can be called multiple times
156 without worrying about *further* damaging state.
156 without worrying about *further* damaging state.
157 """
157 """
158 if not self._oinfo:
158 if not self._oinfo:
159 # ip.shell._ofind is actually on the Magic class!
159 # ip.shell._ofind is actually on the Magic class!
160 self._oinfo = ip.shell._ofind(self.ifun)
160 self._oinfo = ip.shell._ofind(self.ifun)
161 return self._oinfo
161 return self._oinfo
162
162
163 def __str__(self):
163 def __str__(self):
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
165
165
166
166
167 #-----------------------------------------------------------------------------
167 #-----------------------------------------------------------------------------
168 # Main Prefilter manager
168 # Main Prefilter manager
169 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
170
170
171
171
172 class PrefilterManager(Configurable):
172 class PrefilterManager(Configurable):
173 """Main prefilter component.
173 """Main prefilter component.
174
174
175 The IPython prefilter is run on all user input before it is run. The
175 The IPython prefilter is run on all user input before it is run. The
176 prefilter consumes lines of input and produces transformed lines of
176 prefilter consumes lines of input and produces transformed lines of
177 input.
177 input.
178
178
179 The iplementation consists of two phases:
179 The iplementation consists of two phases:
180
180
181 1. Transformers
181 1. Transformers
182 2. Checkers and handlers
182 2. Checkers and handlers
183
183
184 Over time, we plan on deprecating the checkers and handlers and doing
184 Over time, we plan on deprecating the checkers and handlers and doing
185 everything in the transformers.
185 everything in the transformers.
186
186
187 The transformers are instances of :class:`PrefilterTransformer` and have
187 The transformers are instances of :class:`PrefilterTransformer` and have
188 a single method :meth:`transform` that takes a line and returns a
188 a single method :meth:`transform` that takes a line and returns a
189 transformed line. The transformation can be accomplished using any
189 transformed line. The transformation can be accomplished using any
190 tool, but our current ones use regular expressions for speed. We also
190 tool, but our current ones use regular expressions for speed. We also
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192
192
193 After all the transformers have been run, the line is fed to the checkers,
193 After all the transformers have been run, the line is fed to the checkers,
194 which are instances of :class:`PrefilterChecker`. The line is passed to
194 which are instances of :class:`PrefilterChecker`. The line is passed to
195 the :meth:`check` method, which either returns `None` or a
195 the :meth:`check` method, which either returns `None` or a
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 the line is passed to the :meth:`handle` method of the returned
198 the line is passed to the :meth:`handle` method of the returned
199 handler and no further checkers are tried.
199 handler and no further checkers are tried.
200
200
201 Both transformers and checkers have a `priority` attribute, that determines
201 Both transformers and checkers have a `priority` attribute, that determines
202 the order in which they are called. Smaller priorities are tried first.
202 the order in which they are called. Smaller priorities are tried first.
203
203
204 Both transformers and checkers also have `enabled` attribute, which is
204 Both transformers and checkers also have `enabled` attribute, which is
205 a boolean that determines if the instance is used.
205 a boolean that determines if the instance is used.
206
206
207 Users or developers can change the priority or enabled attribute of
207 Users or developers can change the priority or enabled attribute of
208 transformers or checkers, but they must call the :meth:`sort_checkers`
208 transformers or checkers, but they must call the :meth:`sort_checkers`
209 or :meth:`sort_transformers` method after changing the priority.
209 or :meth:`sort_transformers` method after changing the priority.
210 """
210 """
211
211
212 multi_line_specials = CBool(True, config=True)
212 multi_line_specials = CBool(True, config=True)
213 shell = Instance('IPython.core.iplib.InteractiveShellABC')
213 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
214
214
215 def __init__(self, shell=None, config=None):
215 def __init__(self, shell=None, config=None):
216 super(PrefilterManager, self).__init__(shell=shell, config=config)
216 super(PrefilterManager, self).__init__(shell=shell, config=config)
217 self.shell = shell
217 self.shell = shell
218 self.init_transformers()
218 self.init_transformers()
219 self.init_handlers()
219 self.init_handlers()
220 self.init_checkers()
220 self.init_checkers()
221
221
222 #-------------------------------------------------------------------------
222 #-------------------------------------------------------------------------
223 # API for managing transformers
223 # API for managing transformers
224 #-------------------------------------------------------------------------
224 #-------------------------------------------------------------------------
225
225
226 def init_transformers(self):
226 def init_transformers(self):
227 """Create the default transformers."""
227 """Create the default transformers."""
228 self._transformers = []
228 self._transformers = []
229 for transformer_cls in _default_transformers:
229 for transformer_cls in _default_transformers:
230 transformer_cls(
230 transformer_cls(
231 shell=self.shell, prefilter_manager=self, config=self.config
231 shell=self.shell, prefilter_manager=self, config=self.config
232 )
232 )
233
233
234 def sort_transformers(self):
234 def sort_transformers(self):
235 """Sort the transformers by priority.
235 """Sort the transformers by priority.
236
236
237 This must be called after the priority of a transformer is changed.
237 This must be called after the priority of a transformer is changed.
238 The :meth:`register_transformer` method calls this automatically.
238 The :meth:`register_transformer` method calls this automatically.
239 """
239 """
240 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
240 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
241
241
242 @property
242 @property
243 def transformers(self):
243 def transformers(self):
244 """Return a list of checkers, sorted by priority."""
244 """Return a list of checkers, sorted by priority."""
245 return self._transformers
245 return self._transformers
246
246
247 def register_transformer(self, transformer):
247 def register_transformer(self, transformer):
248 """Register a transformer instance."""
248 """Register a transformer instance."""
249 if transformer not in self._transformers:
249 if transformer not in self._transformers:
250 self._transformers.append(transformer)
250 self._transformers.append(transformer)
251 self.sort_transformers()
251 self.sort_transformers()
252
252
253 def unregister_transformer(self, transformer):
253 def unregister_transformer(self, transformer):
254 """Unregister a transformer instance."""
254 """Unregister a transformer instance."""
255 if transformer in self._transformers:
255 if transformer in self._transformers:
256 self._transformers.remove(transformer)
256 self._transformers.remove(transformer)
257
257
258 #-------------------------------------------------------------------------
258 #-------------------------------------------------------------------------
259 # API for managing checkers
259 # API for managing checkers
260 #-------------------------------------------------------------------------
260 #-------------------------------------------------------------------------
261
261
262 def init_checkers(self):
262 def init_checkers(self):
263 """Create the default checkers."""
263 """Create the default checkers."""
264 self._checkers = []
264 self._checkers = []
265 for checker in _default_checkers:
265 for checker in _default_checkers:
266 checker(
266 checker(
267 shell=self.shell, prefilter_manager=self, config=self.config
267 shell=self.shell, prefilter_manager=self, config=self.config
268 )
268 )
269
269
270 def sort_checkers(self):
270 def sort_checkers(self):
271 """Sort the checkers by priority.
271 """Sort the checkers by priority.
272
272
273 This must be called after the priority of a checker is changed.
273 This must be called after the priority of a checker is changed.
274 The :meth:`register_checker` method calls this automatically.
274 The :meth:`register_checker` method calls this automatically.
275 """
275 """
276 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
276 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
277
277
278 @property
278 @property
279 def checkers(self):
279 def checkers(self):
280 """Return a list of checkers, sorted by priority."""
280 """Return a list of checkers, sorted by priority."""
281 return self._checkers
281 return self._checkers
282
282
283 def register_checker(self, checker):
283 def register_checker(self, checker):
284 """Register a checker instance."""
284 """Register a checker instance."""
285 if checker not in self._checkers:
285 if checker not in self._checkers:
286 self._checkers.append(checker)
286 self._checkers.append(checker)
287 self.sort_checkers()
287 self.sort_checkers()
288
288
289 def unregister_checker(self, checker):
289 def unregister_checker(self, checker):
290 """Unregister a checker instance."""
290 """Unregister a checker instance."""
291 if checker in self._checkers:
291 if checker in self._checkers:
292 self._checkers.remove(checker)
292 self._checkers.remove(checker)
293
293
294 #-------------------------------------------------------------------------
294 #-------------------------------------------------------------------------
295 # API for managing checkers
295 # API for managing checkers
296 #-------------------------------------------------------------------------
296 #-------------------------------------------------------------------------
297
297
298 def init_handlers(self):
298 def init_handlers(self):
299 """Create the default handlers."""
299 """Create the default handlers."""
300 self._handlers = {}
300 self._handlers = {}
301 self._esc_handlers = {}
301 self._esc_handlers = {}
302 for handler in _default_handlers:
302 for handler in _default_handlers:
303 handler(
303 handler(
304 shell=self.shell, prefilter_manager=self, config=self.config
304 shell=self.shell, prefilter_manager=self, config=self.config
305 )
305 )
306
306
307 @property
307 @property
308 def handlers(self):
308 def handlers(self):
309 """Return a dict of all the handlers."""
309 """Return a dict of all the handlers."""
310 return self._handlers
310 return self._handlers
311
311
312 def register_handler(self, name, handler, esc_strings):
312 def register_handler(self, name, handler, esc_strings):
313 """Register a handler instance by name with esc_strings."""
313 """Register a handler instance by name with esc_strings."""
314 self._handlers[name] = handler
314 self._handlers[name] = handler
315 for esc_str in esc_strings:
315 for esc_str in esc_strings:
316 self._esc_handlers[esc_str] = handler
316 self._esc_handlers[esc_str] = handler
317
317
318 def unregister_handler(self, name, handler, esc_strings):
318 def unregister_handler(self, name, handler, esc_strings):
319 """Unregister a handler instance by name with esc_strings."""
319 """Unregister a handler instance by name with esc_strings."""
320 try:
320 try:
321 del self._handlers[name]
321 del self._handlers[name]
322 except KeyError:
322 except KeyError:
323 pass
323 pass
324 for esc_str in esc_strings:
324 for esc_str in esc_strings:
325 h = self._esc_handlers.get(esc_str)
325 h = self._esc_handlers.get(esc_str)
326 if h is handler:
326 if h is handler:
327 del self._esc_handlers[esc_str]
327 del self._esc_handlers[esc_str]
328
328
329 def get_handler_by_name(self, name):
329 def get_handler_by_name(self, name):
330 """Get a handler by its name."""
330 """Get a handler by its name."""
331 return self._handlers.get(name)
331 return self._handlers.get(name)
332
332
333 def get_handler_by_esc(self, esc_str):
333 def get_handler_by_esc(self, esc_str):
334 """Get a handler by its escape string."""
334 """Get a handler by its escape string."""
335 return self._esc_handlers.get(esc_str)
335 return self._esc_handlers.get(esc_str)
336
336
337 #-------------------------------------------------------------------------
337 #-------------------------------------------------------------------------
338 # Main prefiltering API
338 # Main prefiltering API
339 #-------------------------------------------------------------------------
339 #-------------------------------------------------------------------------
340
340
341 def prefilter_line_info(self, line_info):
341 def prefilter_line_info(self, line_info):
342 """Prefilter a line that has been converted to a LineInfo object.
342 """Prefilter a line that has been converted to a LineInfo object.
343
343
344 This implements the checker/handler part of the prefilter pipe.
344 This implements the checker/handler part of the prefilter pipe.
345 """
345 """
346 # print "prefilter_line_info: ", line_info
346 # print "prefilter_line_info: ", line_info
347 handler = self.find_handler(line_info)
347 handler = self.find_handler(line_info)
348 return handler.handle(line_info)
348 return handler.handle(line_info)
349
349
350 def find_handler(self, line_info):
350 def find_handler(self, line_info):
351 """Find a handler for the line_info by trying checkers."""
351 """Find a handler for the line_info by trying checkers."""
352 for checker in self.checkers:
352 for checker in self.checkers:
353 if checker.enabled:
353 if checker.enabled:
354 handler = checker.check(line_info)
354 handler = checker.check(line_info)
355 if handler:
355 if handler:
356 return handler
356 return handler
357 return self.get_handler_by_name('normal')
357 return self.get_handler_by_name('normal')
358
358
359 def transform_line(self, line, continue_prompt):
359 def transform_line(self, line, continue_prompt):
360 """Calls the enabled transformers in order of increasing priority."""
360 """Calls the enabled transformers in order of increasing priority."""
361 for transformer in self.transformers:
361 for transformer in self.transformers:
362 if transformer.enabled:
362 if transformer.enabled:
363 line = transformer.transform(line, continue_prompt)
363 line = transformer.transform(line, continue_prompt)
364 return line
364 return line
365
365
366 def prefilter_line(self, line, continue_prompt=False):
366 def prefilter_line(self, line, continue_prompt=False):
367 """Prefilter a single input line as text.
367 """Prefilter a single input line as text.
368
368
369 This method prefilters a single line of text by calling the
369 This method prefilters a single line of text by calling the
370 transformers and then the checkers/handlers.
370 transformers and then the checkers/handlers.
371 """
371 """
372
372
373 # print "prefilter_line: ", line, continue_prompt
373 # print "prefilter_line: ", line, continue_prompt
374 # All handlers *must* return a value, even if it's blank ('').
374 # All handlers *must* return a value, even if it's blank ('').
375
375
376 # Lines are NOT logged here. Handlers should process the line as
376 # Lines are NOT logged here. Handlers should process the line as
377 # needed, update the cache AND log it (so that the input cache array
377 # needed, update the cache AND log it (so that the input cache array
378 # stays synced).
378 # stays synced).
379
379
380 # save the line away in case we crash, so the post-mortem handler can
380 # save the line away in case we crash, so the post-mortem handler can
381 # record it
381 # record it
382 self.shell._last_input_line = line
382 self.shell._last_input_line = line
383
383
384 if not line:
384 if not line:
385 # Return immediately on purely empty lines, so that if the user
385 # Return immediately on purely empty lines, so that if the user
386 # previously typed some whitespace that started a continuation
386 # previously typed some whitespace that started a continuation
387 # prompt, he can break out of that loop with just an empty line.
387 # prompt, he can break out of that loop with just an empty line.
388 # This is how the default python prompt works.
388 # This is how the default python prompt works.
389
389
390 # Only return if the accumulated input buffer was just whitespace!
390 # Only return if the accumulated input buffer was just whitespace!
391 if ''.join(self.shell.buffer).isspace():
391 if ''.join(self.shell.buffer).isspace():
392 self.shell.buffer[:] = []
392 self.shell.buffer[:] = []
393 return ''
393 return ''
394
394
395 # At this point, we invoke our transformers.
395 # At this point, we invoke our transformers.
396 if not continue_prompt or (continue_prompt and self.multi_line_specials):
396 if not continue_prompt or (continue_prompt and self.multi_line_specials):
397 line = self.transform_line(line, continue_prompt)
397 line = self.transform_line(line, continue_prompt)
398
398
399 # Now we compute line_info for the checkers and handlers
399 # Now we compute line_info for the checkers and handlers
400 line_info = LineInfo(line, continue_prompt)
400 line_info = LineInfo(line, continue_prompt)
401
401
402 # the input history needs to track even empty lines
402 # the input history needs to track even empty lines
403 stripped = line.strip()
403 stripped = line.strip()
404
404
405 normal_handler = self.get_handler_by_name('normal')
405 normal_handler = self.get_handler_by_name('normal')
406 if not stripped:
406 if not stripped:
407 if not continue_prompt:
407 if not continue_prompt:
408 self.shell.outputcache.prompt_count -= 1
408 self.shell.outputcache.prompt_count -= 1
409
409
410 return normal_handler.handle(line_info)
410 return normal_handler.handle(line_info)
411
411
412 # special handlers are only allowed for single line statements
412 # special handlers are only allowed for single line statements
413 if continue_prompt and not self.multi_line_specials:
413 if continue_prompt and not self.multi_line_specials:
414 return normal_handler.handle(line_info)
414 return normal_handler.handle(line_info)
415
415
416 prefiltered = self.prefilter_line_info(line_info)
416 prefiltered = self.prefilter_line_info(line_info)
417 # print "prefiltered line: %r" % prefiltered
417 # print "prefiltered line: %r" % prefiltered
418 return prefiltered
418 return prefiltered
419
419
420 def prefilter_lines(self, lines, continue_prompt=False):
420 def prefilter_lines(self, lines, continue_prompt=False):
421 """Prefilter multiple input lines of text.
421 """Prefilter multiple input lines of text.
422
422
423 This is the main entry point for prefiltering multiple lines of
423 This is the main entry point for prefiltering multiple lines of
424 input. This simply calls :meth:`prefilter_line` for each line of
424 input. This simply calls :meth:`prefilter_line` for each line of
425 input.
425 input.
426
426
427 This covers cases where there are multiple lines in the user entry,
427 This covers cases where there are multiple lines in the user entry,
428 which is the case when the user goes back to a multiline history
428 which is the case when the user goes back to a multiline history
429 entry and presses enter.
429 entry and presses enter.
430 """
430 """
431 llines = lines.rstrip('\n').split('\n')
431 llines = lines.rstrip('\n').split('\n')
432 # We can get multiple lines in one shot, where multiline input 'blends'
432 # We can get multiple lines in one shot, where multiline input 'blends'
433 # into one line, in cases like recalling from the readline history
433 # into one line, in cases like recalling from the readline history
434 # buffer. We need to make sure that in such cases, we correctly
434 # buffer. We need to make sure that in such cases, we correctly
435 # communicate downstream which line is first and which are continuation
435 # communicate downstream which line is first and which are continuation
436 # ones.
436 # ones.
437 if len(llines) > 1:
437 if len(llines) > 1:
438 out = '\n'.join([self.prefilter_line(line, lnum>0)
438 out = '\n'.join([self.prefilter_line(line, lnum>0)
439 for lnum, line in enumerate(llines) ])
439 for lnum, line in enumerate(llines) ])
440 else:
440 else:
441 out = self.prefilter_line(llines[0], continue_prompt)
441 out = self.prefilter_line(llines[0], continue_prompt)
442
442
443 return out
443 return out
444
444
445 #-----------------------------------------------------------------------------
445 #-----------------------------------------------------------------------------
446 # Prefilter transformers
446 # Prefilter transformers
447 #-----------------------------------------------------------------------------
447 #-----------------------------------------------------------------------------
448
448
449
449
450 class PrefilterTransformer(Configurable):
450 class PrefilterTransformer(Configurable):
451 """Transform a line of user input."""
451 """Transform a line of user input."""
452
452
453 priority = Int(100, config=True)
453 priority = Int(100, config=True)
454 # Transformers don't currently use shell or prefilter_manager, but as we
454 # Transformers don't currently use shell or prefilter_manager, but as we
455 # move away from checkers and handlers, they will need them.
455 # move away from checkers and handlers, they will need them.
456 shell = Instance('IPython.core.iplib.InteractiveShellABC')
456 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
457 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
457 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
458 enabled = Bool(True, config=True)
458 enabled = Bool(True, config=True)
459
459
460 def __init__(self, shell=None, prefilter_manager=None, config=None):
460 def __init__(self, shell=None, prefilter_manager=None, config=None):
461 super(PrefilterTransformer, self).__init__(
461 super(PrefilterTransformer, self).__init__(
462 shell=shell, prefilter_manager=prefilter_manager, config=config
462 shell=shell, prefilter_manager=prefilter_manager, config=config
463 )
463 )
464 self.prefilter_manager.register_transformer(self)
464 self.prefilter_manager.register_transformer(self)
465
465
466 def transform(self, line, continue_prompt):
466 def transform(self, line, continue_prompt):
467 """Transform a line, returning the new one."""
467 """Transform a line, returning the new one."""
468 return None
468 return None
469
469
470 def __repr__(self):
470 def __repr__(self):
471 return "<%s(priority=%r, enabled=%r)>" % (
471 return "<%s(priority=%r, enabled=%r)>" % (
472 self.__class__.__name__, self.priority, self.enabled)
472 self.__class__.__name__, self.priority, self.enabled)
473
473
474
474
475 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
475 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
476 r'\s*=\s*!(?P<cmd>.*)')
476 r'\s*=\s*!(?P<cmd>.*)')
477
477
478
478
479 class AssignSystemTransformer(PrefilterTransformer):
479 class AssignSystemTransformer(PrefilterTransformer):
480 """Handle the `files = !ls` syntax."""
480 """Handle the `files = !ls` syntax."""
481
481
482 priority = Int(100, config=True)
482 priority = Int(100, config=True)
483
483
484 def transform(self, line, continue_prompt):
484 def transform(self, line, continue_prompt):
485 m = _assign_system_re.match(line)
485 m = _assign_system_re.match(line)
486 if m is not None:
486 if m is not None:
487 cmd = m.group('cmd')
487 cmd = m.group('cmd')
488 lhs = m.group('lhs')
488 lhs = m.group('lhs')
489 expr = make_quoted_expr("sc -l =%s" % cmd)
489 expr = make_quoted_expr("sc -l =%s" % cmd)
490 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
490 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
491 return new_line
491 return new_line
492 return line
492 return line
493
493
494
494
495 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
495 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
496 r'\s*=\s*%(?P<cmd>.*)')
496 r'\s*=\s*%(?P<cmd>.*)')
497
497
498 class AssignMagicTransformer(PrefilterTransformer):
498 class AssignMagicTransformer(PrefilterTransformer):
499 """Handle the `a = %who` syntax."""
499 """Handle the `a = %who` syntax."""
500
500
501 priority = Int(200, config=True)
501 priority = Int(200, config=True)
502
502
503 def transform(self, line, continue_prompt):
503 def transform(self, line, continue_prompt):
504 m = _assign_magic_re.match(line)
504 m = _assign_magic_re.match(line)
505 if m is not None:
505 if m is not None:
506 cmd = m.group('cmd')
506 cmd = m.group('cmd')
507 lhs = m.group('lhs')
507 lhs = m.group('lhs')
508 expr = make_quoted_expr(cmd)
508 expr = make_quoted_expr(cmd)
509 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
509 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
510 return new_line
510 return new_line
511 return line
511 return line
512
512
513
513
514 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
514 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
515
515
516 class PyPromptTransformer(PrefilterTransformer):
516 class PyPromptTransformer(PrefilterTransformer):
517 """Handle inputs that start with '>>> ' syntax."""
517 """Handle inputs that start with '>>> ' syntax."""
518
518
519 priority = Int(50, config=True)
519 priority = Int(50, config=True)
520
520
521 def transform(self, line, continue_prompt):
521 def transform(self, line, continue_prompt):
522
522
523 if not line or line.isspace() or line.strip() == '...':
523 if not line or line.isspace() or line.strip() == '...':
524 # This allows us to recognize multiple input prompts separated by
524 # This allows us to recognize multiple input prompts separated by
525 # blank lines and pasted in a single chunk, very common when
525 # blank lines and pasted in a single chunk, very common when
526 # pasting doctests or long tutorial passages.
526 # pasting doctests or long tutorial passages.
527 return ''
527 return ''
528 m = _classic_prompt_re.match(line)
528 m = _classic_prompt_re.match(line)
529 if m:
529 if m:
530 return line[len(m.group(0)):]
530 return line[len(m.group(0)):]
531 else:
531 else:
532 return line
532 return line
533
533
534
534
535 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
535 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
536
536
537 class IPyPromptTransformer(PrefilterTransformer):
537 class IPyPromptTransformer(PrefilterTransformer):
538 """Handle inputs that start classic IPython prompt syntax."""
538 """Handle inputs that start classic IPython prompt syntax."""
539
539
540 priority = Int(50, config=True)
540 priority = Int(50, config=True)
541
541
542 def transform(self, line, continue_prompt):
542 def transform(self, line, continue_prompt):
543
543
544 if not line or line.isspace() or line.strip() == '...':
544 if not line or line.isspace() or line.strip() == '...':
545 # This allows us to recognize multiple input prompts separated by
545 # This allows us to recognize multiple input prompts separated by
546 # blank lines and pasted in a single chunk, very common when
546 # blank lines and pasted in a single chunk, very common when
547 # pasting doctests or long tutorial passages.
547 # pasting doctests or long tutorial passages.
548 return ''
548 return ''
549 m = _ipy_prompt_re.match(line)
549 m = _ipy_prompt_re.match(line)
550 if m:
550 if m:
551 return line[len(m.group(0)):]
551 return line[len(m.group(0)):]
552 else:
552 else:
553 return line
553 return line
554
554
555 #-----------------------------------------------------------------------------
555 #-----------------------------------------------------------------------------
556 # Prefilter checkers
556 # Prefilter checkers
557 #-----------------------------------------------------------------------------
557 #-----------------------------------------------------------------------------
558
558
559
559
560 class PrefilterChecker(Configurable):
560 class PrefilterChecker(Configurable):
561 """Inspect an input line and return a handler for that line."""
561 """Inspect an input line and return a handler for that line."""
562
562
563 priority = Int(100, config=True)
563 priority = Int(100, config=True)
564 shell = Instance('IPython.core.iplib.InteractiveShellABC')
564 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
565 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
565 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
566 enabled = Bool(True, config=True)
566 enabled = Bool(True, config=True)
567
567
568 def __init__(self, shell=None, prefilter_manager=None, config=None):
568 def __init__(self, shell=None, prefilter_manager=None, config=None):
569 super(PrefilterChecker, self).__init__(
569 super(PrefilterChecker, self).__init__(
570 shell=shell, prefilter_manager=prefilter_manager, config=config
570 shell=shell, prefilter_manager=prefilter_manager, config=config
571 )
571 )
572 self.prefilter_manager.register_checker(self)
572 self.prefilter_manager.register_checker(self)
573
573
574 def check(self, line_info):
574 def check(self, line_info):
575 """Inspect line_info and return a handler instance or None."""
575 """Inspect line_info and return a handler instance or None."""
576 return None
576 return None
577
577
578 def __repr__(self):
578 def __repr__(self):
579 return "<%s(priority=%r, enabled=%r)>" % (
579 return "<%s(priority=%r, enabled=%r)>" % (
580 self.__class__.__name__, self.priority, self.enabled)
580 self.__class__.__name__, self.priority, self.enabled)
581
581
582
582
583 class EmacsChecker(PrefilterChecker):
583 class EmacsChecker(PrefilterChecker):
584
584
585 priority = Int(100, config=True)
585 priority = Int(100, config=True)
586 enabled = Bool(False, config=True)
586 enabled = Bool(False, config=True)
587
587
588 def check(self, line_info):
588 def check(self, line_info):
589 "Emacs ipython-mode tags certain input lines."
589 "Emacs ipython-mode tags certain input lines."
590 if line_info.line.endswith('# PYTHON-MODE'):
590 if line_info.line.endswith('# PYTHON-MODE'):
591 return self.prefilter_manager.get_handler_by_name('emacs')
591 return self.prefilter_manager.get_handler_by_name('emacs')
592 else:
592 else:
593 return None
593 return None
594
594
595
595
596 class ShellEscapeChecker(PrefilterChecker):
596 class ShellEscapeChecker(PrefilterChecker):
597
597
598 priority = Int(200, config=True)
598 priority = Int(200, config=True)
599
599
600 def check(self, line_info):
600 def check(self, line_info):
601 if line_info.line.lstrip().startswith(ESC_SHELL):
601 if line_info.line.lstrip().startswith(ESC_SHELL):
602 return self.prefilter_manager.get_handler_by_name('shell')
602 return self.prefilter_manager.get_handler_by_name('shell')
603
603
604
604
605 class IPyAutocallChecker(PrefilterChecker):
605 class IPyAutocallChecker(PrefilterChecker):
606
606
607 priority = Int(300, config=True)
607 priority = Int(300, config=True)
608
608
609 def check(self, line_info):
609 def check(self, line_info):
610 "Instances of IPyAutocall in user_ns get autocalled immediately"
610 "Instances of IPyAutocall in user_ns get autocalled immediately"
611 obj = self.shell.user_ns.get(line_info.ifun, None)
611 obj = self.shell.user_ns.get(line_info.ifun, None)
612 if isinstance(obj, IPyAutocall):
612 if isinstance(obj, IPyAutocall):
613 obj.set_ip(self.shell)
613 obj.set_ip(self.shell)
614 return self.prefilter_manager.get_handler_by_name('auto')
614 return self.prefilter_manager.get_handler_by_name('auto')
615 else:
615 else:
616 return None
616 return None
617
617
618
618
619 class MultiLineMagicChecker(PrefilterChecker):
619 class MultiLineMagicChecker(PrefilterChecker):
620
620
621 priority = Int(400, config=True)
621 priority = Int(400, config=True)
622
622
623 def check(self, line_info):
623 def check(self, line_info):
624 "Allow ! and !! in multi-line statements if multi_line_specials is on"
624 "Allow ! and !! in multi-line statements if multi_line_specials is on"
625 # Note that this one of the only places we check the first character of
625 # Note that this one of the only places we check the first character of
626 # ifun and *not* the pre_char. Also note that the below test matches
626 # ifun and *not* the pre_char. Also note that the below test matches
627 # both ! and !!.
627 # both ! and !!.
628 if line_info.continue_prompt \
628 if line_info.continue_prompt \
629 and self.prefilter_manager.multi_line_specials:
629 and self.prefilter_manager.multi_line_specials:
630 if line_info.ifun.startswith(ESC_MAGIC):
630 if line_info.ifun.startswith(ESC_MAGIC):
631 return self.prefilter_manager.get_handler_by_name('magic')
631 return self.prefilter_manager.get_handler_by_name('magic')
632 else:
632 else:
633 return None
633 return None
634
634
635
635
636 class EscCharsChecker(PrefilterChecker):
636 class EscCharsChecker(PrefilterChecker):
637
637
638 priority = Int(500, config=True)
638 priority = Int(500, config=True)
639
639
640 def check(self, line_info):
640 def check(self, line_info):
641 """Check for escape character and return either a handler to handle it,
641 """Check for escape character and return either a handler to handle it,
642 or None if there is no escape char."""
642 or None if there is no escape char."""
643 if line_info.line[-1] == ESC_HELP \
643 if line_info.line[-1] == ESC_HELP \
644 and line_info.pre_char != ESC_SHELL \
644 and line_info.pre_char != ESC_SHELL \
645 and line_info.pre_char != ESC_SH_CAP:
645 and line_info.pre_char != ESC_SH_CAP:
646 # the ? can be at the end, but *not* for either kind of shell escape,
646 # the ? can be at the end, but *not* for either kind of shell escape,
647 # because a ? can be a vaild final char in a shell cmd
647 # because a ? can be a vaild final char in a shell cmd
648 return self.prefilter_manager.get_handler_by_name('help')
648 return self.prefilter_manager.get_handler_by_name('help')
649 else:
649 else:
650 # This returns None like it should if no handler exists
650 # This returns None like it should if no handler exists
651 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
651 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
652
652
653
653
654 class AssignmentChecker(PrefilterChecker):
654 class AssignmentChecker(PrefilterChecker):
655
655
656 priority = Int(600, config=True)
656 priority = Int(600, config=True)
657
657
658 def check(self, line_info):
658 def check(self, line_info):
659 """Check to see if user is assigning to a var for the first time, in
659 """Check to see if user is assigning to a var for the first time, in
660 which case we want to avoid any sort of automagic / autocall games.
660 which case we want to avoid any sort of automagic / autocall games.
661
661
662 This allows users to assign to either alias or magic names true python
662 This allows users to assign to either alias or magic names true python
663 variables (the magic/alias systems always take second seat to true
663 variables (the magic/alias systems always take second seat to true
664 python code). E.g. ls='hi', or ls,that=1,2"""
664 python code). E.g. ls='hi', or ls,that=1,2"""
665 if line_info.the_rest:
665 if line_info.the_rest:
666 if line_info.the_rest[0] in '=,':
666 if line_info.the_rest[0] in '=,':
667 return self.prefilter_manager.get_handler_by_name('normal')
667 return self.prefilter_manager.get_handler_by_name('normal')
668 else:
668 else:
669 return None
669 return None
670
670
671
671
672 class AutoMagicChecker(PrefilterChecker):
672 class AutoMagicChecker(PrefilterChecker):
673
673
674 priority = Int(700, config=True)
674 priority = Int(700, config=True)
675
675
676 def check(self, line_info):
676 def check(self, line_info):
677 """If the ifun is magic, and automagic is on, run it. Note: normal,
677 """If the ifun is magic, and automagic is on, run it. Note: normal,
678 non-auto magic would already have been triggered via '%' in
678 non-auto magic would already have been triggered via '%' in
679 check_esc_chars. This just checks for automagic. Also, before
679 check_esc_chars. This just checks for automagic. Also, before
680 triggering the magic handler, make sure that there is nothing in the
680 triggering the magic handler, make sure that there is nothing in the
681 user namespace which could shadow it."""
681 user namespace which could shadow it."""
682 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
682 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
683 return None
683 return None
684
684
685 # We have a likely magic method. Make sure we should actually call it.
685 # We have a likely magic method. Make sure we should actually call it.
686 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
686 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
687 return None
687 return None
688
688
689 head = line_info.ifun.split('.',1)[0]
689 head = line_info.ifun.split('.',1)[0]
690 if is_shadowed(head, self.shell):
690 if is_shadowed(head, self.shell):
691 return None
691 return None
692
692
693 return self.prefilter_manager.get_handler_by_name('magic')
693 return self.prefilter_manager.get_handler_by_name('magic')
694
694
695
695
696 class AliasChecker(PrefilterChecker):
696 class AliasChecker(PrefilterChecker):
697
697
698 priority = Int(800, config=True)
698 priority = Int(800, config=True)
699
699
700 def check(self, line_info):
700 def check(self, line_info):
701 "Check if the initital identifier on the line is an alias."
701 "Check if the initital identifier on the line is an alias."
702 # Note: aliases can not contain '.'
702 # Note: aliases can not contain '.'
703 head = line_info.ifun.split('.',1)[0]
703 head = line_info.ifun.split('.',1)[0]
704 if line_info.ifun not in self.shell.alias_manager \
704 if line_info.ifun not in self.shell.alias_manager \
705 or head not in self.shell.alias_manager \
705 or head not in self.shell.alias_manager \
706 or is_shadowed(head, self.shell):
706 or is_shadowed(head, self.shell):
707 return None
707 return None
708
708
709 return self.prefilter_manager.get_handler_by_name('alias')
709 return self.prefilter_manager.get_handler_by_name('alias')
710
710
711
711
712 class PythonOpsChecker(PrefilterChecker):
712 class PythonOpsChecker(PrefilterChecker):
713
713
714 priority = Int(900, config=True)
714 priority = Int(900, config=True)
715
715
716 def check(self, line_info):
716 def check(self, line_info):
717 """If the 'rest' of the line begins with a function call or pretty much
717 """If the 'rest' of the line begins with a function call or pretty much
718 any python operator, we should simply execute the line (regardless of
718 any python operator, we should simply execute the line (regardless of
719 whether or not there's a possible autocall expansion). This avoids
719 whether or not there's a possible autocall expansion). This avoids
720 spurious (and very confusing) geattr() accesses."""
720 spurious (and very confusing) geattr() accesses."""
721 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
721 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
722 return self.prefilter_manager.get_handler_by_name('normal')
722 return self.prefilter_manager.get_handler_by_name('normal')
723 else:
723 else:
724 return None
724 return None
725
725
726
726
727 class AutocallChecker(PrefilterChecker):
727 class AutocallChecker(PrefilterChecker):
728
728
729 priority = Int(1000, config=True)
729 priority = Int(1000, config=True)
730
730
731 def check(self, line_info):
731 def check(self, line_info):
732 "Check if the initial word/function is callable and autocall is on."
732 "Check if the initial word/function is callable and autocall is on."
733 if not self.shell.autocall:
733 if not self.shell.autocall:
734 return None
734 return None
735
735
736 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
736 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
737 if not oinfo['found']:
737 if not oinfo['found']:
738 return None
738 return None
739
739
740 if callable(oinfo['obj']) \
740 if callable(oinfo['obj']) \
741 and (not re_exclude_auto.match(line_info.the_rest)) \
741 and (not re_exclude_auto.match(line_info.the_rest)) \
742 and re_fun_name.match(line_info.ifun):
742 and re_fun_name.match(line_info.ifun):
743 return self.prefilter_manager.get_handler_by_name('auto')
743 return self.prefilter_manager.get_handler_by_name('auto')
744 else:
744 else:
745 return None
745 return None
746
746
747
747
748 #-----------------------------------------------------------------------------
748 #-----------------------------------------------------------------------------
749 # Prefilter handlers
749 # Prefilter handlers
750 #-----------------------------------------------------------------------------
750 #-----------------------------------------------------------------------------
751
751
752
752
753 class PrefilterHandler(Configurable):
753 class PrefilterHandler(Configurable):
754
754
755 handler_name = Str('normal')
755 handler_name = Str('normal')
756 esc_strings = List([])
756 esc_strings = List([])
757 shell = Instance('IPython.core.iplib.InteractiveShellABC')
757 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
758 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
758 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
759
759
760 def __init__(self, shell=None, prefilter_manager=None, config=None):
760 def __init__(self, shell=None, prefilter_manager=None, config=None):
761 super(PrefilterHandler, self).__init__(
761 super(PrefilterHandler, self).__init__(
762 shell=shell, prefilter_manager=prefilter_manager, config=config
762 shell=shell, prefilter_manager=prefilter_manager, config=config
763 )
763 )
764 self.prefilter_manager.register_handler(
764 self.prefilter_manager.register_handler(
765 self.handler_name,
765 self.handler_name,
766 self,
766 self,
767 self.esc_strings
767 self.esc_strings
768 )
768 )
769
769
770 def handle(self, line_info):
770 def handle(self, line_info):
771 # print "normal: ", line_info
771 # print "normal: ", line_info
772 """Handle normal input lines. Use as a template for handlers."""
772 """Handle normal input lines. Use as a template for handlers."""
773
773
774 # With autoindent on, we need some way to exit the input loop, and I
774 # With autoindent on, we need some way to exit the input loop, and I
775 # don't want to force the user to have to backspace all the way to
775 # don't want to force the user to have to backspace all the way to
776 # clear the line. The rule will be in this case, that either two
776 # clear the line. The rule will be in this case, that either two
777 # lines of pure whitespace in a row, or a line of pure whitespace but
777 # lines of pure whitespace in a row, or a line of pure whitespace but
778 # of a size different to the indent level, will exit the input loop.
778 # of a size different to the indent level, will exit the input loop.
779 line = line_info.line
779 line = line_info.line
780 continue_prompt = line_info.continue_prompt
780 continue_prompt = line_info.continue_prompt
781
781
782 if (continue_prompt and
782 if (continue_prompt and
783 self.shell.autoindent and
783 self.shell.autoindent and
784 line.isspace() and
784 line.isspace() and
785
785
786 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
786 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
787 or
787 or
788 not self.shell.buffer
788 not self.shell.buffer
789 or
789 or
790 (self.shell.buffer[-1]).isspace()
790 (self.shell.buffer[-1]).isspace()
791 )
791 )
792 ):
792 ):
793 line = ''
793 line = ''
794
794
795 self.shell.log(line, line, continue_prompt)
795 self.shell.log(line, line, continue_prompt)
796 return line
796 return line
797
797
798 def __str__(self):
798 def __str__(self):
799 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
799 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
800
800
801
801
802 class AliasHandler(PrefilterHandler):
802 class AliasHandler(PrefilterHandler):
803
803
804 handler_name = Str('alias')
804 handler_name = Str('alias')
805
805
806 def handle(self, line_info):
806 def handle(self, line_info):
807 """Handle alias input lines. """
807 """Handle alias input lines. """
808 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
808 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
809 # pre is needed, because it carries the leading whitespace. Otherwise
809 # pre is needed, because it carries the leading whitespace. Otherwise
810 # aliases won't work in indented sections.
810 # aliases won't work in indented sections.
811 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
811 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
812 make_quoted_expr(transformed))
812 make_quoted_expr(transformed))
813
813
814 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
814 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
815 return line_out
815 return line_out
816
816
817
817
818 class ShellEscapeHandler(PrefilterHandler):
818 class ShellEscapeHandler(PrefilterHandler):
819
819
820 handler_name = Str('shell')
820 handler_name = Str('shell')
821 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
821 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
822
822
823 def handle(self, line_info):
823 def handle(self, line_info):
824 """Execute the line in a shell, empty return value"""
824 """Execute the line in a shell, empty return value"""
825 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
825 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
826
826
827 line = line_info.line
827 line = line_info.line
828 if line.lstrip().startswith(ESC_SH_CAP):
828 if line.lstrip().startswith(ESC_SH_CAP):
829 # rewrite LineInfo's line, ifun and the_rest to properly hold the
829 # rewrite LineInfo's line, ifun and the_rest to properly hold the
830 # call to %sx and the actual command to be executed, so
830 # call to %sx and the actual command to be executed, so
831 # handle_magic can work correctly. Note that this works even if
831 # handle_magic can work correctly. Note that this works even if
832 # the line is indented, so it handles multi_line_specials
832 # the line is indented, so it handles multi_line_specials
833 # properly.
833 # properly.
834 new_rest = line.lstrip()[2:]
834 new_rest = line.lstrip()[2:]
835 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
835 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
836 line_info.ifun = 'sx'
836 line_info.ifun = 'sx'
837 line_info.the_rest = new_rest
837 line_info.the_rest = new_rest
838 return magic_handler.handle(line_info)
838 return magic_handler.handle(line_info)
839 else:
839 else:
840 cmd = line.lstrip().lstrip(ESC_SHELL)
840 cmd = line.lstrip().lstrip(ESC_SHELL)
841 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
841 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
842 make_quoted_expr(cmd))
842 make_quoted_expr(cmd))
843 # update cache/log and return
843 # update cache/log and return
844 self.shell.log(line, line_out, line_info.continue_prompt)
844 self.shell.log(line, line_out, line_info.continue_prompt)
845 return line_out
845 return line_out
846
846
847
847
848 class MagicHandler(PrefilterHandler):
848 class MagicHandler(PrefilterHandler):
849
849
850 handler_name = Str('magic')
850 handler_name = Str('magic')
851 esc_strings = List([ESC_MAGIC])
851 esc_strings = List([ESC_MAGIC])
852
852
853 def handle(self, line_info):
853 def handle(self, line_info):
854 """Execute magic functions."""
854 """Execute magic functions."""
855 ifun = line_info.ifun
855 ifun = line_info.ifun
856 the_rest = line_info.the_rest
856 the_rest = line_info.the_rest
857 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
857 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
858 make_quoted_expr(ifun + " " + the_rest))
858 make_quoted_expr(ifun + " " + the_rest))
859 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
859 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
860 return cmd
860 return cmd
861
861
862
862
863 class AutoHandler(PrefilterHandler):
863 class AutoHandler(PrefilterHandler):
864
864
865 handler_name = Str('auto')
865 handler_name = Str('auto')
866 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
866 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
867
867
868 def handle(self, line_info):
868 def handle(self, line_info):
869 """Handle lines which can be auto-executed, quoting if requested."""
869 """Handle lines which can be auto-executed, quoting if requested."""
870 line = line_info.line
870 line = line_info.line
871 ifun = line_info.ifun
871 ifun = line_info.ifun
872 the_rest = line_info.the_rest
872 the_rest = line_info.the_rest
873 pre = line_info.pre
873 pre = line_info.pre
874 continue_prompt = line_info.continue_prompt
874 continue_prompt = line_info.continue_prompt
875 obj = line_info.ofind(self)['obj']
875 obj = line_info.ofind(self)['obj']
876 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
876 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
877
877
878 # This should only be active for single-line input!
878 # This should only be active for single-line input!
879 if continue_prompt:
879 if continue_prompt:
880 self.shell.log(line,line,continue_prompt)
880 self.shell.log(line,line,continue_prompt)
881 return line
881 return line
882
882
883 force_auto = isinstance(obj, IPyAutocall)
883 force_auto = isinstance(obj, IPyAutocall)
884 auto_rewrite = True
884 auto_rewrite = True
885
885
886 if pre == ESC_QUOTE:
886 if pre == ESC_QUOTE:
887 # Auto-quote splitting on whitespace
887 # Auto-quote splitting on whitespace
888 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
888 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
889 elif pre == ESC_QUOTE2:
889 elif pre == ESC_QUOTE2:
890 # Auto-quote whole string
890 # Auto-quote whole string
891 newcmd = '%s("%s")' % (ifun,the_rest)
891 newcmd = '%s("%s")' % (ifun,the_rest)
892 elif pre == ESC_PAREN:
892 elif pre == ESC_PAREN:
893 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
893 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
894 else:
894 else:
895 # Auto-paren.
895 # Auto-paren.
896 # We only apply it to argument-less calls if the autocall
896 # We only apply it to argument-less calls if the autocall
897 # parameter is set to 2. We only need to check that autocall is <
897 # parameter is set to 2. We only need to check that autocall is <
898 # 2, since this function isn't called unless it's at least 1.
898 # 2, since this function isn't called unless it's at least 1.
899 if not the_rest and (self.shell.autocall < 2) and not force_auto:
899 if not the_rest and (self.shell.autocall < 2) and not force_auto:
900 newcmd = '%s %s' % (ifun,the_rest)
900 newcmd = '%s %s' % (ifun,the_rest)
901 auto_rewrite = False
901 auto_rewrite = False
902 else:
902 else:
903 if not force_auto and the_rest.startswith('['):
903 if not force_auto and the_rest.startswith('['):
904 if hasattr(obj,'__getitem__'):
904 if hasattr(obj,'__getitem__'):
905 # Don't autocall in this case: item access for an object
905 # Don't autocall in this case: item access for an object
906 # which is BOTH callable and implements __getitem__.
906 # which is BOTH callable and implements __getitem__.
907 newcmd = '%s %s' % (ifun,the_rest)
907 newcmd = '%s %s' % (ifun,the_rest)
908 auto_rewrite = False
908 auto_rewrite = False
909 else:
909 else:
910 # if the object doesn't support [] access, go ahead and
910 # if the object doesn't support [] access, go ahead and
911 # autocall
911 # autocall
912 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
912 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
913 elif the_rest.endswith(';'):
913 elif the_rest.endswith(';'):
914 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
914 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
915 else:
915 else:
916 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
916 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
917
917
918 if auto_rewrite:
918 if auto_rewrite:
919 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
919 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
920
920
921 try:
921 try:
922 # plain ascii works better w/ pyreadline, on some machines, so
922 # plain ascii works better w/ pyreadline, on some machines, so
923 # we use it and only print uncolored rewrite if we have unicode
923 # we use it and only print uncolored rewrite if we have unicode
924 rw = str(rw)
924 rw = str(rw)
925 print >>Term.cout, rw
925 print >>Term.cout, rw
926 except UnicodeEncodeError:
926 except UnicodeEncodeError:
927 print "-------------->" + newcmd
927 print "-------------->" + newcmd
928
928
929 # log what is now valid Python, not the actual user input (without the
929 # log what is now valid Python, not the actual user input (without the
930 # final newline)
930 # final newline)
931 self.shell.log(line,newcmd,continue_prompt)
931 self.shell.log(line,newcmd,continue_prompt)
932 return newcmd
932 return newcmd
933
933
934
934
935 class HelpHandler(PrefilterHandler):
935 class HelpHandler(PrefilterHandler):
936
936
937 handler_name = Str('help')
937 handler_name = Str('help')
938 esc_strings = List([ESC_HELP])
938 esc_strings = List([ESC_HELP])
939
939
940 def handle(self, line_info):
940 def handle(self, line_info):
941 """Try to get some help for the object.
941 """Try to get some help for the object.
942
942
943 obj? or ?obj -> basic information.
943 obj? or ?obj -> basic information.
944 obj?? or ??obj -> more details.
944 obj?? or ??obj -> more details.
945 """
945 """
946 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
946 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
947 line = line_info.line
947 line = line_info.line
948 # We need to make sure that we don't process lines which would be
948 # We need to make sure that we don't process lines which would be
949 # otherwise valid python, such as "x=1 # what?"
949 # otherwise valid python, such as "x=1 # what?"
950 try:
950 try:
951 codeop.compile_command(line)
951 codeop.compile_command(line)
952 except SyntaxError:
952 except SyntaxError:
953 # We should only handle as help stuff which is NOT valid syntax
953 # We should only handle as help stuff which is NOT valid syntax
954 if line[0]==ESC_HELP:
954 if line[0]==ESC_HELP:
955 line = line[1:]
955 line = line[1:]
956 elif line[-1]==ESC_HELP:
956 elif line[-1]==ESC_HELP:
957 line = line[:-1]
957 line = line[:-1]
958 self.shell.log(line, '#?'+line, line_info.continue_prompt)
958 self.shell.log(line, '#?'+line, line_info.continue_prompt)
959 if line:
959 if line:
960 #print 'line:<%r>' % line # dbg
960 #print 'line:<%r>' % line # dbg
961 self.shell.magic_pinfo(line)
961 self.shell.magic_pinfo(line)
962 else:
962 else:
963 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
963 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
964 return '' # Empty string is needed here!
964 return '' # Empty string is needed here!
965 except:
965 except:
966 raise
966 raise
967 # Pass any other exceptions through to the normal handler
967 # Pass any other exceptions through to the normal handler
968 return normal_handler.handle(line_info)
968 return normal_handler.handle(line_info)
969 else:
969 else:
970 # If the code compiles ok, we should handle it normally
970 # If the code compiles ok, we should handle it normally
971 return normal_handler.handle(line_info)
971 return normal_handler.handle(line_info)
972
972
973
973
974 class EmacsHandler(PrefilterHandler):
974 class EmacsHandler(PrefilterHandler):
975
975
976 handler_name = Str('emacs')
976 handler_name = Str('emacs')
977 esc_strings = List([])
977 esc_strings = List([])
978
978
979 def handle(self, line_info):
979 def handle(self, line_info):
980 """Handle input lines marked by python-mode."""
980 """Handle input lines marked by python-mode."""
981
981
982 # Currently, nothing is done. Later more functionality can be added
982 # Currently, nothing is done. Later more functionality can be added
983 # here if needed.
983 # here if needed.
984
984
985 # The input cache shouldn't be updated
985 # The input cache shouldn't be updated
986 return line_info.line
986 return line_info.line
987
987
988
988
989 #-----------------------------------------------------------------------------
989 #-----------------------------------------------------------------------------
990 # Defaults
990 # Defaults
991 #-----------------------------------------------------------------------------
991 #-----------------------------------------------------------------------------
992
992
993
993
994 _default_transformers = [
994 _default_transformers = [
995 AssignSystemTransformer,
995 AssignSystemTransformer,
996 AssignMagicTransformer,
996 AssignMagicTransformer,
997 PyPromptTransformer,
997 PyPromptTransformer,
998 IPyPromptTransformer,
998 IPyPromptTransformer,
999 ]
999 ]
1000
1000
1001 _default_checkers = [
1001 _default_checkers = [
1002 EmacsChecker,
1002 EmacsChecker,
1003 ShellEscapeChecker,
1003 ShellEscapeChecker,
1004 IPyAutocallChecker,
1004 IPyAutocallChecker,
1005 MultiLineMagicChecker,
1005 MultiLineMagicChecker,
1006 EscCharsChecker,
1006 EscCharsChecker,
1007 AssignmentChecker,
1007 AssignmentChecker,
1008 AutoMagicChecker,
1008 AutoMagicChecker,
1009 AliasChecker,
1009 AliasChecker,
1010 PythonOpsChecker,
1010 PythonOpsChecker,
1011 AutocallChecker
1011 AutocallChecker
1012 ]
1012 ]
1013
1013
1014 _default_handlers = [
1014 _default_handlers = [
1015 PrefilterHandler,
1015 PrefilterHandler,
1016 AliasHandler,
1016 AliasHandler,
1017 ShellEscapeHandler,
1017 ShellEscapeHandler,
1018 MagicHandler,
1018 MagicHandler,
1019 AutoHandler,
1019 AutoHandler,
1020 HelpHandler,
1020 HelpHandler,
1021 EmacsHandler
1021 EmacsHandler
1022 ]
1022 ]
@@ -1,83 +1,83 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Simple utility for splitting user input.
4 Simple utility for splitting user input.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import re
23 import re
24
24
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 # Main function
26 # Main function
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28
28
29
29
30 # RegExp for splitting line contents into pre-char//first word-method//rest.
30 # RegExp for splitting line contents into pre-char//first word-method//rest.
31 # For clarity, each group in on one line.
31 # For clarity, each group in on one line.
32
32
33 # WARNING: update the regexp if the escapes in iplib are changed, as they
33 # WARNING: update the regexp if the escapes in interactiveshell are changed, as they
34 # are hardwired in.
34 # are hardwired in.
35
35
36 # Although it's not solely driven by the regex, note that:
36 # Although it's not solely driven by the regex, note that:
37 # ,;/% only trigger if they are the first character on the line
37 # ,;/% only trigger if they are the first character on the line
38 # ! and !! trigger if they are first char(s) *or* follow an indent
38 # ! and !! trigger if they are first char(s) *or* follow an indent
39 # ? triggers as first or last char.
39 # ? triggers as first or last char.
40
40
41 # The three parts of the regex are:
41 # The three parts of the regex are:
42 # 1) pre: pre_char *or* initial whitespace
42 # 1) pre: pre_char *or* initial whitespace
43 # 2) ifun: first word/method (mix of \w and '.')
43 # 2) ifun: first word/method (mix of \w and '.')
44 # 3) the_rest: rest of line (separated from ifun by space if non-empty)
44 # 3) the_rest: rest of line (separated from ifun by space if non-empty)
45 line_split = re.compile(r'^([,;/%?]|!!?|\s*)'
45 line_split = re.compile(r'^([,;/%?]|!!?|\s*)'
46 r'\s*([\w\.]+)'
46 r'\s*([\w\.]+)'
47 r'(\s+.*$|$)')
47 r'(\s+.*$|$)')
48
48
49 # r'[\w\.]+'
49 # r'[\w\.]+'
50 # r'\s*=\s*%.*'
50 # r'\s*=\s*%.*'
51
51
52 def split_user_input(line, pattern=None):
52 def split_user_input(line, pattern=None):
53 """Split user input into pre-char/whitespace, function part and rest.
53 """Split user input into pre-char/whitespace, function part and rest.
54
54
55 This is currently handles lines with '=' in them in a very inconsistent
55 This is currently handles lines with '=' in them in a very inconsistent
56 manner.
56 manner.
57 """
57 """
58
58
59 if pattern is None:
59 if pattern is None:
60 pattern = line_split
60 pattern = line_split
61 match = pattern.match(line)
61 match = pattern.match(line)
62 if not match:
62 if not match:
63 # print "match failed for line '%s'" % line
63 # print "match failed for line '%s'" % line
64 try:
64 try:
65 ifun, the_rest = line.split(None,1)
65 ifun, the_rest = line.split(None,1)
66 except ValueError:
66 except ValueError:
67 # print "split failed for line '%s'" % line
67 # print "split failed for line '%s'" % line
68 ifun, the_rest = line,''
68 ifun, the_rest = line,''
69 pre = re.match('^(\s*)(.*)',line).groups()[0]
69 pre = re.match('^(\s*)(.*)',line).groups()[0]
70 else:
70 else:
71 pre,ifun,the_rest = match.groups()
71 pre,ifun,the_rest = match.groups()
72
72
73 # ifun has to be a valid python identifier, so it better be only pure
73 # ifun has to be a valid python identifier, so it better be only pure
74 # ascii, no unicode:
74 # ascii, no unicode:
75 try:
75 try:
76 ifun = ifun.encode('ascii')
76 ifun = ifun.encode('ascii')
77 except UnicodeEncodeError:
77 except UnicodeEncodeError:
78 the_rest = ifun + u' ' + the_rest
78 the_rest = ifun + u' ' + the_rest
79 ifun = u''
79 ifun = u''
80
80
81 #print 'line:<%s>' % line # dbg
81 #print 'line:<%s>' % line # dbg
82 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest) # dbg
82 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun.strip(),the_rest) # dbg
83 return pre, ifun.strip(), the_rest.lstrip()
83 return pre, ifun.strip(), the_rest.lstrip()
@@ -1,62 +1,62 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 def test_import_completer():
4 def test_import_completer():
5 from IPython.core import completer
5 from IPython.core import completer
6
6
7 def test_import_crashhandler():
7 def test_import_crashhandler():
8 from IPython.core import crashhandler
8 from IPython.core import crashhandler
9
9
10 def test_import_debugger():
10 def test_import_debugger():
11 from IPython.core import debugger
11 from IPython.core import debugger
12
12
13 def test_import_fakemodule():
13 def test_import_fakemodule():
14 from IPython.core import fakemodule
14 from IPython.core import fakemodule
15
15
16 def test_import_excolors():
16 def test_import_excolors():
17 from IPython.core import excolors
17 from IPython.core import excolors
18
18
19 def test_import_history():
19 def test_import_history():
20 from IPython.core import history
20 from IPython.core import history
21
21
22 def test_import_hooks():
22 def test_import_hooks():
23 from IPython.core import hooks
23 from IPython.core import hooks
24
24
25 def test_import_ipapi():
25 def test_import_ipapi():
26 from IPython.core import ipapi
26 from IPython.core import ipapi
27
27
28 def test_import_iplib():
28 def test_import_interactiveshell():
29 from IPython.core import iplib
29 from IPython.core import interactiveshell
30
30
31 def test_import_logger():
31 def test_import_logger():
32 from IPython.core import logger
32 from IPython.core import logger
33
33
34 def test_import_macro():
34 def test_import_macro():
35 from IPython.core import macro
35 from IPython.core import macro
36
36
37 def test_import_magic():
37 def test_import_magic():
38 from IPython.core import magic
38 from IPython.core import magic
39
39
40 def test_import_oinspect():
40 def test_import_oinspect():
41 from IPython.core import oinspect
41 from IPython.core import oinspect
42
42
43 def test_import_outputtrap():
43 def test_import_outputtrap():
44 from IPython.core import outputtrap
44 from IPython.core import outputtrap
45
45
46 def test_import_prefilter():
46 def test_import_prefilter():
47 from IPython.core import prefilter
47 from IPython.core import prefilter
48
48
49 def test_import_prompts():
49 def test_import_prompts():
50 from IPython.core import prompts
50 from IPython.core import prompts
51
51
52 def test_import_release():
52 def test_import_release():
53 from IPython.core import release
53 from IPython.core import release
54
54
55 def test_import_shadowns():
55 def test_import_shadowns():
56 from IPython.core import shadowns
56 from IPython.core import shadowns
57
57
58 def test_import_ultratb():
58 def test_import_ultratb():
59 from IPython.core import ultratb
59 from IPython.core import ultratb
60
60
61 def test_import_usage():
61 def test_import_usage():
62 from IPython.core import usage
62 from IPython.core import usage
@@ -1,279 +1,279 b''
1 """Tests for the key iplib module, where the main ipython class is defined.
1 """Tests for the key interactiveshell module, where the main ipython class is defined.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # stdlib
7 # stdlib
8 import os
8 import os
9 import shutil
9 import shutil
10 import tempfile
10 import tempfile
11
11
12 # third party
12 # third party
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 # our own packages
15 # our own packages
16 from IPython.testing import decorators as dec
16 from IPython.testing import decorators as dec
17 from IPython.testing.globalipapp import get_ipython
17 from IPython.testing.globalipapp import get_ipython
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Globals
20 # Globals
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 # Get the public instance of IPython
23 # Get the public instance of IPython
24 ip = get_ipython()
24 ip = get_ipython()
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Test functions
27 # Test functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 @dec.parametric
30 @dec.parametric
31 def test_reset():
31 def test_reset():
32 """reset must clear most namespaces."""
32 """reset must clear most namespaces."""
33 # The number of variables in the private user_ns_hidden is not zero, but it
33 # The number of variables in the private user_ns_hidden is not zero, but it
34 # should be constant regardless of what we do
34 # should be constant regardless of what we do
35 nvars_config_ns = len(ip.user_ns_hidden)
35 nvars_config_ns = len(ip.user_ns_hidden)
36
36
37 # Check that reset runs without error
37 # Check that reset runs without error
38 ip.reset()
38 ip.reset()
39
39
40 # Once we've reset it (to clear of any junk that might have been there from
40 # Once we've reset it (to clear of any junk that might have been there from
41 # other tests, we can count how many variables are in the user's namespace
41 # other tests, we can count how many variables are in the user's namespace
42 nvars_user_ns = len(ip.user_ns)
42 nvars_user_ns = len(ip.user_ns)
43
43
44 # Now add a few variables to user_ns, and check that reset clears them
44 # Now add a few variables to user_ns, and check that reset clears them
45 ip.user_ns['x'] = 1
45 ip.user_ns['x'] = 1
46 ip.user_ns['y'] = 1
46 ip.user_ns['y'] = 1
47 ip.reset()
47 ip.reset()
48
48
49 # Finally, check that all namespaces have only as many variables as we
49 # Finally, check that all namespaces have only as many variables as we
50 # expect to find in them:
50 # expect to find in them:
51 for ns in ip.ns_refs_table:
51 for ns in ip.ns_refs_table:
52 if ns is ip.user_ns:
52 if ns is ip.user_ns:
53 nvars_expected = nvars_user_ns
53 nvars_expected = nvars_user_ns
54 elif ns is ip.user_ns_hidden:
54 elif ns is ip.user_ns_hidden:
55 nvars_expected = nvars_config_ns
55 nvars_expected = nvars_config_ns
56 else:
56 else:
57 nvars_expected = 0
57 nvars_expected = 0
58
58
59 yield nt.assert_equals(len(ns), nvars_expected)
59 yield nt.assert_equals(len(ns), nvars_expected)
60
60
61
61
62 # Tests for reporting of exceptions in various modes, handling of SystemExit,
62 # Tests for reporting of exceptions in various modes, handling of SystemExit,
63 # and %tb functionality. This is really a mix of testing ultraTB and iplib.
63 # and %tb functionality. This is really a mix of testing ultraTB and interactiveshell.
64
64
65 def doctest_tb_plain():
65 def doctest_tb_plain():
66 """
66 """
67 In [18]: xmode plain
67 In [18]: xmode plain
68 Exception reporting mode: Plain
68 Exception reporting mode: Plain
69
69
70 In [19]: run simpleerr.py
70 In [19]: run simpleerr.py
71 Traceback (most recent call last):
71 Traceback (most recent call last):
72 ...line 32, in <module>
72 ...line 32, in <module>
73 bar(mode)
73 bar(mode)
74 ...line 16, in bar
74 ...line 16, in bar
75 div0()
75 div0()
76 ...line 8, in div0
76 ...line 8, in div0
77 x/y
77 x/y
78 ZeroDivisionError: integer division or modulo by zero
78 ZeroDivisionError: integer division or modulo by zero
79 """
79 """
80
80
81
81
82 def doctest_tb_context():
82 def doctest_tb_context():
83 """
83 """
84 In [3]: xmode context
84 In [3]: xmode context
85 Exception reporting mode: Context
85 Exception reporting mode: Context
86
86
87 In [4]: run simpleerr.py
87 In [4]: run simpleerr.py
88 ---------------------------------------------------------------------------
88 ---------------------------------------------------------------------------
89 ZeroDivisionError Traceback (most recent call last)
89 ZeroDivisionError Traceback (most recent call last)
90 <BLANKLINE>
90 <BLANKLINE>
91 ... in <module>()
91 ... in <module>()
92 30 mode = 'div'
92 30 mode = 'div'
93 31
93 31
94 ---> 32 bar(mode)
94 ---> 32 bar(mode)
95 33
95 33
96 34
96 34
97 <BLANKLINE>
97 <BLANKLINE>
98 ... in bar(mode)
98 ... in bar(mode)
99 14 "bar"
99 14 "bar"
100 15 if mode=='div':
100 15 if mode=='div':
101 ---> 16 div0()
101 ---> 16 div0()
102 17 elif mode=='exit':
102 17 elif mode=='exit':
103 18 try:
103 18 try:
104 <BLANKLINE>
104 <BLANKLINE>
105 ... in div0()
105 ... in div0()
106 6 x = 1
106 6 x = 1
107 7 y = 0
107 7 y = 0
108 ----> 8 x/y
108 ----> 8 x/y
109 9
109 9
110 10 def sysexit(stat, mode):
110 10 def sysexit(stat, mode):
111 <BLANKLINE>
111 <BLANKLINE>
112 ZeroDivisionError: integer division or modulo by zero
112 ZeroDivisionError: integer division or modulo by zero
113 """
113 """
114
114
115
115
116 def doctest_tb_verbose():
116 def doctest_tb_verbose():
117 """
117 """
118 In [5]: xmode verbose
118 In [5]: xmode verbose
119 Exception reporting mode: Verbose
119 Exception reporting mode: Verbose
120
120
121 In [6]: run simpleerr.py
121 In [6]: run simpleerr.py
122 ---------------------------------------------------------------------------
122 ---------------------------------------------------------------------------
123 ZeroDivisionError Traceback (most recent call last)
123 ZeroDivisionError Traceback (most recent call last)
124 <BLANKLINE>
124 <BLANKLINE>
125 ... in <module>()
125 ... in <module>()
126 30 mode = 'div'
126 30 mode = 'div'
127 31
127 31
128 ---> 32 bar(mode)
128 ---> 32 bar(mode)
129 global bar = <function bar at ...>
129 global bar = <function bar at ...>
130 global mode = 'div'
130 global mode = 'div'
131 33
131 33
132 34
132 34
133 <BLANKLINE>
133 <BLANKLINE>
134 ... in bar(mode='div')
134 ... in bar(mode='div')
135 14 "bar"
135 14 "bar"
136 15 if mode=='div':
136 15 if mode=='div':
137 ---> 16 div0()
137 ---> 16 div0()
138 global div0 = <function div0 at ...>
138 global div0 = <function div0 at ...>
139 17 elif mode=='exit':
139 17 elif mode=='exit':
140 18 try:
140 18 try:
141 <BLANKLINE>
141 <BLANKLINE>
142 ... in div0()
142 ... in div0()
143 6 x = 1
143 6 x = 1
144 7 y = 0
144 7 y = 0
145 ----> 8 x/y
145 ----> 8 x/y
146 x = 1
146 x = 1
147 y = 0
147 y = 0
148 9
148 9
149 10 def sysexit(stat, mode):
149 10 def sysexit(stat, mode):
150 <BLANKLINE>
150 <BLANKLINE>
151 ZeroDivisionError: integer division or modulo by zero
151 ZeroDivisionError: integer division or modulo by zero
152 """
152 """
153
153
154
154
155 def doctest_tb_sysexit():
155 def doctest_tb_sysexit():
156 """
156 """
157 In [17]: %xmode plain
157 In [17]: %xmode plain
158 Exception reporting mode: Plain
158 Exception reporting mode: Plain
159
159
160 In [18]: %run simpleerr.py exit
160 In [18]: %run simpleerr.py exit
161 An exception has occurred, use %tb to see the full traceback.
161 An exception has occurred, use %tb to see the full traceback.
162 SystemExit: (1, 'Mode = exit')
162 SystemExit: (1, 'Mode = exit')
163
163
164 In [19]: %run simpleerr.py exit 2
164 In [19]: %run simpleerr.py exit 2
165 An exception has occurred, use %tb to see the full traceback.
165 An exception has occurred, use %tb to see the full traceback.
166 SystemExit: (2, 'Mode = exit')
166 SystemExit: (2, 'Mode = exit')
167
167
168 In [20]: %tb
168 In [20]: %tb
169 Traceback (most recent call last):
169 Traceback (most recent call last):
170 File ... in <module>
170 File ... in <module>
171 bar(mode)
171 bar(mode)
172 File ... line 22, in bar
172 File ... line 22, in bar
173 sysexit(stat, mode)
173 sysexit(stat, mode)
174 File ... line 11, in sysexit
174 File ... line 11, in sysexit
175 raise SystemExit(stat, 'Mode = %s' % mode)
175 raise SystemExit(stat, 'Mode = %s' % mode)
176 SystemExit: (2, 'Mode = exit')
176 SystemExit: (2, 'Mode = exit')
177
177
178 In [21]: %xmode context
178 In [21]: %xmode context
179 Exception reporting mode: Context
179 Exception reporting mode: Context
180
180
181 In [22]: %tb
181 In [22]: %tb
182 ---------------------------------------------------------------------------
182 ---------------------------------------------------------------------------
183 SystemExit Traceback (most recent call last)
183 SystemExit Traceback (most recent call last)
184 <BLANKLINE>
184 <BLANKLINE>
185 ...<module>()
185 ...<module>()
186 30 mode = 'div'
186 30 mode = 'div'
187 31
187 31
188 ---> 32 bar(mode)
188 ---> 32 bar(mode)
189 33
189 33
190 34
190 34
191 <BLANKLINE>
191 <BLANKLINE>
192 ...bar(mode)
192 ...bar(mode)
193 20 except:
193 20 except:
194 21 stat = 1
194 21 stat = 1
195 ---> 22 sysexit(stat, mode)
195 ---> 22 sysexit(stat, mode)
196 23 else:
196 23 else:
197 24 raise ValueError('Unknown mode')
197 24 raise ValueError('Unknown mode')
198 <BLANKLINE>
198 <BLANKLINE>
199 ...sysexit(stat, mode)
199 ...sysexit(stat, mode)
200 9
200 9
201 10 def sysexit(stat, mode):
201 10 def sysexit(stat, mode):
202 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
202 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
203 12
203 12
204 13 def bar(mode):
204 13 def bar(mode):
205 <BLANKLINE>
205 <BLANKLINE>
206 SystemExit: (2, 'Mode = exit')
206 SystemExit: (2, 'Mode = exit')
207
207
208 In [23]: %xmode verbose
208 In [23]: %xmode verbose
209 Exception reporting mode: Verbose
209 Exception reporting mode: Verbose
210
210
211 In [24]: %tb
211 In [24]: %tb
212 ---------------------------------------------------------------------------
212 ---------------------------------------------------------------------------
213 SystemExit Traceback (most recent call last)
213 SystemExit Traceback (most recent call last)
214 <BLANKLINE>
214 <BLANKLINE>
215 ... in <module>()
215 ... in <module>()
216 30 mode = 'div'
216 30 mode = 'div'
217 31
217 31
218 ---> 32 bar(mode)
218 ---> 32 bar(mode)
219 global bar = <function bar at ...>
219 global bar = <function bar at ...>
220 global mode = 'exit'
220 global mode = 'exit'
221 33
221 33
222 34
222 34
223 <BLANKLINE>
223 <BLANKLINE>
224 ... in bar(mode='exit')
224 ... in bar(mode='exit')
225 20 except:
225 20 except:
226 21 stat = 1
226 21 stat = 1
227 ---> 22 sysexit(stat, mode)
227 ---> 22 sysexit(stat, mode)
228 global sysexit = <function sysexit at ...>
228 global sysexit = <function sysexit at ...>
229 stat = 2
229 stat = 2
230 mode = 'exit'
230 mode = 'exit'
231 23 else:
231 23 else:
232 24 raise ValueError('Unknown mode')
232 24 raise ValueError('Unknown mode')
233 <BLANKLINE>
233 <BLANKLINE>
234 ... in sysexit(stat=2, mode='exit')
234 ... in sysexit(stat=2, mode='exit')
235 9
235 9
236 10 def sysexit(stat, mode):
236 10 def sysexit(stat, mode):
237 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
237 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
238 global SystemExit = undefined
238 global SystemExit = undefined
239 stat = 2
239 stat = 2
240 mode = 'exit'
240 mode = 'exit'
241 12
241 12
242 13 def bar(mode):
242 13 def bar(mode):
243 <BLANKLINE>
243 <BLANKLINE>
244 SystemExit: (2, 'Mode = exit')
244 SystemExit: (2, 'Mode = exit')
245 """
245 """
246
246
247
247
248 def test_runlines():
248 def test_runlines():
249 import textwrap
249 import textwrap
250 ip.runlines(['a = 10', 'a+=1'])
250 ip.runlines(['a = 10', 'a+=1'])
251 ip.runlines('assert a == 11\nassert 1')
251 ip.runlines('assert a == 11\nassert 1')
252
252
253 nt.assert_equals(ip.user_ns['a'], 11)
253 nt.assert_equals(ip.user_ns['a'], 11)
254 complex = textwrap.dedent("""
254 complex = textwrap.dedent("""
255 if 1:
255 if 1:
256 print "hello"
256 print "hello"
257 if 1:
257 if 1:
258 print "world"
258 print "world"
259
259
260 if 2:
260 if 2:
261 print "foo"
261 print "foo"
262
262
263 if 3:
263 if 3:
264 print "bar"
264 print "bar"
265
265
266 if 4:
266 if 4:
267 print "bar"
267 print "bar"
268
268
269 """)
269 """)
270 # Simply verifies that this kind of input is run
270 # Simply verifies that this kind of input is run
271 ip.runlines(complex)
271 ip.runlines(complex)
272
272
273
273
274 def test_db():
274 def test_db():
275 """Test the internal database used for variable persistence."""
275 """Test the internal database used for variable persistence."""
276 ip.db['__unittest_'] = 12
276 ip.db['__unittest_'] = 12
277 nt.assert_equals(ip.db['__unittest_'], 12)
277 nt.assert_equals(ip.db['__unittest_'], 12)
278 del ip.db['__unittest_']
278 del ip.db['__unittest_']
279 assert '__unittest_' not in ip.db
279 assert '__unittest_' not in ip.db
1 NO CONTENT: file renamed from IPython/Shell.py to IPython/deathrow/Shell.py
NO CONTENT: file renamed from IPython/Shell.py to IPython/deathrow/Shell.py
1 NO CONTENT: file renamed from IPython/iplib.py to IPython/deathrow/iplib.py
NO CONTENT: file renamed from IPython/iplib.py to IPython/deathrow/iplib.py
1 NO CONTENT: file renamed from IPython/scripts/ipython-wx to IPython/deathrow/ipython-wx
NO CONTENT: file renamed from IPython/scripts/ipython-wx to IPython/deathrow/ipython-wx
1 NO CONTENT: file renamed from IPython/scripts/ipythonx to IPython/deathrow/ipythonx
NO CONTENT: file renamed from IPython/scripts/ipythonx to IPython/deathrow/ipythonx
@@ -1,201 +1,201 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 """Magic command interface for interactive parallel work."""
4 """Magic command interface for interactive parallel work."""
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import new
17 import new
18
18
19 from IPython.core.plugin import Plugin
19 from IPython.core.plugin import Plugin
20 from IPython.utils.traitlets import Bool, Any, Instance
20 from IPython.utils.traitlets import Bool, Any, Instance
21 from IPython.utils.autoattr import auto_attr
21 from IPython.utils.autoattr import auto_attr
22 from IPython.testing import decorators as testdec
22 from IPython.testing import decorators as testdec
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Definitions of magic functions for use with IPython
25 # Definitions of magic functions for use with IPython
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 NO_ACTIVE_MULTIENGINE_CLIENT = """
29 NO_ACTIVE_MULTIENGINE_CLIENT = """
30 Use activate() on a MultiEngineClient object to activate it for magics.
30 Use activate() on a MultiEngineClient object to activate it for magics.
31 """
31 """
32
32
33
33
34 class ParalleMagic(Plugin):
34 class ParalleMagic(Plugin):
35 """A component to manage the %result, %px and %autopx magics."""
35 """A component to manage the %result, %px and %autopx magics."""
36
36
37 active_multiengine_client = Any()
37 active_multiengine_client = Any()
38 verbose = Bool(False, config=True)
38 verbose = Bool(False, config=True)
39 shell = Instance('IPython.core.iplib.InteractiveShellABC')
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
40
40
41 def __init__(self, shell=None, config=None):
41 def __init__(self, shell=None, config=None):
42 super(ParalleMagic, self).__init__(shell=shell, config=config)
42 super(ParalleMagic, self).__init__(shell=shell, config=config)
43 self._define_magics()
43 self._define_magics()
44 # A flag showing if autopx is activated or not
44 # A flag showing if autopx is activated or not
45 self.autopx = False
45 self.autopx = False
46
46
47 def _define_magics(self):
47 def _define_magics(self):
48 """Define the magic functions."""
48 """Define the magic functions."""
49 self.shell.define_magic('result', self.magic_result)
49 self.shell.define_magic('result', self.magic_result)
50 self.shell.define_magic('px', self.magic_px)
50 self.shell.define_magic('px', self.magic_px)
51 self.shell.define_magic('autopx', self.magic_autopx)
51 self.shell.define_magic('autopx', self.magic_autopx)
52
52
53 @testdec.skip_doctest
53 @testdec.skip_doctest
54 def magic_result(self, ipself, parameter_s=''):
54 def magic_result(self, ipself, parameter_s=''):
55 """Print the result of command i on all engines..
55 """Print the result of command i on all engines..
56
56
57 To use this a :class:`MultiEngineClient` instance must be created
57 To use this a :class:`MultiEngineClient` instance must be created
58 and then activated by calling its :meth:`activate` method.
58 and then activated by calling its :meth:`activate` method.
59
59
60 Then you can do the following::
60 Then you can do the following::
61
61
62 In [23]: %result
62 In [23]: %result
63 Out[23]:
63 Out[23]:
64 <Results List>
64 <Results List>
65 [0] In [6]: a = 10
65 [0] In [6]: a = 10
66 [1] In [6]: a = 10
66 [1] In [6]: a = 10
67
67
68 In [22]: %result 6
68 In [22]: %result 6
69 Out[22]:
69 Out[22]:
70 <Results List>
70 <Results List>
71 [0] In [6]: a = 10
71 [0] In [6]: a = 10
72 [1] In [6]: a = 10
72 [1] In [6]: a = 10
73 """
73 """
74 if self.active_multiengine_client is None:
74 if self.active_multiengine_client is None:
75 print NO_ACTIVE_MULTIENGINE_CLIENT
75 print NO_ACTIVE_MULTIENGINE_CLIENT
76 return
76 return
77
77
78 try:
78 try:
79 index = int(parameter_s)
79 index = int(parameter_s)
80 except:
80 except:
81 index = None
81 index = None
82 result = self.active_multiengine_client.get_result(index)
82 result = self.active_multiengine_client.get_result(index)
83 return result
83 return result
84
84
85 @testdec.skip_doctest
85 @testdec.skip_doctest
86 def magic_px(self, ipself, parameter_s=''):
86 def magic_px(self, ipself, parameter_s=''):
87 """Executes the given python command in parallel.
87 """Executes the given python command in parallel.
88
88
89 To use this a :class:`MultiEngineClient` instance must be created
89 To use this a :class:`MultiEngineClient` instance must be created
90 and then activated by calling its :meth:`activate` method.
90 and then activated by calling its :meth:`activate` method.
91
91
92 Then you can do the following::
92 Then you can do the following::
93
93
94 In [24]: %px a = 5
94 In [24]: %px a = 5
95 Parallel execution on engines: all
95 Parallel execution on engines: all
96 Out[24]:
96 Out[24]:
97 <Results List>
97 <Results List>
98 [0] In [7]: a = 5
98 [0] In [7]: a = 5
99 [1] In [7]: a = 5
99 [1] In [7]: a = 5
100 """
100 """
101
101
102 if self.active_multiengine_client is None:
102 if self.active_multiengine_client is None:
103 print NO_ACTIVE_MULTIENGINE_CLIENT
103 print NO_ACTIVE_MULTIENGINE_CLIENT
104 return
104 return
105 print "Parallel execution on engines: %s" % self.active_multiengine_client.targets
105 print "Parallel execution on engines: %s" % self.active_multiengine_client.targets
106 result = self.active_multiengine_client.execute(parameter_s)
106 result = self.active_multiengine_client.execute(parameter_s)
107 return result
107 return result
108
108
109 @testdec.skip_doctest
109 @testdec.skip_doctest
110 def magic_autopx(self, ipself, parameter_s=''):
110 def magic_autopx(self, ipself, parameter_s=''):
111 """Toggles auto parallel mode.
111 """Toggles auto parallel mode.
112
112
113 To use this a :class:`MultiEngineClient` instance must be created
113 To use this a :class:`MultiEngineClient` instance must be created
114 and then activated by calling its :meth:`activate` method. Once this
114 and then activated by calling its :meth:`activate` method. Once this
115 is called, all commands typed at the command line are send to
115 is called, all commands typed at the command line are send to
116 the engines to be executed in parallel. To control which engine
116 the engines to be executed in parallel. To control which engine
117 are used, set the ``targets`` attributed of the multiengine client
117 are used, set the ``targets`` attributed of the multiengine client
118 before entering ``%autopx`` mode.
118 before entering ``%autopx`` mode.
119
119
120 Then you can do the following::
120 Then you can do the following::
121
121
122 In [25]: %autopx
122 In [25]: %autopx
123 %autopx to enabled
123 %autopx to enabled
124
124
125 In [26]: a = 10
125 In [26]: a = 10
126 <Results List>
126 <Results List>
127 [0] In [8]: a = 10
127 [0] In [8]: a = 10
128 [1] In [8]: a = 10
128 [1] In [8]: a = 10
129
129
130
130
131 In [27]: %autopx
131 In [27]: %autopx
132 %autopx disabled
132 %autopx disabled
133 """
133 """
134 if self.autopx:
134 if self.autopx:
135 self._disable_autopx()
135 self._disable_autopx()
136 else:
136 else:
137 self._enable_autopx()
137 self._enable_autopx()
138
138
139 def _enable_autopx(self):
139 def _enable_autopx(self):
140 """Enable %autopx mode by saving the original runsource and installing
140 """Enable %autopx mode by saving the original runsource and installing
141 pxrunsource.
141 pxrunsource.
142 """
142 """
143 if self.active_multiengine_client is None:
143 if self.active_multiengine_client is None:
144 print NO_ACTIVE_MULTIENGINE_CLIENT
144 print NO_ACTIVE_MULTIENGINE_CLIENT
145 return
145 return
146
146
147 self._original_runsource = self.shell.runsource
147 self._original_runsource = self.shell.runsource
148 self.shell.runsource = new.instancemethod(
148 self.shell.runsource = new.instancemethod(
149 self.pxrunsource, self.shell, self.shell.__class__
149 self.pxrunsource, self.shell, self.shell.__class__
150 )
150 )
151 self.autopx = True
151 self.autopx = True
152 print "%autopx enabled"
152 print "%autopx enabled"
153
153
154 def _disable_autopx(self):
154 def _disable_autopx(self):
155 """Disable %autopx by restoring the original InteractiveShell.runsource."""
155 """Disable %autopx by restoring the original InteractiveShell.runsource."""
156 if self.autopx:
156 if self.autopx:
157 self.shell.runsource = self._original_runsource
157 self.shell.runsource = self._original_runsource
158 self.autopx = False
158 self.autopx = False
159 print "%autopx disabled"
159 print "%autopx disabled"
160
160
161 def pxrunsource(self, ipself, source, filename="<input>", symbol="single"):
161 def pxrunsource(self, ipself, source, filename="<input>", symbol="single"):
162 """A parallel replacement for InteractiveShell.runsource."""
162 """A parallel replacement for InteractiveShell.runsource."""
163
163
164 try:
164 try:
165 code = ipself.compile(source, filename, symbol)
165 code = ipself.compile(source, filename, symbol)
166 except (OverflowError, SyntaxError, ValueError):
166 except (OverflowError, SyntaxError, ValueError):
167 # Case 1
167 # Case 1
168 ipself.showsyntaxerror(filename)
168 ipself.showsyntaxerror(filename)
169 return None
169 return None
170
170
171 if code is None:
171 if code is None:
172 # Case 2
172 # Case 2
173 return True
173 return True
174
174
175 # Case 3
175 # Case 3
176 # Because autopx is enabled, we now call executeAll or disable autopx if
176 # Because autopx is enabled, we now call executeAll or disable autopx if
177 # %autopx or autopx has been called
177 # %autopx or autopx has been called
178 if 'get_ipython().magic("%autopx' in source or 'get_ipython().magic("autopx' in source:
178 if 'get_ipython().magic("%autopx' in source or 'get_ipython().magic("autopx' in source:
179 self._disable_autopx()
179 self._disable_autopx()
180 return False
180 return False
181 else:
181 else:
182 try:
182 try:
183 result = self.active_multiengine_client.execute(source)
183 result = self.active_multiengine_client.execute(source)
184 except:
184 except:
185 ipself.showtraceback()
185 ipself.showtraceback()
186 else:
186 else:
187 print result.__repr__()
187 print result.__repr__()
188 return False
188 return False
189
189
190
190
191 _loaded = False
191 _loaded = False
192
192
193
193
194 def load_ipython_extension(ip):
194 def load_ipython_extension(ip):
195 """Load the extension in IPython."""
195 """Load the extension in IPython."""
196 global _loaded
196 global _loaded
197 if not _loaded:
197 if not _loaded:
198 plugin = ParalleMagic(shell=ip, config=ip.config)
198 plugin = ParalleMagic(shell=ip, config=ip.config)
199 ip.plugin_manager.register_plugin('parallel_magic', plugin)
199 ip.plugin_manager.register_plugin('parallel_magic', plugin)
200 _loaded = True
200 _loaded = True
201
201
@@ -1,157 +1,157 b''
1 """Use pretty.py for configurable pretty-printing.
1 """Use pretty.py for configurable pretty-printing.
2
2
3 To enable this extension in your configuration
3 To enable this extension in your configuration
4 file, add the following to :file:`ipython_config.py`::
4 file, add the following to :file:`ipython_config.py`::
5
5
6 c.Global.extensions = ['IPython.extensions.pretty']
6 c.Global.extensions = ['IPython.extensions.pretty']
7 def dict_pprinter(obj, p, cycle):
7 def dict_pprinter(obj, p, cycle):
8 return p.text("<dict>")
8 return p.text("<dict>")
9 c.PrettyResultDisplay.verbose = True
9 c.PrettyResultDisplay.verbose = True
10 c.PrettyResultDisplay.defaults_for_type = [
10 c.PrettyResultDisplay.defaults_for_type = [
11 (dict, dict_pprinter)
11 (dict, dict_pprinter)
12 ]
12 ]
13 c.PrettyResultDisplay.defaults_for_type_by_name = [
13 c.PrettyResultDisplay.defaults_for_type_by_name = [
14 ('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')
14 ('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')
15 ]
15 ]
16
16
17 This extension can also be loaded by using the ``%load_ext`` magic::
17 This extension can also be loaded by using the ``%load_ext`` magic::
18
18
19 %load_ext IPython.extensions.pretty
19 %load_ext IPython.extensions.pretty
20
20
21 If this extension is enabled, you can always add additional pretty printers
21 If this extension is enabled, you can always add additional pretty printers
22 by doing::
22 by doing::
23
23
24 ip = get_ipython()
24 ip = get_ipython()
25 prd = ip.get_component('pretty_result_display')
25 prd = ip.get_component('pretty_result_display')
26 import numpy
26 import numpy
27 from IPython.extensions.pretty import dtype_pprinter
27 from IPython.extensions.pretty import dtype_pprinter
28 prd.for_type(numpy.dtype, dtype_pprinter)
28 prd.for_type(numpy.dtype, dtype_pprinter)
29
29
30 # If you don't want to have numpy imported until it needs to be:
30 # If you don't want to have numpy imported until it needs to be:
31 prd.for_type_by_name('numpy', 'dtype', dtype_pprinter)
31 prd.for_type_by_name('numpy', 'dtype', dtype_pprinter)
32 """
32 """
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Imports
35 # Imports
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 from IPython.core.error import TryNext
38 from IPython.core.error import TryNext
39 from IPython.external import pretty
39 from IPython.external import pretty
40 from IPython.core.plugin import Plugin
40 from IPython.core.plugin import Plugin
41 from IPython.utils.traitlets import Bool, List, Instance
41 from IPython.utils.traitlets import Bool, List, Instance
42 from IPython.utils.io import Term
42 from IPython.utils.io import Term
43 from IPython.utils.autoattr import auto_attr
43 from IPython.utils.autoattr import auto_attr
44 from IPython.utils.importstring import import_item
44 from IPython.utils.importstring import import_item
45
45
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47 # Code
47 # Code
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49
49
50
50
51 _loaded = False
51 _loaded = False
52
52
53
53
54 class PrettyResultDisplay(Plugin):
54 class PrettyResultDisplay(Plugin):
55 """A component for pretty printing on steroids."""
55 """A component for pretty printing on steroids."""
56
56
57 verbose = Bool(False, config=True)
57 verbose = Bool(False, config=True)
58 shell = Instance('IPython.core.iplib.InteractiveShellABC')
58 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
59
59
60 # A list of (type, func_name), like
60 # A list of (type, func_name), like
61 # [(dict, 'my_dict_printer')]
61 # [(dict, 'my_dict_printer')]
62 # The final argument can also be a callable
62 # The final argument can also be a callable
63 defaults_for_type = List(default_value=[], config=True)
63 defaults_for_type = List(default_value=[], config=True)
64
64
65 # A list of (module_name, type_name, func_name), like
65 # A list of (module_name, type_name, func_name), like
66 # [('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')]
66 # [('numpy', 'dtype', 'IPython.extensions.pretty.dtype_pprinter')]
67 # The final argument can also be a callable
67 # The final argument can also be a callable
68 defaults_for_type_by_name = List(default_value=[], config=True)
68 defaults_for_type_by_name = List(default_value=[], config=True)
69
69
70 def __init__(self, shell=None, config=None):
70 def __init__(self, shell=None, config=None):
71 super(PrettyResultDisplay, self).__init__(shell=shell, config=config)
71 super(PrettyResultDisplay, self).__init__(shell=shell, config=config)
72 self._setup_defaults()
72 self._setup_defaults()
73
73
74 def _setup_defaults(self):
74 def _setup_defaults(self):
75 """Initialize the default pretty printers."""
75 """Initialize the default pretty printers."""
76 for typ, func_name in self.defaults_for_type:
76 for typ, func_name in self.defaults_for_type:
77 func = self._resolve_func_name(func_name)
77 func = self._resolve_func_name(func_name)
78 self.for_type(typ, func)
78 self.for_type(typ, func)
79 for type_module, type_name, func_name in self.defaults_for_type_by_name:
79 for type_module, type_name, func_name in self.defaults_for_type_by_name:
80 func = self._resolve_func_name(func_name)
80 func = self._resolve_func_name(func_name)
81 self.for_type_by_name(type_module, type_name, func)
81 self.for_type_by_name(type_module, type_name, func)
82
82
83 def _resolve_func_name(self, func_name):
83 def _resolve_func_name(self, func_name):
84 if callable(func_name):
84 if callable(func_name):
85 return func_name
85 return func_name
86 elif isinstance(func_name, basestring):
86 elif isinstance(func_name, basestring):
87 return import_item(func_name)
87 return import_item(func_name)
88 else:
88 else:
89 raise TypeError('func_name must be a str or callable, got: %r' % func_name)
89 raise TypeError('func_name must be a str or callable, got: %r' % func_name)
90
90
91 def __call__(self, otherself, arg):
91 def __call__(self, otherself, arg):
92 """Uber-pretty-printing display hook.
92 """Uber-pretty-printing display hook.
93
93
94 Called for displaying the result to the user.
94 Called for displaying the result to the user.
95 """
95 """
96
96
97 if self.shell.pprint:
97 if self.shell.pprint:
98 out = pretty.pretty(arg, verbose=self.verbose)
98 out = pretty.pretty(arg, verbose=self.verbose)
99 if '\n' in out:
99 if '\n' in out:
100 # So that multi-line strings line up with the left column of
100 # So that multi-line strings line up with the left column of
101 # the screen, instead of having the output prompt mess up
101 # the screen, instead of having the output prompt mess up
102 # their first line.
102 # their first line.
103 Term.cout.write('\n')
103 Term.cout.write('\n')
104 print >>Term.cout, out
104 print >>Term.cout, out
105 else:
105 else:
106 raise TryNext
106 raise TryNext
107
107
108 def for_type(self, typ, func):
108 def for_type(self, typ, func):
109 """Add a pretty printer for a type."""
109 """Add a pretty printer for a type."""
110 return pretty.for_type(typ, func)
110 return pretty.for_type(typ, func)
111
111
112 def for_type_by_name(self, type_module, type_name, func):
112 def for_type_by_name(self, type_module, type_name, func):
113 """Add a pretty printer for a type by its name and module name."""
113 """Add a pretty printer for a type by its name and module name."""
114 return pretty.for_type_by_name(type_module, type_name, func)
114 return pretty.for_type_by_name(type_module, type_name, func)
115
115
116
116
117 #-----------------------------------------------------------------------------
117 #-----------------------------------------------------------------------------
118 # Initialization code for the extension
118 # Initialization code for the extension
119 #-----------------------------------------------------------------------------
119 #-----------------------------------------------------------------------------
120
120
121
121
122 def load_ipython_extension(ip):
122 def load_ipython_extension(ip):
123 """Load the extension in IPython as a hook."""
123 """Load the extension in IPython as a hook."""
124 global _loaded
124 global _loaded
125 if not _loaded:
125 if not _loaded:
126 plugin = PrettyResultDisplay(shell=ip, config=ip.config)
126 plugin = PrettyResultDisplay(shell=ip, config=ip.config)
127 ip.set_hook('result_display', plugin, priority=99)
127 ip.set_hook('result_display', plugin, priority=99)
128 _loaded = True
128 _loaded = True
129 ip.plugin_manager.register_plugin('pretty_result_display', plugin)
129 ip.plugin_manager.register_plugin('pretty_result_display', plugin)
130
130
131 def unload_ipython_extension(ip):
131 def unload_ipython_extension(ip):
132 """Unload the extension."""
132 """Unload the extension."""
133 # The hook system does not have a way to remove a hook so this is a pass
133 # The hook system does not have a way to remove a hook so this is a pass
134 pass
134 pass
135
135
136
136
137 #-----------------------------------------------------------------------------
137 #-----------------------------------------------------------------------------
138 # Example pretty printers
138 # Example pretty printers
139 #-----------------------------------------------------------------------------
139 #-----------------------------------------------------------------------------
140
140
141
141
142 def dtype_pprinter(obj, p, cycle):
142 def dtype_pprinter(obj, p, cycle):
143 """ A pretty-printer for numpy dtype objects.
143 """ A pretty-printer for numpy dtype objects.
144 """
144 """
145 if cycle:
145 if cycle:
146 return p.text('dtype(...)')
146 return p.text('dtype(...)')
147 if hasattr(obj, 'fields'):
147 if hasattr(obj, 'fields'):
148 if obj.fields is None:
148 if obj.fields is None:
149 p.text(repr(obj))
149 p.text(repr(obj))
150 else:
150 else:
151 p.begin_group(7, 'dtype([')
151 p.begin_group(7, 'dtype([')
152 for i, field in enumerate(obj.descr):
152 for i, field in enumerate(obj.descr):
153 if i > 0:
153 if i > 0:
154 p.text(',')
154 p.text(',')
155 p.breakable()
155 p.breakable()
156 p.pretty(field)
156 p.pretty(field)
157 p.end_group(7, '])')
157 p.end_group(7, '])')
@@ -1,100 +1,100 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Simple tests for :mod:`IPython.extensions.pretty`.
4 Simple tests for :mod:`IPython.extensions.pretty`.
5 """
5 """
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 from unittest import TestCase
18 from unittest import TestCase
19
19
20 from IPython.config.configurable import Configurable
20 from IPython.config.configurable import Configurable
21 from IPython.core.iplib import InteractiveShellABC
21 from IPython.core.interactiveshell import InteractiveShellABC
22 from IPython.extensions import pretty as pretty_ext
22 from IPython.extensions import pretty as pretty_ext
23 from IPython.external import pretty
23 from IPython.external import pretty
24 from IPython.testing import decorators as dec
24 from IPython.testing import decorators as dec
25 from IPython.testing import tools as tt
25 from IPython.testing import tools as tt
26 from IPython.utils.traitlets import Bool
26 from IPython.utils.traitlets import Bool
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Tests
29 # Tests
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31
31
32 class InteractiveShellStub(Configurable):
32 class InteractiveShellStub(Configurable):
33 pprint = Bool(True)
33 pprint = Bool(True)
34
34
35 InteractiveShellABC.register(InteractiveShellStub)
35 InteractiveShellABC.register(InteractiveShellStub)
36
36
37 class A(object):
37 class A(object):
38 pass
38 pass
39
39
40 def a_pprinter(o, p, c):
40 def a_pprinter(o, p, c):
41 return p.text("<A>")
41 return p.text("<A>")
42
42
43 class TestPrettyResultDisplay(TestCase):
43 class TestPrettyResultDisplay(TestCase):
44
44
45 def setUp(self):
45 def setUp(self):
46 self.ip = InteractiveShellStub()
46 self.ip = InteractiveShellStub()
47 self.prd = pretty_ext.PrettyResultDisplay(shell=self.ip, config=None)
47 self.prd = pretty_ext.PrettyResultDisplay(shell=self.ip, config=None)
48
48
49 def test_for_type(self):
49 def test_for_type(self):
50 self.prd.for_type(A, a_pprinter)
50 self.prd.for_type(A, a_pprinter)
51 a = A()
51 a = A()
52 result = pretty.pretty(a)
52 result = pretty.pretty(a)
53 self.assertEquals(result, "<A>")
53 self.assertEquals(result, "<A>")
54
54
55 ipy_src = """
55 ipy_src = """
56 class A(object):
56 class A(object):
57 def __repr__(self):
57 def __repr__(self):
58 return 'A()'
58 return 'A()'
59
59
60 class B(object):
60 class B(object):
61 def __repr__(self):
61 def __repr__(self):
62 return 'B()'
62 return 'B()'
63
63
64 a = A()
64 a = A()
65 b = B()
65 b = B()
66
66
67 def a_pretty_printer(obj, p, cycle):
67 def a_pretty_printer(obj, p, cycle):
68 p.text('<A>')
68 p.text('<A>')
69
69
70 def b_pretty_printer(obj, p, cycle):
70 def b_pretty_printer(obj, p, cycle):
71 p.text('<B>')
71 p.text('<B>')
72
72
73
73
74 a
74 a
75 b
75 b
76
76
77 ip = get_ipython()
77 ip = get_ipython()
78 ip.extension_manager.load_extension('pretty')
78 ip.extension_manager.load_extension('pretty')
79 prd = ip.plugin_manager.get_plugin('pretty_result_display')
79 prd = ip.plugin_manager.get_plugin('pretty_result_display')
80 prd.for_type(A, a_pretty_printer)
80 prd.for_type(A, a_pretty_printer)
81 prd.for_type_by_name(B.__module__, B.__name__, b_pretty_printer)
81 prd.for_type_by_name(B.__module__, B.__name__, b_pretty_printer)
82
82
83 a
83 a
84 b
84 b
85 """
85 """
86 ipy_out = """
86 ipy_out = """
87 A()
87 A()
88 B()
88 B()
89 <A>
89 <A>
90 <B>
90 <B>
91 """
91 """
92
92
93 class TestPrettyInteractively(tt.TempFileMixin):
93 class TestPrettyInteractively(tt.TempFileMixin):
94
94
95 # XXX Unfortunately, ipexec_validate fails under win32. If someone helps
95 # XXX Unfortunately, ipexec_validate fails under win32. If someone helps
96 # us write a win32-compatible version, we can reactivate this test.
96 # us write a win32-compatible version, we can reactivate this test.
97 @dec.skip_win32
97 @dec.skip_win32
98 def test_printers(self):
98 def test_printers(self):
99 self.mktmp(ipy_src, '.ipy')
99 self.mktmp(ipy_src, '.ipy')
100 tt.ipexec_validate(self.fname, ipy_out)
100 tt.ipexec_validate(self.fname, ipy_out)
@@ -1,275 +1,275 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 An embedded IPython shell.
4 An embedded IPython shell.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import with_statement
26 from __future__ import with_statement
27 import __main__
27 import __main__
28
28
29 import sys
29 import sys
30 from contextlib import nested
30 from contextlib import nested
31
31
32 from IPython.core import ultratb
32 from IPython.core import ultratb
33 from IPython.core.iplib import InteractiveShell
33 from IPython.core.interactiveshell import InteractiveShell
34 from IPython.core.ipapp import load_default_config
34 from IPython.frontend.terminal.ipapp import load_default_config
35
35
36 from IPython.utils.traitlets import Bool, Str, CBool
36 from IPython.utils.traitlets import Bool, Str, CBool
37 from IPython.utils.io import ask_yes_no
37 from IPython.utils.io import ask_yes_no
38
38
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Classes and functions
41 # Classes and functions
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 # This is an additional magic that is exposed in embedded shells.
44 # This is an additional magic that is exposed in embedded shells.
45 def kill_embedded(self,parameter_s=''):
45 def kill_embedded(self,parameter_s=''):
46 """%kill_embedded : deactivate for good the current embedded IPython.
46 """%kill_embedded : deactivate for good the current embedded IPython.
47
47
48 This function (after asking for confirmation) sets an internal flag so that
48 This function (after asking for confirmation) sets an internal flag so that
49 an embedded IPython will never activate again. This is useful to
49 an embedded IPython will never activate again. This is useful to
50 permanently disable a shell that is being called inside a loop: once you've
50 permanently disable a shell that is being called inside a loop: once you've
51 figured out what you needed from it, you may then kill it and the program
51 figured out what you needed from it, you may then kill it and the program
52 will then continue to run without the interactive shell interfering again.
52 will then continue to run without the interactive shell interfering again.
53 """
53 """
54
54
55 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
55 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
56 "(y/n)? [y/N] ",'n')
56 "(y/n)? [y/N] ",'n')
57 if kill:
57 if kill:
58 self.embedded_active = False
58 self.embedded_active = False
59 print "This embedded IPython will not reactivate anymore once you exit."
59 print "This embedded IPython will not reactivate anymore once you exit."
60
60
61
61
62 class InteractiveShellEmbed(InteractiveShell):
62 class InteractiveShellEmbed(InteractiveShell):
63
63
64 dummy_mode = Bool(False)
64 dummy_mode = Bool(False)
65 exit_msg = Str('')
65 exit_msg = Str('')
66 embedded = CBool(True)
66 embedded = CBool(True)
67 embedded_active = CBool(True)
67 embedded_active = CBool(True)
68 # Like the base class display_banner is not configurable, but here it
68 # Like the base class display_banner is not configurable, but here it
69 # is True by default.
69 # is True by default.
70 display_banner = CBool(True)
70 display_banner = CBool(True)
71
71
72 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
72 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
73 user_ns=None, user_global_ns=None,
73 user_ns=None, user_global_ns=None,
74 banner1=None, banner2=None, display_banner=None,
74 banner1=None, banner2=None, display_banner=None,
75 custom_exceptions=((),None), exit_msg=''):
75 custom_exceptions=((),None), exit_msg=''):
76
76
77 self.save_sys_ipcompleter()
77 self.save_sys_ipcompleter()
78
78
79 super(InteractiveShellEmbed,self).__init__(
79 super(InteractiveShellEmbed,self).__init__(
80 parent=parent, config=config, ipython_dir=ipython_dir, usage=usage,
80 parent=parent, config=config, ipython_dir=ipython_dir, usage=usage,
81 user_ns=user_ns, user_global_ns=user_global_ns,
81 user_ns=user_ns, user_global_ns=user_global_ns,
82 banner1=banner1, banner2=banner2, display_banner=display_banner,
82 banner1=banner1, banner2=banner2, display_banner=display_banner,
83 custom_exceptions=custom_exceptions)
83 custom_exceptions=custom_exceptions)
84
84
85 self.exit_msg = exit_msg
85 self.exit_msg = exit_msg
86 self.define_magic("kill_embedded", kill_embedded)
86 self.define_magic("kill_embedded", kill_embedded)
87
87
88 # don't use the ipython crash handler so that user exceptions aren't
88 # don't use the ipython crash handler so that user exceptions aren't
89 # trapped
89 # trapped
90 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
90 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
91 mode=self.xmode,
91 mode=self.xmode,
92 call_pdb=self.pdb)
92 call_pdb=self.pdb)
93
93
94 self.restore_sys_ipcompleter()
94 self.restore_sys_ipcompleter()
95
95
96 def init_sys_modules(self):
96 def init_sys_modules(self):
97 pass
97 pass
98
98
99 def save_sys_ipcompleter(self):
99 def save_sys_ipcompleter(self):
100 """Save readline completer status."""
100 """Save readline completer status."""
101 try:
101 try:
102 #print 'Save completer',sys.ipcompleter # dbg
102 #print 'Save completer',sys.ipcompleter # dbg
103 self.sys_ipcompleter_orig = sys.ipcompleter
103 self.sys_ipcompleter_orig = sys.ipcompleter
104 except:
104 except:
105 pass # not nested with IPython
105 pass # not nested with IPython
106
106
107 def restore_sys_ipcompleter(self):
107 def restore_sys_ipcompleter(self):
108 """Restores the readline completer which was in place.
108 """Restores the readline completer which was in place.
109
109
110 This allows embedded IPython within IPython not to disrupt the
110 This allows embedded IPython within IPython not to disrupt the
111 parent's completion.
111 parent's completion.
112 """
112 """
113 try:
113 try:
114 self.readline.set_completer(self.sys_ipcompleter_orig)
114 self.readline.set_completer(self.sys_ipcompleter_orig)
115 sys.ipcompleter = self.sys_ipcompleter_orig
115 sys.ipcompleter = self.sys_ipcompleter_orig
116 except:
116 except:
117 pass
117 pass
118
118
119 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
119 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
120 stack_depth=1):
120 stack_depth=1):
121 """Activate the interactive interpreter.
121 """Activate the interactive interpreter.
122
122
123 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
123 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
124 the interpreter shell with the given local and global namespaces, and
124 the interpreter shell with the given local and global namespaces, and
125 optionally print a header string at startup.
125 optionally print a header string at startup.
126
126
127 The shell can be globally activated/deactivated using the
127 The shell can be globally activated/deactivated using the
128 set/get_dummy_mode methods. This allows you to turn off a shell used
128 set/get_dummy_mode methods. This allows you to turn off a shell used
129 for debugging globally.
129 for debugging globally.
130
130
131 However, *each* time you call the shell you can override the current
131 However, *each* time you call the shell you can override the current
132 state of dummy_mode with the optional keyword parameter 'dummy'. For
132 state of dummy_mode with the optional keyword parameter 'dummy'. For
133 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
133 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
134 can still have a specific call work by making it as IPShell(dummy=0).
134 can still have a specific call work by making it as IPShell(dummy=0).
135
135
136 The optional keyword parameter dummy controls whether the call
136 The optional keyword parameter dummy controls whether the call
137 actually does anything.
137 actually does anything.
138 """
138 """
139
139
140 # If the user has turned it off, go away
140 # If the user has turned it off, go away
141 if not self.embedded_active:
141 if not self.embedded_active:
142 return
142 return
143
143
144 # Normal exits from interactive mode set this flag, so the shell can't
144 # Normal exits from interactive mode set this flag, so the shell can't
145 # re-enter (it checks this variable at the start of interactive mode).
145 # re-enter (it checks this variable at the start of interactive mode).
146 self.exit_now = False
146 self.exit_now = False
147
147
148 # Allow the dummy parameter to override the global __dummy_mode
148 # Allow the dummy parameter to override the global __dummy_mode
149 if dummy or (dummy != 0 and self.dummy_mode):
149 if dummy or (dummy != 0 and self.dummy_mode):
150 return
150 return
151
151
152 if self.has_readline:
152 if self.has_readline:
153 self.set_completer()
153 self.set_completer()
154
154
155 # self.banner is auto computed
155 # self.banner is auto computed
156 if header:
156 if header:
157 self.old_banner2 = self.banner2
157 self.old_banner2 = self.banner2
158 self.banner2 = self.banner2 + '\n' + header + '\n'
158 self.banner2 = self.banner2 + '\n' + header + '\n'
159 else:
159 else:
160 self.old_banner2 = ''
160 self.old_banner2 = ''
161
161
162 # Call the embedding code with a stack depth of 1 so it can skip over
162 # Call the embedding code with a stack depth of 1 so it can skip over
163 # our call and get the original caller's namespaces.
163 # our call and get the original caller's namespaces.
164 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
164 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
165
165
166 self.banner2 = self.old_banner2
166 self.banner2 = self.old_banner2
167
167
168 if self.exit_msg is not None:
168 if self.exit_msg is not None:
169 print self.exit_msg
169 print self.exit_msg
170
170
171 self.restore_sys_ipcompleter()
171 self.restore_sys_ipcompleter()
172
172
173 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
173 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
174 display_banner=None):
174 display_banner=None):
175 """Embeds IPython into a running python program.
175 """Embeds IPython into a running python program.
176
176
177 Input:
177 Input:
178
178
179 - header: An optional header message can be specified.
179 - header: An optional header message can be specified.
180
180
181 - local_ns, global_ns: working namespaces. If given as None, the
181 - local_ns, global_ns: working namespaces. If given as None, the
182 IPython-initialized one is updated with __main__.__dict__, so that
182 IPython-initialized one is updated with __main__.__dict__, so that
183 program variables become visible but user-specific configuration
183 program variables become visible but user-specific configuration
184 remains possible.
184 remains possible.
185
185
186 - stack_depth: specifies how many levels in the stack to go to
186 - stack_depth: specifies how many levels in the stack to go to
187 looking for namespaces (when local_ns and global_ns are None). This
187 looking for namespaces (when local_ns and global_ns are None). This
188 allows an intermediate caller to make sure that this function gets
188 allows an intermediate caller to make sure that this function gets
189 the namespace from the intended level in the stack. By default (0)
189 the namespace from the intended level in the stack. By default (0)
190 it will get its locals and globals from the immediate caller.
190 it will get its locals and globals from the immediate caller.
191
191
192 Warning: it's possible to use this in a program which is being run by
192 Warning: it's possible to use this in a program which is being run by
193 IPython itself (via %run), but some funny things will happen (a few
193 IPython itself (via %run), but some funny things will happen (a few
194 globals get overwritten). In the future this will be cleaned up, as
194 globals get overwritten). In the future this will be cleaned up, as
195 there is no fundamental reason why it can't work perfectly."""
195 there is no fundamental reason why it can't work perfectly."""
196
196
197 # Get locals and globals from caller
197 # Get locals and globals from caller
198 if local_ns is None or global_ns is None:
198 if local_ns is None or global_ns is None:
199 call_frame = sys._getframe(stack_depth).f_back
199 call_frame = sys._getframe(stack_depth).f_back
200
200
201 if local_ns is None:
201 if local_ns is None:
202 local_ns = call_frame.f_locals
202 local_ns = call_frame.f_locals
203 if global_ns is None:
203 if global_ns is None:
204 global_ns = call_frame.f_globals
204 global_ns = call_frame.f_globals
205
205
206 # Update namespaces and fire up interpreter
206 # Update namespaces and fire up interpreter
207
207
208 # The global one is easy, we can just throw it in
208 # The global one is easy, we can just throw it in
209 self.user_global_ns = global_ns
209 self.user_global_ns = global_ns
210
210
211 # but the user/local one is tricky: ipython needs it to store internal
211 # but the user/local one is tricky: ipython needs it to store internal
212 # data, but we also need the locals. We'll copy locals in the user
212 # data, but we also need the locals. We'll copy locals in the user
213 # one, but will track what got copied so we can delete them at exit.
213 # one, but will track what got copied so we can delete them at exit.
214 # This is so that a later embedded call doesn't see locals from a
214 # This is so that a later embedded call doesn't see locals from a
215 # previous call (which most likely existed in a separate scope).
215 # previous call (which most likely existed in a separate scope).
216 local_varnames = local_ns.keys()
216 local_varnames = local_ns.keys()
217 self.user_ns.update(local_ns)
217 self.user_ns.update(local_ns)
218 #self.user_ns['local_ns'] = local_ns # dbg
218 #self.user_ns['local_ns'] = local_ns # dbg
219
219
220 # Patch for global embedding to make sure that things don't overwrite
220 # Patch for global embedding to make sure that things don't overwrite
221 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
221 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
222 # FIXME. Test this a bit more carefully (the if.. is new)
222 # FIXME. Test this a bit more carefully (the if.. is new)
223 if local_ns is None and global_ns is None:
223 if local_ns is None and global_ns is None:
224 self.user_global_ns.update(__main__.__dict__)
224 self.user_global_ns.update(__main__.__dict__)
225
225
226 # make sure the tab-completer has the correct frame information, so it
226 # make sure the tab-completer has the correct frame information, so it
227 # actually completes using the frame's locals/globals
227 # actually completes using the frame's locals/globals
228 self.set_completer_frame()
228 self.set_completer_frame()
229
229
230 with nested(self.builtin_trap, self.display_trap):
230 with nested(self.builtin_trap, self.display_trap):
231 self.interact(display_banner=display_banner)
231 self.interact(display_banner=display_banner)
232
232
233 # now, purge out the user namespace from anything we might have added
233 # now, purge out the user namespace from anything we might have added
234 # from the caller's local namespace
234 # from the caller's local namespace
235 delvar = self.user_ns.pop
235 delvar = self.user_ns.pop
236 for var in local_varnames:
236 for var in local_varnames:
237 delvar(var,None)
237 delvar(var,None)
238
238
239
239
240 _embedded_shell = None
240 _embedded_shell = None
241
241
242
242
243 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
243 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
244 display_banner=True, exit_msg=''):
244 display_banner=True, exit_msg=''):
245 """Call this to embed IPython at the current point in your program.
245 """Call this to embed IPython at the current point in your program.
246
246
247 The first invocation of this will create an :class:`InteractiveShellEmbed`
247 The first invocation of this will create an :class:`InteractiveShellEmbed`
248 instance and then call it. Consecutive calls just call the already
248 instance and then call it. Consecutive calls just call the already
249 created instance.
249 created instance.
250
250
251 Here is a simple example::
251 Here is a simple example::
252
252
253 from IPython import embed
253 from IPython import embed
254 a = 10
254 a = 10
255 b = 20
255 b = 20
256 embed('First time')
256 embed('First time')
257 c = 30
257 c = 30
258 d = 40
258 d = 40
259 embed
259 embed
260
260
261 Full customization can be done by passing a :class:`Struct` in as the
261 Full customization can be done by passing a :class:`Struct` in as the
262 config argument.
262 config argument.
263 """
263 """
264 if config is None:
264 if config is None:
265 config = load_default_config()
265 config = load_default_config()
266 config.InteractiveShellEmbed = config.InteractiveShell
266 config.InteractiveShellEmbed = config.InteractiveShell
267 global _embedded_shell
267 global _embedded_shell
268 if _embedded_shell is None:
268 if _embedded_shell is None:
269 _embedded_shell = InteractiveShellEmbed(
269 _embedded_shell = InteractiveShellEmbed(
270 config=config, usage=usage,
270 config=config, usage=usage,
271 banner1=banner1, banner2=banner2,
271 banner1=banner1, banner2=banner2,
272 display_banner=display_banner, exit_msg=exit_msg
272 display_banner=display_banner, exit_msg=exit_msg
273 )
273 )
274 _embedded_shell(header=header, stack_depth=2)
274 _embedded_shell(header=header, stack_depth=2)
275
275
@@ -1,665 +1,665 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors
7 Authors
8 -------
8 -------
9
9
10 * Brian Granger
10 * Brian Granger
11 * Fernando Perez
11 * Fernando Perez
12 """
12 """
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Copyright (C) 2008-2010 The IPython Development Team
15 # Copyright (C) 2008-2010 The IPython Development Team
16 #
16 #
17 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Imports
22 # Imports
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 from __future__ import absolute_import
25 from __future__ import absolute_import
26
26
27 import logging
27 import logging
28 import os
28 import os
29 import sys
29 import sys
30
30
31 from IPython.core import release
31 from IPython.core import release
32 from IPython.core.crashhandler import CrashHandler
32 from IPython.core.crashhandler import CrashHandler
33 from IPython.core.application import Application, BaseAppConfigLoader
33 from IPython.core.application import Application, BaseAppConfigLoader
34 from IPython.core.iplib import InteractiveShell
34 from IPython.core.interactiveshell import InteractiveShell
35 from IPython.config.loader import (
35 from IPython.config.loader import (
36 Config,
36 Config,
37 PyFileConfigLoader
37 PyFileConfigLoader
38 )
38 )
39 from IPython.lib import inputhook
39 from IPython.lib import inputhook
40 from IPython.utils.path import filefind, get_ipython_dir
40 from IPython.utils.path import filefind, get_ipython_dir
41 from . import usage
41 from IPython.core import usage
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Globals, utilities and helpers
44 # Globals, utilities and helpers
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 #: The default config file name for this application.
47 #: The default config file name for this application.
48 default_config_file_name = u'ipython_config.py'
48 default_config_file_name = u'ipython_config.py'
49
49
50
50
51 class IPAppConfigLoader(BaseAppConfigLoader):
51 class IPAppConfigLoader(BaseAppConfigLoader):
52
52
53 def _add_arguments(self):
53 def _add_arguments(self):
54 super(IPAppConfigLoader, self)._add_arguments()
54 super(IPAppConfigLoader, self)._add_arguments()
55 paa = self.parser.add_argument
55 paa = self.parser.add_argument
56 paa('-p',
56 paa('-p',
57 '--profile', dest='Global.profile', type=unicode,
57 '--profile', dest='Global.profile', type=unicode,
58 help=
58 help=
59 """The string name of the ipython profile to be used. Assume that your
59 """The string name of the ipython profile to be used. Assume that your
60 config file is ipython_config-<name>.py (looks in current dir first,
60 config file is ipython_config-<name>.py (looks in current dir first,
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 config files for different tasks, especially if include your basic one
62 config files for different tasks, especially if include your basic one
63 in your more specialized ones. You can keep a basic
63 in your more specialized ones. You can keep a basic
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 include this one and load extra things for particular tasks.""",
65 include this one and load extra things for particular tasks.""",
66 metavar='Global.profile')
66 metavar='Global.profile')
67 paa('--config-file',
67 paa('--config-file',
68 dest='Global.config_file', type=unicode,
68 dest='Global.config_file', type=unicode,
69 help=
69 help=
70 """Set the config file name to override default. Normally IPython
70 """Set the config file name to override default. Normally IPython
71 loads ipython_config.py (from current directory) or
71 loads ipython_config.py (from current directory) or
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 fails, IPython starts with a bare bones configuration (no modules
73 fails, IPython starts with a bare bones configuration (no modules
74 loaded at all).""",
74 loaded at all).""",
75 metavar='Global.config_file')
75 metavar='Global.config_file')
76 paa('--autocall',
76 paa('--autocall',
77 dest='InteractiveShell.autocall', type=int,
77 dest='InteractiveShell.autocall', type=int,
78 help=
78 help=
79 """Make IPython automatically call any callable object even if you
79 """Make IPython automatically call any callable object even if you
80 didn't type explicit parentheses. For example, 'str 43' becomes
80 didn't type explicit parentheses. For example, 'str 43' becomes
81 'str(43)' automatically. The value can be '0' to disable the feature,
81 'str(43)' automatically. The value can be '0' to disable the feature,
82 '1' for 'smart' autocall, where it is not applied if there are no more
82 '1' for 'smart' autocall, where it is not applied if there are no more
83 arguments on the line, and '2' for 'full' autocall, where all callable
83 arguments on the line, and '2' for 'full' autocall, where all callable
84 objects are automatically called (even if no arguments are present).
84 objects are automatically called (even if no arguments are present).
85 The default is '1'.""",
85 The default is '1'.""",
86 metavar='InteractiveShell.autocall')
86 metavar='InteractiveShell.autocall')
87 paa('--autoindent',
87 paa('--autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
89 help='Turn on autoindenting.')
89 help='Turn on autoindenting.')
90 paa('--no-autoindent',
90 paa('--no-autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
92 help='Turn off autoindenting.')
92 help='Turn off autoindenting.')
93 paa('--automagic',
93 paa('--automagic',
94 action='store_true', dest='InteractiveShell.automagic',
94 action='store_true', dest='InteractiveShell.automagic',
95 help=
95 help=
96 """Turn on the auto calling of magic commands. Type %%magic at the
96 """Turn on the auto calling of magic commands. Type %%magic at the
97 IPython prompt for more information.""")
97 IPython prompt for more information.""")
98 paa('--no-automagic',
98 paa('--no-automagic',
99 action='store_false', dest='InteractiveShell.automagic',
99 action='store_false', dest='InteractiveShell.automagic',
100 help='Turn off the auto calling of magic commands.')
100 help='Turn off the auto calling of magic commands.')
101 paa('--autoedit-syntax',
101 paa('--autoedit-syntax',
102 action='store_true', dest='InteractiveShell.autoedit_syntax',
102 action='store_true', dest='InteractiveShell.autoedit_syntax',
103 help='Turn on auto editing of files with syntax errors.')
103 help='Turn on auto editing of files with syntax errors.')
104 paa('--no-autoedit-syntax',
104 paa('--no-autoedit-syntax',
105 action='store_false', dest='InteractiveShell.autoedit_syntax',
105 action='store_false', dest='InteractiveShell.autoedit_syntax',
106 help='Turn off auto editing of files with syntax errors.')
106 help='Turn off auto editing of files with syntax errors.')
107 paa('--banner',
107 paa('--banner',
108 action='store_true', dest='Global.display_banner',
108 action='store_true', dest='Global.display_banner',
109 help='Display a banner upon starting IPython.')
109 help='Display a banner upon starting IPython.')
110 paa('--no-banner',
110 paa('--no-banner',
111 action='store_false', dest='Global.display_banner',
111 action='store_false', dest='Global.display_banner',
112 help="Don't display a banner upon starting IPython.")
112 help="Don't display a banner upon starting IPython.")
113 paa('--cache-size',
113 paa('--cache-size',
114 type=int, dest='InteractiveShell.cache_size',
114 type=int, dest='InteractiveShell.cache_size',
115 help=
115 help=
116 """Set the size of the output cache. The default is 1000, you can
116 """Set the size of the output cache. The default is 1000, you can
117 change it permanently in your config file. Setting it to 0 completely
117 change it permanently in your config file. Setting it to 0 completely
118 disables the caching system, and the minimum value accepted is 20 (if
118 disables the caching system, and the minimum value accepted is 20 (if
119 you provide a value less than 20, it is reset to 0 and a warning is
119 you provide a value less than 20, it is reset to 0 and a warning is
120 issued). This limit is defined because otherwise you'll spend more
120 issued). This limit is defined because otherwise you'll spend more
121 time re-flushing a too small cache than working""",
121 time re-flushing a too small cache than working""",
122 metavar='InteractiveShell.cache_size')
122 metavar='InteractiveShell.cache_size')
123 paa('--classic',
123 paa('--classic',
124 action='store_true', dest='Global.classic',
124 action='store_true', dest='Global.classic',
125 help="Gives IPython a similar feel to the classic Python prompt.")
125 help="Gives IPython a similar feel to the classic Python prompt.")
126 paa('--colors',
126 paa('--colors',
127 type=str, dest='InteractiveShell.colors',
127 type=str, dest='InteractiveShell.colors',
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 metavar='InteractiveShell.colors')
129 metavar='InteractiveShell.colors')
130 paa('--color-info',
130 paa('--color-info',
131 action='store_true', dest='InteractiveShell.color_info',
131 action='store_true', dest='InteractiveShell.color_info',
132 help=
132 help=
133 """IPython can display information about objects via a set of func-
133 """IPython can display information about objects via a set of func-
134 tions, and optionally can use colors for this, syntax highlighting
134 tions, and optionally can use colors for this, syntax highlighting
135 source code and various other elements. However, because this
135 source code and various other elements. However, because this
136 information is passed through a pager (like 'less') and many pagers get
136 information is passed through a pager (like 'less') and many pagers get
137 confused with color codes, this option is off by default. You can test
137 confused with color codes, this option is off by default. You can test
138 it and turn it on permanently in your ipython_config.py file if it
138 it and turn it on permanently in your ipython_config.py file if it
139 works for you. Test it and turn it on permanently if it works with
139 works for you. Test it and turn it on permanently if it works with
140 your system. The magic function %%color_info allows you to toggle this
140 your system. The magic function %%color_info allows you to toggle this
141 inter- actively for testing.""")
141 inter- actively for testing.""")
142 paa('--no-color-info',
142 paa('--no-color-info',
143 action='store_false', dest='InteractiveShell.color_info',
143 action='store_false', dest='InteractiveShell.color_info',
144 help="Disable using colors for info related things.")
144 help="Disable using colors for info related things.")
145 paa('--confirm-exit',
145 paa('--confirm-exit',
146 action='store_true', dest='InteractiveShell.confirm_exit',
146 action='store_true', dest='InteractiveShell.confirm_exit',
147 help=
147 help=
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 '%%Exit', you can force a direct exit without any confirmation.""")
150 '%%Exit', you can force a direct exit without any confirmation.""")
151 paa('--no-confirm-exit',
151 paa('--no-confirm-exit',
152 action='store_false', dest='InteractiveShell.confirm_exit',
152 action='store_false', dest='InteractiveShell.confirm_exit',
153 help="Don't prompt the user when exiting.")
153 help="Don't prompt the user when exiting.")
154 paa('--deep-reload',
154 paa('--deep-reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
156 help=
156 help=
157 """Enable deep (recursive) reloading by default. IPython can use the
157 """Enable deep (recursive) reloading by default. IPython can use the
158 deep_reload module which reloads changes in modules recursively (it
158 deep_reload module which reloads changes in modules recursively (it
159 replaces the reload() function, so you don't need to change anything to
159 replaces the reload() function, so you don't need to change anything to
160 use it). deep_reload() forces a full reload of modules whose code may
160 use it). deep_reload() forces a full reload of modules whose code may
161 have changed, which the default reload() function does not. When
161 have changed, which the default reload() function does not. When
162 deep_reload is off, IPython will use the normal reload(), but
162 deep_reload is off, IPython will use the normal reload(), but
163 deep_reload will still be available as dreload(). This fea- ture is off
163 deep_reload will still be available as dreload(). This fea- ture is off
164 by default [which means that you have both normal reload() and
164 by default [which means that you have both normal reload() and
165 dreload()].""")
165 dreload()].""")
166 paa('--no-deep-reload',
166 paa('--no-deep-reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
168 help="Disable deep (recursive) reloading by default.")
168 help="Disable deep (recursive) reloading by default.")
169 paa('--editor',
169 paa('--editor',
170 type=str, dest='InteractiveShell.editor',
170 type=str, dest='InteractiveShell.editor',
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 metavar='InteractiveShell.editor')
172 metavar='InteractiveShell.editor')
173 paa('--log','-l',
173 paa('--log','-l',
174 action='store_true', dest='InteractiveShell.logstart',
174 action='store_true', dest='InteractiveShell.logstart',
175 help="Start logging to the default log file (./ipython_log.py).")
175 help="Start logging to the default log file (./ipython_log.py).")
176 paa('--logfile','-lf',
176 paa('--logfile','-lf',
177 type=unicode, dest='InteractiveShell.logfile',
177 type=unicode, dest='InteractiveShell.logfile',
178 help="Start logging to logfile with this name.",
178 help="Start logging to logfile with this name.",
179 metavar='InteractiveShell.logfile')
179 metavar='InteractiveShell.logfile')
180 paa('--log-append','-la',
180 paa('--log-append','-la',
181 type=unicode, dest='InteractiveShell.logappend',
181 type=unicode, dest='InteractiveShell.logappend',
182 help="Start logging to the given file in append mode.",
182 help="Start logging to the given file in append mode.",
183 metavar='InteractiveShell.logfile')
183 metavar='InteractiveShell.logfile')
184 paa('--pdb',
184 paa('--pdb',
185 action='store_true', dest='InteractiveShell.pdb',
185 action='store_true', dest='InteractiveShell.pdb',
186 help="Enable auto calling the pdb debugger after every exception.")
186 help="Enable auto calling the pdb debugger after every exception.")
187 paa('--no-pdb',
187 paa('--no-pdb',
188 action='store_false', dest='InteractiveShell.pdb',
188 action='store_false', dest='InteractiveShell.pdb',
189 help="Disable auto calling the pdb debugger after every exception.")
189 help="Disable auto calling the pdb debugger after every exception.")
190 paa('--pprint',
190 paa('--pprint',
191 action='store_true', dest='InteractiveShell.pprint',
191 action='store_true', dest='InteractiveShell.pprint',
192 help="Enable auto pretty printing of results.")
192 help="Enable auto pretty printing of results.")
193 paa('--no-pprint',
193 paa('--no-pprint',
194 action='store_false', dest='InteractiveShell.pprint',
194 action='store_false', dest='InteractiveShell.pprint',
195 help="Disable auto auto pretty printing of results.")
195 help="Disable auto auto pretty printing of results.")
196 paa('--prompt-in1','-pi1',
196 paa('--prompt-in1','-pi1',
197 type=str, dest='InteractiveShell.prompt_in1',
197 type=str, dest='InteractiveShell.prompt_in1',
198 help=
198 help=
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 numbered prompts, the number is represented with a '\#' in the string.
200 numbered prompts, the number is represented with a '\#' in the string.
201 Don't forget to quote strings with spaces embedded in them. Most
201 Don't forget to quote strings with spaces embedded in them. Most
202 bash-like escapes can be used to customize IPython's prompts, as well
202 bash-like escapes can be used to customize IPython's prompts, as well
203 as a few additional ones which are IPython-spe- cific. All valid
203 as a few additional ones which are IPython-spe- cific. All valid
204 prompt escapes are described in detail in the Customization section of
204 prompt escapes are described in detail in the Customization section of
205 the IPython manual.""",
205 the IPython manual.""",
206 metavar='InteractiveShell.prompt_in1')
206 metavar='InteractiveShell.prompt_in1')
207 paa('--prompt-in2','-pi2',
207 paa('--prompt-in2','-pi2',
208 type=str, dest='InteractiveShell.prompt_in2',
208 type=str, dest='InteractiveShell.prompt_in2',
209 help=
209 help=
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 option, but used for the continuation prompts. The special sequence
211 option, but used for the continuation prompts. The special sequence
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 can have your continuation prompt aligned with your input prompt).
213 can have your continuation prompt aligned with your input prompt).
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 'In [\#]')""",
215 'In [\#]')""",
216 metavar='InteractiveShell.prompt_in2')
216 metavar='InteractiveShell.prompt_in2')
217 paa('--prompt-out','-po',
217 paa('--prompt-out','-po',
218 type=str, dest='InteractiveShell.prompt_out',
218 type=str, dest='InteractiveShell.prompt_out',
219 help="Set the output prompt ('Out[\#]:')",
219 help="Set the output prompt ('Out[\#]:')",
220 metavar='InteractiveShell.prompt_out')
220 metavar='InteractiveShell.prompt_out')
221 paa('--quick',
221 paa('--quick',
222 action='store_true', dest='Global.quick',
222 action='store_true', dest='Global.quick',
223 help="Enable quick startup with no config files.")
223 help="Enable quick startup with no config files.")
224 paa('--readline',
224 paa('--readline',
225 action='store_true', dest='InteractiveShell.readline_use',
225 action='store_true', dest='InteractiveShell.readline_use',
226 help="Enable readline for command line usage.")
226 help="Enable readline for command line usage.")
227 paa('--no-readline',
227 paa('--no-readline',
228 action='store_false', dest='InteractiveShell.readline_use',
228 action='store_false', dest='InteractiveShell.readline_use',
229 help="Disable readline for command line usage.")
229 help="Disable readline for command line usage.")
230 paa('--screen-length','-sl',
230 paa('--screen-length','-sl',
231 type=int, dest='InteractiveShell.screen_length',
231 type=int, dest='InteractiveShell.screen_length',
232 help=
232 help=
233 """Number of lines of your screen, used to control printing of very
233 """Number of lines of your screen, used to control printing of very
234 long strings. Strings longer than this number of lines will be sent
234 long strings. Strings longer than this number of lines will be sent
235 through a pager instead of directly printed. The default value for
235 through a pager instead of directly printed. The default value for
236 this is 0, which means IPython will auto-detect your screen size every
236 this is 0, which means IPython will auto-detect your screen size every
237 time it needs to print certain potentially long strings (this doesn't
237 time it needs to print certain potentially long strings (this doesn't
238 change the behavior of the 'print' keyword, it's only triggered
238 change the behavior of the 'print' keyword, it's only triggered
239 internally). If for some reason this isn't working well (it needs
239 internally). If for some reason this isn't working well (it needs
240 curses support), specify it yourself. Otherwise don't change the
240 curses support), specify it yourself. Otherwise don't change the
241 default.""",
241 default.""",
242 metavar='InteractiveShell.screen_length')
242 metavar='InteractiveShell.screen_length')
243 paa('--separate-in','-si',
243 paa('--separate-in','-si',
244 type=str, dest='InteractiveShell.separate_in',
244 type=str, dest='InteractiveShell.separate_in',
245 help="Separator before input prompts. Default '\\n'.",
245 help="Separator before input prompts. Default '\\n'.",
246 metavar='InteractiveShell.separate_in')
246 metavar='InteractiveShell.separate_in')
247 paa('--separate-out','-so',
247 paa('--separate-out','-so',
248 type=str, dest='InteractiveShell.separate_out',
248 type=str, dest='InteractiveShell.separate_out',
249 help="Separator before output prompts. Default 0 (nothing).",
249 help="Separator before output prompts. Default 0 (nothing).",
250 metavar='InteractiveShell.separate_out')
250 metavar='InteractiveShell.separate_out')
251 paa('--separate-out2','-so2',
251 paa('--separate-out2','-so2',
252 type=str, dest='InteractiveShell.separate_out2',
252 type=str, dest='InteractiveShell.separate_out2',
253 help="Separator after output prompts. Default 0 (nonight).",
253 help="Separator after output prompts. Default 0 (nonight).",
254 metavar='InteractiveShell.separate_out2')
254 metavar='InteractiveShell.separate_out2')
255 paa('--no-sep',
255 paa('--no-sep',
256 action='store_true', dest='Global.nosep',
256 action='store_true', dest='Global.nosep',
257 help="Eliminate all spacing between prompts.")
257 help="Eliminate all spacing between prompts.")
258 paa('--term-title',
258 paa('--term-title',
259 action='store_true', dest='InteractiveShell.term_title',
259 action='store_true', dest='InteractiveShell.term_title',
260 help="Enable auto setting the terminal title.")
260 help="Enable auto setting the terminal title.")
261 paa('--no-term-title',
261 paa('--no-term-title',
262 action='store_false', dest='InteractiveShell.term_title',
262 action='store_false', dest='InteractiveShell.term_title',
263 help="Disable auto setting the terminal title.")
263 help="Disable auto setting the terminal title.")
264 paa('--xmode',
264 paa('--xmode',
265 type=str, dest='InteractiveShell.xmode',
265 type=str, dest='InteractiveShell.xmode',
266 help=
266 help=
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 similar to python's normal traceback printing. Context: prints 5 lines
268 similar to python's normal traceback printing. Context: prints 5 lines
269 of context source code around each line in the traceback. Verbose:
269 of context source code around each line in the traceback. Verbose:
270 similar to Context, but additionally prints the variables currently
270 similar to Context, but additionally prints the variables currently
271 visible where the exception happened (shortening their strings if too
271 visible where the exception happened (shortening their strings if too
272 long). This can potentially be very slow, if you happen to have a huge
272 long). This can potentially be very slow, if you happen to have a huge
273 data structure whose string representation is complex to compute.
273 data structure whose string representation is complex to compute.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 it more than once).
276 it more than once).
277 """,
277 """,
278 metavar='InteractiveShell.xmode')
278 metavar='InteractiveShell.xmode')
279 paa('--ext',
279 paa('--ext',
280 type=str, dest='Global.extra_extension',
280 type=str, dest='Global.extra_extension',
281 help="The dotted module name of an IPython extension to load.",
281 help="The dotted module name of an IPython extension to load.",
282 metavar='Global.extra_extension')
282 metavar='Global.extra_extension')
283 paa('-c',
283 paa('-c',
284 type=str, dest='Global.code_to_run',
284 type=str, dest='Global.code_to_run',
285 help="Execute the given command string.",
285 help="Execute the given command string.",
286 metavar='Global.code_to_run')
286 metavar='Global.code_to_run')
287 paa('-i',
287 paa('-i',
288 action='store_true', dest='Global.force_interact',
288 action='store_true', dest='Global.force_interact',
289 help=
289 help=
290 "If running code from the command line, become interactive afterwards.")
290 "If running code from the command line, become interactive afterwards.")
291
291
292 # Options to start with GUI control enabled from the beginning
292 # Options to start with GUI control enabled from the beginning
293 paa('--gui',
293 paa('--gui',
294 type=str, dest='Global.gui',
294 type=str, dest='Global.gui',
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 metavar='gui-mode')
296 metavar='gui-mode')
297 paa('--pylab','-pylab',
297 paa('--pylab','-pylab',
298 type=str, dest='Global.pylab',
298 type=str, dest='Global.pylab',
299 nargs='?', const='auto', metavar='gui-mode',
299 nargs='?', const='auto', metavar='gui-mode',
300 help="Pre-load matplotlib and numpy for interactive use. "+
300 help="Pre-load matplotlib and numpy for interactive use. "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
303
303
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 # 'thread' names are really a misnomer now.
305 # 'thread' names are really a misnomer now.
306 paa('--wthread', '-wthread',
306 paa('--wthread', '-wthread',
307 action='store_true', dest='Global.wthread',
307 action='store_true', dest='Global.wthread',
308 help=
308 help=
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 action='store_true', dest='Global.q4thread',
311 action='store_true', dest='Global.q4thread',
312 help=
312 help=
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 (DEPRECATED, use --gui qt)""")
314 (DEPRECATED, use --gui qt)""")
315 paa('--gthread', '-gthread',
315 paa('--gthread', '-gthread',
316 action='store_true', dest='Global.gthread',
316 action='store_true', dest='Global.gthread',
317 help=
317 help=
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
319
319
320
320
321 #-----------------------------------------------------------------------------
321 #-----------------------------------------------------------------------------
322 # Crash handler for this application
322 # Crash handler for this application
323 #-----------------------------------------------------------------------------
323 #-----------------------------------------------------------------------------
324
324
325
325
326 _message_template = """\
326 _message_template = """\
327 Oops, $self.app_name crashed. We do our best to make it stable, but...
327 Oops, $self.app_name crashed. We do our best to make it stable, but...
328
328
329 A crash report was automatically generated with the following information:
329 A crash report was automatically generated with the following information:
330 - A verbatim copy of the crash traceback.
330 - A verbatim copy of the crash traceback.
331 - A copy of your input history during this session.
331 - A copy of your input history during this session.
332 - Data on your current $self.app_name configuration.
332 - Data on your current $self.app_name configuration.
333
333
334 It was left in the file named:
334 It was left in the file named:
335 \t'$self.crash_report_fname'
335 \t'$self.crash_report_fname'
336 If you can email this file to the developers, the information in it will help
336 If you can email this file to the developers, the information in it will help
337 them in understanding and correcting the problem.
337 them in understanding and correcting the problem.
338
338
339 You can mail it to: $self.contact_name at $self.contact_email
339 You can mail it to: $self.contact_name at $self.contact_email
340 with the subject '$self.app_name Crash Report'.
340 with the subject '$self.app_name Crash Report'.
341
341
342 If you want to do it now, the following command will work (under Unix):
342 If you want to do it now, the following command will work (under Unix):
343 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
343 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
344
344
345 To ensure accurate tracking of this issue, please file a report about it at:
345 To ensure accurate tracking of this issue, please file a report about it at:
346 $self.bug_tracker
346 $self.bug_tracker
347 """
347 """
348
348
349 class IPAppCrashHandler(CrashHandler):
349 class IPAppCrashHandler(CrashHandler):
350 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
350 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
351
351
352 message_template = _message_template
352 message_template = _message_template
353
353
354 def __init__(self, app):
354 def __init__(self, app):
355 contact_name = release.authors['Fernando'][0]
355 contact_name = release.authors['Fernando'][0]
356 contact_email = release.authors['Fernando'][1]
356 contact_email = release.authors['Fernando'][1]
357 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
357 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
358 super(IPAppCrashHandler,self).__init__(
358 super(IPAppCrashHandler,self).__init__(
359 app, contact_name, contact_email, bug_tracker
359 app, contact_name, contact_email, bug_tracker
360 )
360 )
361
361
362 def make_report(self,traceback):
362 def make_report(self,traceback):
363 """Return a string containing a crash report."""
363 """Return a string containing a crash report."""
364
364
365 sec_sep = self.section_sep
365 sec_sep = self.section_sep
366 # Start with parent report
366 # Start with parent report
367 report = [super(IPAppCrashHandler, self).make_report(traceback)]
367 report = [super(IPAppCrashHandler, self).make_report(traceback)]
368 # Add interactive-specific info we may have
368 # Add interactive-specific info we may have
369 rpt_add = report.append
369 rpt_add = report.append
370 try:
370 try:
371 rpt_add(sec_sep+"History of session input:")
371 rpt_add(sec_sep+"History of session input:")
372 for line in self.app.shell.user_ns['_ih']:
372 for line in self.app.shell.user_ns['_ih']:
373 rpt_add(line)
373 rpt_add(line)
374 rpt_add('\n*** Last line of input (may not be in above history):\n')
374 rpt_add('\n*** Last line of input (may not be in above history):\n')
375 rpt_add(self.app.shell._last_input_line+'\n')
375 rpt_add(self.app.shell._last_input_line+'\n')
376 except:
376 except:
377 pass
377 pass
378
378
379 return ''.join(report)
379 return ''.join(report)
380
380
381
381
382 #-----------------------------------------------------------------------------
382 #-----------------------------------------------------------------------------
383 # Main classes and functions
383 # Main classes and functions
384 #-----------------------------------------------------------------------------
384 #-----------------------------------------------------------------------------
385
385
386 class IPythonApp(Application):
386 class IPythonApp(Application):
387 name = u'ipython'
387 name = u'ipython'
388 #: argparse formats better the 'usage' than the 'description' field
388 #: argparse formats better the 'usage' than the 'description' field
389 description = None
389 description = None
390 usage = usage.cl_usage
390 usage = usage.cl_usage
391 command_line_loader = IPAppConfigLoader
391 command_line_loader = IPAppConfigLoader
392 default_config_file_name = default_config_file_name
392 default_config_file_name = default_config_file_name
393 crash_handler_class = IPAppCrashHandler
393 crash_handler_class = IPAppCrashHandler
394
394
395 def create_default_config(self):
395 def create_default_config(self):
396 super(IPythonApp, self).create_default_config()
396 super(IPythonApp, self).create_default_config()
397 # Eliminate multiple lookups
397 # Eliminate multiple lookups
398 Global = self.default_config.Global
398 Global = self.default_config.Global
399
399
400 # Set all default values
400 # Set all default values
401 Global.display_banner = True
401 Global.display_banner = True
402
402
403 # If the -c flag is given or a file is given to run at the cmd line
403 # If the -c flag is given or a file is given to run at the cmd line
404 # like "ipython foo.py", normally we exit without starting the main
404 # like "ipython foo.py", normally we exit without starting the main
405 # loop. The force_interact config variable allows a user to override
405 # loop. The force_interact config variable allows a user to override
406 # this and interact. It is also set by the -i cmd line flag, just
406 # this and interact. It is also set by the -i cmd line flag, just
407 # like Python.
407 # like Python.
408 Global.force_interact = False
408 Global.force_interact = False
409
409
410 # By default always interact by starting the IPython mainloop.
410 # By default always interact by starting the IPython mainloop.
411 Global.interact = True
411 Global.interact = True
412
412
413 # No GUI integration by default
413 # No GUI integration by default
414 Global.gui = False
414 Global.gui = False
415 # Pylab off by default
415 # Pylab off by default
416 Global.pylab = False
416 Global.pylab = False
417
417
418 # Deprecated versions of gui support that used threading, we support
418 # Deprecated versions of gui support that used threading, we support
419 # them just for bacwards compatibility as an alternate spelling for
419 # them just for bacwards compatibility as an alternate spelling for
420 # '--gui X'
420 # '--gui X'
421 Global.qthread = False
421 Global.qthread = False
422 Global.q4thread = False
422 Global.q4thread = False
423 Global.wthread = False
423 Global.wthread = False
424 Global.gthread = False
424 Global.gthread = False
425
425
426 def load_file_config(self):
426 def load_file_config(self):
427 if hasattr(self.command_line_config.Global, 'quick'):
427 if hasattr(self.command_line_config.Global, 'quick'):
428 if self.command_line_config.Global.quick:
428 if self.command_line_config.Global.quick:
429 self.file_config = Config()
429 self.file_config = Config()
430 return
430 return
431 super(IPythonApp, self).load_file_config()
431 super(IPythonApp, self).load_file_config()
432
432
433 def post_load_file_config(self):
433 def post_load_file_config(self):
434 if hasattr(self.command_line_config.Global, 'extra_extension'):
434 if hasattr(self.command_line_config.Global, 'extra_extension'):
435 if not hasattr(self.file_config.Global, 'extensions'):
435 if not hasattr(self.file_config.Global, 'extensions'):
436 self.file_config.Global.extensions = []
436 self.file_config.Global.extensions = []
437 self.file_config.Global.extensions.append(
437 self.file_config.Global.extensions.append(
438 self.command_line_config.Global.extra_extension)
438 self.command_line_config.Global.extra_extension)
439 del self.command_line_config.Global.extra_extension
439 del self.command_line_config.Global.extra_extension
440
440
441 def pre_construct(self):
441 def pre_construct(self):
442 config = self.master_config
442 config = self.master_config
443
443
444 if hasattr(config.Global, 'classic'):
444 if hasattr(config.Global, 'classic'):
445 if config.Global.classic:
445 if config.Global.classic:
446 config.InteractiveShell.cache_size = 0
446 config.InteractiveShell.cache_size = 0
447 config.InteractiveShell.pprint = 0
447 config.InteractiveShell.pprint = 0
448 config.InteractiveShell.prompt_in1 = '>>> '
448 config.InteractiveShell.prompt_in1 = '>>> '
449 config.InteractiveShell.prompt_in2 = '... '
449 config.InteractiveShell.prompt_in2 = '... '
450 config.InteractiveShell.prompt_out = ''
450 config.InteractiveShell.prompt_out = ''
451 config.InteractiveShell.separate_in = \
451 config.InteractiveShell.separate_in = \
452 config.InteractiveShell.separate_out = \
452 config.InteractiveShell.separate_out = \
453 config.InteractiveShell.separate_out2 = ''
453 config.InteractiveShell.separate_out2 = ''
454 config.InteractiveShell.colors = 'NoColor'
454 config.InteractiveShell.colors = 'NoColor'
455 config.InteractiveShell.xmode = 'Plain'
455 config.InteractiveShell.xmode = 'Plain'
456
456
457 if hasattr(config.Global, 'nosep'):
457 if hasattr(config.Global, 'nosep'):
458 if config.Global.nosep:
458 if config.Global.nosep:
459 config.InteractiveShell.separate_in = \
459 config.InteractiveShell.separate_in = \
460 config.InteractiveShell.separate_out = \
460 config.InteractiveShell.separate_out = \
461 config.InteractiveShell.separate_out2 = ''
461 config.InteractiveShell.separate_out2 = ''
462
462
463 # if there is code of files to run from the cmd line, don't interact
463 # if there is code of files to run from the cmd line, don't interact
464 # unless the -i flag (Global.force_interact) is true.
464 # unless the -i flag (Global.force_interact) is true.
465 code_to_run = config.Global.get('code_to_run','')
465 code_to_run = config.Global.get('code_to_run','')
466 file_to_run = False
466 file_to_run = False
467 if self.extra_args and self.extra_args[0]:
467 if self.extra_args and self.extra_args[0]:
468 file_to_run = True
468 file_to_run = True
469 if file_to_run or code_to_run:
469 if file_to_run or code_to_run:
470 if not config.Global.force_interact:
470 if not config.Global.force_interact:
471 config.Global.interact = False
471 config.Global.interact = False
472
472
473 def construct(self):
473 def construct(self):
474 # I am a little hesitant to put these into InteractiveShell itself.
474 # I am a little hesitant to put these into InteractiveShell itself.
475 # But that might be the place for them
475 # But that might be the place for them
476 sys.path.insert(0, '')
476 sys.path.insert(0, '')
477
477
478 # Create an InteractiveShell instance.
478 # Create an InteractiveShell instance.
479 self.shell = InteractiveShell.instance(config=self.master_config)
479 self.shell = InteractiveShell.instance(config=self.master_config)
480
480
481 def post_construct(self):
481 def post_construct(self):
482 """Do actions after construct, but before starting the app."""
482 """Do actions after construct, but before starting the app."""
483 config = self.master_config
483 config = self.master_config
484
484
485 # shell.display_banner should always be False for the terminal
485 # shell.display_banner should always be False for the terminal
486 # based app, because we call shell.show_banner() by hand below
486 # based app, because we call shell.show_banner() by hand below
487 # so the banner shows *before* all extension loading stuff.
487 # so the banner shows *before* all extension loading stuff.
488 self.shell.display_banner = False
488 self.shell.display_banner = False
489 if config.Global.display_banner and \
489 if config.Global.display_banner and \
490 config.Global.interact:
490 config.Global.interact:
491 self.shell.show_banner()
491 self.shell.show_banner()
492
492
493 # Make sure there is a space below the banner.
493 # Make sure there is a space below the banner.
494 if self.log_level <= logging.INFO: print
494 if self.log_level <= logging.INFO: print
495
495
496 # Now a variety of things that happen after the banner is printed.
496 # Now a variety of things that happen after the banner is printed.
497 self._enable_gui_pylab()
497 self._enable_gui_pylab()
498 self._load_extensions()
498 self._load_extensions()
499 self._run_exec_lines()
499 self._run_exec_lines()
500 self._run_exec_files()
500 self._run_exec_files()
501 self._run_cmd_line_code()
501 self._run_cmd_line_code()
502
502
503 def _enable_gui_pylab(self):
503 def _enable_gui_pylab(self):
504 """Enable GUI event loop integration, taking pylab into account."""
504 """Enable GUI event loop integration, taking pylab into account."""
505 Global = self.master_config.Global
505 Global = self.master_config.Global
506
506
507 # Select which gui to use
507 # Select which gui to use
508 if Global.gui:
508 if Global.gui:
509 gui = Global.gui
509 gui = Global.gui
510 # The following are deprecated, but there's likely to be a lot of use
510 # The following are deprecated, but there's likely to be a lot of use
511 # of this form out there, so we might as well support it for now. But
511 # of this form out there, so we might as well support it for now. But
512 # the --gui option above takes precedence.
512 # the --gui option above takes precedence.
513 elif Global.wthread:
513 elif Global.wthread:
514 gui = inputhook.GUI_WX
514 gui = inputhook.GUI_WX
515 elif Global.qthread:
515 elif Global.qthread:
516 gui = inputhook.GUI_QT
516 gui = inputhook.GUI_QT
517 elif Global.gthread:
517 elif Global.gthread:
518 gui = inputhook.GUI_GTK
518 gui = inputhook.GUI_GTK
519 else:
519 else:
520 gui = None
520 gui = None
521
521
522 # Using --pylab will also require gui activation, though which toolkit
522 # Using --pylab will also require gui activation, though which toolkit
523 # to use may be chosen automatically based on mpl configuration.
523 # to use may be chosen automatically based on mpl configuration.
524 if Global.pylab:
524 if Global.pylab:
525 activate = self.shell.enable_pylab
525 activate = self.shell.enable_pylab
526 if Global.pylab == 'auto':
526 if Global.pylab == 'auto':
527 gui = None
527 gui = None
528 else:
528 else:
529 gui = Global.pylab
529 gui = Global.pylab
530 else:
530 else:
531 # Enable only GUI integration, no pylab
531 # Enable only GUI integration, no pylab
532 activate = inputhook.enable_gui
532 activate = inputhook.enable_gui
533
533
534 if gui or Global.pylab:
534 if gui or Global.pylab:
535 try:
535 try:
536 self.log.info("Enabling GUI event loop integration, "
536 self.log.info("Enabling GUI event loop integration, "
537 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
537 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
538 activate(gui)
538 activate(gui)
539 except:
539 except:
540 self.log.warn("Error in enabling GUI event loop integration:")
540 self.log.warn("Error in enabling GUI event loop integration:")
541 self.shell.showtraceback()
541 self.shell.showtraceback()
542
542
543 def _load_extensions(self):
543 def _load_extensions(self):
544 """Load all IPython extensions in Global.extensions.
544 """Load all IPython extensions in Global.extensions.
545
545
546 This uses the :meth:`ExtensionManager.load_extensions` to load all
546 This uses the :meth:`ExtensionManager.load_extensions` to load all
547 the extensions listed in ``self.master_config.Global.extensions``.
547 the extensions listed in ``self.master_config.Global.extensions``.
548 """
548 """
549 try:
549 try:
550 if hasattr(self.master_config.Global, 'extensions'):
550 if hasattr(self.master_config.Global, 'extensions'):
551 self.log.debug("Loading IPython extensions...")
551 self.log.debug("Loading IPython extensions...")
552 extensions = self.master_config.Global.extensions
552 extensions = self.master_config.Global.extensions
553 for ext in extensions:
553 for ext in extensions:
554 try:
554 try:
555 self.log.info("Loading IPython extension: %s" % ext)
555 self.log.info("Loading IPython extension: %s" % ext)
556 self.shell.extension_manager.load_extension(ext)
556 self.shell.extension_manager.load_extension(ext)
557 except:
557 except:
558 self.log.warn("Error in loading extension: %s" % ext)
558 self.log.warn("Error in loading extension: %s" % ext)
559 self.shell.showtraceback()
559 self.shell.showtraceback()
560 except:
560 except:
561 self.log.warn("Unknown error in loading extensions:")
561 self.log.warn("Unknown error in loading extensions:")
562 self.shell.showtraceback()
562 self.shell.showtraceback()
563
563
564 def _run_exec_lines(self):
564 def _run_exec_lines(self):
565 """Run lines of code in Global.exec_lines in the user's namespace."""
565 """Run lines of code in Global.exec_lines in the user's namespace."""
566 try:
566 try:
567 if hasattr(self.master_config.Global, 'exec_lines'):
567 if hasattr(self.master_config.Global, 'exec_lines'):
568 self.log.debug("Running code from Global.exec_lines...")
568 self.log.debug("Running code from Global.exec_lines...")
569 exec_lines = self.master_config.Global.exec_lines
569 exec_lines = self.master_config.Global.exec_lines
570 for line in exec_lines:
570 for line in exec_lines:
571 try:
571 try:
572 self.log.info("Running code in user namespace: %s" %
572 self.log.info("Running code in user namespace: %s" %
573 line)
573 line)
574 self.shell.runlines(line)
574 self.shell.runlines(line)
575 except:
575 except:
576 self.log.warn("Error in executing line in user "
576 self.log.warn("Error in executing line in user "
577 "namespace: %s" % line)
577 "namespace: %s" % line)
578 self.shell.showtraceback()
578 self.shell.showtraceback()
579 except:
579 except:
580 self.log.warn("Unknown error in handling Global.exec_lines:")
580 self.log.warn("Unknown error in handling Global.exec_lines:")
581 self.shell.showtraceback()
581 self.shell.showtraceback()
582
582
583 def _exec_file(self, fname):
583 def _exec_file(self, fname):
584 full_filename = filefind(fname, [u'.', self.ipython_dir])
584 full_filename = filefind(fname, [u'.', self.ipython_dir])
585 if os.path.isfile(full_filename):
585 if os.path.isfile(full_filename):
586 if full_filename.endswith(u'.py'):
586 if full_filename.endswith(u'.py'):
587 self.log.info("Running file in user namespace: %s" %
587 self.log.info("Running file in user namespace: %s" %
588 full_filename)
588 full_filename)
589 # Ensure that __file__ is always defined to match Python behavior
589 # Ensure that __file__ is always defined to match Python behavior
590 self.shell.user_ns['__file__'] = fname
590 self.shell.user_ns['__file__'] = fname
591 try:
591 try:
592 self.shell.safe_execfile(full_filename, self.shell.user_ns)
592 self.shell.safe_execfile(full_filename, self.shell.user_ns)
593 finally:
593 finally:
594 del self.shell.user_ns['__file__']
594 del self.shell.user_ns['__file__']
595 elif full_filename.endswith('.ipy'):
595 elif full_filename.endswith('.ipy'):
596 self.log.info("Running file in user namespace: %s" %
596 self.log.info("Running file in user namespace: %s" %
597 full_filename)
597 full_filename)
598 self.shell.safe_execfile_ipy(full_filename)
598 self.shell.safe_execfile_ipy(full_filename)
599 else:
599 else:
600 self.log.warn("File does not have a .py or .ipy extension: <%s>"
600 self.log.warn("File does not have a .py or .ipy extension: <%s>"
601 % full_filename)
601 % full_filename)
602 def _run_exec_files(self):
602 def _run_exec_files(self):
603 try:
603 try:
604 if hasattr(self.master_config.Global, 'exec_files'):
604 if hasattr(self.master_config.Global, 'exec_files'):
605 self.log.debug("Running files in Global.exec_files...")
605 self.log.debug("Running files in Global.exec_files...")
606 exec_files = self.master_config.Global.exec_files
606 exec_files = self.master_config.Global.exec_files
607 for fname in exec_files:
607 for fname in exec_files:
608 self._exec_file(fname)
608 self._exec_file(fname)
609 except:
609 except:
610 self.log.warn("Unknown error in handling Global.exec_files:")
610 self.log.warn("Unknown error in handling Global.exec_files:")
611 self.shell.showtraceback()
611 self.shell.showtraceback()
612
612
613 def _run_cmd_line_code(self):
613 def _run_cmd_line_code(self):
614 if hasattr(self.master_config.Global, 'code_to_run'):
614 if hasattr(self.master_config.Global, 'code_to_run'):
615 line = self.master_config.Global.code_to_run
615 line = self.master_config.Global.code_to_run
616 try:
616 try:
617 self.log.info("Running code given at command line (-c): %s" %
617 self.log.info("Running code given at command line (-c): %s" %
618 line)
618 line)
619 self.shell.runlines(line)
619 self.shell.runlines(line)
620 except:
620 except:
621 self.log.warn("Error in executing line in user namespace: %s" %
621 self.log.warn("Error in executing line in user namespace: %s" %
622 line)
622 line)
623 self.shell.showtraceback()
623 self.shell.showtraceback()
624 return
624 return
625 # Like Python itself, ignore the second if the first of these is present
625 # Like Python itself, ignore the second if the first of these is present
626 try:
626 try:
627 fname = self.extra_args[0]
627 fname = self.extra_args[0]
628 except:
628 except:
629 pass
629 pass
630 else:
630 else:
631 try:
631 try:
632 self._exec_file(fname)
632 self._exec_file(fname)
633 except:
633 except:
634 self.log.warn("Error in executing file in user namespace: %s" %
634 self.log.warn("Error in executing file in user namespace: %s" %
635 fname)
635 fname)
636 self.shell.showtraceback()
636 self.shell.showtraceback()
637
637
638 def start_app(self):
638 def start_app(self):
639 if self.master_config.Global.interact:
639 if self.master_config.Global.interact:
640 self.log.debug("Starting IPython's mainloop...")
640 self.log.debug("Starting IPython's mainloop...")
641 self.shell.mainloop()
641 self.shell.mainloop()
642 else:
642 else:
643 self.log.debug("IPython not interactive, start_app is no-op...")
643 self.log.debug("IPython not interactive, start_app is no-op...")
644
644
645
645
646 def load_default_config(ipython_dir=None):
646 def load_default_config(ipython_dir=None):
647 """Load the default config file from the default ipython_dir.
647 """Load the default config file from the default ipython_dir.
648
648
649 This is useful for embedded shells.
649 This is useful for embedded shells.
650 """
650 """
651 if ipython_dir is None:
651 if ipython_dir is None:
652 ipython_dir = get_ipython_dir()
652 ipython_dir = get_ipython_dir()
653 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
653 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
654 config = cl.load_config()
654 config = cl.load_config()
655 return config
655 return config
656
656
657
657
658 def launch_new_instance():
658 def launch_new_instance():
659 """Create and run a full blown IPython instance"""
659 """Create and run a full blown IPython instance"""
660 app = IPythonApp()
660 app = IPythonApp()
661 app.start()
661 app.start()
662
662
663
663
664 if __name__ == '__main__':
664 if __name__ == '__main__':
665 launch_new_instance()
665 launch_new_instance()
@@ -1,6 +1,6 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
2 # -*- coding: utf-8 -*-
3
3
4 from IPython.core.ipapp import launch_new_instance
4 from IPython.frontend.terminal.ipapp import launch_new_instance
5
5
6 launch_new_instance()
6 launch_new_instance()
@@ -1,174 +1,174 b''
1 """Global IPython app to support test running.
1 """Global IPython app to support test running.
2
2
3 We must start our own ipython object and heavily muck with it so that all the
3 We must start our own ipython object and heavily muck with it so that all the
4 modifications IPython makes to system behavior don't send the doctest machinery
4 modifications IPython makes to system behavior don't send the doctest machinery
5 into a fit. This code should be considered a gross hack, but it gets the job
5 into a fit. This code should be considered a gross hack, but it gets the job
6 done.
6 done.
7 """
7 """
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2009 The IPython Development Team
12 # Copyright (C) 2009 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import __builtin__
22 import __builtin__
23 import commands
23 import commands
24 import os
24 import os
25 import sys
25 import sys
26
26
27 from . import tools
27 from . import tools
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Functions
30 # Functions
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 # Hack to modify the %run command so we can sync the user's namespace with the
33 # Hack to modify the %run command so we can sync the user's namespace with the
34 # test globals. Once we move over to a clean magic system, this will be done
34 # test globals. Once we move over to a clean magic system, this will be done
35 # with much less ugliness.
35 # with much less ugliness.
36
36
37 class py_file_finder(object):
37 class py_file_finder(object):
38 def __init__(self,test_filename):
38 def __init__(self,test_filename):
39 self.test_filename = test_filename
39 self.test_filename = test_filename
40
40
41 def __call__(self,name):
41 def __call__(self,name):
42 from IPython.utils.path import get_py_filename
42 from IPython.utils.path import get_py_filename
43 try:
43 try:
44 return get_py_filename(name)
44 return get_py_filename(name)
45 except IOError:
45 except IOError:
46 test_dir = os.path.dirname(self.test_filename)
46 test_dir = os.path.dirname(self.test_filename)
47 new_path = os.path.join(test_dir,name)
47 new_path = os.path.join(test_dir,name)
48 return get_py_filename(new_path)
48 return get_py_filename(new_path)
49
49
50
50
51 def _run_ns_sync(self,arg_s,runner=None):
51 def _run_ns_sync(self,arg_s,runner=None):
52 """Modified version of %run that syncs testing namespaces.
52 """Modified version of %run that syncs testing namespaces.
53
53
54 This is strictly needed for running doctests that call %run.
54 This is strictly needed for running doctests that call %run.
55 """
55 """
56 #print >> sys.stderr, 'in run_ns_sync', arg_s # dbg
56 #print >> sys.stderr, 'in run_ns_sync', arg_s # dbg
57
57
58 _ip = get_ipython()
58 _ip = get_ipython()
59 finder = py_file_finder(arg_s)
59 finder = py_file_finder(arg_s)
60 out = _ip.magic_run_ori(arg_s,runner,finder)
60 out = _ip.magic_run_ori(arg_s,runner,finder)
61 return out
61 return out
62
62
63
63
64 class ipnsdict(dict):
64 class ipnsdict(dict):
65 """A special subclass of dict for use as an IPython namespace in doctests.
65 """A special subclass of dict for use as an IPython namespace in doctests.
66
66
67 This subclass adds a simple checkpointing capability so that when testing
67 This subclass adds a simple checkpointing capability so that when testing
68 machinery clears it (we use it as the test execution context), it doesn't
68 machinery clears it (we use it as the test execution context), it doesn't
69 get completely destroyed.
69 get completely destroyed.
70 """
70 """
71
71
72 def __init__(self,*a):
72 def __init__(self,*a):
73 dict.__init__(self,*a)
73 dict.__init__(self,*a)
74 self._savedict = {}
74 self._savedict = {}
75
75
76 def clear(self):
76 def clear(self):
77 dict.clear(self)
77 dict.clear(self)
78 self.update(self._savedict)
78 self.update(self._savedict)
79
79
80 def _checkpoint(self):
80 def _checkpoint(self):
81 self._savedict.clear()
81 self._savedict.clear()
82 self._savedict.update(self)
82 self._savedict.update(self)
83
83
84 def update(self,other):
84 def update(self,other):
85 self._checkpoint()
85 self._checkpoint()
86 dict.update(self,other)
86 dict.update(self,other)
87
87
88 # If '_' is in the namespace, python won't set it when executing code,
88 # If '_' is in the namespace, python won't set it when executing code,
89 # and we have examples that test it. So we ensure that the namespace
89 # and we have examples that test it. So we ensure that the namespace
90 # is always 'clean' of it before it's used for test code execution.
90 # is always 'clean' of it before it's used for test code execution.
91 self.pop('_',None)
91 self.pop('_',None)
92
92
93 # The builtins namespace must *always* be the real __builtin__ module,
93 # The builtins namespace must *always* be the real __builtin__ module,
94 # else weird stuff happens. The main ipython code does have provisions
94 # else weird stuff happens. The main ipython code does have provisions
95 # to ensure this after %run, but since in this class we do some
95 # to ensure this after %run, but since in this class we do some
96 # aggressive low-level cleaning of the execution namespace, we need to
96 # aggressive low-level cleaning of the execution namespace, we need to
97 # correct for that ourselves, to ensure consitency with the 'real'
97 # correct for that ourselves, to ensure consitency with the 'real'
98 # ipython.
98 # ipython.
99 self['__builtins__'] = __builtin__
99 self['__builtins__'] = __builtin__
100
100
101
101
102 def get_ipython():
102 def get_ipython():
103 # This will get replaced by the real thing once we start IPython below
103 # This will get replaced by the real thing once we start IPython below
104 return start_ipython()
104 return start_ipython()
105
105
106
106
107 def start_ipython():
107 def start_ipython():
108 """Start a global IPython shell, which we need for IPython-specific syntax.
108 """Start a global IPython shell, which we need for IPython-specific syntax.
109 """
109 """
110 global get_ipython
110 global get_ipython
111
111
112 # This function should only ever run once!
112 # This function should only ever run once!
113 if hasattr(start_ipython, 'already_called'):
113 if hasattr(start_ipython, 'already_called'):
114 return
114 return
115 start_ipython.already_called = True
115 start_ipython.already_called = True
116
116
117 # Ok, first time we're called, go ahead
117 # Ok, first time we're called, go ahead
118 from IPython.core import iplib
118 from IPython.core import interactiveshell
119
119
120 def xsys(cmd):
120 def xsys(cmd):
121 """Execute a command and print its output.
121 """Execute a command and print its output.
122
122
123 This is just a convenience function to replace the IPython system call
123 This is just a convenience function to replace the IPython system call
124 with one that is more doctest-friendly.
124 with one that is more doctest-friendly.
125 """
125 """
126 cmd = _ip.var_expand(cmd,depth=1)
126 cmd = _ip.var_expand(cmd,depth=1)
127 sys.stdout.write(commands.getoutput(cmd))
127 sys.stdout.write(commands.getoutput(cmd))
128 sys.stdout.flush()
128 sys.stdout.flush()
129
129
130 # Store certain global objects that IPython modifies
130 # Store certain global objects that IPython modifies
131 _displayhook = sys.displayhook
131 _displayhook = sys.displayhook
132 _excepthook = sys.excepthook
132 _excepthook = sys.excepthook
133 _main = sys.modules.get('__main__')
133 _main = sys.modules.get('__main__')
134
134
135 # Create custom argv and namespaces for our IPython to be test-friendly
135 # Create custom argv and namespaces for our IPython to be test-friendly
136 config = tools.default_config()
136 config = tools.default_config()
137
137
138 # Create and initialize our test-friendly IPython instance.
138 # Create and initialize our test-friendly IPython instance.
139 shell = iplib.InteractiveShell.instance(
139 shell = interactiveshell.InteractiveShell.instance(
140 config=config,
140 config=config,
141 user_ns=ipnsdict(), user_global_ns={}
141 user_ns=ipnsdict(), user_global_ns={}
142 )
142 )
143
143
144 # A few more tweaks needed for playing nicely with doctests...
144 # A few more tweaks needed for playing nicely with doctests...
145
145
146 # These traps are normally only active for interactive use, set them
146 # These traps are normally only active for interactive use, set them
147 # permanently since we'll be mocking interactive sessions.
147 # permanently since we'll be mocking interactive sessions.
148 shell.builtin_trap.set()
148 shell.builtin_trap.set()
149
149
150 # Set error printing to stdout so nose can doctest exceptions
150 # Set error printing to stdout so nose can doctest exceptions
151 shell.InteractiveTB.out_stream = 'stdout'
151 shell.InteractiveTB.out_stream = 'stdout'
152
152
153 # Modify the IPython system call with one that uses getoutput, so that we
153 # Modify the IPython system call with one that uses getoutput, so that we
154 # can capture subcommands and print them to Python's stdout, otherwise the
154 # can capture subcommands and print them to Python's stdout, otherwise the
155 # doctest machinery would miss them.
155 # doctest machinery would miss them.
156 shell.system = xsys
156 shell.system = xsys
157
157
158 # IPython is ready, now clean up some global state...
158 # IPython is ready, now clean up some global state...
159
159
160 # Deactivate the various python system hooks added by ipython for
160 # Deactivate the various python system hooks added by ipython for
161 # interactive convenience so we don't confuse the doctest system
161 # interactive convenience so we don't confuse the doctest system
162 sys.modules['__main__'] = _main
162 sys.modules['__main__'] = _main
163 sys.displayhook = _displayhook
163 sys.displayhook = _displayhook
164 sys.excepthook = _excepthook
164 sys.excepthook = _excepthook
165
165
166 # So that ipython magics and aliases can be doctested (they work by making
166 # So that ipython magics and aliases can be doctested (they work by making
167 # a call into a global _ip object). Also make the top-level get_ipython
167 # a call into a global _ip object). Also make the top-level get_ipython
168 # now return this without recursively calling here again.
168 # now return this without recursively calling here again.
169 _ip = shell
169 _ip = shell
170 get_ipython = _ip.get_ipython
170 get_ipython = _ip.get_ipython
171 __builtin__._ip = _ip
171 __builtin__._ip = _ip
172 __builtin__.get_ipython = get_ipython
172 __builtin__.get_ipython = get_ipython
173
173
174 return _ip
174 return _ip
@@ -1,446 +1,442 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Test Suite Runner.
2 """IPython Test Suite Runner.
3
3
4 This module provides a main entry point to a user script to test IPython
4 This module provides a main entry point to a user script to test IPython
5 itself from the command line. There are two ways of running this script:
5 itself from the command line. There are two ways of running this script:
6
6
7 1. With the syntax `iptest all`. This runs our entire test suite by
7 1. With the syntax `iptest all`. This runs our entire test suite by
8 calling this script (with different arguments) or trial recursively. This
8 calling this script (with different arguments) or trial recursively. This
9 causes modules and package to be tested in different processes, using nose
9 causes modules and package to be tested in different processes, using nose
10 or trial where appropriate.
10 or trial where appropriate.
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
12 the script simply calls nose, but with special command line flags and
12 the script simply calls nose, but with special command line flags and
13 plugins loaded.
13 plugins loaded.
14
14
15 For now, this script requires that both nose and twisted are installed. This
15 For now, this script requires that both nose and twisted are installed. This
16 will change in the future.
16 will change in the future.
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2009 The IPython Development Team
20 # Copyright (C) 2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 # Stdlib
30 # Stdlib
31 import os
31 import os
32 import os.path as path
32 import os.path as path
33 import signal
33 import signal
34 import sys
34 import sys
35 import subprocess
35 import subprocess
36 import tempfile
36 import tempfile
37 import time
37 import time
38 import warnings
38 import warnings
39
39
40 # Note: monkeypatch!
40 # Note: monkeypatch!
41 # We need to monkeypatch a small problem in nose itself first, before importing
41 # We need to monkeypatch a small problem in nose itself first, before importing
42 # it for actual use. This should get into nose upstream, but its release cycle
42 # it for actual use. This should get into nose upstream, but its release cycle
43 # is slow and we need it for our parametric tests to work correctly.
43 # is slow and we need it for our parametric tests to work correctly.
44 from IPython.testing import nosepatch
44 from IPython.testing import nosepatch
45 # Now, proceed to import nose itself
45 # Now, proceed to import nose itself
46 import nose.plugins.builtin
46 import nose.plugins.builtin
47 from nose.core import TestProgram
47 from nose.core import TestProgram
48
48
49 # Our own imports
49 # Our own imports
50 from IPython.utils.path import get_ipython_module_path
50 from IPython.utils.path import get_ipython_module_path
51 from IPython.utils.process import find_cmd, pycmd2argv
51 from IPython.utils.process import find_cmd, pycmd2argv
52 from IPython.utils.sysinfo import sys_info
52 from IPython.utils.sysinfo import sys_info
53
53
54 from IPython.testing import globalipapp
54 from IPython.testing import globalipapp
55 from IPython.testing.plugin.ipdoctest import IPythonDoctest
55 from IPython.testing.plugin.ipdoctest import IPythonDoctest
56
56
57 pjoin = path.join
57 pjoin = path.join
58
58
59
59
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61 # Globals
61 # Globals
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63
63
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Warnings control
66 # Warnings control
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 # Twisted generates annoying warnings with Python 2.6, as will do other code
69 # Twisted generates annoying warnings with Python 2.6, as will do other code
70 # that imports 'sets' as of today
70 # that imports 'sets' as of today
71 warnings.filterwarnings('ignore', 'the sets module is deprecated',
71 warnings.filterwarnings('ignore', 'the sets module is deprecated',
72 DeprecationWarning )
72 DeprecationWarning )
73
73
74 # This one also comes from Twisted
74 # This one also comes from Twisted
75 warnings.filterwarnings('ignore', 'the sha module is deprecated',
75 warnings.filterwarnings('ignore', 'the sha module is deprecated',
76 DeprecationWarning)
76 DeprecationWarning)
77
77
78 # Wx on Fedora11 spits these out
78 # Wx on Fedora11 spits these out
79 warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
79 warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
80 UserWarning)
80 UserWarning)
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 # Logic for skipping doctests
83 # Logic for skipping doctests
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85
85
86 def test_for(mod):
86 def test_for(mod):
87 """Test to see if mod is importable."""
87 """Test to see if mod is importable."""
88 try:
88 try:
89 __import__(mod)
89 __import__(mod)
90 except (ImportError, RuntimeError):
90 except (ImportError, RuntimeError):
91 # GTK reports Runtime error if it can't be initialized even if it's
91 # GTK reports Runtime error if it can't be initialized even if it's
92 # importable.
92 # importable.
93 return False
93 return False
94 else:
94 else:
95 return True
95 return True
96
96
97 # Global dict where we can store information on what we have and what we don't
97 # Global dict where we can store information on what we have and what we don't
98 # have available at test run time
98 # have available at test run time
99 have = {}
99 have = {}
100
100
101 have['curses'] = test_for('_curses')
101 have['curses'] = test_for('_curses')
102 have['wx'] = test_for('wx')
102 have['wx'] = test_for('wx')
103 have['wx.aui'] = test_for('wx.aui')
103 have['wx.aui'] = test_for('wx.aui')
104 have['zope.interface'] = test_for('zope.interface')
104 have['zope.interface'] = test_for('zope.interface')
105 have['twisted'] = test_for('twisted')
105 have['twisted'] = test_for('twisted')
106 have['foolscap'] = test_for('foolscap')
106 have['foolscap'] = test_for('foolscap')
107 have['pexpect'] = test_for('pexpect')
107 have['pexpect'] = test_for('pexpect')
108 have['gtk'] = test_for('gtk')
108 have['gtk'] = test_for('gtk')
109 have['gobject'] = test_for('gobject')
109 have['gobject'] = test_for('gobject')
110
110
111 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
112 # Functions and classes
112 # Functions and classes
113 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
114
114
115 def report():
115 def report():
116 """Return a string with a summary report of test-related variables."""
116 """Return a string with a summary report of test-related variables."""
117
117
118 out = [ sys_info() ]
118 out = [ sys_info() ]
119
119
120 avail = []
120 avail = []
121 not_avail = []
121 not_avail = []
122
122
123 for k, is_avail in have.items():
123 for k, is_avail in have.items():
124 if is_avail:
124 if is_avail:
125 avail.append(k)
125 avail.append(k)
126 else:
126 else:
127 not_avail.append(k)
127 not_avail.append(k)
128
128
129 if avail:
129 if avail:
130 out.append('\nTools and libraries available at test time:\n')
130 out.append('\nTools and libraries available at test time:\n')
131 avail.sort()
131 avail.sort()
132 out.append(' ' + ' '.join(avail)+'\n')
132 out.append(' ' + ' '.join(avail)+'\n')
133
133
134 if not_avail:
134 if not_avail:
135 out.append('\nTools and libraries NOT available at test time:\n')
135 out.append('\nTools and libraries NOT available at test time:\n')
136 not_avail.sort()
136 not_avail.sort()
137 out.append(' ' + ' '.join(not_avail)+'\n')
137 out.append(' ' + ' '.join(not_avail)+'\n')
138
138
139 return ''.join(out)
139 return ''.join(out)
140
140
141
141
142 def make_exclude():
142 def make_exclude():
143 """Make patterns of modules and packages to exclude from testing.
143 """Make patterns of modules and packages to exclude from testing.
144
144
145 For the IPythonDoctest plugin, we need to exclude certain patterns that
145 For the IPythonDoctest plugin, we need to exclude certain patterns that
146 cause testing problems. We should strive to minimize the number of
146 cause testing problems. We should strive to minimize the number of
147 skipped modules, since this means untested code.
147 skipped modules, since this means untested code.
148
148
149 These modules and packages will NOT get scanned by nose at all for tests.
149 These modules and packages will NOT get scanned by nose at all for tests.
150 """
150 """
151 # Simple utility to make IPython paths more readably, we need a lot of
151 # Simple utility to make IPython paths more readably, we need a lot of
152 # these below
152 # these below
153 ipjoin = lambda *paths: pjoin('IPython', *paths)
153 ipjoin = lambda *paths: pjoin('IPython', *paths)
154
154
155 exclusions = [ipjoin('external'),
155 exclusions = [ipjoin('external'),
156 # Deprecated old Shell and iplib modules, skip to avoid
157 # warnings
158 ipjoin('Shell'),
159 ipjoin('iplib'),
160 pjoin('IPython_doctest_plugin'),
156 pjoin('IPython_doctest_plugin'),
161 ipjoin('quarantine'),
157 ipjoin('quarantine'),
162 ipjoin('deathrow'),
158 ipjoin('deathrow'),
163 ipjoin('testing', 'attic'),
159 ipjoin('testing', 'attic'),
164 # This guy is probably attic material
160 # This guy is probably attic material
165 ipjoin('testing', 'mkdoctests'),
161 ipjoin('testing', 'mkdoctests'),
166 # Testing inputhook will need a lot of thought, to figure out
162 # Testing inputhook will need a lot of thought, to figure out
167 # how to have tests that don't lock up with the gui event
163 # how to have tests that don't lock up with the gui event
168 # loops in the picture
164 # loops in the picture
169 ipjoin('lib', 'inputhook'),
165 ipjoin('lib', 'inputhook'),
170 # Config files aren't really importable stand-alone
166 # Config files aren't really importable stand-alone
171 ipjoin('config', 'default'),
167 ipjoin('config', 'default'),
172 ipjoin('config', 'profile'),
168 ipjoin('config', 'profile'),
173 ]
169 ]
174
170
175 if not have['wx']:
171 if not have['wx']:
176 exclusions.append(ipjoin('lib', 'inputhookwx'))
172 exclusions.append(ipjoin('lib', 'inputhookwx'))
177
173
178 if not have['gtk'] or not have['gobject']:
174 if not have['gtk'] or not have['gobject']:
179 exclusions.append(ipjoin('lib', 'inputhookgtk'))
175 exclusions.append(ipjoin('lib', 'inputhookgtk'))
180
176
181 # These have to be skipped on win32 because the use echo, rm, cd, etc.
177 # These have to be skipped on win32 because the use echo, rm, cd, etc.
182 # See ticket https://bugs.launchpad.net/bugs/366982
178 # See ticket https://bugs.launchpad.net/bugs/366982
183 if sys.platform == 'win32':
179 if sys.platform == 'win32':
184 exclusions.append(ipjoin('testing', 'plugin', 'test_exampleip'))
180 exclusions.append(ipjoin('testing', 'plugin', 'test_exampleip'))
185 exclusions.append(ipjoin('testing', 'plugin', 'dtexample'))
181 exclusions.append(ipjoin('testing', 'plugin', 'dtexample'))
186
182
187 if not have['pexpect']:
183 if not have['pexpect']:
188 exclusions.extend([ipjoin('scripts', 'irunner'),
184 exclusions.extend([ipjoin('scripts', 'irunner'),
189 ipjoin('lib', 'irunner')])
185 ipjoin('lib', 'irunner')])
190
186
191 # This is scary. We still have things in frontend and testing that
187 # This is scary. We still have things in frontend and testing that
192 # are being tested by nose that use twisted. We need to rethink
188 # are being tested by nose that use twisted. We need to rethink
193 # how we are isolating dependencies in testing.
189 # how we are isolating dependencies in testing.
194 if not (have['twisted'] and have['zope.interface'] and have['foolscap']):
190 if not (have['twisted'] and have['zope.interface'] and have['foolscap']):
195 exclusions.extend(
191 exclusions.extend(
196 [ipjoin('testing', 'parametric'),
192 [ipjoin('testing', 'parametric'),
197 ipjoin('testing', 'util'),
193 ipjoin('testing', 'util'),
198 ipjoin('testing', 'tests', 'test_decorators_trial'),
194 ipjoin('testing', 'tests', 'test_decorators_trial'),
199 ] )
195 ] )
200
196
201 # This is needed for the reg-exp to match on win32 in the ipdoctest plugin.
197 # This is needed for the reg-exp to match on win32 in the ipdoctest plugin.
202 if sys.platform == 'win32':
198 if sys.platform == 'win32':
203 exclusions = [s.replace('\\','\\\\') for s in exclusions]
199 exclusions = [s.replace('\\','\\\\') for s in exclusions]
204
200
205 return exclusions
201 return exclusions
206
202
207
203
208 class IPTester(object):
204 class IPTester(object):
209 """Call that calls iptest or trial in a subprocess.
205 """Call that calls iptest or trial in a subprocess.
210 """
206 """
211 #: string, name of test runner that will be called
207 #: string, name of test runner that will be called
212 runner = None
208 runner = None
213 #: list, parameters for test runner
209 #: list, parameters for test runner
214 params = None
210 params = None
215 #: list, arguments of system call to be made to call test runner
211 #: list, arguments of system call to be made to call test runner
216 call_args = None
212 call_args = None
217 #: list, process ids of subprocesses we start (for cleanup)
213 #: list, process ids of subprocesses we start (for cleanup)
218 pids = None
214 pids = None
219
215
220 def __init__(self, runner='iptest', params=None):
216 def __init__(self, runner='iptest', params=None):
221 """Create new test runner."""
217 """Create new test runner."""
222 p = os.path
218 p = os.path
223 if runner == 'iptest':
219 if runner == 'iptest':
224 iptest_app = get_ipython_module_path('IPython.testing.iptest')
220 iptest_app = get_ipython_module_path('IPython.testing.iptest')
225 self.runner = pycmd2argv(iptest_app) + sys.argv[1:]
221 self.runner = pycmd2argv(iptest_app) + sys.argv[1:]
226 elif runner == 'trial':
222 elif runner == 'trial':
227 # For trial, it needs to be installed system-wide
223 # For trial, it needs to be installed system-wide
228 self.runner = pycmd2argv(p.abspath(find_cmd('trial')))
224 self.runner = pycmd2argv(p.abspath(find_cmd('trial')))
229 else:
225 else:
230 raise Exception('Not a valid test runner: %s' % repr(runner))
226 raise Exception('Not a valid test runner: %s' % repr(runner))
231 if params is None:
227 if params is None:
232 params = []
228 params = []
233 if isinstance(params, str):
229 if isinstance(params, str):
234 params = [params]
230 params = [params]
235 self.params = params
231 self.params = params
236
232
237 # Assemble call
233 # Assemble call
238 self.call_args = self.runner+self.params
234 self.call_args = self.runner+self.params
239
235
240 # Store pids of anything we start to clean up on deletion, if possible
236 # Store pids of anything we start to clean up on deletion, if possible
241 # (on posix only, since win32 has no os.kill)
237 # (on posix only, since win32 has no os.kill)
242 self.pids = []
238 self.pids = []
243
239
244 if sys.platform == 'win32':
240 if sys.platform == 'win32':
245 def _run_cmd(self):
241 def _run_cmd(self):
246 # On Windows, use os.system instead of subprocess.call, because I
242 # On Windows, use os.system instead of subprocess.call, because I
247 # was having problems with subprocess and I just don't know enough
243 # was having problems with subprocess and I just don't know enough
248 # about win32 to debug this reliably. Os.system may be the 'old
244 # about win32 to debug this reliably. Os.system may be the 'old
249 # fashioned' way to do it, but it works just fine. If someone
245 # fashioned' way to do it, but it works just fine. If someone
250 # later can clean this up that's fine, as long as the tests run
246 # later can clean this up that's fine, as long as the tests run
251 # reliably in win32.
247 # reliably in win32.
252 # What types of problems are you having. They may be related to
248 # What types of problems are you having. They may be related to
253 # running Python in unboffered mode. BG.
249 # running Python in unboffered mode. BG.
254 return os.system(' '.join(self.call_args))
250 return os.system(' '.join(self.call_args))
255 else:
251 else:
256 def _run_cmd(self):
252 def _run_cmd(self):
257 #print >> sys.stderr, '*** CMD:', ' '.join(self.call_args) # dbg
253 #print >> sys.stderr, '*** CMD:', ' '.join(self.call_args) # dbg
258 subp = subprocess.Popen(self.call_args)
254 subp = subprocess.Popen(self.call_args)
259 self.pids.append(subp.pid)
255 self.pids.append(subp.pid)
260 # If this fails, the pid will be left in self.pids and cleaned up
256 # If this fails, the pid will be left in self.pids and cleaned up
261 # later, but if the wait call succeeds, then we can clear the
257 # later, but if the wait call succeeds, then we can clear the
262 # stored pid.
258 # stored pid.
263 retcode = subp.wait()
259 retcode = subp.wait()
264 self.pids.pop()
260 self.pids.pop()
265 return retcode
261 return retcode
266
262
267 def run(self):
263 def run(self):
268 """Run the stored commands"""
264 """Run the stored commands"""
269 try:
265 try:
270 return self._run_cmd()
266 return self._run_cmd()
271 except:
267 except:
272 import traceback
268 import traceback
273 traceback.print_exc()
269 traceback.print_exc()
274 return 1 # signal failure
270 return 1 # signal failure
275
271
276 def __del__(self):
272 def __del__(self):
277 """Cleanup on exit by killing any leftover processes."""
273 """Cleanup on exit by killing any leftover processes."""
278
274
279 if not hasattr(os, 'kill'):
275 if not hasattr(os, 'kill'):
280 return
276 return
281
277
282 for pid in self.pids:
278 for pid in self.pids:
283 try:
279 try:
284 print 'Cleaning stale PID:', pid
280 print 'Cleaning stale PID:', pid
285 os.kill(pid, signal.SIGKILL)
281 os.kill(pid, signal.SIGKILL)
286 except OSError:
282 except OSError:
287 # This is just a best effort, if we fail or the process was
283 # This is just a best effort, if we fail or the process was
288 # really gone, ignore it.
284 # really gone, ignore it.
289 pass
285 pass
290
286
291
287
292 def make_runners():
288 def make_runners():
293 """Define the top-level packages that need to be tested.
289 """Define the top-level packages that need to be tested.
294 """
290 """
295
291
296 # Packages to be tested via nose, that only depend on the stdlib
292 # Packages to be tested via nose, that only depend on the stdlib
297 nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib',
293 nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib',
298 'scripts', 'testing', 'utils' ]
294 'scripts', 'testing', 'utils' ]
299 # The machinery in kernel needs twisted for real testing
295 # The machinery in kernel needs twisted for real testing
300 trial_pkg_names = []
296 trial_pkg_names = []
301
297
302 # And add twisted ones if conditions are met
298 # And add twisted ones if conditions are met
303 if have['zope.interface'] and have['twisted'] and have['foolscap']:
299 if have['zope.interface'] and have['twisted'] and have['foolscap']:
304 # We only list IPython.kernel for testing using twisted.trial as
300 # We only list IPython.kernel for testing using twisted.trial as
305 # nose and twisted.trial have conflicts that make the testing system
301 # nose and twisted.trial have conflicts that make the testing system
306 # unstable.
302 # unstable.
307 trial_pkg_names.append('kernel')
303 trial_pkg_names.append('kernel')
308
304
309 # For debugging this code, only load quick stuff
305 # For debugging this code, only load quick stuff
310 #nose_pkg_names = ['core', 'extensions'] # dbg
306 #nose_pkg_names = ['core', 'extensions'] # dbg
311 #trial_pkg_names = [] # dbg
307 #trial_pkg_names = [] # dbg
312
308
313 # Make fully qualified package names prepending 'IPython.' to our name lists
309 # Make fully qualified package names prepending 'IPython.' to our name lists
314 nose_packages = ['IPython.%s' % m for m in nose_pkg_names ]
310 nose_packages = ['IPython.%s' % m for m in nose_pkg_names ]
315 trial_packages = ['IPython.%s' % m for m in trial_pkg_names ]
311 trial_packages = ['IPython.%s' % m for m in trial_pkg_names ]
316
312
317 # Make runners
313 # Make runners
318 runners = [ (v, IPTester('iptest', params=v)) for v in nose_packages ]
314 runners = [ (v, IPTester('iptest', params=v)) for v in nose_packages ]
319 runners.extend([ (v, IPTester('trial', params=v)) for v in trial_packages ])
315 runners.extend([ (v, IPTester('trial', params=v)) for v in trial_packages ])
320
316
321 return runners
317 return runners
322
318
323
319
324 def run_iptest():
320 def run_iptest():
325 """Run the IPython test suite using nose.
321 """Run the IPython test suite using nose.
326
322
327 This function is called when this script is **not** called with the form
323 This function is called when this script is **not** called with the form
328 `iptest all`. It simply calls nose with appropriate command line flags
324 `iptest all`. It simply calls nose with appropriate command line flags
329 and accepts all of the standard nose arguments.
325 and accepts all of the standard nose arguments.
330 """
326 """
331
327
332 warnings.filterwarnings('ignore',
328 warnings.filterwarnings('ignore',
333 'This will be removed soon. Use IPython.testing.util instead')
329 'This will be removed soon. Use IPython.testing.util instead')
334
330
335 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
331 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
336
332
337 # Loading ipdoctest causes problems with Twisted, but
333 # Loading ipdoctest causes problems with Twisted, but
338 # our test suite runner now separates things and runs
334 # our test suite runner now separates things and runs
339 # all Twisted tests with trial.
335 # all Twisted tests with trial.
340 '--with-ipdoctest',
336 '--with-ipdoctest',
341 '--ipdoctest-tests','--ipdoctest-extension=txt',
337 '--ipdoctest-tests','--ipdoctest-extension=txt',
342
338
343 # We add --exe because of setuptools' imbecility (it
339 # We add --exe because of setuptools' imbecility (it
344 # blindly does chmod +x on ALL files). Nose does the
340 # blindly does chmod +x on ALL files). Nose does the
345 # right thing and it tries to avoid executables,
341 # right thing and it tries to avoid executables,
346 # setuptools unfortunately forces our hand here. This
342 # setuptools unfortunately forces our hand here. This
347 # has been discussed on the distutils list and the
343 # has been discussed on the distutils list and the
348 # setuptools devs refuse to fix this problem!
344 # setuptools devs refuse to fix this problem!
349 '--exe',
345 '--exe',
350 ]
346 ]
351
347
352 if nose.__version__ >= '0.11':
348 if nose.__version__ >= '0.11':
353 # I don't fully understand why we need this one, but depending on what
349 # I don't fully understand why we need this one, but depending on what
354 # directory the test suite is run from, if we don't give it, 0 tests
350 # directory the test suite is run from, if we don't give it, 0 tests
355 # get run. Specifically, if the test suite is run from the source dir
351 # get run. Specifically, if the test suite is run from the source dir
356 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
352 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
357 # even if the same call done in this directory works fine). It appears
353 # even if the same call done in this directory works fine). It appears
358 # that if the requested package is in the current dir, nose bails early
354 # that if the requested package is in the current dir, nose bails early
359 # by default. Since it's otherwise harmless, leave it in by default
355 # by default. Since it's otherwise harmless, leave it in by default
360 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
356 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
361 argv.append('--traverse-namespace')
357 argv.append('--traverse-namespace')
362
358
363 # Construct list of plugins, omitting the existing doctest plugin, which
359 # Construct list of plugins, omitting the existing doctest plugin, which
364 # ours replaces (and extends).
360 # ours replaces (and extends).
365 plugins = [IPythonDoctest(make_exclude())]
361 plugins = [IPythonDoctest(make_exclude())]
366 for p in nose.plugins.builtin.plugins:
362 for p in nose.plugins.builtin.plugins:
367 plug = p()
363 plug = p()
368 if plug.name == 'doctest':
364 if plug.name == 'doctest':
369 continue
365 continue
370 plugins.append(plug)
366 plugins.append(plug)
371
367
372 # We need a global ipython running in this process
368 # We need a global ipython running in this process
373 globalipapp.start_ipython()
369 globalipapp.start_ipython()
374 # Now nose can run
370 # Now nose can run
375 TestProgram(argv=argv, plugins=plugins)
371 TestProgram(argv=argv, plugins=plugins)
376
372
377
373
378 def run_iptestall():
374 def run_iptestall():
379 """Run the entire IPython test suite by calling nose and trial.
375 """Run the entire IPython test suite by calling nose and trial.
380
376
381 This function constructs :class:`IPTester` instances for all IPython
377 This function constructs :class:`IPTester` instances for all IPython
382 modules and package and then runs each of them. This causes the modules
378 modules and package and then runs each of them. This causes the modules
383 and packages of IPython to be tested each in their own subprocess using
379 and packages of IPython to be tested each in their own subprocess using
384 nose or twisted.trial appropriately.
380 nose or twisted.trial appropriately.
385 """
381 """
386
382
387 runners = make_runners()
383 runners = make_runners()
388
384
389 # Run the test runners in a temporary dir so we can nuke it when finished
385 # Run the test runners in a temporary dir so we can nuke it when finished
390 # to clean up any junk files left over by accident. This also makes it
386 # to clean up any junk files left over by accident. This also makes it
391 # robust against being run in non-writeable directories by mistake, as the
387 # robust against being run in non-writeable directories by mistake, as the
392 # temp dir will always be user-writeable.
388 # temp dir will always be user-writeable.
393 curdir = os.getcwd()
389 curdir = os.getcwd()
394 testdir = tempfile.gettempdir()
390 testdir = tempfile.gettempdir()
395 os.chdir(testdir)
391 os.chdir(testdir)
396
392
397 # Run all test runners, tracking execution time
393 # Run all test runners, tracking execution time
398 failed = []
394 failed = []
399 t_start = time.time()
395 t_start = time.time()
400 try:
396 try:
401 for (name, runner) in runners:
397 for (name, runner) in runners:
402 print '*'*70
398 print '*'*70
403 print 'IPython test group:',name
399 print 'IPython test group:',name
404 res = runner.run()
400 res = runner.run()
405 if res:
401 if res:
406 failed.append( (name, runner) )
402 failed.append( (name, runner) )
407 finally:
403 finally:
408 os.chdir(curdir)
404 os.chdir(curdir)
409 t_end = time.time()
405 t_end = time.time()
410 t_tests = t_end - t_start
406 t_tests = t_end - t_start
411 nrunners = len(runners)
407 nrunners = len(runners)
412 nfail = len(failed)
408 nfail = len(failed)
413 # summarize results
409 # summarize results
414 print
410 print
415 print '*'*70
411 print '*'*70
416 print 'Test suite completed for system with the following information:'
412 print 'Test suite completed for system with the following information:'
417 print report()
413 print report()
418 print 'Ran %s test groups in %.3fs' % (nrunners, t_tests)
414 print 'Ran %s test groups in %.3fs' % (nrunners, t_tests)
419 print
415 print
420 print 'Status:'
416 print 'Status:'
421 if not failed:
417 if not failed:
422 print 'OK'
418 print 'OK'
423 else:
419 else:
424 # If anything went wrong, point out what command to rerun manually to
420 # If anything went wrong, point out what command to rerun manually to
425 # see the actual errors and individual summary
421 # see the actual errors and individual summary
426 print 'ERROR - %s out of %s test groups failed.' % (nfail, nrunners)
422 print 'ERROR - %s out of %s test groups failed.' % (nfail, nrunners)
427 for name, failed_runner in failed:
423 for name, failed_runner in failed:
428 print '-'*40
424 print '-'*40
429 print 'Runner failed:',name
425 print 'Runner failed:',name
430 print 'You may wish to rerun this one individually, with:'
426 print 'You may wish to rerun this one individually, with:'
431 print ' '.join(failed_runner.call_args)
427 print ' '.join(failed_runner.call_args)
432 print
428 print
433
429
434
430
435 def main():
431 def main():
436 for arg in sys.argv[1:]:
432 for arg in sys.argv[1:]:
437 if arg.startswith('IPython'):
433 if arg.startswith('IPython'):
438 # This is in-process
434 # This is in-process
439 run_iptest()
435 run_iptest()
440 else:
436 else:
441 # This starts subprocesses
437 # This starts subprocesses
442 run_iptestall()
438 run_iptestall()
443
439
444
440
445 if __name__ == '__main__':
441 if __name__ == '__main__':
446 main()
442 main()
@@ -1,74 +1,74 b''
1 # Set this prefix to where you want to install the plugin
1 # Set this prefix to where you want to install the plugin
2 PREFIX=/usr/local
2 PREFIX=/usr/local
3
3
4 NOSE0=nosetests -vs --with-doctest --doctest-tests --detailed-errors
4 NOSE0=nosetests -vs --with-doctest --doctest-tests --detailed-errors
5 NOSE=nosetests -vvs --with-ipdoctest --doctest-tests --doctest-extension=txt \
5 NOSE=nosetests -vvs --with-ipdoctest --doctest-tests --doctest-extension=txt \
6 --detailed-errors
6 --detailed-errors
7
7
8 SRC=ipdoctest.py setup.py ../decorators.py
8 SRC=ipdoctest.py setup.py ../decorators.py
9
9
10 # Default target for clean 'make'
10 # Default target for clean 'make'
11 default: iplib
11 default: interactiveshell
12
12
13 # The actual plugin installation
13 # The actual plugin installation
14 plugin: IPython_doctest_plugin.egg-info
14 plugin: IPython_doctest_plugin.egg-info
15
15
16 # Simple targets that test one thing
16 # Simple targets that test one thing
17 simple: plugin simple.py
17 simple: plugin simple.py
18 $(NOSE) simple.py
18 $(NOSE) simple.py
19
19
20 dtest: plugin dtexample.py
20 dtest: plugin dtexample.py
21 $(NOSE) dtexample.py
21 $(NOSE) dtexample.py
22
22
23 rtest: plugin test_refs.py
23 rtest: plugin test_refs.py
24 $(NOSE) test_refs.py
24 $(NOSE) test_refs.py
25
25
26 test: plugin dtexample.py
26 test: plugin dtexample.py
27 $(NOSE) dtexample.py test*.py test*.txt
27 $(NOSE) dtexample.py test*.py test*.txt
28
28
29 deb: plugin dtexample.py
29 deb: plugin dtexample.py
30 $(NOSE) test_combo.txt
30 $(NOSE) test_combo.txt
31
31
32 # IPython tests
32 # IPython tests
33 deco:
33 deco:
34 $(NOSE0) IPython.testing.decorators
34 $(NOSE0) IPython.testing.decorators
35
35
36 magic: plugin
36 magic: plugin
37 $(NOSE) IPython.core.magic
37 $(NOSE) IPython.core.magic
38
38
39 excolors: plugin
39 excolors: plugin
40 $(NOSE) IPython.core.excolors
40 $(NOSE) IPython.core.excolors
41
41
42 iplib: plugin
42 interactiveshell: plugin
43 $(NOSE) IPython.core.iplib
43 $(NOSE) IPython.core.interactiveshell
44
44
45 strd: plugin
45 strd: plugin
46 $(NOSE) IPython.core.strdispatch
46 $(NOSE) IPython.core.strdispatch
47
47
48 engine: plugin
48 engine: plugin
49 $(NOSE) IPython.kernel
49 $(NOSE) IPython.kernel
50
50
51 tf: plugin
51 tf: plugin
52 $(NOSE) IPython.config.traitlets
52 $(NOSE) IPython.config.traitlets
53
53
54 # All of ipython itself
54 # All of ipython itself
55 ipython: plugin
55 ipython: plugin
56 $(NOSE) IPython
56 $(NOSE) IPython
57
57
58
58
59 # Combined targets
59 # Combined targets
60 sr: rtest strd
60 sr: rtest strd
61
61
62 base: dtest rtest test strd deco
62 base: dtest rtest test strd deco
63
63
64 quick: base iplib ipipe
64 quick: base interactiveshell ipipe
65
65
66 all: base ipython
66 all: base ipython
67
67
68 # Main plugin and cleanup
68 # Main plugin and cleanup
69 IPython_doctest_plugin.egg-info: $(SRC)
69 IPython_doctest_plugin.egg-info: $(SRC)
70 python setup.py install --prefix=$(PREFIX)
70 python setup.py install --prefix=$(PREFIX)
71 touch $@
71 touch $@
72
72
73 clean:
73 clean:
74 rm -rf IPython_doctest_plugin.egg-info *~ *pyc build/ dist/
74 rm -rf IPython_doctest_plugin.egg-info *~ *pyc build/ dist/
@@ -1,367 +1,367 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with external processes.
3 Utilities for working with external processes.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import os
17 import os
18 import sys
18 import sys
19 import shlex
19 import shlex
20 import subprocess
20 import subprocess
21
21
22 from IPython.utils.terminal import set_term_title
22 from IPython.utils.terminal import set_term_title
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Code
25 # Code
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 class FindCmdError(Exception):
29 class FindCmdError(Exception):
30 pass
30 pass
31
31
32
32
33 def _find_cmd(cmd):
33 def _find_cmd(cmd):
34 """Find the full path to a command using which."""
34 """Find the full path to a command using which."""
35 return os.popen('which %s' % cmd).read().strip()
35 return os.popen('which %s' % cmd).read().strip()
36
36
37
37
38 if os.name == 'posix':
38 if os.name == 'posix':
39 def _find_cmd(cmd):
39 def _find_cmd(cmd):
40 """Find the full path to a command using which."""
40 """Find the full path to a command using which."""
41 return getoutputerror('/usr/bin/env which %s' % cmd)[0]
41 return getoutputerror('/usr/bin/env which %s' % cmd)[0]
42
42
43
43
44 if sys.platform == 'win32':
44 if sys.platform == 'win32':
45 def _find_cmd(cmd):
45 def _find_cmd(cmd):
46 """Find the full path to a .bat or .exe using the win32api module."""
46 """Find the full path to a .bat or .exe using the win32api module."""
47 try:
47 try:
48 from win32api import SearchPath
48 from win32api import SearchPath
49 except ImportError:
49 except ImportError:
50 raise ImportError('you need to have pywin32 installed for this to work')
50 raise ImportError('you need to have pywin32 installed for this to work')
51 else:
51 else:
52 PATH = os.environ['PATH']
52 PATH = os.environ['PATH']
53 extensions = ['.exe', '.com', '.bat', '.py']
53 extensions = ['.exe', '.com', '.bat', '.py']
54 path = None
54 path = None
55 for ext in extensions:
55 for ext in extensions:
56 try:
56 try:
57 path = SearchPath(PATH,cmd + ext)[0]
57 path = SearchPath(PATH,cmd + ext)[0]
58 except:
58 except:
59 pass
59 pass
60 if path is None:
60 if path is None:
61 raise OSError("command %r not found" % cmd)
61 raise OSError("command %r not found" % cmd)
62 else:
62 else:
63 return path
63 return path
64
64
65
65
66 def find_cmd(cmd):
66 def find_cmd(cmd):
67 """Find absolute path to executable cmd in a cross platform manner.
67 """Find absolute path to executable cmd in a cross platform manner.
68
68
69 This function tries to determine the full path to a command line program
69 This function tries to determine the full path to a command line program
70 using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
70 using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
71 time it will use the version that is first on the users `PATH`. If
71 time it will use the version that is first on the users `PATH`. If
72 cmd is `python` return `sys.executable`.
72 cmd is `python` return `sys.executable`.
73
73
74 Warning, don't use this to find IPython command line programs as there
74 Warning, don't use this to find IPython command line programs as there
75 is a risk you will find the wrong one. Instead find those using the
75 is a risk you will find the wrong one. Instead find those using the
76 following code and looking for the application itself::
76 following code and looking for the application itself::
77
77
78 from IPython.utils.path import get_ipython_module_path
78 from IPython.utils.path import get_ipython_module_path
79 from IPython.utils.process import pycmd2argv
79 from IPython.utils.process import pycmd2argv
80 argv = pycmd2argv(get_ipython_module_path('IPython.core.ipapp'))
80 argv = pycmd2argv(get_ipython_module_path('IPython.frontend.terminal.ipapp'))
81
81
82 Parameters
82 Parameters
83 ----------
83 ----------
84 cmd : str
84 cmd : str
85 The command line program to look for.
85 The command line program to look for.
86 """
86 """
87 if cmd == 'python':
87 if cmd == 'python':
88 return os.path.abspath(sys.executable)
88 return os.path.abspath(sys.executable)
89 try:
89 try:
90 path = _find_cmd(cmd)
90 path = _find_cmd(cmd)
91 except OSError:
91 except OSError:
92 raise FindCmdError('command could not be found: %s' % cmd)
92 raise FindCmdError('command could not be found: %s' % cmd)
93 # which returns empty if not found
93 # which returns empty if not found
94 if path == '':
94 if path == '':
95 raise FindCmdError('command could not be found: %s' % cmd)
95 raise FindCmdError('command could not be found: %s' % cmd)
96 return os.path.abspath(path)
96 return os.path.abspath(path)
97
97
98
98
99 def pycmd2argv(cmd):
99 def pycmd2argv(cmd):
100 r"""Take the path of a python command and return a list (argv-style).
100 r"""Take the path of a python command and return a list (argv-style).
101
101
102 This only works on Python based command line programs and will find the
102 This only works on Python based command line programs and will find the
103 location of the ``python`` executable using ``sys.executable`` to make
103 location of the ``python`` executable using ``sys.executable`` to make
104 sure the right version is used.
104 sure the right version is used.
105
105
106 For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
106 For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
107 .com or .bat, and [, cmd] otherwise.
107 .com or .bat, and [, cmd] otherwise.
108
108
109 Parameters
109 Parameters
110 ----------
110 ----------
111 cmd : string
111 cmd : string
112 The path of the command.
112 The path of the command.
113
113
114 Returns
114 Returns
115 -------
115 -------
116 argv-style list.
116 argv-style list.
117 """
117 """
118 ext = os.path.splitext(cmd)[1]
118 ext = os.path.splitext(cmd)[1]
119 if ext in ['.exe', '.com', '.bat']:
119 if ext in ['.exe', '.com', '.bat']:
120 return [cmd]
120 return [cmd]
121 else:
121 else:
122 if sys.platform == 'win32':
122 if sys.platform == 'win32':
123 # The -u option here turns on unbuffered output, which is required
123 # The -u option here turns on unbuffered output, which is required
124 # on Win32 to prevent wierd conflict and problems with Twisted.
124 # on Win32 to prevent wierd conflict and problems with Twisted.
125 # Also, use sys.executable to make sure we are picking up the
125 # Also, use sys.executable to make sure we are picking up the
126 # right python exe.
126 # right python exe.
127 return [sys.executable, '-u', cmd]
127 return [sys.executable, '-u', cmd]
128 else:
128 else:
129 return [sys.executable, cmd]
129 return [sys.executable, cmd]
130
130
131
131
132 def arg_split(s, posix=False):
132 def arg_split(s, posix=False):
133 """Split a command line's arguments in a shell-like manner.
133 """Split a command line's arguments in a shell-like manner.
134
134
135 This is a modified version of the standard library's shlex.split()
135 This is a modified version of the standard library's shlex.split()
136 function, but with a default of posix=False for splitting, so that quotes
136 function, but with a default of posix=False for splitting, so that quotes
137 in inputs are respected."""
137 in inputs are respected."""
138
138
139 # Unfortunately, python's shlex module is buggy with unicode input:
139 # Unfortunately, python's shlex module is buggy with unicode input:
140 # http://bugs.python.org/issue1170
140 # http://bugs.python.org/issue1170
141 # At least encoding the input when it's unicode seems to help, but there
141 # At least encoding the input when it's unicode seems to help, but there
142 # may be more problems lurking. Apparently this is fixed in python3.
142 # may be more problems lurking. Apparently this is fixed in python3.
143 if isinstance(s, unicode):
143 if isinstance(s, unicode):
144 s = s.encode(sys.stdin.encoding)
144 s = s.encode(sys.stdin.encoding)
145 lex = shlex.shlex(s, posix=posix)
145 lex = shlex.shlex(s, posix=posix)
146 lex.whitespace_split = True
146 lex.whitespace_split = True
147 return list(lex)
147 return list(lex)
148
148
149
149
150 def system(cmd, verbose=0, debug=0, header=''):
150 def system(cmd, verbose=0, debug=0, header=''):
151 """Execute a system command, return its exit status.
151 """Execute a system command, return its exit status.
152
152
153 Options:
153 Options:
154
154
155 - verbose (0): print the command to be executed.
155 - verbose (0): print the command to be executed.
156
156
157 - debug (0): only print, do not actually execute.
157 - debug (0): only print, do not actually execute.
158
158
159 - header (''): Header to print on screen prior to the executed command (it
159 - header (''): Header to print on screen prior to the executed command (it
160 is only prepended to the command, no newlines are added).
160 is only prepended to the command, no newlines are added).
161
161
162 Note: a stateful version of this function is available through the
162 Note: a stateful version of this function is available through the
163 SystemExec class."""
163 SystemExec class."""
164
164
165 stat = 0
165 stat = 0
166 if verbose or debug: print header+cmd
166 if verbose or debug: print header+cmd
167 sys.stdout.flush()
167 sys.stdout.flush()
168 if not debug: stat = os.system(cmd)
168 if not debug: stat = os.system(cmd)
169 return stat
169 return stat
170
170
171
171
172 def abbrev_cwd():
172 def abbrev_cwd():
173 """ Return abbreviated version of cwd, e.g. d:mydir """
173 """ Return abbreviated version of cwd, e.g. d:mydir """
174 cwd = os.getcwd().replace('\\','/')
174 cwd = os.getcwd().replace('\\','/')
175 drivepart = ''
175 drivepart = ''
176 tail = cwd
176 tail = cwd
177 if sys.platform == 'win32':
177 if sys.platform == 'win32':
178 if len(cwd) < 4:
178 if len(cwd) < 4:
179 return cwd
179 return cwd
180 drivepart,tail = os.path.splitdrive(cwd)
180 drivepart,tail = os.path.splitdrive(cwd)
181
181
182
182
183 parts = tail.split('/')
183 parts = tail.split('/')
184 if len(parts) > 2:
184 if len(parts) > 2:
185 tail = '/'.join(parts[-2:])
185 tail = '/'.join(parts[-2:])
186
186
187 return (drivepart + (
187 return (drivepart + (
188 cwd == '/' and '/' or tail))
188 cwd == '/' and '/' or tail))
189
189
190
190
191 # This function is used by ipython in a lot of places to make system calls.
191 # This function is used by ipython in a lot of places to make system calls.
192 # We need it to be slightly different under win32, due to the vagaries of
192 # We need it to be slightly different under win32, due to the vagaries of
193 # 'network shares'. A win32 override is below.
193 # 'network shares'. A win32 override is below.
194
194
195 def shell(cmd, verbose=0, debug=0, header=''):
195 def shell(cmd, verbose=0, debug=0, header=''):
196 """Execute a command in the system shell, always return None.
196 """Execute a command in the system shell, always return None.
197
197
198 Options:
198 Options:
199
199
200 - verbose (0): print the command to be executed.
200 - verbose (0): print the command to be executed.
201
201
202 - debug (0): only print, do not actually execute.
202 - debug (0): only print, do not actually execute.
203
203
204 - header (''): Header to print on screen prior to the executed command (it
204 - header (''): Header to print on screen prior to the executed command (it
205 is only prepended to the command, no newlines are added).
205 is only prepended to the command, no newlines are added).
206
206
207 Note: this is similar to system(), but it returns None so it can
207 Note: this is similar to system(), but it returns None so it can
208 be conveniently used in interactive loops without getting the return value
208 be conveniently used in interactive loops without getting the return value
209 (typically 0) printed many times."""
209 (typically 0) printed many times."""
210
210
211 stat = 0
211 stat = 0
212 if verbose or debug: print header+cmd
212 if verbose or debug: print header+cmd
213 # flush stdout so we don't mangle python's buffering
213 # flush stdout so we don't mangle python's buffering
214 sys.stdout.flush()
214 sys.stdout.flush()
215
215
216 if not debug:
216 if not debug:
217 set_term_title("IPy " + cmd)
217 set_term_title("IPy " + cmd)
218 os.system(cmd)
218 os.system(cmd)
219 set_term_title("IPy " + abbrev_cwd())
219 set_term_title("IPy " + abbrev_cwd())
220
220
221 # override shell() for win32 to deal with network shares
221 # override shell() for win32 to deal with network shares
222 if os.name in ('nt','dos'):
222 if os.name in ('nt','dos'):
223
223
224 shell_ori = shell
224 shell_ori = shell
225
225
226 def shell(cmd, verbose=0, debug=0, header=''):
226 def shell(cmd, verbose=0, debug=0, header=''):
227 if os.getcwd().startswith(r"\\"):
227 if os.getcwd().startswith(r"\\"):
228 path = os.getcwd()
228 path = os.getcwd()
229 # change to c drive (cannot be on UNC-share when issuing os.system,
229 # change to c drive (cannot be on UNC-share when issuing os.system,
230 # as cmd.exe cannot handle UNC addresses)
230 # as cmd.exe cannot handle UNC addresses)
231 os.chdir("c:")
231 os.chdir("c:")
232 # issue pushd to the UNC-share and then run the command
232 # issue pushd to the UNC-share and then run the command
233 try:
233 try:
234 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
234 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
235 finally:
235 finally:
236 os.chdir(path)
236 os.chdir(path)
237 else:
237 else:
238 shell_ori(cmd,verbose,debug,header)
238 shell_ori(cmd,verbose,debug,header)
239
239
240 shell.__doc__ = shell_ori.__doc__
240 shell.__doc__ = shell_ori.__doc__
241
241
242
242
243 def getoutput(cmd, verbose=0, debug=0, header='', split=0):
243 def getoutput(cmd, verbose=0, debug=0, header='', split=0):
244 """Dummy substitute for perl's backquotes.
244 """Dummy substitute for perl's backquotes.
245
245
246 Executes a command and returns the output.
246 Executes a command and returns the output.
247
247
248 Accepts the same arguments as system(), plus:
248 Accepts the same arguments as system(), plus:
249
249
250 - split(0): if true, the output is returned as a list split on newlines.
250 - split(0): if true, the output is returned as a list split on newlines.
251
251
252 Note: a stateful version of this function is available through the
252 Note: a stateful version of this function is available through the
253 SystemExec class.
253 SystemExec class.
254
254
255 This is pretty much deprecated and rarely used, getoutputerror may be
255 This is pretty much deprecated and rarely used, getoutputerror may be
256 what you need.
256 what you need.
257
257
258 """
258 """
259
259
260 if verbose or debug: print header+cmd
260 if verbose or debug: print header+cmd
261 if not debug:
261 if not debug:
262 pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
262 pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
263 output = pipe.read()
263 output = pipe.read()
264 # stipping last \n is here for backwards compat.
264 # stipping last \n is here for backwards compat.
265 if output.endswith('\n'):
265 if output.endswith('\n'):
266 output = output[:-1]
266 output = output[:-1]
267 if split:
267 if split:
268 return output.split('\n')
268 return output.split('\n')
269 else:
269 else:
270 return output
270 return output
271
271
272
272
273 # for compatibility with older naming conventions
273 # for compatibility with older naming conventions
274 xsys = system
274 xsys = system
275
275
276
276
277 def getoutputerror(cmd, verbose=0, debug=0, header='', split=0):
277 def getoutputerror(cmd, verbose=0, debug=0, header='', split=0):
278 """Return (standard output,standard error) of executing cmd in a shell.
278 """Return (standard output,standard error) of executing cmd in a shell.
279
279
280 Accepts the same arguments as system(), plus:
280 Accepts the same arguments as system(), plus:
281
281
282 - split(0): if true, each of stdout/err is returned as a list split on
282 - split(0): if true, each of stdout/err is returned as a list split on
283 newlines.
283 newlines.
284
284
285 Note: a stateful version of this function is available through the
285 Note: a stateful version of this function is available through the
286 SystemExec class."""
286 SystemExec class."""
287
287
288 if verbose or debug: print header+cmd
288 if verbose or debug: print header+cmd
289 if not cmd:
289 if not cmd:
290 if split:
290 if split:
291 return [],[]
291 return [],[]
292 else:
292 else:
293 return '',''
293 return '',''
294 if not debug:
294 if not debug:
295 p = subprocess.Popen(cmd, shell=True,
295 p = subprocess.Popen(cmd, shell=True,
296 stdin=subprocess.PIPE,
296 stdin=subprocess.PIPE,
297 stdout=subprocess.PIPE,
297 stdout=subprocess.PIPE,
298 stderr=subprocess.PIPE,
298 stderr=subprocess.PIPE,
299 close_fds=True)
299 close_fds=True)
300 pin, pout, perr = (p.stdin, p.stdout, p.stderr)
300 pin, pout, perr = (p.stdin, p.stdout, p.stderr)
301
301
302 tout = pout.read().rstrip()
302 tout = pout.read().rstrip()
303 terr = perr.read().rstrip()
303 terr = perr.read().rstrip()
304 pin.close()
304 pin.close()
305 pout.close()
305 pout.close()
306 perr.close()
306 perr.close()
307 if split:
307 if split:
308 return tout.split('\n'),terr.split('\n')
308 return tout.split('\n'),terr.split('\n')
309 else:
309 else:
310 return tout,terr
310 return tout,terr
311
311
312
312
313 class SystemExec:
313 class SystemExec:
314 """Access the system and getoutput functions through a stateful interface.
314 """Access the system and getoutput functions through a stateful interface.
315
315
316 Note: here we refer to the system and getoutput functions from this
316 Note: here we refer to the system and getoutput functions from this
317 library, not the ones from the standard python library.
317 library, not the ones from the standard python library.
318
318
319 This class offers the system and getoutput functions as methods, but the
319 This class offers the system and getoutput functions as methods, but the
320 verbose, debug and header parameters can be set for the instance (at
320 verbose, debug and header parameters can be set for the instance (at
321 creation time or later) so that they don't need to be specified on each
321 creation time or later) so that they don't need to be specified on each
322 call.
322 call.
323
323
324 For efficiency reasons, there's no way to override the parameters on a
324 For efficiency reasons, there's no way to override the parameters on a
325 per-call basis other than by setting instance attributes. If you need
325 per-call basis other than by setting instance attributes. If you need
326 local overrides, it's best to directly call system() or getoutput().
326 local overrides, it's best to directly call system() or getoutput().
327
327
328 The following names are provided as alternate options:
328 The following names are provided as alternate options:
329 - xsys: alias to system
329 - xsys: alias to system
330 - bq: alias to getoutput
330 - bq: alias to getoutput
331
331
332 An instance can then be created as:
332 An instance can then be created as:
333 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
333 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
334 """
334 """
335
335
336 def __init__(self, verbose=0, debug=0, header='', split=0):
336 def __init__(self, verbose=0, debug=0, header='', split=0):
337 """Specify the instance's values for verbose, debug and header."""
337 """Specify the instance's values for verbose, debug and header."""
338 self.verbose = verbose
338 self.verbose = verbose
339 self.debug = debug
339 self.debug = debug
340 self.header = header
340 self.header = header
341 self.split = split
341 self.split = split
342
342
343 def system(self, cmd):
343 def system(self, cmd):
344 """Stateful interface to system(), with the same keyword parameters."""
344 """Stateful interface to system(), with the same keyword parameters."""
345
345
346 system(cmd, self.verbose, self.debug, self.header)
346 system(cmd, self.verbose, self.debug, self.header)
347
347
348 def shell(self, cmd):
348 def shell(self, cmd):
349 """Stateful interface to shell(), with the same keyword parameters."""
349 """Stateful interface to shell(), with the same keyword parameters."""
350
350
351 shell(cmd, self.verbose, self.debug, self.header)
351 shell(cmd, self.verbose, self.debug, self.header)
352
352
353 xsys = system # alias
353 xsys = system # alias
354
354
355 def getoutput(self, cmd):
355 def getoutput(self, cmd):
356 """Stateful interface to getoutput()."""
356 """Stateful interface to getoutput()."""
357
357
358 return getoutput(cmd, self.verbose, self.debug, self.header, self.split)
358 return getoutput(cmd, self.verbose, self.debug, self.header, self.split)
359
359
360 def getoutputerror(self, cmd):
360 def getoutputerror(self, cmd):
361 """Stateful interface to getoutputerror()."""
361 """Stateful interface to getoutputerror()."""
362
362
363 return getoutputerror(cmd, self.verbose, self.debug, self.header, self.split)
363 return getoutputerror(cmd, self.verbose, self.debug, self.header, self.split)
364
364
365 bq = getoutput # alias
365 bq = getoutput # alias
366
366
367
367
@@ -1,272 +1,272 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for IPython.utils.path.py"""
2 """Tests for IPython.utils.path.py"""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008 The IPython Development Team
5 # Copyright (C) 2008 The IPython Development Team
6 #
6 #
7 # Distributed under the terms of the BSD License. The full license is in
7 # Distributed under the terms of the BSD License. The full license is in
8 # the file COPYING, distributed as part of this software.
8 # the file COPYING, distributed as part of this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import os
15 import os
16 import shutil
16 import shutil
17 import sys
17 import sys
18 import tempfile
18 import tempfile
19
19
20 from os.path import join, abspath, split
20 from os.path import join, abspath, split
21
21
22 import nose.tools as nt
22 import nose.tools as nt
23
23
24 from nose import with_setup
24 from nose import with_setup
25
25
26 import IPython
26 import IPython
27 from IPython.testing import decorators as dec
27 from IPython.testing import decorators as dec
28 from IPython.testing.decorators import skip_if_not_win32, skip_win32
28 from IPython.testing.decorators import skip_if_not_win32, skip_win32
29 from IPython.utils import path
29 from IPython.utils import path
30
30
31 # Platform-dependent imports
31 # Platform-dependent imports
32 try:
32 try:
33 import _winreg as wreg
33 import _winreg as wreg
34 except ImportError:
34 except ImportError:
35 #Fake _winreg module on none windows platforms
35 #Fake _winreg module on none windows platforms
36 import new
36 import new
37 sys.modules["_winreg"] = new.module("_winreg")
37 sys.modules["_winreg"] = new.module("_winreg")
38 import _winreg as wreg
38 import _winreg as wreg
39 #Add entries that needs to be stubbed by the testing code
39 #Add entries that needs to be stubbed by the testing code
40 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
40 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # Globals
43 # Globals
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 env = os.environ
45 env = os.environ
46 TEST_FILE_PATH = split(abspath(__file__))[0]
46 TEST_FILE_PATH = split(abspath(__file__))[0]
47 TMP_TEST_DIR = tempfile.mkdtemp()
47 TMP_TEST_DIR = tempfile.mkdtemp()
48 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
48 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
49 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
49 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
50 #
50 #
51 # Setup/teardown functions/decorators
51 # Setup/teardown functions/decorators
52 #
52 #
53
53
54 def setup():
54 def setup():
55 """Setup testenvironment for the module:
55 """Setup testenvironment for the module:
56
56
57 - Adds dummy home dir tree
57 - Adds dummy home dir tree
58 """
58 """
59 # Do not mask exceptions here. In particular, catching WindowsError is a
59 # Do not mask exceptions here. In particular, catching WindowsError is a
60 # problem because that exception is only defined on Windows...
60 # problem because that exception is only defined on Windows...
61 os.makedirs(IP_TEST_DIR)
61 os.makedirs(IP_TEST_DIR)
62
62
63
63
64 def teardown():
64 def teardown():
65 """Teardown testenvironment for the module:
65 """Teardown testenvironment for the module:
66
66
67 - Remove dummy home dir tree
67 - Remove dummy home dir tree
68 """
68 """
69 # Note: we remove the parent test dir, which is the root of all test
69 # Note: we remove the parent test dir, which is the root of all test
70 # subdirs we may have created. Use shutil instead of os.removedirs, so
70 # subdirs we may have created. Use shutil instead of os.removedirs, so
71 # that non-empty directories are all recursively removed.
71 # that non-empty directories are all recursively removed.
72 shutil.rmtree(TMP_TEST_DIR)
72 shutil.rmtree(TMP_TEST_DIR)
73
73
74
74
75 def setup_environment():
75 def setup_environment():
76 """Setup testenvironment for some functions that are tested
76 """Setup testenvironment for some functions that are tested
77 in this module. In particular this functions stores attributes
77 in this module. In particular this functions stores attributes
78 and other things that we need to stub in some test functions.
78 and other things that we need to stub in some test functions.
79 This needs to be done on a function level and not module level because
79 This needs to be done on a function level and not module level because
80 each testfunction needs a pristine environment.
80 each testfunction needs a pristine environment.
81 """
81 """
82 global oldstuff, platformstuff
82 global oldstuff, platformstuff
83 oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__)
83 oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__)
84
84
85 if os.name == 'nt':
85 if os.name == 'nt':
86 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
86 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
87
87
88
88
89 def teardown_environment():
89 def teardown_environment():
90 """Restore things that were remebered by the setup_environment function
90 """Restore things that were remebered by the setup_environment function
91 """
91 """
92 (oldenv, os.name, get_home_dir, IPython.__file__,) = oldstuff
92 (oldenv, os.name, get_home_dir, IPython.__file__,) = oldstuff
93
93
94 for key in env.keys():
94 for key in env.keys():
95 if key not in oldenv:
95 if key not in oldenv:
96 del env[key]
96 del env[key]
97 env.update(oldenv)
97 env.update(oldenv)
98 if hasattr(sys, 'frozen'):
98 if hasattr(sys, 'frozen'):
99 del sys.frozen
99 del sys.frozen
100 if os.name == 'nt':
100 if os.name == 'nt':
101 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
101 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
102
102
103 # Build decorator that uses the setup_environment/setup_environment
103 # Build decorator that uses the setup_environment/setup_environment
104 with_environment = with_setup(setup_environment, teardown_environment)
104 with_environment = with_setup(setup_environment, teardown_environment)
105
105
106
106
107 @skip_if_not_win32
107 @skip_if_not_win32
108 @with_environment
108 @with_environment
109 def test_get_home_dir_1():
109 def test_get_home_dir_1():
110 """Testcase for py2exe logic, un-compressed lib
110 """Testcase for py2exe logic, un-compressed lib
111 """
111 """
112 sys.frozen = True
112 sys.frozen = True
113
113
114 #fake filename for IPython.__init__
114 #fake filename for IPython.__init__
115 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
115 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
116
116
117 home_dir = path.get_home_dir()
117 home_dir = path.get_home_dir()
118 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
118 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
119
119
120
120
121 @skip_if_not_win32
121 @skip_if_not_win32
122 @with_environment
122 @with_environment
123 def test_get_home_dir_2():
123 def test_get_home_dir_2():
124 """Testcase for py2exe logic, compressed lib
124 """Testcase for py2exe logic, compressed lib
125 """
125 """
126 sys.frozen = True
126 sys.frozen = True
127 #fake filename for IPython.__init__
127 #fake filename for IPython.__init__
128 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
128 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
129
129
130 home_dir = path.get_home_dir()
130 home_dir = path.get_home_dir()
131 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
131 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
132
132
133
133
134 @with_environment
134 @with_environment
135 @skip_win32
135 @skip_win32
136 def test_get_home_dir_3():
136 def test_get_home_dir_3():
137 """Testcase $HOME is set, then use its value as home directory."""
137 """Testcase $HOME is set, then use its value as home directory."""
138 env["HOME"] = HOME_TEST_DIR
138 env["HOME"] = HOME_TEST_DIR
139 home_dir = path.get_home_dir()
139 home_dir = path.get_home_dir()
140 nt.assert_equal(home_dir, env["HOME"])
140 nt.assert_equal(home_dir, env["HOME"])
141
141
142
142
143 @with_environment
143 @with_environment
144 def test_get_home_dir_4():
144 def test_get_home_dir_4():
145 """Testcase $HOME is not set, os=='posix'.
145 """Testcase $HOME is not set, os=='posix'.
146 This should fail with HomeDirError"""
146 This should fail with HomeDirError"""
147
147
148 os.name = 'posix'
148 os.name = 'posix'
149 if 'HOME' in env: del env['HOME']
149 if 'HOME' in env: del env['HOME']
150 nt.assert_raises(path.HomeDirError, path.get_home_dir)
150 nt.assert_raises(path.HomeDirError, path.get_home_dir)
151
151
152
152
153 @skip_if_not_win32
153 @skip_if_not_win32
154 @with_environment
154 @with_environment
155 def test_get_home_dir_5():
155 def test_get_home_dir_5():
156 """Using HOMEDRIVE + HOMEPATH, os=='nt'.
156 """Using HOMEDRIVE + HOMEPATH, os=='nt'.
157
157
158 HOMESHARE is missing.
158 HOMESHARE is missing.
159 """
159 """
160
160
161 os.name = 'nt'
161 os.name = 'nt'
162 env.pop('HOMESHARE', None)
162 env.pop('HOMESHARE', None)
163 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
163 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
164 home_dir = path.get_home_dir()
164 home_dir = path.get_home_dir()
165 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
165 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
166
166
167
167
168 @skip_if_not_win32
168 @skip_if_not_win32
169 @with_environment
169 @with_environment
170 def test_get_home_dir_6():
170 def test_get_home_dir_6():
171 """Using USERPROFILE, os=='nt'.
171 """Using USERPROFILE, os=='nt'.
172
172
173 HOMESHARE, HOMEDRIVE, HOMEPATH are missing.
173 HOMESHARE, HOMEDRIVE, HOMEPATH are missing.
174 """
174 """
175
175
176 os.name = 'nt'
176 os.name = 'nt'
177 env.pop('HOMESHARE', None)
177 env.pop('HOMESHARE', None)
178 env.pop('HOMEDRIVE', None)
178 env.pop('HOMEDRIVE', None)
179 env.pop('HOMEPATH', None)
179 env.pop('HOMEPATH', None)
180 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
180 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
181 home_dir = path.get_home_dir()
181 home_dir = path.get_home_dir()
182 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
182 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
183
183
184
184
185 @skip_if_not_win32
185 @skip_if_not_win32
186 @with_environment
186 @with_environment
187 def test_get_home_dir_7():
187 def test_get_home_dir_7():
188 """Using HOMESHARE, os=='nt'."""
188 """Using HOMESHARE, os=='nt'."""
189
189
190 os.name = 'nt'
190 os.name = 'nt'
191 env["HOMESHARE"] = abspath(HOME_TEST_DIR)
191 env["HOMESHARE"] = abspath(HOME_TEST_DIR)
192 home_dir = path.get_home_dir()
192 home_dir = path.get_home_dir()
193 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
193 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
194
194
195 # Should we stub wreg fully so we can run the test on all platforms?
195 # Should we stub wreg fully so we can run the test on all platforms?
196 @skip_if_not_win32
196 @skip_if_not_win32
197 @with_environment
197 @with_environment
198 def test_get_home_dir_8():
198 def test_get_home_dir_8():
199 """Using registry hack for 'My Documents', os=='nt'
199 """Using registry hack for 'My Documents', os=='nt'
200
200
201 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
201 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
202 """
202 """
203 os.name = 'nt'
203 os.name = 'nt'
204 # Remove from stub environment all keys that may be set
204 # Remove from stub environment all keys that may be set
205 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
205 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
206 env.pop(key, None)
206 env.pop(key, None)
207
207
208 #Stub windows registry functions
208 #Stub windows registry functions
209 def OpenKey(x, y):
209 def OpenKey(x, y):
210 class key:
210 class key:
211 def Close(self):
211 def Close(self):
212 pass
212 pass
213 return key()
213 return key()
214 def QueryValueEx(x, y):
214 def QueryValueEx(x, y):
215 return [abspath(HOME_TEST_DIR)]
215 return [abspath(HOME_TEST_DIR)]
216
216
217 wreg.OpenKey = OpenKey
217 wreg.OpenKey = OpenKey
218 wreg.QueryValueEx = QueryValueEx
218 wreg.QueryValueEx = QueryValueEx
219
219
220 home_dir = path.get_home_dir()
220 home_dir = path.get_home_dir()
221 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
221 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
222
222
223
223
224 @with_environment
224 @with_environment
225 def test_get_ipython_dir_1():
225 def test_get_ipython_dir_1():
226 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
226 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
227 env['IPYTHON_DIR'] = "someplace/.ipython"
227 env['IPYTHON_DIR'] = "someplace/.ipython"
228 ipdir = path.get_ipython_dir()
228 ipdir = path.get_ipython_dir()
229 nt.assert_equal(ipdir, "someplace/.ipython")
229 nt.assert_equal(ipdir, "someplace/.ipython")
230
230
231
231
232 @with_environment
232 @with_environment
233 def test_get_ipython_dir_2():
233 def test_get_ipython_dir_2():
234 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
234 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
235 path.get_home_dir = lambda : "someplace"
235 path.get_home_dir = lambda : "someplace"
236 os.name = "posix"
236 os.name = "posix"
237 env.pop('IPYTHON_DIR', None)
237 env.pop('IPYTHON_DIR', None)
238 env.pop('IPYTHONDIR', None)
238 env.pop('IPYTHONDIR', None)
239 ipdir = path.get_ipython_dir()
239 ipdir = path.get_ipython_dir()
240 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
240 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
241
241
242
242
243 def test_filefind():
243 def test_filefind():
244 """Various tests for filefind"""
244 """Various tests for filefind"""
245 f = tempfile.NamedTemporaryFile()
245 f = tempfile.NamedTemporaryFile()
246 # print 'fname:',f.name
246 # print 'fname:',f.name
247 alt_dirs = path.get_ipython_dir()
247 alt_dirs = path.get_ipython_dir()
248 t = path.filefind(f.name, alt_dirs)
248 t = path.filefind(f.name, alt_dirs)
249 # print 'found:',t
249 # print 'found:',t
250
250
251
251
252 def test_get_ipython_package_dir():
252 def test_get_ipython_package_dir():
253 ipdir = path.get_ipython_package_dir()
253 ipdir = path.get_ipython_package_dir()
254 nt.assert_true(os.path.isdir(ipdir))
254 nt.assert_true(os.path.isdir(ipdir))
255
255
256
256
257 def test_get_ipython_module_path():
257 def test_get_ipython_module_path():
258 ipapp_path = path.get_ipython_module_path('IPython.core.ipapp')
258 ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp')
259 nt.assert_true(os.path.isfile(ipapp_path))
259 nt.assert_true(os.path.isfile(ipapp_path))
260
260
261
261
262 @dec.skip_if_not_win32
262 @dec.skip_if_not_win32
263 def test_get_long_path_name_win32():
263 def test_get_long_path_name_win32():
264 p = path.get_long_path_name('c:\\docume~1')
264 p = path.get_long_path_name('c:\\docume~1')
265 nt.assert_equals(p,u'c:\\Documents and Settings')
265 nt.assert_equals(p,u'c:\\Documents and Settings')
266
266
267
267
268 @dec.skip_win32
268 @dec.skip_win32
269 def test_get_long_path_name():
269 def test_get_long_path_name():
270 p = path.get_long_path_name('/usr/local')
270 p = path.get_long_path_name('/usr/local')
271 nt.assert_equals(p,'/usr/local')
271 nt.assert_equals(p,'/usr/local')
272
272
@@ -1,364 +1,364 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """A simple interactive kernel that talks to a frontend over 0MQ.
2 """A simple interactive kernel that talks to a frontend over 0MQ.
3
3
4 Things to do:
4 Things to do:
5
5
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 call set_parent on all the PUB objects with the message about to be executed.
7 call set_parent on all the PUB objects with the message about to be executed.
8 * Implement random port and security key logic.
8 * Implement random port and security key logic.
9 * Implement control messages.
9 * Implement control messages.
10 * Implement event loop and poll version.
10 * Implement event loop and poll version.
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 # Standard library imports.
17 # Standard library imports.
18 import __builtin__
18 import __builtin__
19 from code import CommandCompiler
19 from code import CommandCompiler
20 import os
20 import os
21 import sys
21 import sys
22 import time
22 import time
23 import traceback
23 import traceback
24
24
25 # System library imports.
25 # System library imports.
26 import zmq
26 import zmq
27
27
28 # Local imports.
28 # Local imports.
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.core.iplib import InteractiveShell, InteractiveShellABC
30 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
31 from IPython.external.argparse import ArgumentParser
31 from IPython.external.argparse import ArgumentParser
32 from IPython.utils.traitlets import Instance
32 from IPython.utils.traitlets import Instance
33 from IPython.zmq.session import Session, Message
33 from IPython.zmq.session import Session, Message
34 from completer import KernelCompleter
34 from completer import KernelCompleter
35 from iostream import OutStream
35 from iostream import OutStream
36 from displayhook import DisplayHook
36 from displayhook import DisplayHook
37 from exitpoller import ExitPollerUnix, ExitPollerWindows
37 from exitpoller import ExitPollerUnix, ExitPollerWindows
38
38
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40 # Main kernel class
40 # Main kernel class
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42
42
43 class Kernel(Configurable):
43 class Kernel(Configurable):
44
44
45 shell = Instance('IPython.core.iplib.InteractiveShellABC')
45 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
46 session = Instance('IPython.zmq.session.Session')
46 session = Instance('IPython.zmq.session.Session')
47 reply_socket = Instance('zmq.Socket')
47 reply_socket = Instance('zmq.Socket')
48 pub_socket = Instance('zmq.Socket')
48 pub_socket = Instance('zmq.Socket')
49 req_socket = Instance('zmq.Socket')
49 req_socket = Instance('zmq.Socket')
50
50
51 def __init__(self, **kwargs):
51 def __init__(self, **kwargs):
52 super(Kernel, self).__init__(**kwargs)
52 super(Kernel, self).__init__(**kwargs)
53 self.shell = InteractiveShell.instance()
53 self.shell = InteractiveShell.instance()
54
54
55 # Build dict of handlers for message types
55 # Build dict of handlers for message types
56 msg_types = [ 'execute_request', 'complete_request',
56 msg_types = [ 'execute_request', 'complete_request',
57 'object_info_request' ]
57 'object_info_request' ]
58 self.handlers = {}
58 self.handlers = {}
59 for msg_type in msg_types:
59 for msg_type in msg_types:
60 self.handlers[msg_type] = getattr(self, msg_type)
60 self.handlers[msg_type] = getattr(self, msg_type)
61
61
62 def abort_queue(self):
62 def abort_queue(self):
63 while True:
63 while True:
64 try:
64 try:
65 ident = self.reply_socket.recv(zmq.NOBLOCK)
65 ident = self.reply_socket.recv(zmq.NOBLOCK)
66 except zmq.ZMQError, e:
66 except zmq.ZMQError, e:
67 if e.errno == zmq.EAGAIN:
67 if e.errno == zmq.EAGAIN:
68 break
68 break
69 else:
69 else:
70 assert self.reply_socket.rcvmore(), "Unexpected missing message part."
70 assert self.reply_socket.rcvmore(), "Unexpected missing message part."
71 msg = self.reply_socket.recv_json()
71 msg = self.reply_socket.recv_json()
72 print>>sys.__stdout__, "Aborting:"
72 print>>sys.__stdout__, "Aborting:"
73 print>>sys.__stdout__, Message(msg)
73 print>>sys.__stdout__, Message(msg)
74 msg_type = msg['msg_type']
74 msg_type = msg['msg_type']
75 reply_type = msg_type.split('_')[0] + '_reply'
75 reply_type = msg_type.split('_')[0] + '_reply'
76 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
76 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
77 print>>sys.__stdout__, Message(reply_msg)
77 print>>sys.__stdout__, Message(reply_msg)
78 self.reply_socket.send(ident,zmq.SNDMORE)
78 self.reply_socket.send(ident,zmq.SNDMORE)
79 self.reply_socket.send_json(reply_msg)
79 self.reply_socket.send_json(reply_msg)
80 # We need to wait a bit for requests to come in. This can probably
80 # We need to wait a bit for requests to come in. This can probably
81 # be set shorter for true asynchronous clients.
81 # be set shorter for true asynchronous clients.
82 time.sleep(0.1)
82 time.sleep(0.1)
83
83
84 def execute_request(self, ident, parent):
84 def execute_request(self, ident, parent):
85 try:
85 try:
86 code = parent[u'content'][u'code']
86 code = parent[u'content'][u'code']
87 except:
87 except:
88 print>>sys.__stderr__, "Got bad msg: "
88 print>>sys.__stderr__, "Got bad msg: "
89 print>>sys.__stderr__, Message(parent)
89 print>>sys.__stderr__, Message(parent)
90 return
90 return
91 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
91 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
92 self.pub_socket.send_json(pyin_msg)
92 self.pub_socket.send_json(pyin_msg)
93
93
94 try:
94 try:
95 # Replace raw_input. Note that is not sufficient to replace
95 # Replace raw_input. Note that is not sufficient to replace
96 # raw_input in the user namespace.
96 # raw_input in the user namespace.
97 raw_input = lambda prompt='': self.raw_input(prompt, ident, parent)
97 raw_input = lambda prompt='': self.raw_input(prompt, ident, parent)
98 __builtin__.raw_input = raw_input
98 __builtin__.raw_input = raw_input
99
99
100 # Configure the display hook.
100 # Configure the display hook.
101 sys.displayhook.set_parent(parent)
101 sys.displayhook.set_parent(parent)
102
102
103 self.shell.runlines(code)
103 self.shell.runlines(code)
104 # exec comp_code in self.user_ns, self.user_ns
104 # exec comp_code in self.user_ns, self.user_ns
105 except:
105 except:
106 etype, evalue, tb = sys.exc_info()
106 etype, evalue, tb = sys.exc_info()
107 tb = traceback.format_exception(etype, evalue, tb)
107 tb = traceback.format_exception(etype, evalue, tb)
108 exc_content = {
108 exc_content = {
109 u'status' : u'error',
109 u'status' : u'error',
110 u'traceback' : tb,
110 u'traceback' : tb,
111 u'ename' : unicode(etype.__name__),
111 u'ename' : unicode(etype.__name__),
112 u'evalue' : unicode(evalue)
112 u'evalue' : unicode(evalue)
113 }
113 }
114 exc_msg = self.session.msg(u'pyerr', exc_content, parent)
114 exc_msg = self.session.msg(u'pyerr', exc_content, parent)
115 self.pub_socket.send_json(exc_msg)
115 self.pub_socket.send_json(exc_msg)
116 reply_content = exc_content
116 reply_content = exc_content
117 else:
117 else:
118 reply_content = {'status' : 'ok'}
118 reply_content = {'status' : 'ok'}
119
119
120 # Flush output before sending the reply.
120 # Flush output before sending the reply.
121 sys.stderr.flush()
121 sys.stderr.flush()
122 sys.stdout.flush()
122 sys.stdout.flush()
123
123
124 # Send the reply.
124 # Send the reply.
125 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
125 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
126 print>>sys.__stdout__, Message(reply_msg)
126 print>>sys.__stdout__, Message(reply_msg)
127 self.reply_socket.send(ident, zmq.SNDMORE)
127 self.reply_socket.send(ident, zmq.SNDMORE)
128 self.reply_socket.send_json(reply_msg)
128 self.reply_socket.send_json(reply_msg)
129 if reply_msg['content']['status'] == u'error':
129 if reply_msg['content']['status'] == u'error':
130 self.abort_queue()
130 self.abort_queue()
131
131
132 def raw_input(self, prompt, ident, parent):
132 def raw_input(self, prompt, ident, parent):
133 # Flush output before making the request.
133 # Flush output before making the request.
134 sys.stderr.flush()
134 sys.stderr.flush()
135 sys.stdout.flush()
135 sys.stdout.flush()
136
136
137 # Send the input request.
137 # Send the input request.
138 content = dict(prompt=prompt)
138 content = dict(prompt=prompt)
139 msg = self.session.msg(u'input_request', content, parent)
139 msg = self.session.msg(u'input_request', content, parent)
140 self.req_socket.send_json(msg)
140 self.req_socket.send_json(msg)
141
141
142 # Await a response.
142 # Await a response.
143 reply = self.req_socket.recv_json()
143 reply = self.req_socket.recv_json()
144 try:
144 try:
145 value = reply['content']['value']
145 value = reply['content']['value']
146 except:
146 except:
147 print>>sys.__stderr__, "Got bad raw_input reply: "
147 print>>sys.__stderr__, "Got bad raw_input reply: "
148 print>>sys.__stderr__, Message(parent)
148 print>>sys.__stderr__, Message(parent)
149 value = ''
149 value = ''
150 return value
150 return value
151
151
152 def complete_request(self, ident, parent):
152 def complete_request(self, ident, parent):
153 matches = {'matches' : self.complete(parent),
153 matches = {'matches' : self.complete(parent),
154 'status' : 'ok'}
154 'status' : 'ok'}
155 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
155 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
156 matches, parent, ident)
156 matches, parent, ident)
157 print >> sys.__stdout__, completion_msg
157 print >> sys.__stdout__, completion_msg
158
158
159 def complete(self, msg):
159 def complete(self, msg):
160 return self.shell.complete(msg.content.line)
160 return self.shell.complete(msg.content.line)
161
161
162 def object_info_request(self, ident, parent):
162 def object_info_request(self, ident, parent):
163 context = parent['content']['oname'].split('.')
163 context = parent['content']['oname'].split('.')
164 object_info = self.object_info(context)
164 object_info = self.object_info(context)
165 msg = self.session.send(self.reply_socket, 'object_info_reply',
165 msg = self.session.send(self.reply_socket, 'object_info_reply',
166 object_info, parent, ident)
166 object_info, parent, ident)
167 print >> sys.__stdout__, msg
167 print >> sys.__stdout__, msg
168
168
169 def object_info(self, context):
169 def object_info(self, context):
170 symbol, leftover = self.symbol_from_context(context)
170 symbol, leftover = self.symbol_from_context(context)
171 if symbol is not None and not leftover:
171 if symbol is not None and not leftover:
172 doc = getattr(symbol, '__doc__', '')
172 doc = getattr(symbol, '__doc__', '')
173 else:
173 else:
174 doc = ''
174 doc = ''
175 object_info = dict(docstring = doc)
175 object_info = dict(docstring = doc)
176 return object_info
176 return object_info
177
177
178 def symbol_from_context(self, context):
178 def symbol_from_context(self, context):
179 if not context:
179 if not context:
180 return None, context
180 return None, context
181
181
182 base_symbol_string = context[0]
182 base_symbol_string = context[0]
183 symbol = self.shell.user_ns.get(base_symbol_string, None)
183 symbol = self.shell.user_ns.get(base_symbol_string, None)
184 if symbol is None:
184 if symbol is None:
185 symbol = __builtin__.__dict__.get(base_symbol_string, None)
185 symbol = __builtin__.__dict__.get(base_symbol_string, None)
186 if symbol is None:
186 if symbol is None:
187 return None, context
187 return None, context
188
188
189 context = context[1:]
189 context = context[1:]
190 for i, name in enumerate(context):
190 for i, name in enumerate(context):
191 new_symbol = getattr(symbol, name, None)
191 new_symbol = getattr(symbol, name, None)
192 if new_symbol is None:
192 if new_symbol is None:
193 return symbol, context[i:]
193 return symbol, context[i:]
194 else:
194 else:
195 symbol = new_symbol
195 symbol = new_symbol
196
196
197 return symbol, []
197 return symbol, []
198
198
199 def start(self):
199 def start(self):
200 while True:
200 while True:
201 ident = self.reply_socket.recv()
201 ident = self.reply_socket.recv()
202 assert self.reply_socket.rcvmore(), "Missing message part."
202 assert self.reply_socket.rcvmore(), "Missing message part."
203 msg = self.reply_socket.recv_json()
203 msg = self.reply_socket.recv_json()
204 omsg = Message(msg)
204 omsg = Message(msg)
205 print>>sys.__stdout__
205 print>>sys.__stdout__
206 print>>sys.__stdout__, omsg
206 print>>sys.__stdout__, omsg
207 handler = self.handlers.get(omsg.msg_type, None)
207 handler = self.handlers.get(omsg.msg_type, None)
208 if handler is None:
208 if handler is None:
209 print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg
209 print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg
210 else:
210 else:
211 handler(ident, omsg)
211 handler(ident, omsg)
212
212
213 #-----------------------------------------------------------------------------
213 #-----------------------------------------------------------------------------
214 # Kernel main and launch functions
214 # Kernel main and launch functions
215 #-----------------------------------------------------------------------------
215 #-----------------------------------------------------------------------------
216
216
217 def bind_port(socket, ip, port):
217 def bind_port(socket, ip, port):
218 """ Binds the specified ZMQ socket. If the port is less than zero, a random
218 """ Binds the specified ZMQ socket. If the port is less than zero, a random
219 port is chosen. Returns the port that was bound.
219 port is chosen. Returns the port that was bound.
220 """
220 """
221 connection = 'tcp://%s' % ip
221 connection = 'tcp://%s' % ip
222 if port <= 0:
222 if port <= 0:
223 port = socket.bind_to_random_port(connection)
223 port = socket.bind_to_random_port(connection)
224 else:
224 else:
225 connection += ':%i' % port
225 connection += ':%i' % port
226 socket.bind(connection)
226 socket.bind(connection)
227 return port
227 return port
228
228
229
229
230 def main():
230 def main():
231 """ Main entry point for launching a kernel.
231 """ Main entry point for launching a kernel.
232 """
232 """
233 # Parse command line arguments.
233 # Parse command line arguments.
234 parser = ArgumentParser()
234 parser = ArgumentParser()
235 parser.add_argument('--ip', type=str, default='127.0.0.1',
235 parser.add_argument('--ip', type=str, default='127.0.0.1',
236 help='set the kernel\'s IP address [default: local]')
236 help='set the kernel\'s IP address [default: local]')
237 parser.add_argument('--xrep', type=int, metavar='PORT', default=0,
237 parser.add_argument('--xrep', type=int, metavar='PORT', default=0,
238 help='set the XREP channel port [default: random]')
238 help='set the XREP channel port [default: random]')
239 parser.add_argument('--pub', type=int, metavar='PORT', default=0,
239 parser.add_argument('--pub', type=int, metavar='PORT', default=0,
240 help='set the PUB channel port [default: random]')
240 help='set the PUB channel port [default: random]')
241 parser.add_argument('--req', type=int, metavar='PORT', default=0,
241 parser.add_argument('--req', type=int, metavar='PORT', default=0,
242 help='set the REQ channel port [default: random]')
242 help='set the REQ channel port [default: random]')
243 if sys.platform == 'win32':
243 if sys.platform == 'win32':
244 parser.add_argument('--parent', type=int, metavar='HANDLE',
244 parser.add_argument('--parent', type=int, metavar='HANDLE',
245 default=0, help='kill this process if the process '
245 default=0, help='kill this process if the process '
246 'with HANDLE dies')
246 'with HANDLE dies')
247 else:
247 else:
248 parser.add_argument('--parent', action='store_true',
248 parser.add_argument('--parent', action='store_true',
249 help='kill this process if its parent dies')
249 help='kill this process if its parent dies')
250 namespace = parser.parse_args()
250 namespace = parser.parse_args()
251
251
252 # Create a context, a session, and the kernel sockets.
252 # Create a context, a session, and the kernel sockets.
253 print >>sys.__stdout__, "Starting the kernel..."
253 print >>sys.__stdout__, "Starting the kernel..."
254 context = zmq.Context()
254 context = zmq.Context()
255 session = Session(username=u'kernel')
255 session = Session(username=u'kernel')
256
256
257 reply_socket = context.socket(zmq.XREP)
257 reply_socket = context.socket(zmq.XREP)
258 xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep)
258 xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep)
259 print >>sys.__stdout__, "XREP Channel on port", xrep_port
259 print >>sys.__stdout__, "XREP Channel on port", xrep_port
260
260
261 pub_socket = context.socket(zmq.PUB)
261 pub_socket = context.socket(zmq.PUB)
262 pub_port = bind_port(pub_socket, namespace.ip, namespace.pub)
262 pub_port = bind_port(pub_socket, namespace.ip, namespace.pub)
263 print >>sys.__stdout__, "PUB Channel on port", pub_port
263 print >>sys.__stdout__, "PUB Channel on port", pub_port
264
264
265 req_socket = context.socket(zmq.XREQ)
265 req_socket = context.socket(zmq.XREQ)
266 req_port = bind_port(req_socket, namespace.ip, namespace.req)
266 req_port = bind_port(req_socket, namespace.ip, namespace.req)
267 print >>sys.__stdout__, "REQ Channel on port", req_port
267 print >>sys.__stdout__, "REQ Channel on port", req_port
268
268
269 # Redirect input streams and set a display hook.
269 # Redirect input streams and set a display hook.
270 sys.stdout = OutStream(session, pub_socket, u'stdout')
270 sys.stdout = OutStream(session, pub_socket, u'stdout')
271 sys.stderr = OutStream(session, pub_socket, u'stderr')
271 sys.stderr = OutStream(session, pub_socket, u'stderr')
272 sys.displayhook = DisplayHook(session, pub_socket)
272 sys.displayhook = DisplayHook(session, pub_socket)
273
273
274 # Create the kernel.
274 # Create the kernel.
275 kernel = Kernel(
275 kernel = Kernel(
276 session=session, reply_socket=reply_socket,
276 session=session, reply_socket=reply_socket,
277 pub_socket=pub_socket, req_socket=req_socket
277 pub_socket=pub_socket, req_socket=req_socket
278 )
278 )
279
279
280 # Configure this kernel/process to die on parent termination, if necessary.
280 # Configure this kernel/process to die on parent termination, if necessary.
281 if namespace.parent:
281 if namespace.parent:
282 if sys.platform == 'win32':
282 if sys.platform == 'win32':
283 poller = ExitPollerWindows(namespace.parent)
283 poller = ExitPollerWindows(namespace.parent)
284 else:
284 else:
285 poller = ExitPollerUnix()
285 poller = ExitPollerUnix()
286 poller.start()
286 poller.start()
287
287
288 # Start the kernel mainloop.
288 # Start the kernel mainloop.
289 kernel.start()
289 kernel.start()
290
290
291
291
292 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, independent=False):
292 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, independent=False):
293 """ Launches a localhost kernel, binding to the specified ports.
293 """ Launches a localhost kernel, binding to the specified ports.
294
294
295 Parameters
295 Parameters
296 ----------
296 ----------
297 xrep_port : int, optional
297 xrep_port : int, optional
298 The port to use for XREP channel.
298 The port to use for XREP channel.
299
299
300 pub_port : int, optional
300 pub_port : int, optional
301 The port to use for the SUB channel.
301 The port to use for the SUB channel.
302
302
303 req_port : int, optional
303 req_port : int, optional
304 The port to use for the REQ (raw input) channel.
304 The port to use for the REQ (raw input) channel.
305
305
306 independent : bool, optional (default False)
306 independent : bool, optional (default False)
307 If set, the kernel process is guaranteed to survive if this process
307 If set, the kernel process is guaranteed to survive if this process
308 dies. If not set, an effort is made to ensure that the kernel is killed
308 dies. If not set, an effort is made to ensure that the kernel is killed
309 when this process dies. Note that in this case it is still good practice
309 when this process dies. Note that in this case it is still good practice
310 to kill kernels manually before exiting.
310 to kill kernels manually before exiting.
311
311
312 Returns
312 Returns
313 -------
313 -------
314 A tuple of form:
314 A tuple of form:
315 (kernel_process, xrep_port, pub_port, req_port)
315 (kernel_process, xrep_port, pub_port, req_port)
316 where kernel_process is a Popen object and the ports are integers.
316 where kernel_process is a Popen object and the ports are integers.
317 """
317 """
318 import socket
318 import socket
319 from subprocess import Popen
319 from subprocess import Popen
320
320
321 # Find open ports as necessary.
321 # Find open ports as necessary.
322 ports = []
322 ports = []
323 ports_needed = int(xrep_port <= 0) + int(pub_port <= 0) + int(req_port <= 0)
323 ports_needed = int(xrep_port <= 0) + int(pub_port <= 0) + int(req_port <= 0)
324 for i in xrange(ports_needed):
324 for i in xrange(ports_needed):
325 sock = socket.socket()
325 sock = socket.socket()
326 sock.bind(('', 0))
326 sock.bind(('', 0))
327 ports.append(sock)
327 ports.append(sock)
328 for i, sock in enumerate(ports):
328 for i, sock in enumerate(ports):
329 port = sock.getsockname()[1]
329 port = sock.getsockname()[1]
330 sock.close()
330 sock.close()
331 ports[i] = port
331 ports[i] = port
332 if xrep_port <= 0:
332 if xrep_port <= 0:
333 xrep_port = ports.pop(0)
333 xrep_port = ports.pop(0)
334 if pub_port <= 0:
334 if pub_port <= 0:
335 pub_port = ports.pop(0)
335 pub_port = ports.pop(0)
336 if req_port <= 0:
336 if req_port <= 0:
337 req_port = ports.pop(0)
337 req_port = ports.pop(0)
338
338
339 # Spawn a kernel.
339 # Spawn a kernel.
340 command = 'from IPython.zmq.ipkernel import main; main()'
340 command = 'from IPython.zmq.ipkernel import main; main()'
341 arguments = [ sys.executable, '-c', command, '--xrep', str(xrep_port),
341 arguments = [ sys.executable, '-c', command, '--xrep', str(xrep_port),
342 '--pub', str(pub_port), '--req', str(req_port) ]
342 '--pub', str(pub_port), '--req', str(req_port) ]
343 if independent:
343 if independent:
344 if sys.platform == 'win32':
344 if sys.platform == 'win32':
345 proc = Popen(['start', '/b'] + arguments, shell=True)
345 proc = Popen(['start', '/b'] + arguments, shell=True)
346 else:
346 else:
347 proc = Popen(arguments, preexec_fn=lambda: os.setsid())
347 proc = Popen(arguments, preexec_fn=lambda: os.setsid())
348 else:
348 else:
349 if sys.platform == 'win32':
349 if sys.platform == 'win32':
350 from _subprocess import DuplicateHandle, GetCurrentProcess, \
350 from _subprocess import DuplicateHandle, GetCurrentProcess, \
351 DUPLICATE_SAME_ACCESS
351 DUPLICATE_SAME_ACCESS
352 pid = GetCurrentProcess()
352 pid = GetCurrentProcess()
353 handle = DuplicateHandle(pid, pid, pid, 0,
353 handle = DuplicateHandle(pid, pid, pid, 0,
354 True, # Inheritable by new processes.
354 True, # Inheritable by new processes.
355 DUPLICATE_SAME_ACCESS)
355 DUPLICATE_SAME_ACCESS)
356 proc = Popen(arguments + ['--parent', str(int(handle))])
356 proc = Popen(arguments + ['--parent', str(int(handle))])
357 else:
357 else:
358 proc = Popen(arguments + ['--parent'])
358 proc = Popen(arguments + ['--parent'])
359
359
360 return proc, xrep_port, pub_port, req_port
360 return proc, xrep_port, pub_port, req_port
361
361
362
362
363 if __name__ == '__main__':
363 if __name__ == '__main__':
364 main()
364 main()
@@ -1,16 +1,18 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
2 # -*- coding: utf-8 -*-
3 """IPython -- An enhanced Interactive Python
3 """IPython -- An enhanced Interactive Python
4
4
5 The actual ipython script to be installed with 'python setup.py install' is
5 The actual ipython script to be installed with 'python setup.py install' is
6 in './scripts' directory. This file is here (ipython source root directory)
6 in './scripts' directory. This file is here (ipython source root directory)
7 to facilitate non-root 'zero-installation' (just copy the source tree
7 to facilitate non-root 'zero-installation' (just copy the source tree
8 somewhere and run ipython.py) and development. """
8 somewhere and run ipython.py) and development. """
9
9
10 # Ensure that the imported IPython is the local one, not a system-wide one
10 # Ensure that the imported IPython is the local one, not a system-wide one
11 import os, sys
11 import os, sys
12 this_dir = os.path.dirname(os.path.abspath(__file__))
12 this_dir = os.path.dirname(os.path.abspath(__file__))
13 sys.path.insert(0, this_dir)
13 sys.path.insert(0, this_dir)
14
14
15 # Now proceed with execution
15 # Now proceed with execution
16 execfile(os.path.join(this_dir, 'IPython', 'scripts', 'ipython'))
16 execfile(os.path.join(
17 this_dir, 'IPython', 'frontend', 'terminal', 'scripts', 'ipython'
18 ))
@@ -1,98 +1,96 b''
1 #!python
1 #!python
2 """Windows-specific part of the installation"""
2 """Windows-specific part of the installation"""
3
3
4 import os, sys, shutil
4 import os, sys, shutil
5 pjoin = os.path.join
5 pjoin = os.path.join
6
6
7 def mkshortcut(target,description,link_file,*args,**kw):
7 def mkshortcut(target,description,link_file,*args,**kw):
8 """make a shortcut if it doesn't exist, and register its creation"""
8 """make a shortcut if it doesn't exist, and register its creation"""
9
9
10 create_shortcut(target, description, link_file,*args,**kw)
10 create_shortcut(target, description, link_file,*args,**kw)
11 file_created(link_file)
11 file_created(link_file)
12
12
13 def install():
13 def install():
14 """Routine to be run by the win32 installer with the -install switch."""
14 """Routine to be run by the win32 installer with the -install switch."""
15
15
16 from IPython.core.release import version
16 from IPython.core.release import version
17
17
18 # Get some system constants
18 # Get some system constants
19 prefix = sys.prefix
19 prefix = sys.prefix
20 python = pjoin(prefix, 'python.exe')
20 python = pjoin(prefix, 'python.exe')
21
21
22 # Lookup path to common startmenu ...
22 # Lookup path to common startmenu ...
23 ip_start_menu = pjoin(get_special_folder_path('CSIDL_COMMON_PROGRAMS'), 'IPython')
23 ip_start_menu = pjoin(get_special_folder_path('CSIDL_COMMON_PROGRAMS'), 'IPython')
24 # Create IPython entry ...
24 # Create IPython entry ...
25 if not os.path.isdir(ip_start_menu):
25 if not os.path.isdir(ip_start_menu):
26 os.mkdir(ip_start_menu)
26 os.mkdir(ip_start_menu)
27 directory_created(ip_start_menu)
27 directory_created(ip_start_menu)
28
28
29 # Create .py and .bat files to make things available from
29 # Create .py and .bat files to make things available from
30 # the Windows command line. Thanks to the Twisted project
30 # the Windows command line. Thanks to the Twisted project
31 # for this logic!
31 # for this logic!
32 programs = [
32 programs = [
33 'ipython',
33 'ipython',
34 'iptest',
34 'iptest',
35 'ipcontroller',
35 'ipcontroller',
36 'ipengine',
36 'ipengine',
37 'ipcluster',
37 'ipcluster',
38 'ipythonx',
39 'ipython-wx',
40 'irunner'
38 'irunner'
41 ]
39 ]
42 scripts = pjoin(prefix,'scripts')
40 scripts = pjoin(prefix,'scripts')
43 for program in programs:
41 for program in programs:
44 raw = pjoin(scripts, program)
42 raw = pjoin(scripts, program)
45 bat = raw + '.bat'
43 bat = raw + '.bat'
46 py = raw + '.py'
44 py = raw + '.py'
47 # Create .py versions of the scripts
45 # Create .py versions of the scripts
48 shutil.copy(raw, py)
46 shutil.copy(raw, py)
49 # Create .bat files for each of the scripts
47 # Create .bat files for each of the scripts
50 bat_file = file(bat,'w')
48 bat_file = file(bat,'w')
51 bat_file.write("@%s %s %%*" % (python, py))
49 bat_file.write("@%s %s %%*" % (python, py))
52 bat_file.close()
50 bat_file.close()
53
51
54 # Now move onto setting the Start Menu up
52 # Now move onto setting the Start Menu up
55 ipybase = pjoin(scripts, 'ipython')
53 ipybase = pjoin(scripts, 'ipython')
56
54
57 link = pjoin(ip_start_menu, 'IPython.lnk')
55 link = pjoin(ip_start_menu, 'IPython.lnk')
58 cmd = '"%s"' % ipybase
56 cmd = '"%s"' % ipybase
59 mkshortcut(python,'IPython',link,cmd)
57 mkshortcut(python,'IPython',link,cmd)
60
58
61 link = pjoin(ip_start_menu, 'pysh.lnk')
59 link = pjoin(ip_start_menu, 'pysh.lnk')
62 cmd = '"%s" -p sh' % ipybase
60 cmd = '"%s" -p sh' % ipybase
63 mkshortcut(python,'IPython (command prompt mode)',link,cmd)
61 mkshortcut(python,'IPython (command prompt mode)',link,cmd)
64
62
65 link = pjoin(ip_start_menu, 'scipy.lnk')
63 link = pjoin(ip_start_menu, 'scipy.lnk')
66 cmd = '"%s" -p scipy' % ipybase
64 cmd = '"%s" -p scipy' % ipybase
67 mkshortcut(python,'IPython (scipy profile)',link,cmd)
65 mkshortcut(python,'IPython (scipy profile)',link,cmd)
68
66
69 link = pjoin(ip_start_menu, 'ipcontroller.lnk')
67 link = pjoin(ip_start_menu, 'ipcontroller.lnk')
70 cmd = '"%s" -xy' % pjoin(scripts, 'ipcontroller')
68 cmd = '"%s" -xy' % pjoin(scripts, 'ipcontroller')
71 mkshortcut(python,'IPython controller',link,cmd)
69 mkshortcut(python,'IPython controller',link,cmd)
72
70
73 link = pjoin(ip_start_menu, 'ipengine.lnk')
71 link = pjoin(ip_start_menu, 'ipengine.lnk')
74 cmd = '"%s"' % pjoin(scripts, 'ipengine')
72 cmd = '"%s"' % pjoin(scripts, 'ipengine')
75 mkshortcut(python,'IPython engine',link,cmd)
73 mkshortcut(python,'IPython engine',link,cmd)
76
74
77 # Create documentation shortcuts ...
75 # Create documentation shortcuts ...
78 t = prefix + r'\share\doc\ipython\manual\ipython.pdf'
76 t = prefix + r'\share\doc\ipython\manual\ipython.pdf'
79 f = ip_start_menu + r'\Manual in PDF.lnk'
77 f = ip_start_menu + r'\Manual in PDF.lnk'
80 mkshortcut(t,r'IPython Manual - PDF-Format',f)
78 mkshortcut(t,r'IPython Manual - PDF-Format',f)
81
79
82 t = prefix + r'\share\doc\ipython\manual\html\index.html'
80 t = prefix + r'\share\doc\ipython\manual\html\index.html'
83 f = ip_start_menu + r'\Manual in HTML.lnk'
81 f = ip_start_menu + r'\Manual in HTML.lnk'
84 mkshortcut(t,'IPython Manual - HTML-Format',f)
82 mkshortcut(t,'IPython Manual - HTML-Format',f)
85
83
86
84
87 def remove():
85 def remove():
88 """Routine to be run by the win32 installer with the -remove switch."""
86 """Routine to be run by the win32 installer with the -remove switch."""
89 pass
87 pass
90
88
91 # main()
89 # main()
92 if len(sys.argv) > 1:
90 if len(sys.argv) > 1:
93 if sys.argv[1] == '-install':
91 if sys.argv[1] == '-install':
94 install()
92 install()
95 elif sys.argv[1] == '-remove':
93 elif sys.argv[1] == '-remove':
96 remove()
94 remove()
97 else:
95 else:
98 print "Script was called with option %s" % sys.argv[1]
96 print "Script was called with option %s" % sys.argv[1]
@@ -1,251 +1,250 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
2 # -*- coding: utf-8 -*-
3 """Setup script for IPython.
3 """Setup script for IPython.
4
4
5 Under Posix environments it works like a typical setup.py script.
5 Under Posix environments it works like a typical setup.py script.
6 Under Windows, the command sdist is not supported, since IPython
6 Under Windows, the command sdist is not supported, since IPython
7 requires utilities which are not available under Windows."""
7 requires utilities which are not available under Windows."""
8
8
9 #-------------------------------------------------------------------------------
9 #-------------------------------------------------------------------------------
10 # Copyright (C) 2008 The IPython Development Team
10 # Copyright (C) 2008 The IPython Development Team
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 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Minimal Python version sanity check
17 # Minimal Python version sanity check
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 import sys
20 import sys
21
21
22 # This check is also made in IPython/__init__, don't forget to update both when
22 # This check is also made in IPython/__init__, don't forget to update both when
23 # changing Python version requirements.
23 # changing Python version requirements.
24 if sys.version[0:3] < '2.5':
24 if sys.version[0:3] < '2.5':
25 error = """\
25 error = """\
26 ERROR: 'IPython requires Python Version 2.5 or above.'
26 ERROR: 'IPython requires Python Version 2.5 or above.'
27 Exiting."""
27 Exiting."""
28 print >> sys.stderr, error
28 print >> sys.stderr, error
29 sys.exit(1)
29 sys.exit(1)
30
30
31 # At least we're on Python 2.5 or newer, move on.
31 # At least we're on Python 2.5 or newer, move on.
32
32
33 #-------------------------------------------------------------------------------
33 #-------------------------------------------------------------------------------
34 # Imports
34 # Imports
35 #-------------------------------------------------------------------------------
35 #-------------------------------------------------------------------------------
36
36
37 # Stdlib imports
37 # Stdlib imports
38 import os
38 import os
39 import shutil
39 import shutil
40
40
41 from glob import glob
41 from glob import glob
42
42
43 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
43 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
44 # update it when the contents of directories change.
44 # update it when the contents of directories change.
45 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
45 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
46
46
47 from distutils.core import setup
47 from distutils.core import setup
48
48
49 # Our own imports
49 # Our own imports
50 from IPython.utils.path import target_update
50 from IPython.utils.path import target_update
51
51
52 from setupbase import (
52 from setupbase import (
53 setup_args,
53 setup_args,
54 find_packages,
54 find_packages,
55 find_package_data,
55 find_package_data,
56 find_scripts,
56 find_scripts,
57 find_data_files,
57 find_data_files,
58 check_for_dependencies
58 check_for_dependencies
59 )
59 )
60
60
61 isfile = os.path.isfile
61 isfile = os.path.isfile
62 pjoin = os.path.join
62 pjoin = os.path.join
63
63
64 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
65 # Function definitions
65 # Function definitions
66 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
67
67
68 def cleanup():
68 def cleanup():
69 """Clean up the junk left around by the build process"""
69 """Clean up the junk left around by the build process"""
70 if "develop" not in sys.argv:
70 if "develop" not in sys.argv:
71 try:
71 try:
72 shutil.rmtree('ipython.egg-info')
72 shutil.rmtree('ipython.egg-info')
73 except:
73 except:
74 try:
74 try:
75 os.unlink('ipython.egg-info')
75 os.unlink('ipython.egg-info')
76 except:
76 except:
77 pass
77 pass
78
78
79 #-------------------------------------------------------------------------------
79 #-------------------------------------------------------------------------------
80 # Handle OS specific things
80 # Handle OS specific things
81 #-------------------------------------------------------------------------------
81 #-------------------------------------------------------------------------------
82
82
83 if os.name == 'posix':
83 if os.name == 'posix':
84 os_name = 'posix'
84 os_name = 'posix'
85 elif os.name in ['nt','dos']:
85 elif os.name in ['nt','dos']:
86 os_name = 'windows'
86 os_name = 'windows'
87 else:
87 else:
88 print 'Unsupported operating system:',os.name
88 print 'Unsupported operating system:',os.name
89 sys.exit(1)
89 sys.exit(1)
90
90
91 # Under Windows, 'sdist' has not been supported. Now that the docs build with
91 # Under Windows, 'sdist' has not been supported. Now that the docs build with
92 # Sphinx it might work, but let's not turn it on until someone confirms that it
92 # Sphinx it might work, but let's not turn it on until someone confirms that it
93 # actually works.
93 # actually works.
94 if os_name == 'windows' and 'sdist' in sys.argv:
94 if os_name == 'windows' and 'sdist' in sys.argv:
95 print 'The sdist command is not available under Windows. Exiting.'
95 print 'The sdist command is not available under Windows. Exiting.'
96 sys.exit(1)
96 sys.exit(1)
97
97
98 #-------------------------------------------------------------------------------
98 #-------------------------------------------------------------------------------
99 # Things related to the IPython documentation
99 # Things related to the IPython documentation
100 #-------------------------------------------------------------------------------
100 #-------------------------------------------------------------------------------
101
101
102 # update the manuals when building a source dist
102 # update the manuals when building a source dist
103 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
103 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
104 import textwrap
104 import textwrap
105
105
106 # List of things to be updated. Each entry is a triplet of args for
106 # List of things to be updated. Each entry is a triplet of args for
107 # target_update()
107 # target_update()
108 to_update = [
108 to_update = [
109 # FIXME - Disabled for now: we need to redo an automatic way
109 # FIXME - Disabled for now: we need to redo an automatic way
110 # of generating the magic info inside the rst.
110 # of generating the magic info inside the rst.
111 #('docs/magic.tex',
111 #('docs/magic.tex',
112 #['IPython/Magic.py'],
112 #['IPython/Magic.py'],
113 #"cd doc && ./update_magic.sh" ),
113 #"cd doc && ./update_magic.sh" ),
114
114
115 ('docs/man/ipcluster.1.gz',
115 ('docs/man/ipcluster.1.gz',
116 ['docs/man/ipcluster.1'],
116 ['docs/man/ipcluster.1'],
117 'cd docs/man && gzip -9c ipcluster.1 > ipcluster.1.gz'),
117 'cd docs/man && gzip -9c ipcluster.1 > ipcluster.1.gz'),
118
118
119 ('docs/man/ipcontroller.1.gz',
119 ('docs/man/ipcontroller.1.gz',
120 ['docs/man/ipcontroller.1'],
120 ['docs/man/ipcontroller.1'],
121 'cd docs/man && gzip -9c ipcontroller.1 > ipcontroller.1.gz'),
121 'cd docs/man && gzip -9c ipcontroller.1 > ipcontroller.1.gz'),
122
122
123 ('docs/man/ipengine.1.gz',
123 ('docs/man/ipengine.1.gz',
124 ['docs/man/ipengine.1'],
124 ['docs/man/ipengine.1'],
125 'cd docs/man && gzip -9c ipengine.1 > ipengine.1.gz'),
125 'cd docs/man && gzip -9c ipengine.1 > ipengine.1.gz'),
126
126
127 ('docs/man/ipython.1.gz',
127 ('docs/man/ipython.1.gz',
128 ['docs/man/ipython.1'],
128 ['docs/man/ipython.1'],
129 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'),
129 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'),
130
130
131 ('docs/man/ipython-wx.1.gz',
131 ('docs/man/ipython-wx.1.gz',
132 ['docs/man/ipython-wx.1'],
132 ['docs/man/ipython-wx.1'],
133 'cd docs/man && gzip -9c ipython-wx.1 > ipython-wx.1.gz'),
133 'cd docs/man && gzip -9c ipython-wx.1 > ipython-wx.1.gz'),
134
134
135 ('docs/man/ipythonx.1.gz',
135 ('docs/man/ipythonx.1.gz',
136 ['docs/man/ipythonx.1'],
136 ['docs/man/ipythonx.1'],
137 'cd docs/man && gzip -9c ipythonx.1 > ipythonx.1.gz'),
137 'cd docs/man && gzip -9c ipythonx.1 > ipythonx.1.gz'),
138
138
139 ('docs/man/irunner.1.gz',
139 ('docs/man/irunner.1.gz',
140 ['docs/man/irunner.1'],
140 ['docs/man/irunner.1'],
141 'cd docs/man && gzip -9c irunner.1 > irunner.1.gz'),
141 'cd docs/man && gzip -9c irunner.1 > irunner.1.gz'),
142
142
143 ('docs/man/pycolor.1.gz',
143 ('docs/man/pycolor.1.gz',
144 ['docs/man/pycolor.1'],
144 ['docs/man/pycolor.1'],
145 'cd docs/man && gzip -9c pycolor.1 > pycolor.1.gz'),
145 'cd docs/man && gzip -9c pycolor.1 > pycolor.1.gz'),
146 ]
146 ]
147
147
148 # Only build the docs if sphinx is present
148 # Only build the docs if sphinx is present
149 try:
149 try:
150 import sphinx
150 import sphinx
151 except ImportError:
151 except ImportError:
152 pass
152 pass
153 else:
153 else:
154 # The Makefile calls the do_sphinx scripts to build html and pdf, so
154 # The Makefile calls the do_sphinx scripts to build html and pdf, so
155 # just one target is enough to cover all manual generation
155 # just one target is enough to cover all manual generation
156
156
157 # First, compute all the dependencies that can force us to rebuild the
157 # First, compute all the dependencies that can force us to rebuild the
158 # docs. Start with the main release file that contains metadata
158 # docs. Start with the main release file that contains metadata
159 docdeps = ['IPython/core/release.py']
159 docdeps = ['IPython/core/release.py']
160 # Inculde all the reST sources
160 # Inculde all the reST sources
161 pjoin = os.path.join
161 pjoin = os.path.join
162 for dirpath,dirnames,filenames in os.walk('docs/source'):
162 for dirpath,dirnames,filenames in os.walk('docs/source'):
163 if dirpath in ['_static','_templates']:
163 if dirpath in ['_static','_templates']:
164 continue
164 continue
165 docdeps += [ pjoin(dirpath,f) for f in filenames
165 docdeps += [ pjoin(dirpath,f) for f in filenames
166 if f.endswith('.txt') ]
166 if f.endswith('.txt') ]
167 # and the examples
167 # and the examples
168 for dirpath,dirnames,filenames in os.walk('docs/example'):
168 for dirpath,dirnames,filenames in os.walk('docs/example'):
169 docdeps += [ pjoin(dirpath,f) for f in filenames
169 docdeps += [ pjoin(dirpath,f) for f in filenames
170 if not f.endswith('~') ]
170 if not f.endswith('~') ]
171 # then, make them all dependencies for the main PDF (the html will get
171 # then, make them all dependencies for the main PDF (the html will get
172 # auto-generated as well).
172 # auto-generated as well).
173 to_update.append(
173 to_update.append(
174 ('docs/dist/ipython.pdf',
174 ('docs/dist/ipython.pdf',
175 docdeps,
175 docdeps,
176 "cd docs && make dist")
176 "cd docs && make dist")
177 )
177 )
178
178
179 [ target_update(*t) for t in to_update ]
179 [ target_update(*t) for t in to_update ]
180
180
181 #---------------------------------------------------------------------------
181 #---------------------------------------------------------------------------
182 # Find all the packages, package data, scripts and data_files
182 # Find all the packages, package data, scripts and data_files
183 #---------------------------------------------------------------------------
183 #---------------------------------------------------------------------------
184
184
185 packages = find_packages()
185 packages = find_packages()
186 package_data = find_package_data()
186 package_data = find_package_data()
187 scripts = find_scripts()
187 scripts = find_scripts()
188 data_files = find_data_files()
188 data_files = find_data_files()
189
189
190 #---------------------------------------------------------------------------
190 #---------------------------------------------------------------------------
191 # Handle dependencies and setuptools specific things
191 # Handle dependencies and setuptools specific things
192 #---------------------------------------------------------------------------
192 #---------------------------------------------------------------------------
193
193
194 # For some commands, use setuptools. Note that we do NOT list install here!
194 # For some commands, use setuptools. Note that we do NOT list install here!
195 # If you want a setuptools-enhanced install, just run 'setupegg.py install'
195 # If you want a setuptools-enhanced install, just run 'setupegg.py install'
196 if len(set(('develop', 'sdist', 'release', 'bdist_egg', 'bdist_rpm',
196 if len(set(('develop', 'sdist', 'release', 'bdist_egg', 'bdist_rpm',
197 'bdist', 'bdist_dumb', 'bdist_wininst', 'install_egg_info',
197 'bdist', 'bdist_dumb', 'bdist_wininst', 'install_egg_info',
198 'build_sphinx', 'egg_info', 'easy_install', 'upload',
198 'build_sphinx', 'egg_info', 'easy_install', 'upload',
199 )).intersection(sys.argv)) > 0:
199 )).intersection(sys.argv)) > 0:
200 import setuptools
200 import setuptools
201
201
202 # This dict is used for passing extra arguments that are setuptools
202 # This dict is used for passing extra arguments that are setuptools
203 # specific to setup
203 # specific to setup
204 setuptools_extra_args = {}
204 setuptools_extra_args = {}
205
205
206 if 'setuptools' in sys.modules:
206 if 'setuptools' in sys.modules:
207 setuptools_extra_args['zip_safe'] = False
207 setuptools_extra_args['zip_safe'] = False
208 setuptools_extra_args['entry_points'] = {
208 setuptools_extra_args['entry_points'] = {
209 'console_scripts': [
209 'console_scripts': [
210 'ipython = IPython.core.ipapp:launch_new_instance',
210 'ipython = IPython.frontend.terminal.ipapp:launch_new_instance',
211 'pycolor = IPython.utils.PyColorize:main',
211 'pycolor = IPython.utils.PyColorize:main',
212 'ipcontroller = IPython.kernel.ipcontrollerapp:launch_new_instance',
212 'ipcontroller = IPython.kernel.ipcontrollerapp:launch_new_instance',
213 'ipengine = IPython.kernel.ipengineapp:launch_new_instance',
213 'ipengine = IPython.kernel.ipengineapp:launch_new_instance',
214 'ipcluster = IPython.kernel.ipclusterapp:launch_new_instance',
214 'ipcluster = IPython.kernel.ipclusterapp:launch_new_instance',
215 'ipythonx = IPython.frontend.wx.ipythonx:main',
216 'iptest = IPython.testing.iptest:main',
215 'iptest = IPython.testing.iptest:main',
217 'irunner = IPython.lib.irunner:main'
216 'irunner = IPython.lib.irunner:main'
218 ]
217 ]
219 }
218 }
220 setup_args['extras_require'] = dict(
219 setup_args['extras_require'] = dict(
221 kernel = [
220 kernel = [
222 'zope.interface>=3.4.1',
221 'zope.interface>=3.4.1',
223 'Twisted>=8.0.1',
222 'Twisted>=8.0.1',
224 'foolscap>=0.2.6'
223 'foolscap>=0.2.6'
225 ],
224 ],
226 doc='Sphinx>=0.3',
225 doc='Sphinx>=0.3',
227 test='nose>=0.10.1',
226 test='nose>=0.10.1',
228 security='pyOpenSSL>=0.6'
227 security='pyOpenSSL>=0.6'
229 )
228 )
230 # Allow setuptools to handle the scripts
229 # Allow setuptools to handle the scripts
231 scripts = []
230 scripts = []
232 else:
231 else:
233 # If we are running without setuptools, call this function which will
232 # If we are running without setuptools, call this function which will
234 # check for dependencies an inform the user what is needed. This is
233 # check for dependencies an inform the user what is needed. This is
235 # just to make life easy for users.
234 # just to make life easy for users.
236 check_for_dependencies()
235 check_for_dependencies()
237
236
238 #---------------------------------------------------------------------------
237 #---------------------------------------------------------------------------
239 # Do the actual setup now
238 # Do the actual setup now
240 #---------------------------------------------------------------------------
239 #---------------------------------------------------------------------------
241
240
242 setup_args['packages'] = packages
241 setup_args['packages'] = packages
243 setup_args['package_data'] = package_data
242 setup_args['package_data'] = package_data
244 setup_args['scripts'] = scripts
243 setup_args['scripts'] = scripts
245 setup_args['data_files'] = data_files
244 setup_args['data_files'] = data_files
246 setup_args.update(setuptools_extra_args)
245 setup_args.update(setuptools_extra_args)
247
246
248
247
249 if __name__ == '__main__':
248 if __name__ == '__main__':
250 setup(**setup_args)
249 setup(**setup_args)
251 cleanup()
250 cleanup()
@@ -1,313 +1,313 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """
3 """
4 This module defines the things that are used in setup.py for building IPython
4 This module defines the things that are used in setup.py for building IPython
5
5
6 This includes:
6 This includes:
7
7
8 * The basic arguments to setup
8 * The basic arguments to setup
9 * Functions for finding things like packages, package data, etc.
9 * Functions for finding things like packages, package data, etc.
10 * A function for checking dependencies.
10 * A function for checking dependencies.
11 """
11 """
12
12
13 __docformat__ = "restructuredtext en"
13 __docformat__ = "restructuredtext en"
14
14
15 #-------------------------------------------------------------------------------
15 #-------------------------------------------------------------------------------
16 # Copyright (C) 2008 The IPython Development Team
16 # Copyright (C) 2008 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-------------------------------------------------------------------------------
20 #-------------------------------------------------------------------------------
21
21
22 #-------------------------------------------------------------------------------
22 #-------------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-------------------------------------------------------------------------------
24 #-------------------------------------------------------------------------------
25
25
26 import os, sys
26 import os, sys
27
27
28 from glob import glob
28 from glob import glob
29
29
30 from setupext import install_data_ext
30 from setupext import install_data_ext
31
31
32 #-------------------------------------------------------------------------------
32 #-------------------------------------------------------------------------------
33 # Useful globals and utility functions
33 # Useful globals and utility functions
34 #-------------------------------------------------------------------------------
34 #-------------------------------------------------------------------------------
35
35
36 # A few handy globals
36 # A few handy globals
37 isfile = os.path.isfile
37 isfile = os.path.isfile
38 pjoin = os.path.join
38 pjoin = os.path.join
39
39
40 def oscmd(s):
40 def oscmd(s):
41 print ">", s
41 print ">", s
42 os.system(s)
42 os.system(s)
43
43
44 # A little utility we'll need below, since glob() does NOT allow you to do
44 # A little utility we'll need below, since glob() does NOT allow you to do
45 # exclusion on multiple endings!
45 # exclusion on multiple endings!
46 def file_doesnt_endwith(test,endings):
46 def file_doesnt_endwith(test,endings):
47 """Return true if test is a file and its name does NOT end with any
47 """Return true if test is a file and its name does NOT end with any
48 of the strings listed in endings."""
48 of the strings listed in endings."""
49 if not isfile(test):
49 if not isfile(test):
50 return False
50 return False
51 for e in endings:
51 for e in endings:
52 if test.endswith(e):
52 if test.endswith(e):
53 return False
53 return False
54 return True
54 return True
55
55
56 #---------------------------------------------------------------------------
56 #---------------------------------------------------------------------------
57 # Basic project information
57 # Basic project information
58 #---------------------------------------------------------------------------
58 #---------------------------------------------------------------------------
59
59
60 # release.py contains version, authors, license, url, keywords, etc.
60 # release.py contains version, authors, license, url, keywords, etc.
61 execfile(pjoin('IPython','core','release.py'))
61 execfile(pjoin('IPython','core','release.py'))
62
62
63 # Create a dict with the basic information
63 # Create a dict with the basic information
64 # This dict is eventually passed to setup after additional keys are added.
64 # This dict is eventually passed to setup after additional keys are added.
65 setup_args = dict(
65 setup_args = dict(
66 name = name,
66 name = name,
67 version = version,
67 version = version,
68 description = description,
68 description = description,
69 long_description = long_description,
69 long_description = long_description,
70 author = author,
70 author = author,
71 author_email = author_email,
71 author_email = author_email,
72 url = url,
72 url = url,
73 download_url = download_url,
73 download_url = download_url,
74 license = license,
74 license = license,
75 platforms = platforms,
75 platforms = platforms,
76 keywords = keywords,
76 keywords = keywords,
77 cmdclass = {'install_data': install_data_ext},
77 cmdclass = {'install_data': install_data_ext},
78 )
78 )
79
79
80
80
81 #---------------------------------------------------------------------------
81 #---------------------------------------------------------------------------
82 # Find packages
82 # Find packages
83 #---------------------------------------------------------------------------
83 #---------------------------------------------------------------------------
84
84
85 def add_package(packages,pname,config=False,tests=False,scripts=False,
85 def add_package(packages,pname,config=False,tests=False,scripts=False,
86 others=None):
86 others=None):
87 """
87 """
88 Add a package to the list of packages, including certain subpackages.
88 Add a package to the list of packages, including certain subpackages.
89 """
89 """
90 packages.append('.'.join(['IPython',pname]))
90 packages.append('.'.join(['IPython',pname]))
91 if config:
91 if config:
92 packages.append('.'.join(['IPython',pname,'config']))
92 packages.append('.'.join(['IPython',pname,'config']))
93 if tests:
93 if tests:
94 packages.append('.'.join(['IPython',pname,'tests']))
94 packages.append('.'.join(['IPython',pname,'tests']))
95 if scripts:
95 if scripts:
96 packages.append('.'.join(['IPython',pname,'scripts']))
96 packages.append('.'.join(['IPython',pname,'scripts']))
97 if others is not None:
97 if others is not None:
98 for o in others:
98 for o in others:
99 packages.append('.'.join(['IPython',pname,o]))
99 packages.append('.'.join(['IPython',pname,o]))
100
100
101 def find_packages():
101 def find_packages():
102 """
102 """
103 Find all of IPython's packages.
103 Find all of IPython's packages.
104 """
104 """
105 packages = ['IPython']
105 packages = ['IPython']
106 add_package(packages, 'config', tests=True, others=['default','profile'])
106 add_package(packages, 'config', tests=True, others=['default','profile'])
107 add_package(packages, 'core', tests=True)
107 add_package(packages, 'core', tests=True)
108 add_package(packages, 'deathrow', tests=True)
108 add_package(packages, 'deathrow', tests=True)
109 add_package(packages, 'extensions')
109 add_package(packages, 'extensions')
110 add_package(packages, 'external')
110 add_package(packages, 'external')
111 add_package(packages, 'frontend')
111 add_package(packages, 'frontend')
112 add_package(packages, 'frontend.qt')
112 add_package(packages, 'frontend.qt')
113 add_package(packages, 'frontend.qt.console')
113 add_package(packages, 'frontend.qt.console')
114 add_package(packages, 'frontend.terminal', config=False, tests=True, scripts=True)
114 add_package(packages, 'kernel', config=False, tests=True, scripts=True)
115 add_package(packages, 'kernel', config=False, tests=True, scripts=True)
115 add_package(packages, 'kernel.core', config=False, tests=True)
116 add_package(packages, 'kernel.core', config=False, tests=True)
116 add_package(packages, 'lib', tests=True)
117 add_package(packages, 'lib', tests=True)
117 add_package(packages, 'quarantine', tests=True)
118 add_package(packages, 'quarantine', tests=True)
118 add_package(packages, 'scripts')
119 add_package(packages, 'scripts')
119 add_package(packages, 'testing', tests=True)
120 add_package(packages, 'testing', tests=True)
120 add_package(packages, 'testing.plugin', tests=False)
121 add_package(packages, 'testing.plugin', tests=False)
121 add_package(packages, 'utils', tests=True)
122 add_package(packages, 'utils', tests=True)
122 add_package(packages, 'zmq')
123 add_package(packages, 'zmq')
123 return packages
124 return packages
124
125
125 #---------------------------------------------------------------------------
126 #---------------------------------------------------------------------------
126 # Find package data
127 # Find package data
127 #---------------------------------------------------------------------------
128 #---------------------------------------------------------------------------
128
129
129 def find_package_data():
130 def find_package_data():
130 """
131 """
131 Find IPython's package_data.
132 Find IPython's package_data.
132 """
133 """
133 # This is not enough for these things to appear in an sdist.
134 # This is not enough for these things to appear in an sdist.
134 # We need to muck with the MANIFEST to get this to work
135 # We need to muck with the MANIFEST to get this to work
135 package_data = {
136 package_data = {
136 'IPython.config.userconfig' : ['*'],
137 'IPython.config.userconfig' : ['*'],
137 'IPython.testing' : ['*.txt']
138 'IPython.testing' : ['*.txt']
138 }
139 }
139 return package_data
140 return package_data
140
141
141
142
142 #---------------------------------------------------------------------------
143 #---------------------------------------------------------------------------
143 # Find data files
144 # Find data files
144 #---------------------------------------------------------------------------
145 #---------------------------------------------------------------------------
145
146
146 def make_dir_struct(tag,base,out_base):
147 def make_dir_struct(tag,base,out_base):
147 """Make the directory structure of all files below a starting dir.
148 """Make the directory structure of all files below a starting dir.
148
149
149 This is just a convenience routine to help build a nested directory
150 This is just a convenience routine to help build a nested directory
150 hierarchy because distutils is too stupid to do this by itself.
151 hierarchy because distutils is too stupid to do this by itself.
151
152
152 XXX - this needs a proper docstring!
153 XXX - this needs a proper docstring!
153 """
154 """
154
155
155 # we'll use these a lot below
156 # we'll use these a lot below
156 lbase = len(base)
157 lbase = len(base)
157 pathsep = os.path.sep
158 pathsep = os.path.sep
158 lpathsep = len(pathsep)
159 lpathsep = len(pathsep)
159
160
160 out = []
161 out = []
161 for (dirpath,dirnames,filenames) in os.walk(base):
162 for (dirpath,dirnames,filenames) in os.walk(base):
162 # we need to strip out the dirpath from the base to map it to the
163 # we need to strip out the dirpath from the base to map it to the
163 # output (installation) path. This requires possibly stripping the
164 # output (installation) path. This requires possibly stripping the
164 # path separator, because otherwise pjoin will not work correctly
165 # path separator, because otherwise pjoin will not work correctly
165 # (pjoin('foo/','/bar') returns '/bar').
166 # (pjoin('foo/','/bar') returns '/bar').
166
167
167 dp_eff = dirpath[lbase:]
168 dp_eff = dirpath[lbase:]
168 if dp_eff.startswith(pathsep):
169 if dp_eff.startswith(pathsep):
169 dp_eff = dp_eff[lpathsep:]
170 dp_eff = dp_eff[lpathsep:]
170 # The output path must be anchored at the out_base marker
171 # The output path must be anchored at the out_base marker
171 out_path = pjoin(out_base,dp_eff)
172 out_path = pjoin(out_base,dp_eff)
172 # Now we can generate the final filenames. Since os.walk only produces
173 # Now we can generate the final filenames. Since os.walk only produces
173 # filenames, we must join back with the dirpath to get full valid file
174 # filenames, we must join back with the dirpath to get full valid file
174 # paths:
175 # paths:
175 pfiles = [pjoin(dirpath,f) for f in filenames]
176 pfiles = [pjoin(dirpath,f) for f in filenames]
176 # Finally, generate the entry we need, which is a triple of (tag,output
177 # Finally, generate the entry we need, which is a triple of (tag,output
177 # path, files) for use as a data_files parameter in install_data.
178 # path, files) for use as a data_files parameter in install_data.
178 out.append((tag,out_path,pfiles))
179 out.append((tag,out_path,pfiles))
179
180
180 return out
181 return out
181
182
182
183
183 def find_data_files():
184 def find_data_files():
184 """
185 """
185 Find IPython's data_files.
186 Find IPython's data_files.
186
187
187 Most of these are docs.
188 Most of these are docs.
188 """
189 """
189
190
190 docdirbase = pjoin('share', 'doc', 'ipython')
191 docdirbase = pjoin('share', 'doc', 'ipython')
191 manpagebase = pjoin('share', 'man', 'man1')
192 manpagebase = pjoin('share', 'man', 'man1')
192
193
193 # Simple file lists can be made by hand
194 # Simple file lists can be made by hand
194 manpages = filter(isfile, glob(pjoin('docs','man','*.1.gz')))
195 manpages = filter(isfile, glob(pjoin('docs','man','*.1.gz')))
195 igridhelpfiles = filter(isfile, glob(pjoin('IPython','extensions','igrid_help.*')))
196 igridhelpfiles = filter(isfile, glob(pjoin('IPython','extensions','igrid_help.*')))
196
197
197 # For nested structures, use the utility above
198 # For nested structures, use the utility above
198 example_files = make_dir_struct(
199 example_files = make_dir_struct(
199 'data',
200 'data',
200 pjoin('docs','examples'),
201 pjoin('docs','examples'),
201 pjoin(docdirbase,'examples')
202 pjoin(docdirbase,'examples')
202 )
203 )
203 manual_files = make_dir_struct(
204 manual_files = make_dir_struct(
204 'data',
205 'data',
205 pjoin('docs','dist'),
206 pjoin('docs','dist'),
206 pjoin(docdirbase,'manual')
207 pjoin(docdirbase,'manual')
207 )
208 )
208
209
209 # And assemble the entire output list
210 # And assemble the entire output list
210 data_files = [ ('data',manpagebase, manpages),
211 data_files = [ ('data',manpagebase, manpages),
211 ('data',pjoin(docdirbase,'extensions'),igridhelpfiles),
212 ('data',pjoin(docdirbase,'extensions'),igridhelpfiles),
212 ] + manual_files + example_files
213 ] + manual_files + example_files
213
214
214 ## import pprint # dbg
215 ## import pprint # dbg
215 ## print '*'*80
216 ## print '*'*80
216 ## print 'data files'
217 ## print 'data files'
217 ## pprint.pprint(data_files)
218 ## pprint.pprint(data_files)
218 ## print '*'*80
219 ## print '*'*80
219
220
220 return data_files
221 return data_files
221
222
222
223
223 def make_man_update_target(manpage):
224 def make_man_update_target(manpage):
224 """Return a target_update-compliant tuple for the given manpage.
225 """Return a target_update-compliant tuple for the given manpage.
225
226
226 Parameters
227 Parameters
227 ----------
228 ----------
228 manpage : string
229 manpage : string
229 Name of the manpage, must include the section number (trailing number).
230 Name of the manpage, must include the section number (trailing number).
230
231
231 Example
232 Example
232 -------
233 -------
233
234
234 >>> make_man_update_target('ipython.1') #doctest: +NORMALIZE_WHITESPACE
235 >>> make_man_update_target('ipython.1') #doctest: +NORMALIZE_WHITESPACE
235 ('docs/man/ipython.1.gz',
236 ('docs/man/ipython.1.gz',
236 ['docs/man/ipython.1'],
237 ['docs/man/ipython.1'],
237 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz')
238 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz')
238 """
239 """
239 man_dir = pjoin('docs', 'man')
240 man_dir = pjoin('docs', 'man')
240 manpage_gz = manpage + '.gz'
241 manpage_gz = manpage + '.gz'
241 manpath = pjoin(man_dir, manpage)
242 manpath = pjoin(man_dir, manpage)
242 manpath_gz = pjoin(man_dir, manpage_gz)
243 manpath_gz = pjoin(man_dir, manpage_gz)
243 gz_cmd = ( "cd %(man_dir)s && gzip -9c %(manpage)s > %(manpage_gz)s" %
244 gz_cmd = ( "cd %(man_dir)s && gzip -9c %(manpage)s > %(manpage_gz)s" %
244 locals() )
245 locals() )
245 return (manpath_gz, [manpath], gz_cmd)
246 return (manpath_gz, [manpath], gz_cmd)
246
247
247 #---------------------------------------------------------------------------
248 #---------------------------------------------------------------------------
248 # Find scripts
249 # Find scripts
249 #---------------------------------------------------------------------------
250 #---------------------------------------------------------------------------
250
251
251 def find_scripts():
252 def find_scripts():
252 """
253 """
253 Find IPython's scripts.
254 Find IPython's scripts.
254 """
255 """
255 kernel_scripts = pjoin('IPython','kernel','scripts')
256 kernel_scripts = pjoin('IPython','kernel','scripts')
256 main_scripts = pjoin('IPython','scripts')
257 main_scripts = pjoin('IPython','scripts')
258 frontend_terminal_scripts = pjoin('IPython','frontend','terminal','scripts')
257 scripts = [pjoin(kernel_scripts, 'ipengine'),
259 scripts = [pjoin(kernel_scripts, 'ipengine'),
258 pjoin(kernel_scripts, 'ipcontroller'),
260 pjoin(kernel_scripts, 'ipcontroller'),
259 pjoin(kernel_scripts, 'ipcluster'),
261 pjoin(kernel_scripts, 'ipcluster'),
260 pjoin(main_scripts, 'ipython'),
262 pjoin(frontend_terminal_scripts, 'ipython'),
261 pjoin(main_scripts, 'ipythonx'),
262 pjoin(main_scripts, 'ipython-wx'),
263 pjoin(main_scripts, 'pycolor'),
263 pjoin(main_scripts, 'pycolor'),
264 pjoin(main_scripts, 'irunner'),
264 pjoin(main_scripts, 'irunner'),
265 pjoin(main_scripts, 'iptest')
265 pjoin(main_scripts, 'iptest')
266 ]
266 ]
267
267
268 # Script to be run by the windows binary installer after the default setup
268 # Script to be run by the windows binary installer after the default setup
269 # routine, to add shortcuts and similar windows-only things. Windows
269 # routine, to add shortcuts and similar windows-only things. Windows
270 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
270 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
271 # doesn't find them.
271 # doesn't find them.
272 if 'bdist_wininst' in sys.argv:
272 if 'bdist_wininst' in sys.argv:
273 if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
273 if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
274 print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting."
274 print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting."
275 sys.exit(1)
275 sys.exit(1)
276 scripts.append(pjoin('scripts','ipython_win_post_install.py'))
276 scripts.append(pjoin('scripts','ipython_win_post_install.py'))
277
277
278 return scripts
278 return scripts
279
279
280 #---------------------------------------------------------------------------
280 #---------------------------------------------------------------------------
281 # Verify all dependencies
281 # Verify all dependencies
282 #---------------------------------------------------------------------------
282 #---------------------------------------------------------------------------
283
283
284 def check_for_dependencies():
284 def check_for_dependencies():
285 """Check for IPython's dependencies.
285 """Check for IPython's dependencies.
286
286
287 This function should NOT be called if running under setuptools!
287 This function should NOT be called if running under setuptools!
288 """
288 """
289 from setupext.setupext import (
289 from setupext.setupext import (
290 print_line, print_raw, print_status, print_message,
290 print_line, print_raw, print_status, print_message,
291 check_for_zopeinterface, check_for_twisted,
291 check_for_zopeinterface, check_for_twisted,
292 check_for_foolscap, check_for_pyopenssl,
292 check_for_foolscap, check_for_pyopenssl,
293 check_for_sphinx, check_for_pygments,
293 check_for_sphinx, check_for_pygments,
294 check_for_nose, check_for_pexpect
294 check_for_nose, check_for_pexpect
295 )
295 )
296 print_line()
296 print_line()
297 print_raw("BUILDING IPYTHON")
297 print_raw("BUILDING IPYTHON")
298 print_status('python', sys.version)
298 print_status('python', sys.version)
299 print_status('platform', sys.platform)
299 print_status('platform', sys.platform)
300 if sys.platform == 'win32':
300 if sys.platform == 'win32':
301 print_status('Windows version', sys.getwindowsversion())
301 print_status('Windows version', sys.getwindowsversion())
302
302
303 print_raw("")
303 print_raw("")
304 print_raw("OPTIONAL DEPENDENCIES")
304 print_raw("OPTIONAL DEPENDENCIES")
305
305
306 check_for_zopeinterface()
306 check_for_zopeinterface()
307 check_for_twisted()
307 check_for_twisted()
308 check_for_foolscap()
308 check_for_foolscap()
309 check_for_pyopenssl()
309 check_for_pyopenssl()
310 check_for_sphinx()
310 check_for_sphinx()
311 check_for_pygments()
311 check_for_pygments()
312 check_for_nose()
312 check_for_nose()
313 check_for_pexpect()
313 check_for_pexpect()
General Comments 0
You need to be logged in to leave comments. Login now