##// END OF EJS Templates
Merge pull request #4151 from takluyver/drop-alias...
Thomas Kluyver -
r12759:b1100aa2 merge
parent child Browse files
Show More
@@ -0,0 +1,41 b''
1 from IPython.utils.capture import capture_output
2
3 import nose.tools as nt
4
5 def test_alias_lifecycle():
6 name = 'test_alias1'
7 cmd = 'echo "Hello"'
8 am = _ip.alias_manager
9 am.clear_aliases()
10 am.define_alias(name, cmd)
11 assert am.is_alias(name)
12 nt.assert_equal(am.retrieve_alias(name), cmd)
13 nt.assert_in((name, cmd), am.aliases)
14
15 # Test running the alias
16 orig_system = _ip.system
17 result = []
18 _ip.system = result.append
19 try:
20 _ip.run_cell('%{}'.format(name))
21 result = [c.strip() for c in result]
22 nt.assert_equal(result, [cmd])
23 finally:
24 _ip.system = orig_system
25
26 # Test removing the alias
27 am.undefine_alias(name)
28 assert not am.is_alias(name)
29 with nt.assert_raises(ValueError):
30 am.retrieve_alias(name)
31 nt.assert_not_in((name, cmd), am.aliases)
32
33
34 def test_alias_args_error():
35 """Error expanding with wrong number of arguments"""
36 _ip.alias_manager.define_alias('parts', 'echo first %s second %s')
37 # capture stderr:
38 with capture_output() as cap:
39 _ip.run_cell('parts 1')
40
41 nt.assert_equal(cap.stderr.split(':')[0], 'UsageError') No newline at end of file
@@ -0,0 +1,3 b''
1 - The alias system has been reimplemented to use magic functions. There should be little
2 visible difference while automagics are enabled, as they are by default, but parts of the
3 :class:`~IPython.core.alias.AliasManager` API have been removed.
@@ -1,262 +1,237 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 System command aliases.
3 System command aliases.
4
4
5 Authors:
5 Authors:
6
6
7 * Fernando Perez
7 * Fernando Perez
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2011 The IPython Development Team
12 # Copyright (C) 2008-2011 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License.
14 # Distributed under the terms of the BSD License.
15 #
15 #
16 # The full license is in the file COPYING.txt, distributed with this software.
16 # The full license is in the file COPYING.txt, distributed with this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import __builtin__
24 import keyword
25 import os
23 import os
26 import re
24 import re
27 import sys
25 import sys
28
26
29 from IPython.config.configurable import Configurable
27 from IPython.config.configurable import Configurable
30 from IPython.core.splitinput import split_user_input
28 from IPython.core.error import UsageError
31
29
32 from IPython.utils.traitlets import List, Instance
30 from IPython.utils.traitlets import List, Instance
33 from IPython.utils.warn import warn, error
31 from IPython.utils.warn import error
34
32
35 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
36 # Utilities
34 # Utilities
37 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
38
36
39 # This is used as the pattern for calls to split_user_input.
37 # This is used as the pattern for calls to split_user_input.
40 shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
38 shell_line_split = re.compile(r'^(\s*)()(\S+)(.*$)')
41
39
42 def default_aliases():
40 def default_aliases():
43 """Return list of shell aliases to auto-define.
41 """Return list of shell aliases to auto-define.
44 """
42 """
45 # Note: the aliases defined here should be safe to use on a kernel
43 # Note: the aliases defined here should be safe to use on a kernel
46 # regardless of what frontend it is attached to. Frontends that use a
44 # regardless of what frontend it is attached to. Frontends that use a
47 # kernel in-process can define additional aliases that will only work in
45 # kernel in-process can define additional aliases that will only work in
48 # their case. For example, things like 'less' or 'clear' that manipulate
46 # their case. For example, things like 'less' or 'clear' that manipulate
49 # the terminal should NOT be declared here, as they will only work if the
47 # the terminal should NOT be declared here, as they will only work if the
50 # kernel is running inside a true terminal, and not over the network.
48 # kernel is running inside a true terminal, and not over the network.
51
49
52 if os.name == 'posix':
50 if os.name == 'posix':
53 default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
51 default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
54 ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'),
52 ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'),
55 ('cat', 'cat'),
53 ('cat', 'cat'),
56 ]
54 ]
57 # Useful set of ls aliases. The GNU and BSD options are a little
55 # Useful set of ls aliases. The GNU and BSD options are a little
58 # different, so we make aliases that provide as similar as possible
56 # different, so we make aliases that provide as similar as possible
59 # behavior in ipython, by passing the right flags for each platform
57 # behavior in ipython, by passing the right flags for each platform
60 if sys.platform.startswith('linux'):
58 if sys.platform.startswith('linux'):
61 ls_aliases = [('ls', 'ls -F --color'),
59 ls_aliases = [('ls', 'ls -F --color'),
62 # long ls
60 # long ls
63 ('ll', 'ls -F -o --color'),
61 ('ll', 'ls -F -o --color'),
64 # ls normal files only
62 # ls normal files only
65 ('lf', 'ls -F -o --color %l | grep ^-'),
63 ('lf', 'ls -F -o --color %l | grep ^-'),
66 # ls symbolic links
64 # ls symbolic links
67 ('lk', 'ls -F -o --color %l | grep ^l'),
65 ('lk', 'ls -F -o --color %l | grep ^l'),
68 # directories or links to directories,
66 # directories or links to directories,
69 ('ldir', 'ls -F -o --color %l | grep /$'),
67 ('ldir', 'ls -F -o --color %l | grep /$'),
70 # things which are executable
68 # things which are executable
71 ('lx', 'ls -F -o --color %l | grep ^-..x'),
69 ('lx', 'ls -F -o --color %l | grep ^-..x'),
72 ]
70 ]
73 else:
71 else:
74 # BSD, OSX, etc.
72 # BSD, OSX, etc.
75 ls_aliases = [('ls', 'ls -F -G'),
73 ls_aliases = [('ls', 'ls -F -G'),
76 # long ls
74 # long ls
77 ('ll', 'ls -F -l -G'),
75 ('ll', 'ls -F -l -G'),
78 # ls normal files only
76 # ls normal files only
79 ('lf', 'ls -F -l -G %l | grep ^-'),
77 ('lf', 'ls -F -l -G %l | grep ^-'),
80 # ls symbolic links
78 # ls symbolic links
81 ('lk', 'ls -F -l -G %l | grep ^l'),
79 ('lk', 'ls -F -l -G %l | grep ^l'),
82 # directories or links to directories,
80 # directories or links to directories,
83 ('ldir', 'ls -F -G -l %l | grep /$'),
81 ('ldir', 'ls -F -G -l %l | grep /$'),
84 # things which are executable
82 # things which are executable
85 ('lx', 'ls -F -l -G %l | grep ^-..x'),
83 ('lx', 'ls -F -l -G %l | grep ^-..x'),
86 ]
84 ]
87 default_aliases = default_aliases + ls_aliases
85 default_aliases = default_aliases + ls_aliases
88 elif os.name in ['nt', 'dos']:
86 elif os.name in ['nt', 'dos']:
89 default_aliases = [('ls', 'dir /on'),
87 default_aliases = [('ls', 'dir /on'),
90 ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
88 ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
91 ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
89 ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
92 ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
90 ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
93 ]
91 ]
94 else:
92 else:
95 default_aliases = []
93 default_aliases = []
96
94
97 return default_aliases
95 return default_aliases
98
96
99
97
100 class AliasError(Exception):
98 class AliasError(Exception):
101 pass
99 pass
102
100
103
101
104 class InvalidAliasError(AliasError):
102 class InvalidAliasError(AliasError):
105 pass
103 pass
106
104
105 class Alias(object):
106 """Callable object storing the details of one alias.
107
108 Instances are registered as magic functions to allow use of aliases.
109 """
110
111 # Prepare blacklist
112 blacklist = {'cd','popd','pushd','dhist','alias','unalias'}
113
114 def __init__(self, shell, name, cmd):
115 self.shell = shell
116 self.name = name
117 self.cmd = cmd
118 self.nargs = self.validate()
119
120 def validate(self):
121 """Validate the alias, and return the number of arguments."""
122 if self.name in self.blacklist:
123 raise InvalidAliasError("The name %s can't be aliased "
124 "because it is a keyword or builtin." % self.name)
125 try:
126 caller = self.shell.magics_manager.magics['line'][self.name]
127 except KeyError:
128 pass
129 else:
130 if not isinstance(caller, Alias):
131 raise InvalidAliasError("The name %s can't be aliased "
132 "because it is another magic command." % self.name)
133
134 if not (isinstance(self.cmd, basestring)):
135 raise InvalidAliasError("An alias command must be a string, "
136 "got: %r" % self.cmd)
137
138 nargs = self.cmd.count('%s')
139
140 if (nargs > 0) and (self.cmd.find('%l') >= 0):
141 raise InvalidAliasError('The %s and %l specifiers are mutually '
142 'exclusive in alias definitions.')
143
144 return nargs
145
146 def __repr__(self):
147 return "<alias {} for {!r}>".format(self.name, self.cmd)
148
149 def __call__(self, rest=''):
150 cmd = self.cmd
151 nargs = self.nargs
152 # Expand the %l special to be the user's input line
153 if cmd.find('%l') >= 0:
154 cmd = cmd.replace('%l', rest)
155 rest = ''
156 if nargs==0:
157 # Simple, argument-less aliases
158 cmd = '%s %s' % (cmd, rest)
159 else:
160 # Handle aliases with positional arguments
161 args = rest.split(None, nargs)
162 if len(args) < nargs:
163 raise UsageError('Alias <%s> requires %s arguments, %s given.' %
164 (self.name, nargs, len(args)))
165 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
166
167 self.shell.system(cmd)
168
107 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
108 # Main AliasManager class
170 # Main AliasManager class
109 #-----------------------------------------------------------------------------
171 #-----------------------------------------------------------------------------
110
172
111 class AliasManager(Configurable):
173 class AliasManager(Configurable):
112
174
113 default_aliases = List(default_aliases(), config=True)
175 default_aliases = List(default_aliases(), config=True)
114 user_aliases = List(default_value=[], config=True)
176 user_aliases = List(default_value=[], config=True)
115 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
177 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
116
178
117 def __init__(self, shell=None, **kwargs):
179 def __init__(self, shell=None, **kwargs):
118 super(AliasManager, self).__init__(shell=shell, **kwargs)
180 super(AliasManager, self).__init__(shell=shell, **kwargs)
119 self.alias_table = {}
181 # For convenient access
120 self.exclude_aliases()
182 self.linemagics = self.shell.magics_manager.magics['line']
121 self.init_aliases()
183 self.init_aliases()
122
184
123 def __contains__(self, name):
124 return name in self.alias_table
125
126 @property
127 def aliases(self):
128 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
129
130 def exclude_aliases(self):
131 # set of things NOT to alias (keywords, builtins and some magics)
132 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
133 no_alias.update(set(keyword.kwlist))
134 no_alias.update(set(__builtin__.__dict__.keys()))
135 self.no_alias = no_alias
136
137 def init_aliases(self):
185 def init_aliases(self):
138 # Load default aliases
186 # Load default & user aliases
139 for name, cmd in self.default_aliases:
187 for name, cmd in self.default_aliases + self.user_aliases:
140 self.soft_define_alias(name, cmd)
141
142 # Load user aliases
143 for name, cmd in self.user_aliases:
144 self.soft_define_alias(name, cmd)
188 self.soft_define_alias(name, cmd)
145
189
146 def clear_aliases(self):
190 @property
147 self.alias_table.clear()
191 def aliases(self):
192 return [(n, func.cmd) for (n, func) in self.linemagics.items()
193 if isinstance(func, Alias)]
148
194
149 def soft_define_alias(self, name, cmd):
195 def soft_define_alias(self, name, cmd):
150 """Define an alias, but don't raise on an AliasError."""
196 """Define an alias, but don't raise on an AliasError."""
151 try:
197 try:
152 self.define_alias(name, cmd)
198 self.define_alias(name, cmd)
153 except AliasError as e:
199 except AliasError as e:
154 error("Invalid alias: %s" % e)
200 error("Invalid alias: %s" % e)
155
201
156 def define_alias(self, name, cmd):
202 def define_alias(self, name, cmd):
157 """Define a new alias after validating it.
203 """Define a new alias after validating it.
158
204
159 This will raise an :exc:`AliasError` if there are validation
205 This will raise an :exc:`AliasError` if there are validation
160 problems.
206 problems.
161 """
207 """
162 nargs = self.validate_alias(name, cmd)
208 caller = Alias(shell=self.shell, name=name, cmd=cmd)
163 self.alias_table[name] = (nargs, cmd)
209 self.shell.magics_manager.register_function(caller, magic_kind='line',
210 magic_name=name)
164
211
165 def undefine_alias(self, name):
212 def get_alias(self, name):
166 if name in self.alias_table:
213 """Return an alias, or None if no alias by that name exists."""
167 del self.alias_table[name]
214 aname = self.linemagics.get(name, None)
215 return aname if isinstance(aname, Alias) else None
168
216
169 def validate_alias(self, name, cmd):
217 def is_alias(self, name):
170 """Validate an alias and return the its number of arguments."""
218 """Return whether or not a given name has been defined as an alias"""
171 if name in self.no_alias:
219 return self.get_alias(name) is not None
172 raise InvalidAliasError("The name %s can't be aliased "
173 "because it is a keyword or builtin." % name)
174 if not (isinstance(cmd, basestring)):
175 raise InvalidAliasError("An alias command must be a string, "
176 "got: %r" % cmd)
177 nargs = cmd.count('%s')
178 if nargs>0 and cmd.find('%l')>=0:
179 raise InvalidAliasError('The %s and %l specifiers are mutually '
180 'exclusive in alias definitions.')
181 return nargs
182
220
183 def call_alias(self, alias, rest=''):
221 def undefine_alias(self, name):
184 """Call an alias given its name and the rest of the line."""
222 if self.is_alias(name):
185 cmd = self.transform_alias(alias, rest)
223 del self.linemagics[name]
186 try:
187 self.shell.system(cmd)
188 except:
189 self.shell.showtraceback()
190
191 def transform_alias(self, alias,rest=''):
192 """Transform alias to system command string."""
193 nargs, cmd = self.alias_table[alias]
194
195 if ' ' in cmd and os.path.isfile(cmd):
196 cmd = '"%s"' % cmd
197
198 # Expand the %l special to be the user's input line
199 if cmd.find('%l') >= 0:
200 cmd = cmd.replace('%l', rest)
201 rest = ''
202 if nargs==0:
203 # Simple, argument-less aliases
204 cmd = '%s %s' % (cmd, rest)
205 else:
224 else:
206 # Handle aliases with positional arguments
225 raise ValueError('%s is not an alias' % name)
207 args = rest.split(None, nargs)
208 if len(args) < nargs:
209 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
210 (alias, nargs, len(args)))
211 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
212 return cmd
213
214 def expand_alias(self, line):
215 """ Expand an alias in the command line
216
226
217 Returns the provided command line, possibly with the first word
227 def clear_aliases(self):
218 (command) translated according to alias expansion rules.
228 for name, cmd in self.aliases:
219
229 self.undefine_alias(name)
220 [ipython]|16> _ip.expand_aliases("np myfile.txt")
230
221 <16> 'q:/opt/np/notepad++.exe myfile.txt'
231 def retrieve_alias(self, name):
222 """
232 """Retrieve the command to which an alias expands."""
223
233 caller = self.get_alias(name)
224 pre,_,fn,rest = split_user_input(line)
234 if caller:
225 res = pre + self.expand_aliases(fn, rest)
235 return caller.cmd
226 return res
236 else:
227
237 raise ValueError('%s is not an alias' % name)
228 def expand_aliases(self, fn, rest):
229 """Expand multiple levels of aliases:
230
231 if:
232
233 alias foo bar /tmp
234 alias baz foo
235
236 then:
237
238 baz huhhahhei -> bar /tmp huhhahhei
239 """
240 line = fn + " " + rest
241
242 done = set()
243 while 1:
244 pre,_,fn,rest = split_user_input(line, shell_line_split)
245 if fn in self.alias_table:
246 if fn in done:
247 warn("Cyclic alias definition, repeated '%s'" % fn)
248 return ""
249 done.add(fn)
250
251 l2 = self.transform_alias(fn, rest)
252 if l2 == line:
253 break
254 # ls -> ls -F should not recurse forever
255 if l2.split(None,1)[0] == line.split(None,1)[0]:
256 line = l2
257 break
258 line = l2
259 else:
260 break
261
262 return line
@@ -1,979 +1,955 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 Original rlcompleter documentation:
9 Original rlcompleter documentation:
10
10
11 This requires the latest extension to the readline module (the
11 This requires the latest extension to the readline module (the
12 completes keywords, built-ins and globals in __main__; when completing
12 completes keywords, built-ins and globals in __main__; when completing
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 completes its attributes.
14 completes its attributes.
15
15
16 It's very cool to do "import string" type "string.", hit the
16 It's very cool to do "import string" type "string.", hit the
17 completion key (twice), and see the list of names defined by the
17 completion key (twice), and see the list of names defined by the
18 string module!
18 string module!
19
19
20 Tip: to use the tab key as the completion key, call
20 Tip: to use the tab key as the completion key, call
21
21
22 readline.parse_and_bind("tab: complete")
22 readline.parse_and_bind("tab: complete")
23
23
24 Notes:
24 Notes:
25
25
26 - Exceptions raised by the completer function are *ignored* (and
26 - Exceptions raised by the completer function are *ignored* (and
27 generally cause the completion to fail). This is a feature -- since
27 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
30 reset and restore the tty state.
31
31
32 - The evaluation of the NAME.NAME... form may cause arbitrary
32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 application defined code to be executed if an object with a
33 application defined code to be executed if an object with a
34 ``__getattr__`` hook is found. Since it is the responsibility of the
34 ``__getattr__`` hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
37 indexing operations) are *not* evaluated.
38
38
39 - GNU readline is also used by the built-in functions input() and
39 - GNU readline is also used by the built-in functions input() and
40 raw_input(), and thus these also benefit/suffer from the completer
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
42 specifying its own completer function and using raw_input() for all
43 its input.
43 its input.
44
44
45 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
47 """
47 """
48
48
49 #*****************************************************************************
49 #*****************************************************************************
50 #
50 #
51 # Since this file is essentially a minimally modified copy of the rlcompleter
51 # Since this file is essentially a minimally modified copy of the rlcompleter
52 # module which is part of the standard Python distribution, I assume that the
52 # module which is part of the standard Python distribution, I assume that the
53 # proper procedure is to maintain its copyright as belonging to the Python
53 # proper procedure is to maintain its copyright as belonging to the Python
54 # Software Foundation (in addition to my own, for all new code).
54 # Software Foundation (in addition to my own, for all new code).
55 #
55 #
56 # Copyright (C) 2008 IPython Development Team
56 # Copyright (C) 2008 IPython Development Team
57 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
57 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #
62 #
63 #*****************************************************************************
63 #*****************************************************************************
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Imports
66 # Imports
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 import __builtin__
69 import __builtin__
70 import __main__
70 import __main__
71 import glob
71 import glob
72 import inspect
72 import inspect
73 import itertools
73 import itertools
74 import keyword
74 import keyword
75 import os
75 import os
76 import re
76 import re
77 import sys
77 import sys
78
78
79 from IPython.config.configurable import Configurable
79 from IPython.config.configurable import Configurable
80 from IPython.core.error import TryNext
80 from IPython.core.error import TryNext
81 from IPython.core.inputsplitter import ESC_MAGIC
81 from IPython.core.inputsplitter import ESC_MAGIC
82 from IPython.utils import generics
82 from IPython.utils import generics
83 from IPython.utils import io
83 from IPython.utils import io
84 from IPython.utils.dir2 import dir2
84 from IPython.utils.dir2 import dir2
85 from IPython.utils.process import arg_split
85 from IPython.utils.process import arg_split
86 from IPython.utils.traitlets import CBool, Enum
86 from IPython.utils.traitlets import CBool, Enum
87
87
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89 # Globals
89 # Globals
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91
91
92 # Public API
92 # Public API
93 __all__ = ['Completer','IPCompleter']
93 __all__ = ['Completer','IPCompleter']
94
94
95 if sys.platform == 'win32':
95 if sys.platform == 'win32':
96 PROTECTABLES = ' '
96 PROTECTABLES = ' '
97 else:
97 else:
98 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
98 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
99
99
100 #-----------------------------------------------------------------------------
100 #-----------------------------------------------------------------------------
101 # Main functions and classes
101 # Main functions and classes
102 #-----------------------------------------------------------------------------
102 #-----------------------------------------------------------------------------
103
103
104 def has_open_quotes(s):
104 def has_open_quotes(s):
105 """Return whether a string has open quotes.
105 """Return whether a string has open quotes.
106
106
107 This simply counts whether the number of quote characters of either type in
107 This simply counts whether the number of quote characters of either type in
108 the string is odd.
108 the string is odd.
109
109
110 Returns
110 Returns
111 -------
111 -------
112 If there is an open quote, the quote character is returned. Else, return
112 If there is an open quote, the quote character is returned. Else, return
113 False.
113 False.
114 """
114 """
115 # We check " first, then ', so complex cases with nested quotes will get
115 # We check " first, then ', so complex cases with nested quotes will get
116 # the " to take precedence.
116 # the " to take precedence.
117 if s.count('"') % 2:
117 if s.count('"') % 2:
118 return '"'
118 return '"'
119 elif s.count("'") % 2:
119 elif s.count("'") % 2:
120 return "'"
120 return "'"
121 else:
121 else:
122 return False
122 return False
123
123
124
124
125 def protect_filename(s):
125 def protect_filename(s):
126 """Escape a string to protect certain characters."""
126 """Escape a string to protect certain characters."""
127
127
128 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
128 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
129 for ch in s])
129 for ch in s])
130
130
131 def expand_user(path):
131 def expand_user(path):
132 """Expand '~'-style usernames in strings.
132 """Expand '~'-style usernames in strings.
133
133
134 This is similar to :func:`os.path.expanduser`, but it computes and returns
134 This is similar to :func:`os.path.expanduser`, but it computes and returns
135 extra information that will be useful if the input was being used in
135 extra information that will be useful if the input was being used in
136 computing completions, and you wish to return the completions with the
136 computing completions, and you wish to return the completions with the
137 original '~' instead of its expanded value.
137 original '~' instead of its expanded value.
138
138
139 Parameters
139 Parameters
140 ----------
140 ----------
141 path : str
141 path : str
142 String to be expanded. If no ~ is present, the output is the same as the
142 String to be expanded. If no ~ is present, the output is the same as the
143 input.
143 input.
144
144
145 Returns
145 Returns
146 -------
146 -------
147 newpath : str
147 newpath : str
148 Result of ~ expansion in the input path.
148 Result of ~ expansion in the input path.
149 tilde_expand : bool
149 tilde_expand : bool
150 Whether any expansion was performed or not.
150 Whether any expansion was performed or not.
151 tilde_val : str
151 tilde_val : str
152 The value that ~ was replaced with.
152 The value that ~ was replaced with.
153 """
153 """
154 # Default values
154 # Default values
155 tilde_expand = False
155 tilde_expand = False
156 tilde_val = ''
156 tilde_val = ''
157 newpath = path
157 newpath = path
158
158
159 if path.startswith('~'):
159 if path.startswith('~'):
160 tilde_expand = True
160 tilde_expand = True
161 rest = len(path)-1
161 rest = len(path)-1
162 newpath = os.path.expanduser(path)
162 newpath = os.path.expanduser(path)
163 if rest:
163 if rest:
164 tilde_val = newpath[:-rest]
164 tilde_val = newpath[:-rest]
165 else:
165 else:
166 tilde_val = newpath
166 tilde_val = newpath
167
167
168 return newpath, tilde_expand, tilde_val
168 return newpath, tilde_expand, tilde_val
169
169
170
170
171 def compress_user(path, tilde_expand, tilde_val):
171 def compress_user(path, tilde_expand, tilde_val):
172 """Does the opposite of expand_user, with its outputs.
172 """Does the opposite of expand_user, with its outputs.
173 """
173 """
174 if tilde_expand:
174 if tilde_expand:
175 return path.replace(tilde_val, '~')
175 return path.replace(tilde_val, '~')
176 else:
176 else:
177 return path
177 return path
178
178
179
179
180 class Bunch(object): pass
180 class Bunch(object): pass
181
181
182
182
183 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
183 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
184 GREEDY_DELIMS = ' =\r\n'
184 GREEDY_DELIMS = ' =\r\n'
185
185
186
186
187 class CompletionSplitter(object):
187 class CompletionSplitter(object):
188 """An object to split an input line in a manner similar to readline.
188 """An object to split an input line in a manner similar to readline.
189
189
190 By having our own implementation, we can expose readline-like completion in
190 By having our own implementation, we can expose readline-like completion in
191 a uniform manner to all frontends. This object only needs to be given the
191 a uniform manner to all frontends. This object only needs to be given the
192 line of text to be split and the cursor position on said line, and it
192 line of text to be split and the cursor position on said line, and it
193 returns the 'word' to be completed on at the cursor after splitting the
193 returns the 'word' to be completed on at the cursor after splitting the
194 entire line.
194 entire line.
195
195
196 What characters are used as splitting delimiters can be controlled by
196 What characters are used as splitting delimiters can be controlled by
197 setting the `delims` attribute (this is a property that internally
197 setting the `delims` attribute (this is a property that internally
198 automatically builds the necessary regular expression)"""
198 automatically builds the necessary regular expression)"""
199
199
200 # Private interface
200 # Private interface
201
201
202 # A string of delimiter characters. The default value makes sense for
202 # A string of delimiter characters. The default value makes sense for
203 # IPython's most typical usage patterns.
203 # IPython's most typical usage patterns.
204 _delims = DELIMS
204 _delims = DELIMS
205
205
206 # The expression (a normal string) to be compiled into a regular expression
206 # The expression (a normal string) to be compiled into a regular expression
207 # for actual splitting. We store it as an attribute mostly for ease of
207 # for actual splitting. We store it as an attribute mostly for ease of
208 # debugging, since this type of code can be so tricky to debug.
208 # debugging, since this type of code can be so tricky to debug.
209 _delim_expr = None
209 _delim_expr = None
210
210
211 # The regular expression that does the actual splitting
211 # The regular expression that does the actual splitting
212 _delim_re = None
212 _delim_re = None
213
213
214 def __init__(self, delims=None):
214 def __init__(self, delims=None):
215 delims = CompletionSplitter._delims if delims is None else delims
215 delims = CompletionSplitter._delims if delims is None else delims
216 self.delims = delims
216 self.delims = delims
217
217
218 @property
218 @property
219 def delims(self):
219 def delims(self):
220 """Return the string of delimiter characters."""
220 """Return the string of delimiter characters."""
221 return self._delims
221 return self._delims
222
222
223 @delims.setter
223 @delims.setter
224 def delims(self, delims):
224 def delims(self, delims):
225 """Set the delimiters for line splitting."""
225 """Set the delimiters for line splitting."""
226 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
226 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
227 self._delim_re = re.compile(expr)
227 self._delim_re = re.compile(expr)
228 self._delims = delims
228 self._delims = delims
229 self._delim_expr = expr
229 self._delim_expr = expr
230
230
231 def split_line(self, line, cursor_pos=None):
231 def split_line(self, line, cursor_pos=None):
232 """Split a line of text with a cursor at the given position.
232 """Split a line of text with a cursor at the given position.
233 """
233 """
234 l = line if cursor_pos is None else line[:cursor_pos]
234 l = line if cursor_pos is None else line[:cursor_pos]
235 return self._delim_re.split(l)[-1]
235 return self._delim_re.split(l)[-1]
236
236
237
237
238 class Completer(Configurable):
238 class Completer(Configurable):
239
239
240 greedy = CBool(False, config=True,
240 greedy = CBool(False, config=True,
241 help="""Activate greedy completion
241 help="""Activate greedy completion
242
242
243 This will enable completion on elements of lists, results of function calls, etc.,
243 This will enable completion on elements of lists, results of function calls, etc.,
244 but can be unsafe because the code is actually evaluated on TAB.
244 but can be unsafe because the code is actually evaluated on TAB.
245 """
245 """
246 )
246 )
247
247
248
248
249 def __init__(self, namespace=None, global_namespace=None, **kwargs):
249 def __init__(self, namespace=None, global_namespace=None, **kwargs):
250 """Create a new completer for the command line.
250 """Create a new completer for the command line.
251
251
252 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
252 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
253
253
254 If unspecified, the default namespace where completions are performed
254 If unspecified, the default namespace where completions are performed
255 is __main__ (technically, __main__.__dict__). Namespaces should be
255 is __main__ (technically, __main__.__dict__). Namespaces should be
256 given as dictionaries.
256 given as dictionaries.
257
257
258 An optional second namespace can be given. This allows the completer
258 An optional second namespace can be given. This allows the completer
259 to handle cases where both the local and global scopes need to be
259 to handle cases where both the local and global scopes need to be
260 distinguished.
260 distinguished.
261
261
262 Completer instances should be used as the completion mechanism of
262 Completer instances should be used as the completion mechanism of
263 readline via the set_completer() call:
263 readline via the set_completer() call:
264
264
265 readline.set_completer(Completer(my_namespace).complete)
265 readline.set_completer(Completer(my_namespace).complete)
266 """
266 """
267
267
268 # Don't bind to namespace quite yet, but flag whether the user wants a
268 # Don't bind to namespace quite yet, but flag whether the user wants a
269 # specific namespace or to use __main__.__dict__. This will allow us
269 # specific namespace or to use __main__.__dict__. This will allow us
270 # to bind to __main__.__dict__ at completion time, not now.
270 # to bind to __main__.__dict__ at completion time, not now.
271 if namespace is None:
271 if namespace is None:
272 self.use_main_ns = 1
272 self.use_main_ns = 1
273 else:
273 else:
274 self.use_main_ns = 0
274 self.use_main_ns = 0
275 self.namespace = namespace
275 self.namespace = namespace
276
276
277 # The global namespace, if given, can be bound directly
277 # The global namespace, if given, can be bound directly
278 if global_namespace is None:
278 if global_namespace is None:
279 self.global_namespace = {}
279 self.global_namespace = {}
280 else:
280 else:
281 self.global_namespace = global_namespace
281 self.global_namespace = global_namespace
282
282
283 super(Completer, self).__init__(**kwargs)
283 super(Completer, self).__init__(**kwargs)
284
284
285 def complete(self, text, state):
285 def complete(self, text, state):
286 """Return the next possible completion for 'text'.
286 """Return the next possible completion for 'text'.
287
287
288 This is called successively with state == 0, 1, 2, ... until it
288 This is called successively with state == 0, 1, 2, ... until it
289 returns None. The completion should begin with 'text'.
289 returns None. The completion should begin with 'text'.
290
290
291 """
291 """
292 if self.use_main_ns:
292 if self.use_main_ns:
293 self.namespace = __main__.__dict__
293 self.namespace = __main__.__dict__
294
294
295 if state == 0:
295 if state == 0:
296 if "." in text:
296 if "." in text:
297 self.matches = self.attr_matches(text)
297 self.matches = self.attr_matches(text)
298 else:
298 else:
299 self.matches = self.global_matches(text)
299 self.matches = self.global_matches(text)
300 try:
300 try:
301 return self.matches[state]
301 return self.matches[state]
302 except IndexError:
302 except IndexError:
303 return None
303 return None
304
304
305 def global_matches(self, text):
305 def global_matches(self, text):
306 """Compute matches when text is a simple name.
306 """Compute matches when text is a simple name.
307
307
308 Return a list of all keywords, built-in functions and names currently
308 Return a list of all keywords, built-in functions and names currently
309 defined in self.namespace or self.global_namespace that match.
309 defined in self.namespace or self.global_namespace that match.
310
310
311 """
311 """
312 #print 'Completer->global_matches, txt=%r' % text # dbg
312 #print 'Completer->global_matches, txt=%r' % text # dbg
313 matches = []
313 matches = []
314 match_append = matches.append
314 match_append = matches.append
315 n = len(text)
315 n = len(text)
316 for lst in [keyword.kwlist,
316 for lst in [keyword.kwlist,
317 __builtin__.__dict__.keys(),
317 __builtin__.__dict__.keys(),
318 self.namespace.keys(),
318 self.namespace.keys(),
319 self.global_namespace.keys()]:
319 self.global_namespace.keys()]:
320 for word in lst:
320 for word in lst:
321 if word[:n] == text and word != "__builtins__":
321 if word[:n] == text and word != "__builtins__":
322 match_append(word)
322 match_append(word)
323 return matches
323 return matches
324
324
325 def attr_matches(self, text):
325 def attr_matches(self, text):
326 """Compute matches when text contains a dot.
326 """Compute matches when text contains a dot.
327
327
328 Assuming the text is of the form NAME.NAME....[NAME], and is
328 Assuming the text is of the form NAME.NAME....[NAME], and is
329 evaluatable in self.namespace or self.global_namespace, it will be
329 evaluatable in self.namespace or self.global_namespace, it will be
330 evaluated and its attributes (as revealed by dir()) are used as
330 evaluated and its attributes (as revealed by dir()) are used as
331 possible completions. (For class instances, class members are are
331 possible completions. (For class instances, class members are are
332 also considered.)
332 also considered.)
333
333
334 WARNING: this can still invoke arbitrary C code, if an object
334 WARNING: this can still invoke arbitrary C code, if an object
335 with a __getattr__ hook is evaluated.
335 with a __getattr__ hook is evaluated.
336
336
337 """
337 """
338
338
339 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
339 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
340 # Another option, seems to work great. Catches things like ''.<tab>
340 # Another option, seems to work great. Catches things like ''.<tab>
341 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
341 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
342
342
343 if m:
343 if m:
344 expr, attr = m.group(1, 3)
344 expr, attr = m.group(1, 3)
345 elif self.greedy:
345 elif self.greedy:
346 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
346 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
347 if not m2:
347 if not m2:
348 return []
348 return []
349 expr, attr = m2.group(1,2)
349 expr, attr = m2.group(1,2)
350 else:
350 else:
351 return []
351 return []
352
352
353 try:
353 try:
354 obj = eval(expr, self.namespace)
354 obj = eval(expr, self.namespace)
355 except:
355 except:
356 try:
356 try:
357 obj = eval(expr, self.global_namespace)
357 obj = eval(expr, self.global_namespace)
358 except:
358 except:
359 return []
359 return []
360
360
361 if self.limit_to__all__ and hasattr(obj, '__all__'):
361 if self.limit_to__all__ and hasattr(obj, '__all__'):
362 words = get__all__entries(obj)
362 words = get__all__entries(obj)
363 else:
363 else:
364 words = dir2(obj)
364 words = dir2(obj)
365
365
366 try:
366 try:
367 words = generics.complete_object(obj, words)
367 words = generics.complete_object(obj, words)
368 except TryNext:
368 except TryNext:
369 pass
369 pass
370 except Exception:
370 except Exception:
371 # Silence errors from completion function
371 # Silence errors from completion function
372 #raise # dbg
372 #raise # dbg
373 pass
373 pass
374 # Build match list to return
374 # Build match list to return
375 n = len(attr)
375 n = len(attr)
376 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
376 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
377 return res
377 return res
378
378
379
379
380 def get__all__entries(obj):
380 def get__all__entries(obj):
381 """returns the strings in the __all__ attribute"""
381 """returns the strings in the __all__ attribute"""
382 try:
382 try:
383 words = getattr(obj, '__all__')
383 words = getattr(obj, '__all__')
384 except:
384 except:
385 return []
385 return []
386
386
387 return [w for w in words if isinstance(w, basestring)]
387 return [w for w in words if isinstance(w, basestring)]
388
388
389
389
390 class IPCompleter(Completer):
390 class IPCompleter(Completer):
391 """Extension of the completer class with IPython-specific features"""
391 """Extension of the completer class with IPython-specific features"""
392
392
393 def _greedy_changed(self, name, old, new):
393 def _greedy_changed(self, name, old, new):
394 """update the splitter and readline delims when greedy is changed"""
394 """update the splitter and readline delims when greedy is changed"""
395 if new:
395 if new:
396 self.splitter.delims = GREEDY_DELIMS
396 self.splitter.delims = GREEDY_DELIMS
397 else:
397 else:
398 self.splitter.delims = DELIMS
398 self.splitter.delims = DELIMS
399
399
400 if self.readline:
400 if self.readline:
401 self.readline.set_completer_delims(self.splitter.delims)
401 self.readline.set_completer_delims(self.splitter.delims)
402
402
403 merge_completions = CBool(True, config=True,
403 merge_completions = CBool(True, config=True,
404 help="""Whether to merge completion results into a single list
404 help="""Whether to merge completion results into a single list
405
405
406 If False, only the completion results from the first non-empty
406 If False, only the completion results from the first non-empty
407 completer will be returned.
407 completer will be returned.
408 """
408 """
409 )
409 )
410 omit__names = Enum((0,1,2), default_value=2, config=True,
410 omit__names = Enum((0,1,2), default_value=2, config=True,
411 help="""Instruct the completer to omit private method names
411 help="""Instruct the completer to omit private method names
412
412
413 Specifically, when completing on ``object.<tab>``.
413 Specifically, when completing on ``object.<tab>``.
414
414
415 When 2 [default]: all names that start with '_' will be excluded.
415 When 2 [default]: all names that start with '_' will be excluded.
416
416
417 When 1: all 'magic' names (``__foo__``) will be excluded.
417 When 1: all 'magic' names (``__foo__``) will be excluded.
418
418
419 When 0: nothing will be excluded.
419 When 0: nothing will be excluded.
420 """
420 """
421 )
421 )
422 limit_to__all__ = CBool(default_value=False, config=True,
422 limit_to__all__ = CBool(default_value=False, config=True,
423 help="""Instruct the completer to use __all__ for the completion
423 help="""Instruct the completer to use __all__ for the completion
424
424
425 Specifically, when completing on ``object.<tab>``.
425 Specifically, when completing on ``object.<tab>``.
426
426
427 When True: only those names in obj.__all__ will be included.
427 When True: only those names in obj.__all__ will be included.
428
428
429 When False [default]: the __all__ attribute is ignored
429 When False [default]: the __all__ attribute is ignored
430 """
430 """
431 )
431 )
432
432
433 def __init__(self, shell=None, namespace=None, global_namespace=None,
433 def __init__(self, shell=None, namespace=None, global_namespace=None,
434 alias_table=None, use_readline=True,
434 use_readline=True, config=None, **kwargs):
435 config=None, **kwargs):
436 """IPCompleter() -> completer
435 """IPCompleter() -> completer
437
436
438 Return a completer object suitable for use by the readline library
437 Return a completer object suitable for use by the readline library
439 via readline.set_completer().
438 via readline.set_completer().
440
439
441 Inputs:
440 Inputs:
442
441
443 - shell: a pointer to the ipython shell itself. This is needed
442 - shell: a pointer to the ipython shell itself. This is needed
444 because this completer knows about magic functions, and those can
443 because this completer knows about magic functions, and those can
445 only be accessed via the ipython instance.
444 only be accessed via the ipython instance.
446
445
447 - namespace: an optional dict where completions are performed.
446 - namespace: an optional dict where completions are performed.
448
447
449 - global_namespace: secondary optional dict for completions, to
448 - global_namespace: secondary optional dict for completions, to
450 handle cases (such as IPython embedded inside functions) where
449 handle cases (such as IPython embedded inside functions) where
451 both Python scopes are visible.
450 both Python scopes are visible.
452
451
453 - If alias_table is supplied, it should be a dictionary of aliases
454 to complete.
455
456 use_readline : bool, optional
452 use_readline : bool, optional
457 If true, use the readline library. This completer can still function
453 If true, use the readline library. This completer can still function
458 without readline, though in that case callers must provide some extra
454 without readline, though in that case callers must provide some extra
459 information on each call about the current line."""
455 information on each call about the current line."""
460
456
461 self.magic_escape = ESC_MAGIC
457 self.magic_escape = ESC_MAGIC
462 self.splitter = CompletionSplitter()
458 self.splitter = CompletionSplitter()
463
459
464 # Readline configuration, only used by the rlcompleter method.
460 # Readline configuration, only used by the rlcompleter method.
465 if use_readline:
461 if use_readline:
466 # We store the right version of readline so that later code
462 # We store the right version of readline so that later code
467 import IPython.utils.rlineimpl as readline
463 import IPython.utils.rlineimpl as readline
468 self.readline = readline
464 self.readline = readline
469 else:
465 else:
470 self.readline = None
466 self.readline = None
471
467
472 # _greedy_changed() depends on splitter and readline being defined:
468 # _greedy_changed() depends on splitter and readline being defined:
473 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
469 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
474 config=config, **kwargs)
470 config=config, **kwargs)
475
471
476 # List where completion matches will be stored
472 # List where completion matches will be stored
477 self.matches = []
473 self.matches = []
478 self.shell = shell
474 self.shell = shell
479 if alias_table is None:
480 alias_table = {}
481 self.alias_table = alias_table
482 # Regexp to split filenames with spaces in them
475 # Regexp to split filenames with spaces in them
483 self.space_name_re = re.compile(r'([^\\] )')
476 self.space_name_re = re.compile(r'([^\\] )')
484 # Hold a local ref. to glob.glob for speed
477 # Hold a local ref. to glob.glob for speed
485 self.glob = glob.glob
478 self.glob = glob.glob
486
479
487 # Determine if we are running on 'dumb' terminals, like (X)Emacs
480 # Determine if we are running on 'dumb' terminals, like (X)Emacs
488 # buffers, to avoid completion problems.
481 # buffers, to avoid completion problems.
489 term = os.environ.get('TERM','xterm')
482 term = os.environ.get('TERM','xterm')
490 self.dumb_terminal = term in ['dumb','emacs']
483 self.dumb_terminal = term in ['dumb','emacs']
491
484
492 # Special handling of backslashes needed in win32 platforms
485 # Special handling of backslashes needed in win32 platforms
493 if sys.platform == "win32":
486 if sys.platform == "win32":
494 self.clean_glob = self._clean_glob_win32
487 self.clean_glob = self._clean_glob_win32
495 else:
488 else:
496 self.clean_glob = self._clean_glob
489 self.clean_glob = self._clean_glob
497
490
498 #regexp to parse docstring for function signature
491 #regexp to parse docstring for function signature
499 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
492 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
500 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
493 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
501 #use this if positional argument name is also needed
494 #use this if positional argument name is also needed
502 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
495 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
503
496
504 # All active matcher routines for completion
497 # All active matcher routines for completion
505 self.matchers = [self.python_matches,
498 self.matchers = [self.python_matches,
506 self.file_matches,
499 self.file_matches,
507 self.magic_matches,
500 self.magic_matches,
508 self.alias_matches,
509 self.python_func_kw_matches,
501 self.python_func_kw_matches,
510 ]
502 ]
511
503
512 def all_completions(self, text):
504 def all_completions(self, text):
513 """
505 """
514 Wrapper around the complete method for the benefit of emacs
506 Wrapper around the complete method for the benefit of emacs
515 and pydb.
507 and pydb.
516 """
508 """
517 return self.complete(text)[1]
509 return self.complete(text)[1]
518
510
519 def _clean_glob(self,text):
511 def _clean_glob(self,text):
520 return self.glob("%s*" % text)
512 return self.glob("%s*" % text)
521
513
522 def _clean_glob_win32(self,text):
514 def _clean_glob_win32(self,text):
523 return [f.replace("\\","/")
515 return [f.replace("\\","/")
524 for f in self.glob("%s*" % text)]
516 for f in self.glob("%s*" % text)]
525
517
526 def file_matches(self, text):
518 def file_matches(self, text):
527 """Match filenames, expanding ~USER type strings.
519 """Match filenames, expanding ~USER type strings.
528
520
529 Most of the seemingly convoluted logic in this completer is an
521 Most of the seemingly convoluted logic in this completer is an
530 attempt to handle filenames with spaces in them. And yet it's not
522 attempt to handle filenames with spaces in them. And yet it's not
531 quite perfect, because Python's readline doesn't expose all of the
523 quite perfect, because Python's readline doesn't expose all of the
532 GNU readline details needed for this to be done correctly.
524 GNU readline details needed for this to be done correctly.
533
525
534 For a filename with a space in it, the printed completions will be
526 For a filename with a space in it, the printed completions will be
535 only the parts after what's already been typed (instead of the
527 only the parts after what's already been typed (instead of the
536 full completions, as is normally done). I don't think with the
528 full completions, as is normally done). I don't think with the
537 current (as of Python 2.3) Python readline it's possible to do
529 current (as of Python 2.3) Python readline it's possible to do
538 better."""
530 better."""
539
531
540 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
532 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
541
533
542 # chars that require escaping with backslash - i.e. chars
534 # chars that require escaping with backslash - i.e. chars
543 # that readline treats incorrectly as delimiters, but we
535 # that readline treats incorrectly as delimiters, but we
544 # don't want to treat as delimiters in filename matching
536 # don't want to treat as delimiters in filename matching
545 # when escaped with backslash
537 # when escaped with backslash
546 if text.startswith('!'):
538 if text.startswith('!'):
547 text = text[1:]
539 text = text[1:]
548 text_prefix = '!'
540 text_prefix = '!'
549 else:
541 else:
550 text_prefix = ''
542 text_prefix = ''
551
543
552 text_until_cursor = self.text_until_cursor
544 text_until_cursor = self.text_until_cursor
553 # track strings with open quotes
545 # track strings with open quotes
554 open_quotes = has_open_quotes(text_until_cursor)
546 open_quotes = has_open_quotes(text_until_cursor)
555
547
556 if '(' in text_until_cursor or '[' in text_until_cursor:
548 if '(' in text_until_cursor or '[' in text_until_cursor:
557 lsplit = text
549 lsplit = text
558 else:
550 else:
559 try:
551 try:
560 # arg_split ~ shlex.split, but with unicode bugs fixed by us
552 # arg_split ~ shlex.split, but with unicode bugs fixed by us
561 lsplit = arg_split(text_until_cursor)[-1]
553 lsplit = arg_split(text_until_cursor)[-1]
562 except ValueError:
554 except ValueError:
563 # typically an unmatched ", or backslash without escaped char.
555 # typically an unmatched ", or backslash without escaped char.
564 if open_quotes:
556 if open_quotes:
565 lsplit = text_until_cursor.split(open_quotes)[-1]
557 lsplit = text_until_cursor.split(open_quotes)[-1]
566 else:
558 else:
567 return []
559 return []
568 except IndexError:
560 except IndexError:
569 # tab pressed on empty line
561 # tab pressed on empty line
570 lsplit = ""
562 lsplit = ""
571
563
572 if not open_quotes and lsplit != protect_filename(lsplit):
564 if not open_quotes and lsplit != protect_filename(lsplit):
573 # if protectables are found, do matching on the whole escaped name
565 # if protectables are found, do matching on the whole escaped name
574 has_protectables = True
566 has_protectables = True
575 text0,text = text,lsplit
567 text0,text = text,lsplit
576 else:
568 else:
577 has_protectables = False
569 has_protectables = False
578 text = os.path.expanduser(text)
570 text = os.path.expanduser(text)
579
571
580 if text == "":
572 if text == "":
581 return [text_prefix + protect_filename(f) for f in self.glob("*")]
573 return [text_prefix + protect_filename(f) for f in self.glob("*")]
582
574
583 # Compute the matches from the filesystem
575 # Compute the matches from the filesystem
584 m0 = self.clean_glob(text.replace('\\',''))
576 m0 = self.clean_glob(text.replace('\\',''))
585
577
586 if has_protectables:
578 if has_protectables:
587 # If we had protectables, we need to revert our changes to the
579 # If we had protectables, we need to revert our changes to the
588 # beginning of filename so that we don't double-write the part
580 # beginning of filename so that we don't double-write the part
589 # of the filename we have so far
581 # of the filename we have so far
590 len_lsplit = len(lsplit)
582 len_lsplit = len(lsplit)
591 matches = [text_prefix + text0 +
583 matches = [text_prefix + text0 +
592 protect_filename(f[len_lsplit:]) for f in m0]
584 protect_filename(f[len_lsplit:]) for f in m0]
593 else:
585 else:
594 if open_quotes:
586 if open_quotes:
595 # if we have a string with an open quote, we don't need to
587 # if we have a string with an open quote, we don't need to
596 # protect the names at all (and we _shouldn't_, as it
588 # protect the names at all (and we _shouldn't_, as it
597 # would cause bugs when the filesystem call is made).
589 # would cause bugs when the filesystem call is made).
598 matches = m0
590 matches = m0
599 else:
591 else:
600 matches = [text_prefix +
592 matches = [text_prefix +
601 protect_filename(f) for f in m0]
593 protect_filename(f) for f in m0]
602
594
603 #io.rprint('mm', matches) # dbg
595 #io.rprint('mm', matches) # dbg
604
596
605 # Mark directories in input list by appending '/' to their names.
597 # Mark directories in input list by appending '/' to their names.
606 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
598 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
607 return matches
599 return matches
608
600
609 def magic_matches(self, text):
601 def magic_matches(self, text):
610 """Match magics"""
602 """Match magics"""
611 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
603 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
612 # Get all shell magics now rather than statically, so magics loaded at
604 # Get all shell magics now rather than statically, so magics loaded at
613 # runtime show up too.
605 # runtime show up too.
614 lsm = self.shell.magics_manager.lsmagic()
606 lsm = self.shell.magics_manager.lsmagic()
615 line_magics = lsm['line']
607 line_magics = lsm['line']
616 cell_magics = lsm['cell']
608 cell_magics = lsm['cell']
617 pre = self.magic_escape
609 pre = self.magic_escape
618 pre2 = pre+pre
610 pre2 = pre+pre
619
611
620 # Completion logic:
612 # Completion logic:
621 # - user gives %%: only do cell magics
613 # - user gives %%: only do cell magics
622 # - user gives %: do both line and cell magics
614 # - user gives %: do both line and cell magics
623 # - no prefix: do both
615 # - no prefix: do both
624 # In other words, line magics are skipped if the user gives %% explicitly
616 # In other words, line magics are skipped if the user gives %% explicitly
625 bare_text = text.lstrip(pre)
617 bare_text = text.lstrip(pre)
626 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
618 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
627 if not text.startswith(pre2):
619 if not text.startswith(pre2):
628 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
620 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
629 return comp
621 return comp
630
622
631 def alias_matches(self, text):
632 """Match internal system aliases"""
633 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
634
635 # if we are not in the first 'item', alias matching
636 # doesn't make sense - unless we are starting with 'sudo' command.
637 main_text = self.text_until_cursor.lstrip()
638 if ' ' in main_text and not main_text.startswith('sudo'):
639 return []
640 text = os.path.expanduser(text)
641 aliases = self.alias_table.keys()
642 if text == '':
643 return aliases
644 else:
645 return [a for a in aliases if a.startswith(text)]
646
647 def python_matches(self,text):
623 def python_matches(self,text):
648 """Match attributes or global python names"""
624 """Match attributes or global python names"""
649
625
650 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
626 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
651 if "." in text:
627 if "." in text:
652 try:
628 try:
653 matches = self.attr_matches(text)
629 matches = self.attr_matches(text)
654 if text.endswith('.') and self.omit__names:
630 if text.endswith('.') and self.omit__names:
655 if self.omit__names == 1:
631 if self.omit__names == 1:
656 # true if txt is _not_ a __ name, false otherwise:
632 # true if txt is _not_ a __ name, false otherwise:
657 no__name = (lambda txt:
633 no__name = (lambda txt:
658 re.match(r'.*\.__.*?__',txt) is None)
634 re.match(r'.*\.__.*?__',txt) is None)
659 else:
635 else:
660 # true if txt is _not_ a _ name, false otherwise:
636 # true if txt is _not_ a _ name, false otherwise:
661 no__name = (lambda txt:
637 no__name = (lambda txt:
662 re.match(r'.*\._.*?',txt) is None)
638 re.match(r'.*\._.*?',txt) is None)
663 matches = filter(no__name, matches)
639 matches = filter(no__name, matches)
664 except NameError:
640 except NameError:
665 # catches <undefined attributes>.<tab>
641 # catches <undefined attributes>.<tab>
666 matches = []
642 matches = []
667 else:
643 else:
668 matches = self.global_matches(text)
644 matches = self.global_matches(text)
669
645
670 return matches
646 return matches
671
647
672 def _default_arguments_from_docstring(self, doc):
648 def _default_arguments_from_docstring(self, doc):
673 """Parse the first line of docstring for call signature.
649 """Parse the first line of docstring for call signature.
674
650
675 Docstring should be of the form 'min(iterable[, key=func])\n'.
651 Docstring should be of the form 'min(iterable[, key=func])\n'.
676 It can also parse cython docstring of the form
652 It can also parse cython docstring of the form
677 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
653 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
678 """
654 """
679 if doc is None:
655 if doc is None:
680 return []
656 return []
681
657
682 #care only the firstline
658 #care only the firstline
683 line = doc.lstrip().splitlines()[0]
659 line = doc.lstrip().splitlines()[0]
684
660
685 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
661 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
686 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
662 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
687 sig = self.docstring_sig_re.search(line)
663 sig = self.docstring_sig_re.search(line)
688 if sig is None:
664 if sig is None:
689 return []
665 return []
690 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
666 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
691 sig = sig.groups()[0].split(',')
667 sig = sig.groups()[0].split(',')
692 ret = []
668 ret = []
693 for s in sig:
669 for s in sig:
694 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
670 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
695 ret += self.docstring_kwd_re.findall(s)
671 ret += self.docstring_kwd_re.findall(s)
696 return ret
672 return ret
697
673
698 def _default_arguments(self, obj):
674 def _default_arguments(self, obj):
699 """Return the list of default arguments of obj if it is callable,
675 """Return the list of default arguments of obj if it is callable,
700 or empty list otherwise."""
676 or empty list otherwise."""
701 call_obj = obj
677 call_obj = obj
702 ret = []
678 ret = []
703 if inspect.isbuiltin(obj):
679 if inspect.isbuiltin(obj):
704 pass
680 pass
705 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
681 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
706 if inspect.isclass(obj):
682 if inspect.isclass(obj):
707 #for cython embededsignature=True the constructor docstring
683 #for cython embededsignature=True the constructor docstring
708 #belongs to the object itself not __init__
684 #belongs to the object itself not __init__
709 ret += self._default_arguments_from_docstring(
685 ret += self._default_arguments_from_docstring(
710 getattr(obj, '__doc__', ''))
686 getattr(obj, '__doc__', ''))
711 # for classes, check for __init__,__new__
687 # for classes, check for __init__,__new__
712 call_obj = (getattr(obj, '__init__', None) or
688 call_obj = (getattr(obj, '__init__', None) or
713 getattr(obj, '__new__', None))
689 getattr(obj, '__new__', None))
714 # for all others, check if they are __call__able
690 # for all others, check if they are __call__able
715 elif hasattr(obj, '__call__'):
691 elif hasattr(obj, '__call__'):
716 call_obj = obj.__call__
692 call_obj = obj.__call__
717
693
718 ret += self._default_arguments_from_docstring(
694 ret += self._default_arguments_from_docstring(
719 getattr(call_obj, '__doc__', ''))
695 getattr(call_obj, '__doc__', ''))
720
696
721 try:
697 try:
722 args,_,_1,defaults = inspect.getargspec(call_obj)
698 args,_,_1,defaults = inspect.getargspec(call_obj)
723 if defaults:
699 if defaults:
724 ret+=args[-len(defaults):]
700 ret+=args[-len(defaults):]
725 except TypeError:
701 except TypeError:
726 pass
702 pass
727
703
728 return list(set(ret))
704 return list(set(ret))
729
705
730 def python_func_kw_matches(self,text):
706 def python_func_kw_matches(self,text):
731 """Match named parameters (kwargs) of the last open function"""
707 """Match named parameters (kwargs) of the last open function"""
732
708
733 if "." in text: # a parameter cannot be dotted
709 if "." in text: # a parameter cannot be dotted
734 return []
710 return []
735 try: regexp = self.__funcParamsRegex
711 try: regexp = self.__funcParamsRegex
736 except AttributeError:
712 except AttributeError:
737 regexp = self.__funcParamsRegex = re.compile(r'''
713 regexp = self.__funcParamsRegex = re.compile(r'''
738 '.*?(?<!\\)' | # single quoted strings or
714 '.*?(?<!\\)' | # single quoted strings or
739 ".*?(?<!\\)" | # double quoted strings or
715 ".*?(?<!\\)" | # double quoted strings or
740 \w+ | # identifier
716 \w+ | # identifier
741 \S # other characters
717 \S # other characters
742 ''', re.VERBOSE | re.DOTALL)
718 ''', re.VERBOSE | re.DOTALL)
743 # 1. find the nearest identifier that comes before an unclosed
719 # 1. find the nearest identifier that comes before an unclosed
744 # parenthesis before the cursor
720 # parenthesis before the cursor
745 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
721 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
746 tokens = regexp.findall(self.text_until_cursor)
722 tokens = regexp.findall(self.text_until_cursor)
747 tokens.reverse()
723 tokens.reverse()
748 iterTokens = iter(tokens); openPar = 0
724 iterTokens = iter(tokens); openPar = 0
749
725
750 for token in iterTokens:
726 for token in iterTokens:
751 if token == ')':
727 if token == ')':
752 openPar -= 1
728 openPar -= 1
753 elif token == '(':
729 elif token == '(':
754 openPar += 1
730 openPar += 1
755 if openPar > 0:
731 if openPar > 0:
756 # found the last unclosed parenthesis
732 # found the last unclosed parenthesis
757 break
733 break
758 else:
734 else:
759 return []
735 return []
760 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
736 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
761 ids = []
737 ids = []
762 isId = re.compile(r'\w+$').match
738 isId = re.compile(r'\w+$').match
763
739
764 while True:
740 while True:
765 try:
741 try:
766 ids.append(next(iterTokens))
742 ids.append(next(iterTokens))
767 if not isId(ids[-1]):
743 if not isId(ids[-1]):
768 ids.pop(); break
744 ids.pop(); break
769 if not next(iterTokens) == '.':
745 if not next(iterTokens) == '.':
770 break
746 break
771 except StopIteration:
747 except StopIteration:
772 break
748 break
773 # lookup the candidate callable matches either using global_matches
749 # lookup the candidate callable matches either using global_matches
774 # or attr_matches for dotted names
750 # or attr_matches for dotted names
775 if len(ids) == 1:
751 if len(ids) == 1:
776 callableMatches = self.global_matches(ids[0])
752 callableMatches = self.global_matches(ids[0])
777 else:
753 else:
778 callableMatches = self.attr_matches('.'.join(ids[::-1]))
754 callableMatches = self.attr_matches('.'.join(ids[::-1]))
779 argMatches = []
755 argMatches = []
780 for callableMatch in callableMatches:
756 for callableMatch in callableMatches:
781 try:
757 try:
782 namedArgs = self._default_arguments(eval(callableMatch,
758 namedArgs = self._default_arguments(eval(callableMatch,
783 self.namespace))
759 self.namespace))
784 except:
760 except:
785 continue
761 continue
786
762
787 for namedArg in namedArgs:
763 for namedArg in namedArgs:
788 if namedArg.startswith(text):
764 if namedArg.startswith(text):
789 argMatches.append("%s=" %namedArg)
765 argMatches.append("%s=" %namedArg)
790 return argMatches
766 return argMatches
791
767
792 def dispatch_custom_completer(self, text):
768 def dispatch_custom_completer(self, text):
793 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
769 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
794 line = self.line_buffer
770 line = self.line_buffer
795 if not line.strip():
771 if not line.strip():
796 return None
772 return None
797
773
798 # Create a little structure to pass all the relevant information about
774 # Create a little structure to pass all the relevant information about
799 # the current completion to any custom completer.
775 # the current completion to any custom completer.
800 event = Bunch()
776 event = Bunch()
801 event.line = line
777 event.line = line
802 event.symbol = text
778 event.symbol = text
803 cmd = line.split(None,1)[0]
779 cmd = line.split(None,1)[0]
804 event.command = cmd
780 event.command = cmd
805 event.text_until_cursor = self.text_until_cursor
781 event.text_until_cursor = self.text_until_cursor
806
782
807 #print "\ncustom:{%s]\n" % event # dbg
783 #print "\ncustom:{%s]\n" % event # dbg
808
784
809 # for foo etc, try also to find completer for %foo
785 # for foo etc, try also to find completer for %foo
810 if not cmd.startswith(self.magic_escape):
786 if not cmd.startswith(self.magic_escape):
811 try_magic = self.custom_completers.s_matches(
787 try_magic = self.custom_completers.s_matches(
812 self.magic_escape + cmd)
788 self.magic_escape + cmd)
813 else:
789 else:
814 try_magic = []
790 try_magic = []
815
791
816 for c in itertools.chain(self.custom_completers.s_matches(cmd),
792 for c in itertools.chain(self.custom_completers.s_matches(cmd),
817 try_magic,
793 try_magic,
818 self.custom_completers.flat_matches(self.text_until_cursor)):
794 self.custom_completers.flat_matches(self.text_until_cursor)):
819 #print "try",c # dbg
795 #print "try",c # dbg
820 try:
796 try:
821 res = c(event)
797 res = c(event)
822 if res:
798 if res:
823 # first, try case sensitive match
799 # first, try case sensitive match
824 withcase = [r for r in res if r.startswith(text)]
800 withcase = [r for r in res if r.startswith(text)]
825 if withcase:
801 if withcase:
826 return withcase
802 return withcase
827 # if none, then case insensitive ones are ok too
803 # if none, then case insensitive ones are ok too
828 text_low = text.lower()
804 text_low = text.lower()
829 return [r for r in res if r.lower().startswith(text_low)]
805 return [r for r in res if r.lower().startswith(text_low)]
830 except TryNext:
806 except TryNext:
831 pass
807 pass
832
808
833 return None
809 return None
834
810
835 def complete(self, text=None, line_buffer=None, cursor_pos=None):
811 def complete(self, text=None, line_buffer=None, cursor_pos=None):
836 """Find completions for the given text and line context.
812 """Find completions for the given text and line context.
837
813
838 This is called successively with state == 0, 1, 2, ... until it
814 This is called successively with state == 0, 1, 2, ... until it
839 returns None. The completion should begin with 'text'.
815 returns None. The completion should begin with 'text'.
840
816
841 Note that both the text and the line_buffer are optional, but at least
817 Note that both the text and the line_buffer are optional, but at least
842 one of them must be given.
818 one of them must be given.
843
819
844 Parameters
820 Parameters
845 ----------
821 ----------
846 text : string, optional
822 text : string, optional
847 Text to perform the completion on. If not given, the line buffer
823 Text to perform the completion on. If not given, the line buffer
848 is split using the instance's CompletionSplitter object.
824 is split using the instance's CompletionSplitter object.
849
825
850 line_buffer : string, optional
826 line_buffer : string, optional
851 If not given, the completer attempts to obtain the current line
827 If not given, the completer attempts to obtain the current line
852 buffer via readline. This keyword allows clients which are
828 buffer via readline. This keyword allows clients which are
853 requesting for text completions in non-readline contexts to inform
829 requesting for text completions in non-readline contexts to inform
854 the completer of the entire text.
830 the completer of the entire text.
855
831
856 cursor_pos : int, optional
832 cursor_pos : int, optional
857 Index of the cursor in the full line buffer. Should be provided by
833 Index of the cursor in the full line buffer. Should be provided by
858 remote frontends where kernel has no access to frontend state.
834 remote frontends where kernel has no access to frontend state.
859
835
860 Returns
836 Returns
861 -------
837 -------
862 text : str
838 text : str
863 Text that was actually used in the completion.
839 Text that was actually used in the completion.
864
840
865 matches : list
841 matches : list
866 A list of completion matches.
842 A list of completion matches.
867 """
843 """
868 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
844 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
869
845
870 # if the cursor position isn't given, the only sane assumption we can
846 # if the cursor position isn't given, the only sane assumption we can
871 # make is that it's at the end of the line (the common case)
847 # make is that it's at the end of the line (the common case)
872 if cursor_pos is None:
848 if cursor_pos is None:
873 cursor_pos = len(line_buffer) if text is None else len(text)
849 cursor_pos = len(line_buffer) if text is None else len(text)
874
850
875 # if text is either None or an empty string, rely on the line buffer
851 # if text is either None or an empty string, rely on the line buffer
876 if not text:
852 if not text:
877 text = self.splitter.split_line(line_buffer, cursor_pos)
853 text = self.splitter.split_line(line_buffer, cursor_pos)
878
854
879 # If no line buffer is given, assume the input text is all there was
855 # If no line buffer is given, assume the input text is all there was
880 if line_buffer is None:
856 if line_buffer is None:
881 line_buffer = text
857 line_buffer = text
882
858
883 self.line_buffer = line_buffer
859 self.line_buffer = line_buffer
884 self.text_until_cursor = self.line_buffer[:cursor_pos]
860 self.text_until_cursor = self.line_buffer[:cursor_pos]
885 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
861 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
886
862
887 # Start with a clean slate of completions
863 # Start with a clean slate of completions
888 self.matches[:] = []
864 self.matches[:] = []
889 custom_res = self.dispatch_custom_completer(text)
865 custom_res = self.dispatch_custom_completer(text)
890 if custom_res is not None:
866 if custom_res is not None:
891 # did custom completers produce something?
867 # did custom completers produce something?
892 self.matches = custom_res
868 self.matches = custom_res
893 else:
869 else:
894 # Extend the list of completions with the results of each
870 # Extend the list of completions with the results of each
895 # matcher, so we return results to the user from all
871 # matcher, so we return results to the user from all
896 # namespaces.
872 # namespaces.
897 if self.merge_completions:
873 if self.merge_completions:
898 self.matches = []
874 self.matches = []
899 for matcher in self.matchers:
875 for matcher in self.matchers:
900 try:
876 try:
901 self.matches.extend(matcher(text))
877 self.matches.extend(matcher(text))
902 except:
878 except:
903 # Show the ugly traceback if the matcher causes an
879 # Show the ugly traceback if the matcher causes an
904 # exception, but do NOT crash the kernel!
880 # exception, but do NOT crash the kernel!
905 sys.excepthook(*sys.exc_info())
881 sys.excepthook(*sys.exc_info())
906 else:
882 else:
907 for matcher in self.matchers:
883 for matcher in self.matchers:
908 self.matches = matcher(text)
884 self.matches = matcher(text)
909 if self.matches:
885 if self.matches:
910 break
886 break
911 # FIXME: we should extend our api to return a dict with completions for
887 # FIXME: we should extend our api to return a dict with completions for
912 # different types of objects. The rlcomplete() method could then
888 # different types of objects. The rlcomplete() method could then
913 # simply collapse the dict into a list for readline, but we'd have
889 # simply collapse the dict into a list for readline, but we'd have
914 # richer completion semantics in other evironments.
890 # richer completion semantics in other evironments.
915 self.matches = sorted(set(self.matches))
891 self.matches = sorted(set(self.matches))
916 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
892 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
917 return text, self.matches
893 return text, self.matches
918
894
919 def rlcomplete(self, text, state):
895 def rlcomplete(self, text, state):
920 """Return the state-th possible completion for 'text'.
896 """Return the state-th possible completion for 'text'.
921
897
922 This is called successively with state == 0, 1, 2, ... until it
898 This is called successively with state == 0, 1, 2, ... until it
923 returns None. The completion should begin with 'text'.
899 returns None. The completion should begin with 'text'.
924
900
925 Parameters
901 Parameters
926 ----------
902 ----------
927 text : string
903 text : string
928 Text to perform the completion on.
904 Text to perform the completion on.
929
905
930 state : int
906 state : int
931 Counter used by readline.
907 Counter used by readline.
932 """
908 """
933 if state==0:
909 if state==0:
934
910
935 self.line_buffer = line_buffer = self.readline.get_line_buffer()
911 self.line_buffer = line_buffer = self.readline.get_line_buffer()
936 cursor_pos = self.readline.get_endidx()
912 cursor_pos = self.readline.get_endidx()
937
913
938 #io.rprint("\nRLCOMPLETE: %r %r %r" %
914 #io.rprint("\nRLCOMPLETE: %r %r %r" %
939 # (text, line_buffer, cursor_pos) ) # dbg
915 # (text, line_buffer, cursor_pos) ) # dbg
940
916
941 # if there is only a tab on a line with only whitespace, instead of
917 # if there is only a tab on a line with only whitespace, instead of
942 # the mostly useless 'do you want to see all million completions'
918 # the mostly useless 'do you want to see all million completions'
943 # message, just do the right thing and give the user his tab!
919 # message, just do the right thing and give the user his tab!
944 # Incidentally, this enables pasting of tabbed text from an editor
920 # Incidentally, this enables pasting of tabbed text from an editor
945 # (as long as autoindent is off).
921 # (as long as autoindent is off).
946
922
947 # It should be noted that at least pyreadline still shows file
923 # It should be noted that at least pyreadline still shows file
948 # completions - is there a way around it?
924 # completions - is there a way around it?
949
925
950 # don't apply this on 'dumb' terminals, such as emacs buffers, so
926 # don't apply this on 'dumb' terminals, such as emacs buffers, so
951 # we don't interfere with their own tab-completion mechanism.
927 # we don't interfere with their own tab-completion mechanism.
952 if not (self.dumb_terminal or line_buffer.strip()):
928 if not (self.dumb_terminal or line_buffer.strip()):
953 self.readline.insert_text('\t')
929 self.readline.insert_text('\t')
954 sys.stdout.flush()
930 sys.stdout.flush()
955 return None
931 return None
956
932
957 # Note: debugging exceptions that may occur in completion is very
933 # Note: debugging exceptions that may occur in completion is very
958 # tricky, because readline unconditionally silences them. So if
934 # tricky, because readline unconditionally silences them. So if
959 # during development you suspect a bug in the completion code, turn
935 # during development you suspect a bug in the completion code, turn
960 # this flag on temporarily by uncommenting the second form (don't
936 # this flag on temporarily by uncommenting the second form (don't
961 # flip the value in the first line, as the '# dbg' marker can be
937 # flip the value in the first line, as the '# dbg' marker can be
962 # automatically detected and is used elsewhere).
938 # automatically detected and is used elsewhere).
963 DEBUG = False
939 DEBUG = False
964 #DEBUG = True # dbg
940 #DEBUG = True # dbg
965 if DEBUG:
941 if DEBUG:
966 try:
942 try:
967 self.complete(text, line_buffer, cursor_pos)
943 self.complete(text, line_buffer, cursor_pos)
968 except:
944 except:
969 import traceback; traceback.print_exc()
945 import traceback; traceback.print_exc()
970 else:
946 else:
971 # The normal production version is here
947 # The normal production version is here
972
948
973 # This method computes the self.matches array
949 # This method computes the self.matches array
974 self.complete(text, line_buffer, cursor_pos)
950 self.complete(text, line_buffer, cursor_pos)
975
951
976 try:
952 try:
977 return self.matches[state]
953 return self.matches[state]
978 except IndexError:
954 except IndexError:
979 return None
955 return None
@@ -1,3160 +1,3154 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 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 from __future__ import absolute_import
17 from __future__ import absolute_import
18 from __future__ import print_function
18 from __future__ import print_function
19
19
20 import __builtin__ as builtin_mod
20 import __builtin__ as builtin_mod
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import functools
25 import functools
26 import os
26 import os
27 import re
27 import re
28 import runpy
28 import runpy
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32 from io import open as io_open
32 from io import open as io_open
33
33
34 from IPython.config.configurable import SingletonConfigurable
34 from IPython.config.configurable import SingletonConfigurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import magic
36 from IPython.core import magic
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager, AliasError
41 from IPython.core.alias import AliasManager, AliasError
42 from IPython.core.autocall import ExitAutocall
42 from IPython.core.autocall import ExitAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import UsageError
48 from IPython.core.error import UsageError
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.formatters import DisplayFormatter
50 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.history import HistoryManager
51 from IPython.core.history import HistoryManager
52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.logger import Logger
53 from IPython.core.logger import Logger
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.payload import PayloadManager
55 from IPython.core.payload import PayloadManager
56 from IPython.core.prefilter import PrefilterManager
56 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.profiledir import ProfileDir
57 from IPython.core.profiledir import ProfileDir
58 from IPython.core.prompts import PromptManager
58 from IPython.core.prompts import PromptManager
59 from IPython.lib.latextools import LaTeXTool
59 from IPython.lib.latextools import LaTeXTool
60 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest
61 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils import py3compat
63 from IPython.utils import py3compat
64 from IPython.utils import openpy
64 from IPython.utils import openpy
65 from IPython.utils.decorators import undoc
65 from IPython.utils.decorators import undoc
66 from IPython.utils.io import ask_yes_no
66 from IPython.utils.io import ask_yes_no
67 from IPython.utils.ipstruct import Struct
67 from IPython.utils.ipstruct import Struct
68 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
68 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
69 from IPython.utils.pickleshare import PickleShareDB
69 from IPython.utils.pickleshare import PickleShareDB
70 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
71 from IPython.utils.strdispatch import StrDispatch
71 from IPython.utils.strdispatch import StrDispatch
72 from IPython.utils.syspathcontext import prepended_to_syspath
72 from IPython.utils.syspathcontext import prepended_to_syspath
73 from IPython.utils.text import (format_screen, LSString, SList,
73 from IPython.utils.text import (format_screen, LSString, SList,
74 DollarFormatter)
74 DollarFormatter)
75 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
75 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
76 List, Unicode, Instance, Type)
76 List, Unicode, Instance, Type)
77 from IPython.utils.warn import warn, error
77 from IPython.utils.warn import warn, error
78 import IPython.core.hooks
78 import IPython.core.hooks
79
79
80 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81 # Globals
81 # Globals
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83
83
84 # compiled regexps for autoindent management
84 # compiled regexps for autoindent management
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
86
86
87 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
88 # Utilities
88 # Utilities
89 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
90
90
91 @undoc
91 @undoc
92 def softspace(file, newvalue):
92 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
93 """Copied from code.py, to remove the dependency"""
94
94
95 oldvalue = 0
95 oldvalue = 0
96 try:
96 try:
97 oldvalue = file.softspace
97 oldvalue = file.softspace
98 except AttributeError:
98 except AttributeError:
99 pass
99 pass
100 try:
100 try:
101 file.softspace = newvalue
101 file.softspace = newvalue
102 except (AttributeError, TypeError):
102 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
103 # "attribute-less object" or "read-only attributes"
104 pass
104 pass
105 return oldvalue
105 return oldvalue
106
106
107 @undoc
107 @undoc
108 def no_op(*a, **kw): pass
108 def no_op(*a, **kw): pass
109
109
110 @undoc
110 @undoc
111 class NoOpContext(object):
111 class NoOpContext(object):
112 def __enter__(self): pass
112 def __enter__(self): pass
113 def __exit__(self, type, value, traceback): pass
113 def __exit__(self, type, value, traceback): pass
114 no_op_context = NoOpContext()
114 no_op_context = NoOpContext()
115
115
116 class SpaceInInput(Exception): pass
116 class SpaceInInput(Exception): pass
117
117
118 @undoc
118 @undoc
119 class Bunch: pass
119 class Bunch: pass
120
120
121
121
122 def get_default_colors():
122 def get_default_colors():
123 if sys.platform=='darwin':
123 if sys.platform=='darwin':
124 return "LightBG"
124 return "LightBG"
125 elif os.name=='nt':
125 elif os.name=='nt':
126 return 'Linux'
126 return 'Linux'
127 else:
127 else:
128 return 'Linux'
128 return 'Linux'
129
129
130
130
131 class SeparateUnicode(Unicode):
131 class SeparateUnicode(Unicode):
132 """A Unicode subclass to validate separate_in, separate_out, etc.
132 """A Unicode subclass to validate separate_in, separate_out, etc.
133
133
134 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
134 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
135 """
135 """
136
136
137 def validate(self, obj, value):
137 def validate(self, obj, value):
138 if value == '0': value = ''
138 if value == '0': value = ''
139 value = value.replace('\\n','\n')
139 value = value.replace('\\n','\n')
140 return super(SeparateUnicode, self).validate(obj, value)
140 return super(SeparateUnicode, self).validate(obj, value)
141
141
142
142
143 class ReadlineNoRecord(object):
143 class ReadlineNoRecord(object):
144 """Context manager to execute some code, then reload readline history
144 """Context manager to execute some code, then reload readline history
145 so that interactive input to the code doesn't appear when pressing up."""
145 so that interactive input to the code doesn't appear when pressing up."""
146 def __init__(self, shell):
146 def __init__(self, shell):
147 self.shell = shell
147 self.shell = shell
148 self._nested_level = 0
148 self._nested_level = 0
149
149
150 def __enter__(self):
150 def __enter__(self):
151 if self._nested_level == 0:
151 if self._nested_level == 0:
152 try:
152 try:
153 self.orig_length = self.current_length()
153 self.orig_length = self.current_length()
154 self.readline_tail = self.get_readline_tail()
154 self.readline_tail = self.get_readline_tail()
155 except (AttributeError, IndexError): # Can fail with pyreadline
155 except (AttributeError, IndexError): # Can fail with pyreadline
156 self.orig_length, self.readline_tail = 999999, []
156 self.orig_length, self.readline_tail = 999999, []
157 self._nested_level += 1
157 self._nested_level += 1
158
158
159 def __exit__(self, type, value, traceback):
159 def __exit__(self, type, value, traceback):
160 self._nested_level -= 1
160 self._nested_level -= 1
161 if self._nested_level == 0:
161 if self._nested_level == 0:
162 # Try clipping the end if it's got longer
162 # Try clipping the end if it's got longer
163 try:
163 try:
164 e = self.current_length() - self.orig_length
164 e = self.current_length() - self.orig_length
165 if e > 0:
165 if e > 0:
166 for _ in range(e):
166 for _ in range(e):
167 self.shell.readline.remove_history_item(self.orig_length)
167 self.shell.readline.remove_history_item(self.orig_length)
168
168
169 # If it still doesn't match, just reload readline history.
169 # If it still doesn't match, just reload readline history.
170 if self.current_length() != self.orig_length \
170 if self.current_length() != self.orig_length \
171 or self.get_readline_tail() != self.readline_tail:
171 or self.get_readline_tail() != self.readline_tail:
172 self.shell.refill_readline_hist()
172 self.shell.refill_readline_hist()
173 except (AttributeError, IndexError):
173 except (AttributeError, IndexError):
174 pass
174 pass
175 # Returning False will cause exceptions to propagate
175 # Returning False will cause exceptions to propagate
176 return False
176 return False
177
177
178 def current_length(self):
178 def current_length(self):
179 return self.shell.readline.get_current_history_length()
179 return self.shell.readline.get_current_history_length()
180
180
181 def get_readline_tail(self, n=10):
181 def get_readline_tail(self, n=10):
182 """Get the last n items in readline history."""
182 """Get the last n items in readline history."""
183 end = self.shell.readline.get_current_history_length() + 1
183 end = self.shell.readline.get_current_history_length() + 1
184 start = max(end-n, 1)
184 start = max(end-n, 1)
185 ghi = self.shell.readline.get_history_item
185 ghi = self.shell.readline.get_history_item
186 return [ghi(x) for x in range(start, end)]
186 return [ghi(x) for x in range(start, end)]
187
187
188
188
189 @undoc
189 @undoc
190 class DummyMod(object):
190 class DummyMod(object):
191 """A dummy module used for IPython's interactive module when
191 """A dummy module used for IPython's interactive module when
192 a namespace must be assigned to the module's __dict__."""
192 a namespace must be assigned to the module's __dict__."""
193 pass
193 pass
194
194
195 #-----------------------------------------------------------------------------
195 #-----------------------------------------------------------------------------
196 # Main IPython class
196 # Main IPython class
197 #-----------------------------------------------------------------------------
197 #-----------------------------------------------------------------------------
198
198
199 class InteractiveShell(SingletonConfigurable):
199 class InteractiveShell(SingletonConfigurable):
200 """An enhanced, interactive shell for Python."""
200 """An enhanced, interactive shell for Python."""
201
201
202 _instance = None
202 _instance = None
203
203
204 ast_transformers = List([], config=True, help=
204 ast_transformers = List([], config=True, help=
205 """
205 """
206 A list of ast.NodeTransformer subclass instances, which will be applied
206 A list of ast.NodeTransformer subclass instances, which will be applied
207 to user input before code is run.
207 to user input before code is run.
208 """
208 """
209 )
209 )
210
210
211 autocall = Enum((0,1,2), default_value=0, config=True, help=
211 autocall = Enum((0,1,2), default_value=0, config=True, help=
212 """
212 """
213 Make IPython automatically call any callable object even if you didn't
213 Make IPython automatically call any callable object even if you didn't
214 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
215 automatically. The value can be '0' to disable the feature, '1' for
215 automatically. The value can be '0' to disable the feature, '1' for
216 'smart' autocall, where it is not applied if there are no more
216 'smart' autocall, where it is not applied if there are no more
217 arguments on the line, and '2' for 'full' autocall, where all callable
217 arguments on the line, and '2' for 'full' autocall, where all callable
218 objects are automatically called (even if no arguments are present).
218 objects are automatically called (even if no arguments are present).
219 """
219 """
220 )
220 )
221 # TODO: remove all autoindent logic and put into frontends.
221 # TODO: remove all autoindent logic and put into frontends.
222 # We can't do this yet because even runlines uses the autoindent.
222 # We can't do this yet because even runlines uses the autoindent.
223 autoindent = CBool(True, config=True, help=
223 autoindent = CBool(True, config=True, help=
224 """
224 """
225 Autoindent IPython code entered interactively.
225 Autoindent IPython code entered interactively.
226 """
226 """
227 )
227 )
228 automagic = CBool(True, config=True, help=
228 automagic = CBool(True, config=True, help=
229 """
229 """
230 Enable magic commands to be called without the leading %.
230 Enable magic commands to be called without the leading %.
231 """
231 """
232 )
232 )
233 cache_size = Integer(1000, config=True, help=
233 cache_size = Integer(1000, config=True, help=
234 """
234 """
235 Set the size of the output cache. The default is 1000, you can
235 Set the size of the output cache. The default is 1000, you can
236 change it permanently in your config file. Setting it to 0 completely
236 change it permanently in your config file. Setting it to 0 completely
237 disables the caching system, and the minimum value accepted is 20 (if
237 disables the caching system, and the minimum value accepted is 20 (if
238 you provide a value less than 20, it is reset to 0 and a warning is
238 you provide a value less than 20, it is reset to 0 and a warning is
239 issued). This limit is defined because otherwise you'll spend more
239 issued). This limit is defined because otherwise you'll spend more
240 time re-flushing a too small cache than working
240 time re-flushing a too small cache than working
241 """
241 """
242 )
242 )
243 color_info = CBool(True, config=True, help=
243 color_info = CBool(True, config=True, help=
244 """
244 """
245 Use colors for displaying information about objects. Because this
245 Use colors for displaying information about objects. Because this
246 information is passed through a pager (like 'less'), and some pagers
246 information is passed through a pager (like 'less'), and some pagers
247 get confused with color codes, this capability can be turned off.
247 get confused with color codes, this capability can be turned off.
248 """
248 """
249 )
249 )
250 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
250 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
251 default_value=get_default_colors(), config=True,
251 default_value=get_default_colors(), config=True,
252 help="Set the color scheme (NoColor, Linux, or LightBG)."
252 help="Set the color scheme (NoColor, Linux, or LightBG)."
253 )
253 )
254 colors_force = CBool(False, help=
254 colors_force = CBool(False, help=
255 """
255 """
256 Force use of ANSI color codes, regardless of OS and readline
256 Force use of ANSI color codes, regardless of OS and readline
257 availability.
257 availability.
258 """
258 """
259 # FIXME: This is essentially a hack to allow ZMQShell to show colors
259 # FIXME: This is essentially a hack to allow ZMQShell to show colors
260 # without readline on Win32. When the ZMQ formatting system is
260 # without readline on Win32. When the ZMQ formatting system is
261 # refactored, this should be removed.
261 # refactored, this should be removed.
262 )
262 )
263 debug = CBool(False, config=True)
263 debug = CBool(False, config=True)
264 deep_reload = CBool(False, config=True, help=
264 deep_reload = CBool(False, config=True, help=
265 """
265 """
266 Enable deep (recursive) reloading by default. IPython can use the
266 Enable deep (recursive) reloading by default. IPython can use the
267 deep_reload module which reloads changes in modules recursively (it
267 deep_reload module which reloads changes in modules recursively (it
268 replaces the reload() function, so you don't need to change anything to
268 replaces the reload() function, so you don't need to change anything to
269 use it). deep_reload() forces a full reload of modules whose code may
269 use it). deep_reload() forces a full reload of modules whose code may
270 have changed, which the default reload() function does not. When
270 have changed, which the default reload() function does not. When
271 deep_reload is off, IPython will use the normal reload(), but
271 deep_reload is off, IPython will use the normal reload(), but
272 deep_reload will still be available as dreload().
272 deep_reload will still be available as dreload().
273 """
273 """
274 )
274 )
275 disable_failing_post_execute = CBool(False, config=True,
275 disable_failing_post_execute = CBool(False, config=True,
276 help="Don't call post-execute functions that have failed in the past."
276 help="Don't call post-execute functions that have failed in the past."
277 )
277 )
278 display_formatter = Instance(DisplayFormatter)
278 display_formatter = Instance(DisplayFormatter)
279 displayhook_class = Type(DisplayHook)
279 displayhook_class = Type(DisplayHook)
280 display_pub_class = Type(DisplayPublisher)
280 display_pub_class = Type(DisplayPublisher)
281 data_pub_class = None
281 data_pub_class = None
282
282
283 exit_now = CBool(False)
283 exit_now = CBool(False)
284 exiter = Instance(ExitAutocall)
284 exiter = Instance(ExitAutocall)
285 def _exiter_default(self):
285 def _exiter_default(self):
286 return ExitAutocall(self)
286 return ExitAutocall(self)
287 # Monotonically increasing execution counter
287 # Monotonically increasing execution counter
288 execution_count = Integer(1)
288 execution_count = Integer(1)
289 filename = Unicode("<ipython console>")
289 filename = Unicode("<ipython console>")
290 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
290 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
291
291
292 # Input splitter, to transform input line by line and detect when a block
292 # Input splitter, to transform input line by line and detect when a block
293 # is ready to be executed.
293 # is ready to be executed.
294 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
294 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
295 (), {'line_input_checker': True})
295 (), {'line_input_checker': True})
296
296
297 # This InputSplitter instance is used to transform completed cells before
297 # This InputSplitter instance is used to transform completed cells before
298 # running them. It allows cell magics to contain blank lines.
298 # running them. It allows cell magics to contain blank lines.
299 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
299 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
300 (), {'line_input_checker': False})
300 (), {'line_input_checker': False})
301
301
302 logstart = CBool(False, config=True, help=
302 logstart = CBool(False, config=True, help=
303 """
303 """
304 Start logging to the default log file.
304 Start logging to the default log file.
305 """
305 """
306 )
306 )
307 logfile = Unicode('', config=True, help=
307 logfile = Unicode('', config=True, help=
308 """
308 """
309 The name of the logfile to use.
309 The name of the logfile to use.
310 """
310 """
311 )
311 )
312 logappend = Unicode('', config=True, help=
312 logappend = Unicode('', config=True, help=
313 """
313 """
314 Start logging to the given file in append mode.
314 Start logging to the given file in append mode.
315 """
315 """
316 )
316 )
317 object_info_string_level = Enum((0,1,2), default_value=0,
317 object_info_string_level = Enum((0,1,2), default_value=0,
318 config=True)
318 config=True)
319 pdb = CBool(False, config=True, help=
319 pdb = CBool(False, config=True, help=
320 """
320 """
321 Automatically call the pdb debugger after every exception.
321 Automatically call the pdb debugger after every exception.
322 """
322 """
323 )
323 )
324 multiline_history = CBool(sys.platform != 'win32', config=True,
324 multiline_history = CBool(sys.platform != 'win32', config=True,
325 help="Save multi-line entries as one entry in readline history"
325 help="Save multi-line entries as one entry in readline history"
326 )
326 )
327
327
328 # deprecated prompt traits:
328 # deprecated prompt traits:
329
329
330 prompt_in1 = Unicode('In [\\#]: ', config=True,
330 prompt_in1 = Unicode('In [\\#]: ', config=True,
331 help="Deprecated, use PromptManager.in_template")
331 help="Deprecated, use PromptManager.in_template")
332 prompt_in2 = Unicode(' .\\D.: ', config=True,
332 prompt_in2 = Unicode(' .\\D.: ', config=True,
333 help="Deprecated, use PromptManager.in2_template")
333 help="Deprecated, use PromptManager.in2_template")
334 prompt_out = Unicode('Out[\\#]: ', config=True,
334 prompt_out = Unicode('Out[\\#]: ', config=True,
335 help="Deprecated, use PromptManager.out_template")
335 help="Deprecated, use PromptManager.out_template")
336 prompts_pad_left = CBool(True, config=True,
336 prompts_pad_left = CBool(True, config=True,
337 help="Deprecated, use PromptManager.justify")
337 help="Deprecated, use PromptManager.justify")
338
338
339 def _prompt_trait_changed(self, name, old, new):
339 def _prompt_trait_changed(self, name, old, new):
340 table = {
340 table = {
341 'prompt_in1' : 'in_template',
341 'prompt_in1' : 'in_template',
342 'prompt_in2' : 'in2_template',
342 'prompt_in2' : 'in2_template',
343 'prompt_out' : 'out_template',
343 'prompt_out' : 'out_template',
344 'prompts_pad_left' : 'justify',
344 'prompts_pad_left' : 'justify',
345 }
345 }
346 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
346 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
347 name=name, newname=table[name])
347 name=name, newname=table[name])
348 )
348 )
349 # protect against weird cases where self.config may not exist:
349 # protect against weird cases where self.config may not exist:
350 if self.config is not None:
350 if self.config is not None:
351 # propagate to corresponding PromptManager trait
351 # propagate to corresponding PromptManager trait
352 setattr(self.config.PromptManager, table[name], new)
352 setattr(self.config.PromptManager, table[name], new)
353
353
354 _prompt_in1_changed = _prompt_trait_changed
354 _prompt_in1_changed = _prompt_trait_changed
355 _prompt_in2_changed = _prompt_trait_changed
355 _prompt_in2_changed = _prompt_trait_changed
356 _prompt_out_changed = _prompt_trait_changed
356 _prompt_out_changed = _prompt_trait_changed
357 _prompt_pad_left_changed = _prompt_trait_changed
357 _prompt_pad_left_changed = _prompt_trait_changed
358
358
359 show_rewritten_input = CBool(True, config=True,
359 show_rewritten_input = CBool(True, config=True,
360 help="Show rewritten input, e.g. for autocall."
360 help="Show rewritten input, e.g. for autocall."
361 )
361 )
362
362
363 quiet = CBool(False, config=True)
363 quiet = CBool(False, config=True)
364
364
365 history_length = Integer(10000, config=True)
365 history_length = Integer(10000, config=True)
366
366
367 # The readline stuff will eventually be moved to the terminal subclass
367 # The readline stuff will eventually be moved to the terminal subclass
368 # but for now, we can't do that as readline is welded in everywhere.
368 # but for now, we can't do that as readline is welded in everywhere.
369 readline_use = CBool(True, config=True)
369 readline_use = CBool(True, config=True)
370 readline_remove_delims = Unicode('-/~', config=True)
370 readline_remove_delims = Unicode('-/~', config=True)
371 readline_delims = Unicode() # set by init_readline()
371 readline_delims = Unicode() # set by init_readline()
372 # don't use \M- bindings by default, because they
372 # don't use \M- bindings by default, because they
373 # conflict with 8-bit encodings. See gh-58,gh-88
373 # conflict with 8-bit encodings. See gh-58,gh-88
374 readline_parse_and_bind = List([
374 readline_parse_and_bind = List([
375 'tab: complete',
375 'tab: complete',
376 '"\C-l": clear-screen',
376 '"\C-l": clear-screen',
377 'set show-all-if-ambiguous on',
377 'set show-all-if-ambiguous on',
378 '"\C-o": tab-insert',
378 '"\C-o": tab-insert',
379 '"\C-r": reverse-search-history',
379 '"\C-r": reverse-search-history',
380 '"\C-s": forward-search-history',
380 '"\C-s": forward-search-history',
381 '"\C-p": history-search-backward',
381 '"\C-p": history-search-backward',
382 '"\C-n": history-search-forward',
382 '"\C-n": history-search-forward',
383 '"\e[A": history-search-backward',
383 '"\e[A": history-search-backward',
384 '"\e[B": history-search-forward',
384 '"\e[B": history-search-forward',
385 '"\C-k": kill-line',
385 '"\C-k": kill-line',
386 '"\C-u": unix-line-discard',
386 '"\C-u": unix-line-discard',
387 ], allow_none=False, config=True)
387 ], allow_none=False, config=True)
388
388
389 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
389 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
390 default_value='last_expr', config=True,
390 default_value='last_expr', config=True,
391 help="""
391 help="""
392 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
392 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
393 run interactively (displaying output from expressions).""")
393 run interactively (displaying output from expressions).""")
394
394
395 # TODO: this part of prompt management should be moved to the frontends.
395 # TODO: this part of prompt management should be moved to the frontends.
396 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
396 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
397 separate_in = SeparateUnicode('\n', config=True)
397 separate_in = SeparateUnicode('\n', config=True)
398 separate_out = SeparateUnicode('', config=True)
398 separate_out = SeparateUnicode('', config=True)
399 separate_out2 = SeparateUnicode('', config=True)
399 separate_out2 = SeparateUnicode('', config=True)
400 wildcards_case_sensitive = CBool(True, config=True)
400 wildcards_case_sensitive = CBool(True, config=True)
401 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
401 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
402 default_value='Context', config=True)
402 default_value='Context', config=True)
403
403
404 # Subcomponents of InteractiveShell
404 # Subcomponents of InteractiveShell
405 alias_manager = Instance('IPython.core.alias.AliasManager')
405 alias_manager = Instance('IPython.core.alias.AliasManager')
406 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
406 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
407 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
407 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
408 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
408 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
409 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
409 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
410 payload_manager = Instance('IPython.core.payload.PayloadManager')
410 payload_manager = Instance('IPython.core.payload.PayloadManager')
411 history_manager = Instance('IPython.core.history.HistoryManager')
411 history_manager = Instance('IPython.core.history.HistoryManager')
412 magics_manager = Instance('IPython.core.magic.MagicsManager')
412 magics_manager = Instance('IPython.core.magic.MagicsManager')
413
413
414 profile_dir = Instance('IPython.core.application.ProfileDir')
414 profile_dir = Instance('IPython.core.application.ProfileDir')
415 @property
415 @property
416 def profile(self):
416 def profile(self):
417 if self.profile_dir is not None:
417 if self.profile_dir is not None:
418 name = os.path.basename(self.profile_dir.location)
418 name = os.path.basename(self.profile_dir.location)
419 return name.replace('profile_','')
419 return name.replace('profile_','')
420
420
421
421
422 # Private interface
422 # Private interface
423 _post_execute = Instance(dict)
423 _post_execute = Instance(dict)
424
424
425 # Tracks any GUI loop loaded for pylab
425 # Tracks any GUI loop loaded for pylab
426 pylab_gui_select = None
426 pylab_gui_select = None
427
427
428 def __init__(self, ipython_dir=None, profile_dir=None,
428 def __init__(self, ipython_dir=None, profile_dir=None,
429 user_module=None, user_ns=None,
429 user_module=None, user_ns=None,
430 custom_exceptions=((), None), **kwargs):
430 custom_exceptions=((), None), **kwargs):
431
431
432 # This is where traits with a config_key argument are updated
432 # This is where traits with a config_key argument are updated
433 # from the values on config.
433 # from the values on config.
434 super(InteractiveShell, self).__init__(**kwargs)
434 super(InteractiveShell, self).__init__(**kwargs)
435 self.configurables = [self]
435 self.configurables = [self]
436
436
437 # These are relatively independent and stateless
437 # These are relatively independent and stateless
438 self.init_ipython_dir(ipython_dir)
438 self.init_ipython_dir(ipython_dir)
439 self.init_profile_dir(profile_dir)
439 self.init_profile_dir(profile_dir)
440 self.init_instance_attrs()
440 self.init_instance_attrs()
441 self.init_environment()
441 self.init_environment()
442
442
443 # Check if we're in a virtualenv, and set up sys.path.
443 # Check if we're in a virtualenv, and set up sys.path.
444 self.init_virtualenv()
444 self.init_virtualenv()
445
445
446 # Create namespaces (user_ns, user_global_ns, etc.)
446 # Create namespaces (user_ns, user_global_ns, etc.)
447 self.init_create_namespaces(user_module, user_ns)
447 self.init_create_namespaces(user_module, user_ns)
448 # This has to be done after init_create_namespaces because it uses
448 # This has to be done after init_create_namespaces because it uses
449 # something in self.user_ns, but before init_sys_modules, which
449 # something in self.user_ns, but before init_sys_modules, which
450 # is the first thing to modify sys.
450 # is the first thing to modify sys.
451 # TODO: When we override sys.stdout and sys.stderr before this class
451 # TODO: When we override sys.stdout and sys.stderr before this class
452 # is created, we are saving the overridden ones here. Not sure if this
452 # is created, we are saving the overridden ones here. Not sure if this
453 # is what we want to do.
453 # is what we want to do.
454 self.save_sys_module_state()
454 self.save_sys_module_state()
455 self.init_sys_modules()
455 self.init_sys_modules()
456
456
457 # While we're trying to have each part of the code directly access what
457 # While we're trying to have each part of the code directly access what
458 # it needs without keeping redundant references to objects, we have too
458 # it needs without keeping redundant references to objects, we have too
459 # much legacy code that expects ip.db to exist.
459 # much legacy code that expects ip.db to exist.
460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
461
461
462 self.init_history()
462 self.init_history()
463 self.init_encoding()
463 self.init_encoding()
464 self.init_prefilter()
464 self.init_prefilter()
465
465
466 self.init_syntax_highlighting()
466 self.init_syntax_highlighting()
467 self.init_hooks()
467 self.init_hooks()
468 self.init_pushd_popd_magic()
468 self.init_pushd_popd_magic()
469 # self.init_traceback_handlers use to be here, but we moved it below
469 # self.init_traceback_handlers use to be here, but we moved it below
470 # because it and init_io have to come after init_readline.
470 # because it and init_io have to come after init_readline.
471 self.init_user_ns()
471 self.init_user_ns()
472 self.init_logger()
472 self.init_logger()
473 self.init_alias()
474 self.init_builtins()
473 self.init_builtins()
475
474
476 # The following was in post_config_initialization
475 # The following was in post_config_initialization
477 self.init_inspector()
476 self.init_inspector()
478 # init_readline() must come before init_io(), because init_io uses
477 # init_readline() must come before init_io(), because init_io uses
479 # readline related things.
478 # readline related things.
480 self.init_readline()
479 self.init_readline()
481 # We save this here in case user code replaces raw_input, but it needs
480 # We save this here in case user code replaces raw_input, but it needs
482 # to be after init_readline(), because PyPy's readline works by replacing
481 # to be after init_readline(), because PyPy's readline works by replacing
483 # raw_input.
482 # raw_input.
484 if py3compat.PY3:
483 if py3compat.PY3:
485 self.raw_input_original = input
484 self.raw_input_original = input
486 else:
485 else:
487 self.raw_input_original = raw_input
486 self.raw_input_original = raw_input
488 # init_completer must come after init_readline, because it needs to
487 # init_completer must come after init_readline, because it needs to
489 # know whether readline is present or not system-wide to configure the
488 # know whether readline is present or not system-wide to configure the
490 # completers, since the completion machinery can now operate
489 # completers, since the completion machinery can now operate
491 # independently of readline (e.g. over the network)
490 # independently of readline (e.g. over the network)
492 self.init_completer()
491 self.init_completer()
493 # TODO: init_io() needs to happen before init_traceback handlers
492 # TODO: init_io() needs to happen before init_traceback handlers
494 # because the traceback handlers hardcode the stdout/stderr streams.
493 # because the traceback handlers hardcode the stdout/stderr streams.
495 # This logic in in debugger.Pdb and should eventually be changed.
494 # This logic in in debugger.Pdb and should eventually be changed.
496 self.init_io()
495 self.init_io()
497 self.init_traceback_handlers(custom_exceptions)
496 self.init_traceback_handlers(custom_exceptions)
498 self.init_prompts()
497 self.init_prompts()
499 self.init_display_formatter()
498 self.init_display_formatter()
500 self.init_display_pub()
499 self.init_display_pub()
501 self.init_data_pub()
500 self.init_data_pub()
502 self.init_displayhook()
501 self.init_displayhook()
503 self.init_latextool()
502 self.init_latextool()
504 self.init_magics()
503 self.init_magics()
504 self.init_alias()
505 self.init_logstart()
505 self.init_logstart()
506 self.init_pdb()
506 self.init_pdb()
507 self.init_extension_manager()
507 self.init_extension_manager()
508 self.init_payload()
508 self.init_payload()
509 self.hooks.late_startup_hook()
509 self.hooks.late_startup_hook()
510 atexit.register(self.atexit_operations)
510 atexit.register(self.atexit_operations)
511
511
512 def get_ipython(self):
512 def get_ipython(self):
513 """Return the currently running IPython instance."""
513 """Return the currently running IPython instance."""
514 return self
514 return self
515
515
516 #-------------------------------------------------------------------------
516 #-------------------------------------------------------------------------
517 # Trait changed handlers
517 # Trait changed handlers
518 #-------------------------------------------------------------------------
518 #-------------------------------------------------------------------------
519
519
520 def _ipython_dir_changed(self, name, new):
520 def _ipython_dir_changed(self, name, new):
521 if not os.path.isdir(new):
521 if not os.path.isdir(new):
522 os.makedirs(new, mode = 0o777)
522 os.makedirs(new, mode = 0o777)
523
523
524 def set_autoindent(self,value=None):
524 def set_autoindent(self,value=None):
525 """Set the autoindent flag, checking for readline support.
525 """Set the autoindent flag, checking for readline support.
526
526
527 If called with no arguments, it acts as a toggle."""
527 If called with no arguments, it acts as a toggle."""
528
528
529 if value != 0 and not self.has_readline:
529 if value != 0 and not self.has_readline:
530 if os.name == 'posix':
530 if os.name == 'posix':
531 warn("The auto-indent feature requires the readline library")
531 warn("The auto-indent feature requires the readline library")
532 self.autoindent = 0
532 self.autoindent = 0
533 return
533 return
534 if value is None:
534 if value is None:
535 self.autoindent = not self.autoindent
535 self.autoindent = not self.autoindent
536 else:
536 else:
537 self.autoindent = value
537 self.autoindent = value
538
538
539 #-------------------------------------------------------------------------
539 #-------------------------------------------------------------------------
540 # init_* methods called by __init__
540 # init_* methods called by __init__
541 #-------------------------------------------------------------------------
541 #-------------------------------------------------------------------------
542
542
543 def init_ipython_dir(self, ipython_dir):
543 def init_ipython_dir(self, ipython_dir):
544 if ipython_dir is not None:
544 if ipython_dir is not None:
545 self.ipython_dir = ipython_dir
545 self.ipython_dir = ipython_dir
546 return
546 return
547
547
548 self.ipython_dir = get_ipython_dir()
548 self.ipython_dir = get_ipython_dir()
549
549
550 def init_profile_dir(self, profile_dir):
550 def init_profile_dir(self, profile_dir):
551 if profile_dir is not None:
551 if profile_dir is not None:
552 self.profile_dir = profile_dir
552 self.profile_dir = profile_dir
553 return
553 return
554 self.profile_dir =\
554 self.profile_dir =\
555 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
555 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
556
556
557 def init_instance_attrs(self):
557 def init_instance_attrs(self):
558 self.more = False
558 self.more = False
559
559
560 # command compiler
560 # command compiler
561 self.compile = CachingCompiler()
561 self.compile = CachingCompiler()
562
562
563 # Make an empty namespace, which extension writers can rely on both
563 # Make an empty namespace, which extension writers can rely on both
564 # existing and NEVER being used by ipython itself. This gives them a
564 # existing and NEVER being used by ipython itself. This gives them a
565 # convenient location for storing additional information and state
565 # convenient location for storing additional information and state
566 # their extensions may require, without fear of collisions with other
566 # their extensions may require, without fear of collisions with other
567 # ipython names that may develop later.
567 # ipython names that may develop later.
568 self.meta = Struct()
568 self.meta = Struct()
569
569
570 # Temporary files used for various purposes. Deleted at exit.
570 # Temporary files used for various purposes. Deleted at exit.
571 self.tempfiles = []
571 self.tempfiles = []
572
572
573 # Keep track of readline usage (later set by init_readline)
573 # Keep track of readline usage (later set by init_readline)
574 self.has_readline = False
574 self.has_readline = False
575
575
576 # keep track of where we started running (mainly for crash post-mortem)
576 # keep track of where we started running (mainly for crash post-mortem)
577 # This is not being used anywhere currently.
577 # This is not being used anywhere currently.
578 self.starting_dir = os.getcwdu()
578 self.starting_dir = os.getcwdu()
579
579
580 # Indentation management
580 # Indentation management
581 self.indent_current_nsp = 0
581 self.indent_current_nsp = 0
582
582
583 # Dict to track post-execution functions that have been registered
583 # Dict to track post-execution functions that have been registered
584 self._post_execute = {}
584 self._post_execute = {}
585
585
586 def init_environment(self):
586 def init_environment(self):
587 """Any changes we need to make to the user's environment."""
587 """Any changes we need to make to the user's environment."""
588 pass
588 pass
589
589
590 def init_encoding(self):
590 def init_encoding(self):
591 # Get system encoding at startup time. Certain terminals (like Emacs
591 # Get system encoding at startup time. Certain terminals (like Emacs
592 # under Win32 have it set to None, and we need to have a known valid
592 # under Win32 have it set to None, and we need to have a known valid
593 # encoding to use in the raw_input() method
593 # encoding to use in the raw_input() method
594 try:
594 try:
595 self.stdin_encoding = sys.stdin.encoding or 'ascii'
595 self.stdin_encoding = sys.stdin.encoding or 'ascii'
596 except AttributeError:
596 except AttributeError:
597 self.stdin_encoding = 'ascii'
597 self.stdin_encoding = 'ascii'
598
598
599 def init_syntax_highlighting(self):
599 def init_syntax_highlighting(self):
600 # Python source parser/formatter for syntax highlighting
600 # Python source parser/formatter for syntax highlighting
601 pyformat = PyColorize.Parser().format
601 pyformat = PyColorize.Parser().format
602 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
602 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
603
603
604 def init_pushd_popd_magic(self):
604 def init_pushd_popd_magic(self):
605 # for pushd/popd management
605 # for pushd/popd management
606 self.home_dir = get_home_dir()
606 self.home_dir = get_home_dir()
607
607
608 self.dir_stack = []
608 self.dir_stack = []
609
609
610 def init_logger(self):
610 def init_logger(self):
611 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
611 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
612 logmode='rotate')
612 logmode='rotate')
613
613
614 def init_logstart(self):
614 def init_logstart(self):
615 """Initialize logging in case it was requested at the command line.
615 """Initialize logging in case it was requested at the command line.
616 """
616 """
617 if self.logappend:
617 if self.logappend:
618 self.magic('logstart %s append' % self.logappend)
618 self.magic('logstart %s append' % self.logappend)
619 elif self.logfile:
619 elif self.logfile:
620 self.magic('logstart %s' % self.logfile)
620 self.magic('logstart %s' % self.logfile)
621 elif self.logstart:
621 elif self.logstart:
622 self.magic('logstart')
622 self.magic('logstart')
623
623
624 def init_builtins(self):
624 def init_builtins(self):
625 # A single, static flag that we set to True. Its presence indicates
625 # A single, static flag that we set to True. Its presence indicates
626 # that an IPython shell has been created, and we make no attempts at
626 # that an IPython shell has been created, and we make no attempts at
627 # removing on exit or representing the existence of more than one
627 # removing on exit or representing the existence of more than one
628 # IPython at a time.
628 # IPython at a time.
629 builtin_mod.__dict__['__IPYTHON__'] = True
629 builtin_mod.__dict__['__IPYTHON__'] = True
630
630
631 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
631 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
632 # manage on enter/exit, but with all our shells it's virtually
632 # manage on enter/exit, but with all our shells it's virtually
633 # impossible to get all the cases right. We're leaving the name in for
633 # impossible to get all the cases right. We're leaving the name in for
634 # those who adapted their codes to check for this flag, but will
634 # those who adapted their codes to check for this flag, but will
635 # eventually remove it after a few more releases.
635 # eventually remove it after a few more releases.
636 builtin_mod.__dict__['__IPYTHON__active'] = \
636 builtin_mod.__dict__['__IPYTHON__active'] = \
637 'Deprecated, check for __IPYTHON__'
637 'Deprecated, check for __IPYTHON__'
638
638
639 self.builtin_trap = BuiltinTrap(shell=self)
639 self.builtin_trap = BuiltinTrap(shell=self)
640
640
641 def init_inspector(self):
641 def init_inspector(self):
642 # Object inspector
642 # Object inspector
643 self.inspector = oinspect.Inspector(oinspect.InspectColors,
643 self.inspector = oinspect.Inspector(oinspect.InspectColors,
644 PyColorize.ANSICodeColors,
644 PyColorize.ANSICodeColors,
645 'NoColor',
645 'NoColor',
646 self.object_info_string_level)
646 self.object_info_string_level)
647
647
648 def init_io(self):
648 def init_io(self):
649 # This will just use sys.stdout and sys.stderr. If you want to
649 # This will just use sys.stdout and sys.stderr. If you want to
650 # override sys.stdout and sys.stderr themselves, you need to do that
650 # override sys.stdout and sys.stderr themselves, you need to do that
651 # *before* instantiating this class, because io holds onto
651 # *before* instantiating this class, because io holds onto
652 # references to the underlying streams.
652 # references to the underlying streams.
653 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
653 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
654 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
654 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
655 else:
655 else:
656 io.stdout = io.IOStream(sys.stdout)
656 io.stdout = io.IOStream(sys.stdout)
657 io.stderr = io.IOStream(sys.stderr)
657 io.stderr = io.IOStream(sys.stderr)
658
658
659 def init_prompts(self):
659 def init_prompts(self):
660 self.prompt_manager = PromptManager(shell=self, parent=self)
660 self.prompt_manager = PromptManager(shell=self, parent=self)
661 self.configurables.append(self.prompt_manager)
661 self.configurables.append(self.prompt_manager)
662 # Set system prompts, so that scripts can decide if they are running
662 # Set system prompts, so that scripts can decide if they are running
663 # interactively.
663 # interactively.
664 sys.ps1 = 'In : '
664 sys.ps1 = 'In : '
665 sys.ps2 = '...: '
665 sys.ps2 = '...: '
666 sys.ps3 = 'Out: '
666 sys.ps3 = 'Out: '
667
667
668 def init_display_formatter(self):
668 def init_display_formatter(self):
669 self.display_formatter = DisplayFormatter(parent=self)
669 self.display_formatter = DisplayFormatter(parent=self)
670 self.configurables.append(self.display_formatter)
670 self.configurables.append(self.display_formatter)
671
671
672 def init_display_pub(self):
672 def init_display_pub(self):
673 self.display_pub = self.display_pub_class(parent=self)
673 self.display_pub = self.display_pub_class(parent=self)
674 self.configurables.append(self.display_pub)
674 self.configurables.append(self.display_pub)
675
675
676 def init_data_pub(self):
676 def init_data_pub(self):
677 if not self.data_pub_class:
677 if not self.data_pub_class:
678 self.data_pub = None
678 self.data_pub = None
679 return
679 return
680 self.data_pub = self.data_pub_class(parent=self)
680 self.data_pub = self.data_pub_class(parent=self)
681 self.configurables.append(self.data_pub)
681 self.configurables.append(self.data_pub)
682
682
683 def init_displayhook(self):
683 def init_displayhook(self):
684 # Initialize displayhook, set in/out prompts and printing system
684 # Initialize displayhook, set in/out prompts and printing system
685 self.displayhook = self.displayhook_class(
685 self.displayhook = self.displayhook_class(
686 parent=self,
686 parent=self,
687 shell=self,
687 shell=self,
688 cache_size=self.cache_size,
688 cache_size=self.cache_size,
689 )
689 )
690 self.configurables.append(self.displayhook)
690 self.configurables.append(self.displayhook)
691 # This is a context manager that installs/revmoes the displayhook at
691 # This is a context manager that installs/revmoes the displayhook at
692 # the appropriate time.
692 # the appropriate time.
693 self.display_trap = DisplayTrap(hook=self.displayhook)
693 self.display_trap = DisplayTrap(hook=self.displayhook)
694
694
695 def init_latextool(self):
695 def init_latextool(self):
696 """Configure LaTeXTool."""
696 """Configure LaTeXTool."""
697 cfg = LaTeXTool.instance(parent=self)
697 cfg = LaTeXTool.instance(parent=self)
698 if cfg not in self.configurables:
698 if cfg not in self.configurables:
699 self.configurables.append(cfg)
699 self.configurables.append(cfg)
700
700
701 def init_virtualenv(self):
701 def init_virtualenv(self):
702 """Add a virtualenv to sys.path so the user can import modules from it.
702 """Add a virtualenv to sys.path so the user can import modules from it.
703 This isn't perfect: it doesn't use the Python interpreter with which the
703 This isn't perfect: it doesn't use the Python interpreter with which the
704 virtualenv was built, and it ignores the --no-site-packages option. A
704 virtualenv was built, and it ignores the --no-site-packages option. A
705 warning will appear suggesting the user installs IPython in the
705 warning will appear suggesting the user installs IPython in the
706 virtualenv, but for many cases, it probably works well enough.
706 virtualenv, but for many cases, it probably works well enough.
707
707
708 Adapted from code snippets online.
708 Adapted from code snippets online.
709
709
710 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
710 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
711 """
711 """
712 if 'VIRTUAL_ENV' not in os.environ:
712 if 'VIRTUAL_ENV' not in os.environ:
713 # Not in a virtualenv
713 # Not in a virtualenv
714 return
714 return
715
715
716 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
716 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
717 # Running properly in the virtualenv, don't need to do anything
717 # Running properly in the virtualenv, don't need to do anything
718 return
718 return
719
719
720 warn("Attempting to work in a virtualenv. If you encounter problems, please "
720 warn("Attempting to work in a virtualenv. If you encounter problems, please "
721 "install IPython inside the virtualenv.")
721 "install IPython inside the virtualenv.")
722 if sys.platform == "win32":
722 if sys.platform == "win32":
723 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
723 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
724 else:
724 else:
725 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
725 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
726 'python%d.%d' % sys.version_info[:2], 'site-packages')
726 'python%d.%d' % sys.version_info[:2], 'site-packages')
727
727
728 import site
728 import site
729 sys.path.insert(0, virtual_env)
729 sys.path.insert(0, virtual_env)
730 site.addsitedir(virtual_env)
730 site.addsitedir(virtual_env)
731
731
732 #-------------------------------------------------------------------------
732 #-------------------------------------------------------------------------
733 # Things related to injections into the sys module
733 # Things related to injections into the sys module
734 #-------------------------------------------------------------------------
734 #-------------------------------------------------------------------------
735
735
736 def save_sys_module_state(self):
736 def save_sys_module_state(self):
737 """Save the state of hooks in the sys module.
737 """Save the state of hooks in the sys module.
738
738
739 This has to be called after self.user_module is created.
739 This has to be called after self.user_module is created.
740 """
740 """
741 self._orig_sys_module_state = {}
741 self._orig_sys_module_state = {}
742 self._orig_sys_module_state['stdin'] = sys.stdin
742 self._orig_sys_module_state['stdin'] = sys.stdin
743 self._orig_sys_module_state['stdout'] = sys.stdout
743 self._orig_sys_module_state['stdout'] = sys.stdout
744 self._orig_sys_module_state['stderr'] = sys.stderr
744 self._orig_sys_module_state['stderr'] = sys.stderr
745 self._orig_sys_module_state['excepthook'] = sys.excepthook
745 self._orig_sys_module_state['excepthook'] = sys.excepthook
746 self._orig_sys_modules_main_name = self.user_module.__name__
746 self._orig_sys_modules_main_name = self.user_module.__name__
747 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
747 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
748
748
749 def restore_sys_module_state(self):
749 def restore_sys_module_state(self):
750 """Restore the state of the sys module."""
750 """Restore the state of the sys module."""
751 try:
751 try:
752 for k, v in self._orig_sys_module_state.iteritems():
752 for k, v in self._orig_sys_module_state.iteritems():
753 setattr(sys, k, v)
753 setattr(sys, k, v)
754 except AttributeError:
754 except AttributeError:
755 pass
755 pass
756 # Reset what what done in self.init_sys_modules
756 # Reset what what done in self.init_sys_modules
757 if self._orig_sys_modules_main_mod is not None:
757 if self._orig_sys_modules_main_mod is not None:
758 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
758 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
759
759
760 #-------------------------------------------------------------------------
760 #-------------------------------------------------------------------------
761 # Things related to hooks
761 # Things related to hooks
762 #-------------------------------------------------------------------------
762 #-------------------------------------------------------------------------
763
763
764 def init_hooks(self):
764 def init_hooks(self):
765 # hooks holds pointers used for user-side customizations
765 # hooks holds pointers used for user-side customizations
766 self.hooks = Struct()
766 self.hooks = Struct()
767
767
768 self.strdispatchers = {}
768 self.strdispatchers = {}
769
769
770 # Set all default hooks, defined in the IPython.hooks module.
770 # Set all default hooks, defined in the IPython.hooks module.
771 hooks = IPython.core.hooks
771 hooks = IPython.core.hooks
772 for hook_name in hooks.__all__:
772 for hook_name in hooks.__all__:
773 # default hooks have priority 100, i.e. low; user hooks should have
773 # default hooks have priority 100, i.e. low; user hooks should have
774 # 0-100 priority
774 # 0-100 priority
775 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
775 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
776
776
777 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
777 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
778 """set_hook(name,hook) -> sets an internal IPython hook.
778 """set_hook(name,hook) -> sets an internal IPython hook.
779
779
780 IPython exposes some of its internal API as user-modifiable hooks. By
780 IPython exposes some of its internal API as user-modifiable hooks. By
781 adding your function to one of these hooks, you can modify IPython's
781 adding your function to one of these hooks, you can modify IPython's
782 behavior to call at runtime your own routines."""
782 behavior to call at runtime your own routines."""
783
783
784 # At some point in the future, this should validate the hook before it
784 # At some point in the future, this should validate the hook before it
785 # accepts it. Probably at least check that the hook takes the number
785 # accepts it. Probably at least check that the hook takes the number
786 # of args it's supposed to.
786 # of args it's supposed to.
787
787
788 f = types.MethodType(hook,self)
788 f = types.MethodType(hook,self)
789
789
790 # check if the hook is for strdispatcher first
790 # check if the hook is for strdispatcher first
791 if str_key is not None:
791 if str_key is not None:
792 sdp = self.strdispatchers.get(name, StrDispatch())
792 sdp = self.strdispatchers.get(name, StrDispatch())
793 sdp.add_s(str_key, f, priority )
793 sdp.add_s(str_key, f, priority )
794 self.strdispatchers[name] = sdp
794 self.strdispatchers[name] = sdp
795 return
795 return
796 if re_key is not None:
796 if re_key is not None:
797 sdp = self.strdispatchers.get(name, StrDispatch())
797 sdp = self.strdispatchers.get(name, StrDispatch())
798 sdp.add_re(re.compile(re_key), f, priority )
798 sdp.add_re(re.compile(re_key), f, priority )
799 self.strdispatchers[name] = sdp
799 self.strdispatchers[name] = sdp
800 return
800 return
801
801
802 dp = getattr(self.hooks, name, None)
802 dp = getattr(self.hooks, name, None)
803 if name not in IPython.core.hooks.__all__:
803 if name not in IPython.core.hooks.__all__:
804 print("Warning! Hook '%s' is not one of %s" % \
804 print("Warning! Hook '%s' is not one of %s" % \
805 (name, IPython.core.hooks.__all__ ))
805 (name, IPython.core.hooks.__all__ ))
806 if not dp:
806 if not dp:
807 dp = IPython.core.hooks.CommandChainDispatcher()
807 dp = IPython.core.hooks.CommandChainDispatcher()
808
808
809 try:
809 try:
810 dp.add(f,priority)
810 dp.add(f,priority)
811 except AttributeError:
811 except AttributeError:
812 # it was not commandchain, plain old func - replace
812 # it was not commandchain, plain old func - replace
813 dp = f
813 dp = f
814
814
815 setattr(self.hooks,name, dp)
815 setattr(self.hooks,name, dp)
816
816
817 def register_post_execute(self, func):
817 def register_post_execute(self, func):
818 """Register a function for calling after code execution.
818 """Register a function for calling after code execution.
819 """
819 """
820 if not callable(func):
820 if not callable(func):
821 raise ValueError('argument %s must be callable' % func)
821 raise ValueError('argument %s must be callable' % func)
822 self._post_execute[func] = True
822 self._post_execute[func] = True
823
823
824 #-------------------------------------------------------------------------
824 #-------------------------------------------------------------------------
825 # Things related to the "main" module
825 # Things related to the "main" module
826 #-------------------------------------------------------------------------
826 #-------------------------------------------------------------------------
827
827
828 def new_main_mod(self, filename, modname):
828 def new_main_mod(self, filename, modname):
829 """Return a new 'main' module object for user code execution.
829 """Return a new 'main' module object for user code execution.
830
830
831 ``filename`` should be the path of the script which will be run in the
831 ``filename`` should be the path of the script which will be run in the
832 module. Requests with the same filename will get the same module, with
832 module. Requests with the same filename will get the same module, with
833 its namespace cleared.
833 its namespace cleared.
834
834
835 ``modname`` should be the module name - normally either '__main__' or
835 ``modname`` should be the module name - normally either '__main__' or
836 the basename of the file without the extension.
836 the basename of the file without the extension.
837
837
838 When scripts are executed via %run, we must keep a reference to their
838 When scripts are executed via %run, we must keep a reference to their
839 __main__ module around so that Python doesn't
839 __main__ module around so that Python doesn't
840 clear it, rendering references to module globals useless.
840 clear it, rendering references to module globals useless.
841
841
842 This method keeps said reference in a private dict, keyed by the
842 This method keeps said reference in a private dict, keyed by the
843 absolute path of the script. This way, for multiple executions of the
843 absolute path of the script. This way, for multiple executions of the
844 same script we only keep one copy of the namespace (the last one),
844 same script we only keep one copy of the namespace (the last one),
845 thus preventing memory leaks from old references while allowing the
845 thus preventing memory leaks from old references while allowing the
846 objects from the last execution to be accessible.
846 objects from the last execution to be accessible.
847 """
847 """
848 filename = os.path.abspath(filename)
848 filename = os.path.abspath(filename)
849 try:
849 try:
850 main_mod = self._main_mod_cache[filename]
850 main_mod = self._main_mod_cache[filename]
851 except KeyError:
851 except KeyError:
852 main_mod = self._main_mod_cache[filename] = types.ModuleType(modname,
852 main_mod = self._main_mod_cache[filename] = types.ModuleType(modname,
853 doc="Module created for script run in IPython")
853 doc="Module created for script run in IPython")
854 else:
854 else:
855 main_mod.__dict__.clear()
855 main_mod.__dict__.clear()
856 main_mod.__name__ = modname
856 main_mod.__name__ = modname
857
857
858 main_mod.__file__ = filename
858 main_mod.__file__ = filename
859 # It seems pydoc (and perhaps others) needs any module instance to
859 # It seems pydoc (and perhaps others) needs any module instance to
860 # implement a __nonzero__ method
860 # implement a __nonzero__ method
861 main_mod.__nonzero__ = lambda : True
861 main_mod.__nonzero__ = lambda : True
862
862
863 return main_mod
863 return main_mod
864
864
865 def clear_main_mod_cache(self):
865 def clear_main_mod_cache(self):
866 """Clear the cache of main modules.
866 """Clear the cache of main modules.
867
867
868 Mainly for use by utilities like %reset.
868 Mainly for use by utilities like %reset.
869
869
870 Examples
870 Examples
871 --------
871 --------
872
872
873 In [15]: import IPython
873 In [15]: import IPython
874
874
875 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
875 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
876
876
877 In [17]: len(_ip._main_mod_cache) > 0
877 In [17]: len(_ip._main_mod_cache) > 0
878 Out[17]: True
878 Out[17]: True
879
879
880 In [18]: _ip.clear_main_mod_cache()
880 In [18]: _ip.clear_main_mod_cache()
881
881
882 In [19]: len(_ip._main_mod_cache) == 0
882 In [19]: len(_ip._main_mod_cache) == 0
883 Out[19]: True
883 Out[19]: True
884 """
884 """
885 self._main_mod_cache.clear()
885 self._main_mod_cache.clear()
886
886
887 #-------------------------------------------------------------------------
887 #-------------------------------------------------------------------------
888 # Things related to debugging
888 # Things related to debugging
889 #-------------------------------------------------------------------------
889 #-------------------------------------------------------------------------
890
890
891 def init_pdb(self):
891 def init_pdb(self):
892 # Set calling of pdb on exceptions
892 # Set calling of pdb on exceptions
893 # self.call_pdb is a property
893 # self.call_pdb is a property
894 self.call_pdb = self.pdb
894 self.call_pdb = self.pdb
895
895
896 def _get_call_pdb(self):
896 def _get_call_pdb(self):
897 return self._call_pdb
897 return self._call_pdb
898
898
899 def _set_call_pdb(self,val):
899 def _set_call_pdb(self,val):
900
900
901 if val not in (0,1,False,True):
901 if val not in (0,1,False,True):
902 raise ValueError('new call_pdb value must be boolean')
902 raise ValueError('new call_pdb value must be boolean')
903
903
904 # store value in instance
904 # store value in instance
905 self._call_pdb = val
905 self._call_pdb = val
906
906
907 # notify the actual exception handlers
907 # notify the actual exception handlers
908 self.InteractiveTB.call_pdb = val
908 self.InteractiveTB.call_pdb = val
909
909
910 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
910 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
911 'Control auto-activation of pdb at exceptions')
911 'Control auto-activation of pdb at exceptions')
912
912
913 def debugger(self,force=False):
913 def debugger(self,force=False):
914 """Call the pydb/pdb debugger.
914 """Call the pydb/pdb debugger.
915
915
916 Keywords:
916 Keywords:
917
917
918 - force(False): by default, this routine checks the instance call_pdb
918 - force(False): by default, this routine checks the instance call_pdb
919 flag and does not actually invoke the debugger if the flag is false.
919 flag and does not actually invoke the debugger if the flag is false.
920 The 'force' option forces the debugger to activate even if the flag
920 The 'force' option forces the debugger to activate even if the flag
921 is false.
921 is false.
922 """
922 """
923
923
924 if not (force or self.call_pdb):
924 if not (force or self.call_pdb):
925 return
925 return
926
926
927 if not hasattr(sys,'last_traceback'):
927 if not hasattr(sys,'last_traceback'):
928 error('No traceback has been produced, nothing to debug.')
928 error('No traceback has been produced, nothing to debug.')
929 return
929 return
930
930
931 # use pydb if available
931 # use pydb if available
932 if debugger.has_pydb:
932 if debugger.has_pydb:
933 from pydb import pm
933 from pydb import pm
934 else:
934 else:
935 # fallback to our internal debugger
935 # fallback to our internal debugger
936 pm = lambda : self.InteractiveTB.debugger(force=True)
936 pm = lambda : self.InteractiveTB.debugger(force=True)
937
937
938 with self.readline_no_record:
938 with self.readline_no_record:
939 pm()
939 pm()
940
940
941 #-------------------------------------------------------------------------
941 #-------------------------------------------------------------------------
942 # Things related to IPython's various namespaces
942 # Things related to IPython's various namespaces
943 #-------------------------------------------------------------------------
943 #-------------------------------------------------------------------------
944 default_user_namespaces = True
944 default_user_namespaces = True
945
945
946 def init_create_namespaces(self, user_module=None, user_ns=None):
946 def init_create_namespaces(self, user_module=None, user_ns=None):
947 # Create the namespace where the user will operate. user_ns is
947 # Create the namespace where the user will operate. user_ns is
948 # normally the only one used, and it is passed to the exec calls as
948 # normally the only one used, and it is passed to the exec calls as
949 # the locals argument. But we do carry a user_global_ns namespace
949 # the locals argument. But we do carry a user_global_ns namespace
950 # given as the exec 'globals' argument, This is useful in embedding
950 # given as the exec 'globals' argument, This is useful in embedding
951 # situations where the ipython shell opens in a context where the
951 # situations where the ipython shell opens in a context where the
952 # distinction between locals and globals is meaningful. For
952 # distinction between locals and globals is meaningful. For
953 # non-embedded contexts, it is just the same object as the user_ns dict.
953 # non-embedded contexts, it is just the same object as the user_ns dict.
954
954
955 # FIXME. For some strange reason, __builtins__ is showing up at user
955 # FIXME. For some strange reason, __builtins__ is showing up at user
956 # level as a dict instead of a module. This is a manual fix, but I
956 # level as a dict instead of a module. This is a manual fix, but I
957 # should really track down where the problem is coming from. Alex
957 # should really track down where the problem is coming from. Alex
958 # Schmolck reported this problem first.
958 # Schmolck reported this problem first.
959
959
960 # A useful post by Alex Martelli on this topic:
960 # A useful post by Alex Martelli on this topic:
961 # Re: inconsistent value from __builtins__
961 # Re: inconsistent value from __builtins__
962 # Von: Alex Martelli <aleaxit@yahoo.com>
962 # Von: Alex Martelli <aleaxit@yahoo.com>
963 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
963 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
964 # Gruppen: comp.lang.python
964 # Gruppen: comp.lang.python
965
965
966 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
966 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
967 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
967 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
968 # > <type 'dict'>
968 # > <type 'dict'>
969 # > >>> print type(__builtins__)
969 # > >>> print type(__builtins__)
970 # > <type 'module'>
970 # > <type 'module'>
971 # > Is this difference in return value intentional?
971 # > Is this difference in return value intentional?
972
972
973 # Well, it's documented that '__builtins__' can be either a dictionary
973 # Well, it's documented that '__builtins__' can be either a dictionary
974 # or a module, and it's been that way for a long time. Whether it's
974 # or a module, and it's been that way for a long time. Whether it's
975 # intentional (or sensible), I don't know. In any case, the idea is
975 # intentional (or sensible), I don't know. In any case, the idea is
976 # that if you need to access the built-in namespace directly, you
976 # that if you need to access the built-in namespace directly, you
977 # should start with "import __builtin__" (note, no 's') which will
977 # should start with "import __builtin__" (note, no 's') which will
978 # definitely give you a module. Yeah, it's somewhat confusing:-(.
978 # definitely give you a module. Yeah, it's somewhat confusing:-(.
979
979
980 # These routines return a properly built module and dict as needed by
980 # These routines return a properly built module and dict as needed by
981 # the rest of the code, and can also be used by extension writers to
981 # the rest of the code, and can also be used by extension writers to
982 # generate properly initialized namespaces.
982 # generate properly initialized namespaces.
983 if (user_ns is not None) or (user_module is not None):
983 if (user_ns is not None) or (user_module is not None):
984 self.default_user_namespaces = False
984 self.default_user_namespaces = False
985 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
985 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
986
986
987 # A record of hidden variables we have added to the user namespace, so
987 # A record of hidden variables we have added to the user namespace, so
988 # we can list later only variables defined in actual interactive use.
988 # we can list later only variables defined in actual interactive use.
989 self.user_ns_hidden = {}
989 self.user_ns_hidden = {}
990
990
991 # Now that FakeModule produces a real module, we've run into a nasty
991 # Now that FakeModule produces a real module, we've run into a nasty
992 # problem: after script execution (via %run), the module where the user
992 # problem: after script execution (via %run), the module where the user
993 # code ran is deleted. Now that this object is a true module (needed
993 # code ran is deleted. Now that this object is a true module (needed
994 # so docetst and other tools work correctly), the Python module
994 # so docetst and other tools work correctly), the Python module
995 # teardown mechanism runs over it, and sets to None every variable
995 # teardown mechanism runs over it, and sets to None every variable
996 # present in that module. Top-level references to objects from the
996 # present in that module. Top-level references to objects from the
997 # script survive, because the user_ns is updated with them. However,
997 # script survive, because the user_ns is updated with them. However,
998 # calling functions defined in the script that use other things from
998 # calling functions defined in the script that use other things from
999 # the script will fail, because the function's closure had references
999 # the script will fail, because the function's closure had references
1000 # to the original objects, which are now all None. So we must protect
1000 # to the original objects, which are now all None. So we must protect
1001 # these modules from deletion by keeping a cache.
1001 # these modules from deletion by keeping a cache.
1002 #
1002 #
1003 # To avoid keeping stale modules around (we only need the one from the
1003 # To avoid keeping stale modules around (we only need the one from the
1004 # last run), we use a dict keyed with the full path to the script, so
1004 # last run), we use a dict keyed with the full path to the script, so
1005 # only the last version of the module is held in the cache. Note,
1005 # only the last version of the module is held in the cache. Note,
1006 # however, that we must cache the module *namespace contents* (their
1006 # however, that we must cache the module *namespace contents* (their
1007 # __dict__). Because if we try to cache the actual modules, old ones
1007 # __dict__). Because if we try to cache the actual modules, old ones
1008 # (uncached) could be destroyed while still holding references (such as
1008 # (uncached) could be destroyed while still holding references (such as
1009 # those held by GUI objects that tend to be long-lived)>
1009 # those held by GUI objects that tend to be long-lived)>
1010 #
1010 #
1011 # The %reset command will flush this cache. See the cache_main_mod()
1011 # The %reset command will flush this cache. See the cache_main_mod()
1012 # and clear_main_mod_cache() methods for details on use.
1012 # and clear_main_mod_cache() methods for details on use.
1013
1013
1014 # This is the cache used for 'main' namespaces
1014 # This is the cache used for 'main' namespaces
1015 self._main_mod_cache = {}
1015 self._main_mod_cache = {}
1016
1016
1017 # A table holding all the namespaces IPython deals with, so that
1017 # A table holding all the namespaces IPython deals with, so that
1018 # introspection facilities can search easily.
1018 # introspection facilities can search easily.
1019 self.ns_table = {'user_global':self.user_module.__dict__,
1019 self.ns_table = {'user_global':self.user_module.__dict__,
1020 'user_local':self.user_ns,
1020 'user_local':self.user_ns,
1021 'builtin':builtin_mod.__dict__
1021 'builtin':builtin_mod.__dict__
1022 }
1022 }
1023
1023
1024 @property
1024 @property
1025 def user_global_ns(self):
1025 def user_global_ns(self):
1026 return self.user_module.__dict__
1026 return self.user_module.__dict__
1027
1027
1028 def prepare_user_module(self, user_module=None, user_ns=None):
1028 def prepare_user_module(self, user_module=None, user_ns=None):
1029 """Prepare the module and namespace in which user code will be run.
1029 """Prepare the module and namespace in which user code will be run.
1030
1030
1031 When IPython is started normally, both parameters are None: a new module
1031 When IPython is started normally, both parameters are None: a new module
1032 is created automatically, and its __dict__ used as the namespace.
1032 is created automatically, and its __dict__ used as the namespace.
1033
1033
1034 If only user_module is provided, its __dict__ is used as the namespace.
1034 If only user_module is provided, its __dict__ is used as the namespace.
1035 If only user_ns is provided, a dummy module is created, and user_ns
1035 If only user_ns is provided, a dummy module is created, and user_ns
1036 becomes the global namespace. If both are provided (as they may be
1036 becomes the global namespace. If both are provided (as they may be
1037 when embedding), user_ns is the local namespace, and user_module
1037 when embedding), user_ns is the local namespace, and user_module
1038 provides the global namespace.
1038 provides the global namespace.
1039
1039
1040 Parameters
1040 Parameters
1041 ----------
1041 ----------
1042 user_module : module, optional
1042 user_module : module, optional
1043 The current user module in which IPython is being run. If None,
1043 The current user module in which IPython is being run. If None,
1044 a clean module will be created.
1044 a clean module will be created.
1045 user_ns : dict, optional
1045 user_ns : dict, optional
1046 A namespace in which to run interactive commands.
1046 A namespace in which to run interactive commands.
1047
1047
1048 Returns
1048 Returns
1049 -------
1049 -------
1050 A tuple of user_module and user_ns, each properly initialised.
1050 A tuple of user_module and user_ns, each properly initialised.
1051 """
1051 """
1052 if user_module is None and user_ns is not None:
1052 if user_module is None and user_ns is not None:
1053 user_ns.setdefault("__name__", "__main__")
1053 user_ns.setdefault("__name__", "__main__")
1054 user_module = DummyMod()
1054 user_module = DummyMod()
1055 user_module.__dict__ = user_ns
1055 user_module.__dict__ = user_ns
1056
1056
1057 if user_module is None:
1057 if user_module is None:
1058 user_module = types.ModuleType("__main__",
1058 user_module = types.ModuleType("__main__",
1059 doc="Automatically created module for IPython interactive environment")
1059 doc="Automatically created module for IPython interactive environment")
1060
1060
1061 # We must ensure that __builtin__ (without the final 's') is always
1061 # We must ensure that __builtin__ (without the final 's') is always
1062 # available and pointing to the __builtin__ *module*. For more details:
1062 # available and pointing to the __builtin__ *module*. For more details:
1063 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1063 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1064 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1064 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1065 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1065 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1066
1066
1067 if user_ns is None:
1067 if user_ns is None:
1068 user_ns = user_module.__dict__
1068 user_ns = user_module.__dict__
1069
1069
1070 return user_module, user_ns
1070 return user_module, user_ns
1071
1071
1072 def init_sys_modules(self):
1072 def init_sys_modules(self):
1073 # We need to insert into sys.modules something that looks like a
1073 # We need to insert into sys.modules something that looks like a
1074 # module but which accesses the IPython namespace, for shelve and
1074 # module but which accesses the IPython namespace, for shelve and
1075 # pickle to work interactively. Normally they rely on getting
1075 # pickle to work interactively. Normally they rely on getting
1076 # everything out of __main__, but for embedding purposes each IPython
1076 # everything out of __main__, but for embedding purposes each IPython
1077 # instance has its own private namespace, so we can't go shoving
1077 # instance has its own private namespace, so we can't go shoving
1078 # everything into __main__.
1078 # everything into __main__.
1079
1079
1080 # note, however, that we should only do this for non-embedded
1080 # note, however, that we should only do this for non-embedded
1081 # ipythons, which really mimic the __main__.__dict__ with their own
1081 # ipythons, which really mimic the __main__.__dict__ with their own
1082 # namespace. Embedded instances, on the other hand, should not do
1082 # namespace. Embedded instances, on the other hand, should not do
1083 # this because they need to manage the user local/global namespaces
1083 # this because they need to manage the user local/global namespaces
1084 # only, but they live within a 'normal' __main__ (meaning, they
1084 # only, but they live within a 'normal' __main__ (meaning, they
1085 # shouldn't overtake the execution environment of the script they're
1085 # shouldn't overtake the execution environment of the script they're
1086 # embedded in).
1086 # embedded in).
1087
1087
1088 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1088 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1089 main_name = self.user_module.__name__
1089 main_name = self.user_module.__name__
1090 sys.modules[main_name] = self.user_module
1090 sys.modules[main_name] = self.user_module
1091
1091
1092 def init_user_ns(self):
1092 def init_user_ns(self):
1093 """Initialize all user-visible namespaces to their minimum defaults.
1093 """Initialize all user-visible namespaces to their minimum defaults.
1094
1094
1095 Certain history lists are also initialized here, as they effectively
1095 Certain history lists are also initialized here, as they effectively
1096 act as user namespaces.
1096 act as user namespaces.
1097
1097
1098 Notes
1098 Notes
1099 -----
1099 -----
1100 All data structures here are only filled in, they are NOT reset by this
1100 All data structures here are only filled in, they are NOT reset by this
1101 method. If they were not empty before, data will simply be added to
1101 method. If they were not empty before, data will simply be added to
1102 therm.
1102 therm.
1103 """
1103 """
1104 # This function works in two parts: first we put a few things in
1104 # This function works in two parts: first we put a few things in
1105 # user_ns, and we sync that contents into user_ns_hidden so that these
1105 # user_ns, and we sync that contents into user_ns_hidden so that these
1106 # initial variables aren't shown by %who. After the sync, we add the
1106 # initial variables aren't shown by %who. After the sync, we add the
1107 # rest of what we *do* want the user to see with %who even on a new
1107 # rest of what we *do* want the user to see with %who even on a new
1108 # session (probably nothing, so theye really only see their own stuff)
1108 # session (probably nothing, so theye really only see their own stuff)
1109
1109
1110 # The user dict must *always* have a __builtin__ reference to the
1110 # The user dict must *always* have a __builtin__ reference to the
1111 # Python standard __builtin__ namespace, which must be imported.
1111 # Python standard __builtin__ namespace, which must be imported.
1112 # This is so that certain operations in prompt evaluation can be
1112 # This is so that certain operations in prompt evaluation can be
1113 # reliably executed with builtins. Note that we can NOT use
1113 # reliably executed with builtins. Note that we can NOT use
1114 # __builtins__ (note the 's'), because that can either be a dict or a
1114 # __builtins__ (note the 's'), because that can either be a dict or a
1115 # module, and can even mutate at runtime, depending on the context
1115 # module, and can even mutate at runtime, depending on the context
1116 # (Python makes no guarantees on it). In contrast, __builtin__ is
1116 # (Python makes no guarantees on it). In contrast, __builtin__ is
1117 # always a module object, though it must be explicitly imported.
1117 # always a module object, though it must be explicitly imported.
1118
1118
1119 # For more details:
1119 # For more details:
1120 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1120 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1121 ns = dict()
1121 ns = dict()
1122
1122
1123 # Put 'help' in the user namespace
1123 # Put 'help' in the user namespace
1124 try:
1124 try:
1125 from site import _Helper
1125 from site import _Helper
1126 ns['help'] = _Helper()
1126 ns['help'] = _Helper()
1127 except ImportError:
1127 except ImportError:
1128 warn('help() not available - check site.py')
1128 warn('help() not available - check site.py')
1129
1129
1130 # make global variables for user access to the histories
1130 # make global variables for user access to the histories
1131 ns['_ih'] = self.history_manager.input_hist_parsed
1131 ns['_ih'] = self.history_manager.input_hist_parsed
1132 ns['_oh'] = self.history_manager.output_hist
1132 ns['_oh'] = self.history_manager.output_hist
1133 ns['_dh'] = self.history_manager.dir_hist
1133 ns['_dh'] = self.history_manager.dir_hist
1134
1134
1135 ns['_sh'] = shadowns
1135 ns['_sh'] = shadowns
1136
1136
1137 # user aliases to input and output histories. These shouldn't show up
1137 # user aliases to input and output histories. These shouldn't show up
1138 # in %who, as they can have very large reprs.
1138 # in %who, as they can have very large reprs.
1139 ns['In'] = self.history_manager.input_hist_parsed
1139 ns['In'] = self.history_manager.input_hist_parsed
1140 ns['Out'] = self.history_manager.output_hist
1140 ns['Out'] = self.history_manager.output_hist
1141
1141
1142 # Store myself as the public api!!!
1142 # Store myself as the public api!!!
1143 ns['get_ipython'] = self.get_ipython
1143 ns['get_ipython'] = self.get_ipython
1144
1144
1145 ns['exit'] = self.exiter
1145 ns['exit'] = self.exiter
1146 ns['quit'] = self.exiter
1146 ns['quit'] = self.exiter
1147
1147
1148 # Sync what we've added so far to user_ns_hidden so these aren't seen
1148 # Sync what we've added so far to user_ns_hidden so these aren't seen
1149 # by %who
1149 # by %who
1150 self.user_ns_hidden.update(ns)
1150 self.user_ns_hidden.update(ns)
1151
1151
1152 # Anything put into ns now would show up in %who. Think twice before
1152 # Anything put into ns now would show up in %who. Think twice before
1153 # putting anything here, as we really want %who to show the user their
1153 # putting anything here, as we really want %who to show the user their
1154 # stuff, not our variables.
1154 # stuff, not our variables.
1155
1155
1156 # Finally, update the real user's namespace
1156 # Finally, update the real user's namespace
1157 self.user_ns.update(ns)
1157 self.user_ns.update(ns)
1158
1158
1159 @property
1159 @property
1160 def all_ns_refs(self):
1160 def all_ns_refs(self):
1161 """Get a list of references to all the namespace dictionaries in which
1161 """Get a list of references to all the namespace dictionaries in which
1162 IPython might store a user-created object.
1162 IPython might store a user-created object.
1163
1163
1164 Note that this does not include the displayhook, which also caches
1164 Note that this does not include the displayhook, which also caches
1165 objects from the output."""
1165 objects from the output."""
1166 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1166 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1167 [m.__dict__ for m in self._main_mod_cache.values()]
1167 [m.__dict__ for m in self._main_mod_cache.values()]
1168
1168
1169 def reset(self, new_session=True):
1169 def reset(self, new_session=True):
1170 """Clear all internal namespaces, and attempt to release references to
1170 """Clear all internal namespaces, and attempt to release references to
1171 user objects.
1171 user objects.
1172
1172
1173 If new_session is True, a new history session will be opened.
1173 If new_session is True, a new history session will be opened.
1174 """
1174 """
1175 # Clear histories
1175 # Clear histories
1176 self.history_manager.reset(new_session)
1176 self.history_manager.reset(new_session)
1177 # Reset counter used to index all histories
1177 # Reset counter used to index all histories
1178 if new_session:
1178 if new_session:
1179 self.execution_count = 1
1179 self.execution_count = 1
1180
1180
1181 # Flush cached output items
1181 # Flush cached output items
1182 if self.displayhook.do_full_cache:
1182 if self.displayhook.do_full_cache:
1183 self.displayhook.flush()
1183 self.displayhook.flush()
1184
1184
1185 # The main execution namespaces must be cleared very carefully,
1185 # The main execution namespaces must be cleared very carefully,
1186 # skipping the deletion of the builtin-related keys, because doing so
1186 # skipping the deletion of the builtin-related keys, because doing so
1187 # would cause errors in many object's __del__ methods.
1187 # would cause errors in many object's __del__ methods.
1188 if self.user_ns is not self.user_global_ns:
1188 if self.user_ns is not self.user_global_ns:
1189 self.user_ns.clear()
1189 self.user_ns.clear()
1190 ns = self.user_global_ns
1190 ns = self.user_global_ns
1191 drop_keys = set(ns.keys())
1191 drop_keys = set(ns.keys())
1192 drop_keys.discard('__builtin__')
1192 drop_keys.discard('__builtin__')
1193 drop_keys.discard('__builtins__')
1193 drop_keys.discard('__builtins__')
1194 drop_keys.discard('__name__')
1194 drop_keys.discard('__name__')
1195 for k in drop_keys:
1195 for k in drop_keys:
1196 del ns[k]
1196 del ns[k]
1197
1197
1198 self.user_ns_hidden.clear()
1198 self.user_ns_hidden.clear()
1199
1199
1200 # Restore the user namespaces to minimal usability
1200 # Restore the user namespaces to minimal usability
1201 self.init_user_ns()
1201 self.init_user_ns()
1202
1202
1203 # Restore the default and user aliases
1203 # Restore the default and user aliases
1204 self.alias_manager.clear_aliases()
1204 self.alias_manager.clear_aliases()
1205 self.alias_manager.init_aliases()
1205 self.alias_manager.init_aliases()
1206
1206
1207 # Flush the private list of module references kept for script
1207 # Flush the private list of module references kept for script
1208 # execution protection
1208 # execution protection
1209 self.clear_main_mod_cache()
1209 self.clear_main_mod_cache()
1210
1210
1211 def del_var(self, varname, by_name=False):
1211 def del_var(self, varname, by_name=False):
1212 """Delete a variable from the various namespaces, so that, as
1212 """Delete a variable from the various namespaces, so that, as
1213 far as possible, we're not keeping any hidden references to it.
1213 far as possible, we're not keeping any hidden references to it.
1214
1214
1215 Parameters
1215 Parameters
1216 ----------
1216 ----------
1217 varname : str
1217 varname : str
1218 The name of the variable to delete.
1218 The name of the variable to delete.
1219 by_name : bool
1219 by_name : bool
1220 If True, delete variables with the given name in each
1220 If True, delete variables with the given name in each
1221 namespace. If False (default), find the variable in the user
1221 namespace. If False (default), find the variable in the user
1222 namespace, and delete references to it.
1222 namespace, and delete references to it.
1223 """
1223 """
1224 if varname in ('__builtin__', '__builtins__'):
1224 if varname in ('__builtin__', '__builtins__'):
1225 raise ValueError("Refusing to delete %s" % varname)
1225 raise ValueError("Refusing to delete %s" % varname)
1226
1226
1227 ns_refs = self.all_ns_refs
1227 ns_refs = self.all_ns_refs
1228
1228
1229 if by_name: # Delete by name
1229 if by_name: # Delete by name
1230 for ns in ns_refs:
1230 for ns in ns_refs:
1231 try:
1231 try:
1232 del ns[varname]
1232 del ns[varname]
1233 except KeyError:
1233 except KeyError:
1234 pass
1234 pass
1235 else: # Delete by object
1235 else: # Delete by object
1236 try:
1236 try:
1237 obj = self.user_ns[varname]
1237 obj = self.user_ns[varname]
1238 except KeyError:
1238 except KeyError:
1239 raise NameError("name '%s' is not defined" % varname)
1239 raise NameError("name '%s' is not defined" % varname)
1240 # Also check in output history
1240 # Also check in output history
1241 ns_refs.append(self.history_manager.output_hist)
1241 ns_refs.append(self.history_manager.output_hist)
1242 for ns in ns_refs:
1242 for ns in ns_refs:
1243 to_delete = [n for n, o in ns.iteritems() if o is obj]
1243 to_delete = [n for n, o in ns.iteritems() if o is obj]
1244 for name in to_delete:
1244 for name in to_delete:
1245 del ns[name]
1245 del ns[name]
1246
1246
1247 # displayhook keeps extra references, but not in a dictionary
1247 # displayhook keeps extra references, but not in a dictionary
1248 for name in ('_', '__', '___'):
1248 for name in ('_', '__', '___'):
1249 if getattr(self.displayhook, name) is obj:
1249 if getattr(self.displayhook, name) is obj:
1250 setattr(self.displayhook, name, None)
1250 setattr(self.displayhook, name, None)
1251
1251
1252 def reset_selective(self, regex=None):
1252 def reset_selective(self, regex=None):
1253 """Clear selective variables from internal namespaces based on a
1253 """Clear selective variables from internal namespaces based on a
1254 specified regular expression.
1254 specified regular expression.
1255
1255
1256 Parameters
1256 Parameters
1257 ----------
1257 ----------
1258 regex : string or compiled pattern, optional
1258 regex : string or compiled pattern, optional
1259 A regular expression pattern that will be used in searching
1259 A regular expression pattern that will be used in searching
1260 variable names in the users namespaces.
1260 variable names in the users namespaces.
1261 """
1261 """
1262 if regex is not None:
1262 if regex is not None:
1263 try:
1263 try:
1264 m = re.compile(regex)
1264 m = re.compile(regex)
1265 except TypeError:
1265 except TypeError:
1266 raise TypeError('regex must be a string or compiled pattern')
1266 raise TypeError('regex must be a string or compiled pattern')
1267 # Search for keys in each namespace that match the given regex
1267 # Search for keys in each namespace that match the given regex
1268 # If a match is found, delete the key/value pair.
1268 # If a match is found, delete the key/value pair.
1269 for ns in self.all_ns_refs:
1269 for ns in self.all_ns_refs:
1270 for var in ns:
1270 for var in ns:
1271 if m.search(var):
1271 if m.search(var):
1272 del ns[var]
1272 del ns[var]
1273
1273
1274 def push(self, variables, interactive=True):
1274 def push(self, variables, interactive=True):
1275 """Inject a group of variables into the IPython user namespace.
1275 """Inject a group of variables into the IPython user namespace.
1276
1276
1277 Parameters
1277 Parameters
1278 ----------
1278 ----------
1279 variables : dict, str or list/tuple of str
1279 variables : dict, str or list/tuple of str
1280 The variables to inject into the user's namespace. If a dict, a
1280 The variables to inject into the user's namespace. If a dict, a
1281 simple update is done. If a str, the string is assumed to have
1281 simple update is done. If a str, the string is assumed to have
1282 variable names separated by spaces. A list/tuple of str can also
1282 variable names separated by spaces. A list/tuple of str can also
1283 be used to give the variable names. If just the variable names are
1283 be used to give the variable names. If just the variable names are
1284 give (list/tuple/str) then the variable values looked up in the
1284 give (list/tuple/str) then the variable values looked up in the
1285 callers frame.
1285 callers frame.
1286 interactive : bool
1286 interactive : bool
1287 If True (default), the variables will be listed with the ``who``
1287 If True (default), the variables will be listed with the ``who``
1288 magic.
1288 magic.
1289 """
1289 """
1290 vdict = None
1290 vdict = None
1291
1291
1292 # We need a dict of name/value pairs to do namespace updates.
1292 # We need a dict of name/value pairs to do namespace updates.
1293 if isinstance(variables, dict):
1293 if isinstance(variables, dict):
1294 vdict = variables
1294 vdict = variables
1295 elif isinstance(variables, (basestring, list, tuple)):
1295 elif isinstance(variables, (basestring, list, tuple)):
1296 if isinstance(variables, basestring):
1296 if isinstance(variables, basestring):
1297 vlist = variables.split()
1297 vlist = variables.split()
1298 else:
1298 else:
1299 vlist = variables
1299 vlist = variables
1300 vdict = {}
1300 vdict = {}
1301 cf = sys._getframe(1)
1301 cf = sys._getframe(1)
1302 for name in vlist:
1302 for name in vlist:
1303 try:
1303 try:
1304 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1304 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1305 except:
1305 except:
1306 print('Could not get variable %s from %s' %
1306 print('Could not get variable %s from %s' %
1307 (name,cf.f_code.co_name))
1307 (name,cf.f_code.co_name))
1308 else:
1308 else:
1309 raise ValueError('variables must be a dict/str/list/tuple')
1309 raise ValueError('variables must be a dict/str/list/tuple')
1310
1310
1311 # Propagate variables to user namespace
1311 # Propagate variables to user namespace
1312 self.user_ns.update(vdict)
1312 self.user_ns.update(vdict)
1313
1313
1314 # And configure interactive visibility
1314 # And configure interactive visibility
1315 user_ns_hidden = self.user_ns_hidden
1315 user_ns_hidden = self.user_ns_hidden
1316 if interactive:
1316 if interactive:
1317 for name in vdict:
1317 for name in vdict:
1318 user_ns_hidden.pop(name, None)
1318 user_ns_hidden.pop(name, None)
1319 else:
1319 else:
1320 user_ns_hidden.update(vdict)
1320 user_ns_hidden.update(vdict)
1321
1321
1322 def drop_by_id(self, variables):
1322 def drop_by_id(self, variables):
1323 """Remove a dict of variables from the user namespace, if they are the
1323 """Remove a dict of variables from the user namespace, if they are the
1324 same as the values in the dictionary.
1324 same as the values in the dictionary.
1325
1325
1326 This is intended for use by extensions: variables that they've added can
1326 This is intended for use by extensions: variables that they've added can
1327 be taken back out if they are unloaded, without removing any that the
1327 be taken back out if they are unloaded, without removing any that the
1328 user has overwritten.
1328 user has overwritten.
1329
1329
1330 Parameters
1330 Parameters
1331 ----------
1331 ----------
1332 variables : dict
1332 variables : dict
1333 A dictionary mapping object names (as strings) to the objects.
1333 A dictionary mapping object names (as strings) to the objects.
1334 """
1334 """
1335 for name, obj in variables.iteritems():
1335 for name, obj in variables.iteritems():
1336 if name in self.user_ns and self.user_ns[name] is obj:
1336 if name in self.user_ns and self.user_ns[name] is obj:
1337 del self.user_ns[name]
1337 del self.user_ns[name]
1338 self.user_ns_hidden.pop(name, None)
1338 self.user_ns_hidden.pop(name, None)
1339
1339
1340 #-------------------------------------------------------------------------
1340 #-------------------------------------------------------------------------
1341 # Things related to object introspection
1341 # Things related to object introspection
1342 #-------------------------------------------------------------------------
1342 #-------------------------------------------------------------------------
1343
1343
1344 def _ofind(self, oname, namespaces=None):
1344 def _ofind(self, oname, namespaces=None):
1345 """Find an object in the available namespaces.
1345 """Find an object in the available namespaces.
1346
1346
1347 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1347 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1348
1348
1349 Has special code to detect magic functions.
1349 Has special code to detect magic functions.
1350 """
1350 """
1351 oname = oname.strip()
1351 oname = oname.strip()
1352 #print '1- oname: <%r>' % oname # dbg
1352 #print '1- oname: <%r>' % oname # dbg
1353 if not oname.startswith(ESC_MAGIC) and \
1353 if not oname.startswith(ESC_MAGIC) and \
1354 not oname.startswith(ESC_MAGIC2) and \
1354 not oname.startswith(ESC_MAGIC2) and \
1355 not py3compat.isidentifier(oname, dotted=True):
1355 not py3compat.isidentifier(oname, dotted=True):
1356 return dict(found=False)
1356 return dict(found=False)
1357
1357
1358 alias_ns = None
1358 alias_ns = None
1359 if namespaces is None:
1359 if namespaces is None:
1360 # Namespaces to search in:
1360 # Namespaces to search in:
1361 # Put them in a list. The order is important so that we
1361 # Put them in a list. The order is important so that we
1362 # find things in the same order that Python finds them.
1362 # find things in the same order that Python finds them.
1363 namespaces = [ ('Interactive', self.user_ns),
1363 namespaces = [ ('Interactive', self.user_ns),
1364 ('Interactive (global)', self.user_global_ns),
1364 ('Interactive (global)', self.user_global_ns),
1365 ('Python builtin', builtin_mod.__dict__),
1365 ('Python builtin', builtin_mod.__dict__),
1366 ('Alias', self.alias_manager.alias_table),
1367 ]
1366 ]
1368 alias_ns = self.alias_manager.alias_table
1369
1367
1370 # initialize results to 'null'
1368 # initialize results to 'null'
1371 found = False; obj = None; ospace = None; ds = None;
1369 found = False; obj = None; ospace = None; ds = None;
1372 ismagic = False; isalias = False; parent = None
1370 ismagic = False; isalias = False; parent = None
1373
1371
1374 # We need to special-case 'print', which as of python2.6 registers as a
1372 # We need to special-case 'print', which as of python2.6 registers as a
1375 # function but should only be treated as one if print_function was
1373 # function but should only be treated as one if print_function was
1376 # loaded with a future import. In this case, just bail.
1374 # loaded with a future import. In this case, just bail.
1377 if (oname == 'print' and not py3compat.PY3 and not \
1375 if (oname == 'print' and not py3compat.PY3 and not \
1378 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1376 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1379 return {'found':found, 'obj':obj, 'namespace':ospace,
1377 return {'found':found, 'obj':obj, 'namespace':ospace,
1380 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1378 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1381
1379
1382 # Look for the given name by splitting it in parts. If the head is
1380 # Look for the given name by splitting it in parts. If the head is
1383 # found, then we look for all the remaining parts as members, and only
1381 # found, then we look for all the remaining parts as members, and only
1384 # declare success if we can find them all.
1382 # declare success if we can find them all.
1385 oname_parts = oname.split('.')
1383 oname_parts = oname.split('.')
1386 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1384 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1387 for nsname,ns in namespaces:
1385 for nsname,ns in namespaces:
1388 try:
1386 try:
1389 obj = ns[oname_head]
1387 obj = ns[oname_head]
1390 except KeyError:
1388 except KeyError:
1391 continue
1389 continue
1392 else:
1390 else:
1393 #print 'oname_rest:', oname_rest # dbg
1391 #print 'oname_rest:', oname_rest # dbg
1394 for part in oname_rest:
1392 for part in oname_rest:
1395 try:
1393 try:
1396 parent = obj
1394 parent = obj
1397 obj = getattr(obj,part)
1395 obj = getattr(obj,part)
1398 except:
1396 except:
1399 # Blanket except b/c some badly implemented objects
1397 # Blanket except b/c some badly implemented objects
1400 # allow __getattr__ to raise exceptions other than
1398 # allow __getattr__ to raise exceptions other than
1401 # AttributeError, which then crashes IPython.
1399 # AttributeError, which then crashes IPython.
1402 break
1400 break
1403 else:
1401 else:
1404 # If we finish the for loop (no break), we got all members
1402 # If we finish the for loop (no break), we got all members
1405 found = True
1403 found = True
1406 ospace = nsname
1404 ospace = nsname
1407 if ns == alias_ns:
1408 isalias = True
1409 break # namespace loop
1405 break # namespace loop
1410
1406
1411 # Try to see if it's magic
1407 # Try to see if it's magic
1412 if not found:
1408 if not found:
1413 obj = None
1409 obj = None
1414 if oname.startswith(ESC_MAGIC2):
1410 if oname.startswith(ESC_MAGIC2):
1415 oname = oname.lstrip(ESC_MAGIC2)
1411 oname = oname.lstrip(ESC_MAGIC2)
1416 obj = self.find_cell_magic(oname)
1412 obj = self.find_cell_magic(oname)
1417 elif oname.startswith(ESC_MAGIC):
1413 elif oname.startswith(ESC_MAGIC):
1418 oname = oname.lstrip(ESC_MAGIC)
1414 oname = oname.lstrip(ESC_MAGIC)
1419 obj = self.find_line_magic(oname)
1415 obj = self.find_line_magic(oname)
1420 else:
1416 else:
1421 # search without prefix, so run? will find %run?
1417 # search without prefix, so run? will find %run?
1422 obj = self.find_line_magic(oname)
1418 obj = self.find_line_magic(oname)
1423 if obj is None:
1419 if obj is None:
1424 obj = self.find_cell_magic(oname)
1420 obj = self.find_cell_magic(oname)
1425 if obj is not None:
1421 if obj is not None:
1426 found = True
1422 found = True
1427 ospace = 'IPython internal'
1423 ospace = 'IPython internal'
1428 ismagic = True
1424 ismagic = True
1429
1425
1430 # Last try: special-case some literals like '', [], {}, etc:
1426 # Last try: special-case some literals like '', [], {}, etc:
1431 if not found and oname_head in ["''",'""','[]','{}','()']:
1427 if not found and oname_head in ["''",'""','[]','{}','()']:
1432 obj = eval(oname_head)
1428 obj = eval(oname_head)
1433 found = True
1429 found = True
1434 ospace = 'Interactive'
1430 ospace = 'Interactive'
1435
1431
1436 return {'found':found, 'obj':obj, 'namespace':ospace,
1432 return {'found':found, 'obj':obj, 'namespace':ospace,
1437 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1433 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1438
1434
1439 def _ofind_property(self, oname, info):
1435 def _ofind_property(self, oname, info):
1440 """Second part of object finding, to look for property details."""
1436 """Second part of object finding, to look for property details."""
1441 if info.found:
1437 if info.found:
1442 # Get the docstring of the class property if it exists.
1438 # Get the docstring of the class property if it exists.
1443 path = oname.split('.')
1439 path = oname.split('.')
1444 root = '.'.join(path[:-1])
1440 root = '.'.join(path[:-1])
1445 if info.parent is not None:
1441 if info.parent is not None:
1446 try:
1442 try:
1447 target = getattr(info.parent, '__class__')
1443 target = getattr(info.parent, '__class__')
1448 # The object belongs to a class instance.
1444 # The object belongs to a class instance.
1449 try:
1445 try:
1450 target = getattr(target, path[-1])
1446 target = getattr(target, path[-1])
1451 # The class defines the object.
1447 # The class defines the object.
1452 if isinstance(target, property):
1448 if isinstance(target, property):
1453 oname = root + '.__class__.' + path[-1]
1449 oname = root + '.__class__.' + path[-1]
1454 info = Struct(self._ofind(oname))
1450 info = Struct(self._ofind(oname))
1455 except AttributeError: pass
1451 except AttributeError: pass
1456 except AttributeError: pass
1452 except AttributeError: pass
1457
1453
1458 # We return either the new info or the unmodified input if the object
1454 # We return either the new info or the unmodified input if the object
1459 # hadn't been found
1455 # hadn't been found
1460 return info
1456 return info
1461
1457
1462 def _object_find(self, oname, namespaces=None):
1458 def _object_find(self, oname, namespaces=None):
1463 """Find an object and return a struct with info about it."""
1459 """Find an object and return a struct with info about it."""
1464 inf = Struct(self._ofind(oname, namespaces))
1460 inf = Struct(self._ofind(oname, namespaces))
1465 return Struct(self._ofind_property(oname, inf))
1461 return Struct(self._ofind_property(oname, inf))
1466
1462
1467 def _inspect(self, meth, oname, namespaces=None, **kw):
1463 def _inspect(self, meth, oname, namespaces=None, **kw):
1468 """Generic interface to the inspector system.
1464 """Generic interface to the inspector system.
1469
1465
1470 This function is meant to be called by pdef, pdoc & friends."""
1466 This function is meant to be called by pdef, pdoc & friends."""
1471 info = self._object_find(oname, namespaces)
1467 info = self._object_find(oname, namespaces)
1472 if info.found:
1468 if info.found:
1473 pmethod = getattr(self.inspector, meth)
1469 pmethod = getattr(self.inspector, meth)
1474 formatter = format_screen if info.ismagic else None
1470 formatter = format_screen if info.ismagic else None
1475 if meth == 'pdoc':
1471 if meth == 'pdoc':
1476 pmethod(info.obj, oname, formatter)
1472 pmethod(info.obj, oname, formatter)
1477 elif meth == 'pinfo':
1473 elif meth == 'pinfo':
1478 pmethod(info.obj, oname, formatter, info, **kw)
1474 pmethod(info.obj, oname, formatter, info, **kw)
1479 else:
1475 else:
1480 pmethod(info.obj, oname)
1476 pmethod(info.obj, oname)
1481 else:
1477 else:
1482 print('Object `%s` not found.' % oname)
1478 print('Object `%s` not found.' % oname)
1483 return 'not found' # so callers can take other action
1479 return 'not found' # so callers can take other action
1484
1480
1485 def object_inspect(self, oname, detail_level=0):
1481 def object_inspect(self, oname, detail_level=0):
1486 with self.builtin_trap:
1482 with self.builtin_trap:
1487 info = self._object_find(oname)
1483 info = self._object_find(oname)
1488 if info.found:
1484 if info.found:
1489 return self.inspector.info(info.obj, oname, info=info,
1485 return self.inspector.info(info.obj, oname, info=info,
1490 detail_level=detail_level
1486 detail_level=detail_level
1491 )
1487 )
1492 else:
1488 else:
1493 return oinspect.object_info(name=oname, found=False)
1489 return oinspect.object_info(name=oname, found=False)
1494
1490
1495 #-------------------------------------------------------------------------
1491 #-------------------------------------------------------------------------
1496 # Things related to history management
1492 # Things related to history management
1497 #-------------------------------------------------------------------------
1493 #-------------------------------------------------------------------------
1498
1494
1499 def init_history(self):
1495 def init_history(self):
1500 """Sets up the command history, and starts regular autosaves."""
1496 """Sets up the command history, and starts regular autosaves."""
1501 self.history_manager = HistoryManager(shell=self, parent=self)
1497 self.history_manager = HistoryManager(shell=self, parent=self)
1502 self.configurables.append(self.history_manager)
1498 self.configurables.append(self.history_manager)
1503
1499
1504 #-------------------------------------------------------------------------
1500 #-------------------------------------------------------------------------
1505 # Things related to exception handling and tracebacks (not debugging)
1501 # Things related to exception handling and tracebacks (not debugging)
1506 #-------------------------------------------------------------------------
1502 #-------------------------------------------------------------------------
1507
1503
1508 def init_traceback_handlers(self, custom_exceptions):
1504 def init_traceback_handlers(self, custom_exceptions):
1509 # Syntax error handler.
1505 # Syntax error handler.
1510 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1506 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1511
1507
1512 # The interactive one is initialized with an offset, meaning we always
1508 # The interactive one is initialized with an offset, meaning we always
1513 # want to remove the topmost item in the traceback, which is our own
1509 # want to remove the topmost item in the traceback, which is our own
1514 # internal code. Valid modes: ['Plain','Context','Verbose']
1510 # internal code. Valid modes: ['Plain','Context','Verbose']
1515 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1511 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1516 color_scheme='NoColor',
1512 color_scheme='NoColor',
1517 tb_offset = 1,
1513 tb_offset = 1,
1518 check_cache=check_linecache_ipython)
1514 check_cache=check_linecache_ipython)
1519
1515
1520 # The instance will store a pointer to the system-wide exception hook,
1516 # The instance will store a pointer to the system-wide exception hook,
1521 # so that runtime code (such as magics) can access it. This is because
1517 # so that runtime code (such as magics) can access it. This is because
1522 # during the read-eval loop, it may get temporarily overwritten.
1518 # during the read-eval loop, it may get temporarily overwritten.
1523 self.sys_excepthook = sys.excepthook
1519 self.sys_excepthook = sys.excepthook
1524
1520
1525 # and add any custom exception handlers the user may have specified
1521 # and add any custom exception handlers the user may have specified
1526 self.set_custom_exc(*custom_exceptions)
1522 self.set_custom_exc(*custom_exceptions)
1527
1523
1528 # Set the exception mode
1524 # Set the exception mode
1529 self.InteractiveTB.set_mode(mode=self.xmode)
1525 self.InteractiveTB.set_mode(mode=self.xmode)
1530
1526
1531 def set_custom_exc(self, exc_tuple, handler):
1527 def set_custom_exc(self, exc_tuple, handler):
1532 """set_custom_exc(exc_tuple,handler)
1528 """set_custom_exc(exc_tuple,handler)
1533
1529
1534 Set a custom exception handler, which will be called if any of the
1530 Set a custom exception handler, which will be called if any of the
1535 exceptions in exc_tuple occur in the mainloop (specifically, in the
1531 exceptions in exc_tuple occur in the mainloop (specifically, in the
1536 run_code() method).
1532 run_code() method).
1537
1533
1538 Parameters
1534 Parameters
1539 ----------
1535 ----------
1540
1536
1541 exc_tuple : tuple of exception classes
1537 exc_tuple : tuple of exception classes
1542 A *tuple* of exception classes, for which to call the defined
1538 A *tuple* of exception classes, for which to call the defined
1543 handler. It is very important that you use a tuple, and NOT A
1539 handler. It is very important that you use a tuple, and NOT A
1544 LIST here, because of the way Python's except statement works. If
1540 LIST here, because of the way Python's except statement works. If
1545 you only want to trap a single exception, use a singleton tuple::
1541 you only want to trap a single exception, use a singleton tuple::
1546
1542
1547 exc_tuple == (MyCustomException,)
1543 exc_tuple == (MyCustomException,)
1548
1544
1549 handler : callable
1545 handler : callable
1550 handler must have the following signature::
1546 handler must have the following signature::
1551
1547
1552 def my_handler(self, etype, value, tb, tb_offset=None):
1548 def my_handler(self, etype, value, tb, tb_offset=None):
1553 ...
1549 ...
1554 return structured_traceback
1550 return structured_traceback
1555
1551
1556 Your handler must return a structured traceback (a list of strings),
1552 Your handler must return a structured traceback (a list of strings),
1557 or None.
1553 or None.
1558
1554
1559 This will be made into an instance method (via types.MethodType)
1555 This will be made into an instance method (via types.MethodType)
1560 of IPython itself, and it will be called if any of the exceptions
1556 of IPython itself, and it will be called if any of the exceptions
1561 listed in the exc_tuple are caught. If the handler is None, an
1557 listed in the exc_tuple are caught. If the handler is None, an
1562 internal basic one is used, which just prints basic info.
1558 internal basic one is used, which just prints basic info.
1563
1559
1564 To protect IPython from crashes, if your handler ever raises an
1560 To protect IPython from crashes, if your handler ever raises an
1565 exception or returns an invalid result, it will be immediately
1561 exception or returns an invalid result, it will be immediately
1566 disabled.
1562 disabled.
1567
1563
1568 WARNING: by putting in your own exception handler into IPython's main
1564 WARNING: by putting in your own exception handler into IPython's main
1569 execution loop, you run a very good chance of nasty crashes. This
1565 execution loop, you run a very good chance of nasty crashes. This
1570 facility should only be used if you really know what you are doing."""
1566 facility should only be used if you really know what you are doing."""
1571
1567
1572 assert type(exc_tuple)==type(()) , \
1568 assert type(exc_tuple)==type(()) , \
1573 "The custom exceptions must be given AS A TUPLE."
1569 "The custom exceptions must be given AS A TUPLE."
1574
1570
1575 def dummy_handler(self,etype,value,tb,tb_offset=None):
1571 def dummy_handler(self,etype,value,tb,tb_offset=None):
1576 print('*** Simple custom exception handler ***')
1572 print('*** Simple custom exception handler ***')
1577 print('Exception type :',etype)
1573 print('Exception type :',etype)
1578 print('Exception value:',value)
1574 print('Exception value:',value)
1579 print('Traceback :',tb)
1575 print('Traceback :',tb)
1580 #print 'Source code :','\n'.join(self.buffer)
1576 #print 'Source code :','\n'.join(self.buffer)
1581
1577
1582 def validate_stb(stb):
1578 def validate_stb(stb):
1583 """validate structured traceback return type
1579 """validate structured traceback return type
1584
1580
1585 return type of CustomTB *should* be a list of strings, but allow
1581 return type of CustomTB *should* be a list of strings, but allow
1586 single strings or None, which are harmless.
1582 single strings or None, which are harmless.
1587
1583
1588 This function will *always* return a list of strings,
1584 This function will *always* return a list of strings,
1589 and will raise a TypeError if stb is inappropriate.
1585 and will raise a TypeError if stb is inappropriate.
1590 """
1586 """
1591 msg = "CustomTB must return list of strings, not %r" % stb
1587 msg = "CustomTB must return list of strings, not %r" % stb
1592 if stb is None:
1588 if stb is None:
1593 return []
1589 return []
1594 elif isinstance(stb, basestring):
1590 elif isinstance(stb, basestring):
1595 return [stb]
1591 return [stb]
1596 elif not isinstance(stb, list):
1592 elif not isinstance(stb, list):
1597 raise TypeError(msg)
1593 raise TypeError(msg)
1598 # it's a list
1594 # it's a list
1599 for line in stb:
1595 for line in stb:
1600 # check every element
1596 # check every element
1601 if not isinstance(line, basestring):
1597 if not isinstance(line, basestring):
1602 raise TypeError(msg)
1598 raise TypeError(msg)
1603 return stb
1599 return stb
1604
1600
1605 if handler is None:
1601 if handler is None:
1606 wrapped = dummy_handler
1602 wrapped = dummy_handler
1607 else:
1603 else:
1608 def wrapped(self,etype,value,tb,tb_offset=None):
1604 def wrapped(self,etype,value,tb,tb_offset=None):
1609 """wrap CustomTB handler, to protect IPython from user code
1605 """wrap CustomTB handler, to protect IPython from user code
1610
1606
1611 This makes it harder (but not impossible) for custom exception
1607 This makes it harder (but not impossible) for custom exception
1612 handlers to crash IPython.
1608 handlers to crash IPython.
1613 """
1609 """
1614 try:
1610 try:
1615 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1611 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1616 return validate_stb(stb)
1612 return validate_stb(stb)
1617 except:
1613 except:
1618 # clear custom handler immediately
1614 # clear custom handler immediately
1619 self.set_custom_exc((), None)
1615 self.set_custom_exc((), None)
1620 print("Custom TB Handler failed, unregistering", file=io.stderr)
1616 print("Custom TB Handler failed, unregistering", file=io.stderr)
1621 # show the exception in handler first
1617 # show the exception in handler first
1622 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1618 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1623 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1619 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1624 print("The original exception:", file=io.stdout)
1620 print("The original exception:", file=io.stdout)
1625 stb = self.InteractiveTB.structured_traceback(
1621 stb = self.InteractiveTB.structured_traceback(
1626 (etype,value,tb), tb_offset=tb_offset
1622 (etype,value,tb), tb_offset=tb_offset
1627 )
1623 )
1628 return stb
1624 return stb
1629
1625
1630 self.CustomTB = types.MethodType(wrapped,self)
1626 self.CustomTB = types.MethodType(wrapped,self)
1631 self.custom_exceptions = exc_tuple
1627 self.custom_exceptions = exc_tuple
1632
1628
1633 def excepthook(self, etype, value, tb):
1629 def excepthook(self, etype, value, tb):
1634 """One more defense for GUI apps that call sys.excepthook.
1630 """One more defense for GUI apps that call sys.excepthook.
1635
1631
1636 GUI frameworks like wxPython trap exceptions and call
1632 GUI frameworks like wxPython trap exceptions and call
1637 sys.excepthook themselves. I guess this is a feature that
1633 sys.excepthook themselves. I guess this is a feature that
1638 enables them to keep running after exceptions that would
1634 enables them to keep running after exceptions that would
1639 otherwise kill their mainloop. This is a bother for IPython
1635 otherwise kill their mainloop. This is a bother for IPython
1640 which excepts to catch all of the program exceptions with a try:
1636 which excepts to catch all of the program exceptions with a try:
1641 except: statement.
1637 except: statement.
1642
1638
1643 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1639 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1644 any app directly invokes sys.excepthook, it will look to the user like
1640 any app directly invokes sys.excepthook, it will look to the user like
1645 IPython crashed. In order to work around this, we can disable the
1641 IPython crashed. In order to work around this, we can disable the
1646 CrashHandler and replace it with this excepthook instead, which prints a
1642 CrashHandler and replace it with this excepthook instead, which prints a
1647 regular traceback using our InteractiveTB. In this fashion, apps which
1643 regular traceback using our InteractiveTB. In this fashion, apps which
1648 call sys.excepthook will generate a regular-looking exception from
1644 call sys.excepthook will generate a regular-looking exception from
1649 IPython, and the CrashHandler will only be triggered by real IPython
1645 IPython, and the CrashHandler will only be triggered by real IPython
1650 crashes.
1646 crashes.
1651
1647
1652 This hook should be used sparingly, only in places which are not likely
1648 This hook should be used sparingly, only in places which are not likely
1653 to be true IPython errors.
1649 to be true IPython errors.
1654 """
1650 """
1655 self.showtraceback((etype,value,tb),tb_offset=0)
1651 self.showtraceback((etype,value,tb),tb_offset=0)
1656
1652
1657 def _get_exc_info(self, exc_tuple=None):
1653 def _get_exc_info(self, exc_tuple=None):
1658 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1654 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1659
1655
1660 Ensures sys.last_type,value,traceback hold the exc_info we found,
1656 Ensures sys.last_type,value,traceback hold the exc_info we found,
1661 from whichever source.
1657 from whichever source.
1662
1658
1663 raises ValueError if none of these contain any information
1659 raises ValueError if none of these contain any information
1664 """
1660 """
1665 if exc_tuple is None:
1661 if exc_tuple is None:
1666 etype, value, tb = sys.exc_info()
1662 etype, value, tb = sys.exc_info()
1667 else:
1663 else:
1668 etype, value, tb = exc_tuple
1664 etype, value, tb = exc_tuple
1669
1665
1670 if etype is None:
1666 if etype is None:
1671 if hasattr(sys, 'last_type'):
1667 if hasattr(sys, 'last_type'):
1672 etype, value, tb = sys.last_type, sys.last_value, \
1668 etype, value, tb = sys.last_type, sys.last_value, \
1673 sys.last_traceback
1669 sys.last_traceback
1674
1670
1675 if etype is None:
1671 if etype is None:
1676 raise ValueError("No exception to find")
1672 raise ValueError("No exception to find")
1677
1673
1678 # Now store the exception info in sys.last_type etc.
1674 # Now store the exception info in sys.last_type etc.
1679 # WARNING: these variables are somewhat deprecated and not
1675 # WARNING: these variables are somewhat deprecated and not
1680 # necessarily safe to use in a threaded environment, but tools
1676 # necessarily safe to use in a threaded environment, but tools
1681 # like pdb depend on their existence, so let's set them. If we
1677 # like pdb depend on their existence, so let's set them. If we
1682 # find problems in the field, we'll need to revisit their use.
1678 # find problems in the field, we'll need to revisit their use.
1683 sys.last_type = etype
1679 sys.last_type = etype
1684 sys.last_value = value
1680 sys.last_value = value
1685 sys.last_traceback = tb
1681 sys.last_traceback = tb
1686
1682
1687 return etype, value, tb
1683 return etype, value, tb
1688
1684
1689 def show_usage_error(self, exc):
1685 def show_usage_error(self, exc):
1690 """Show a short message for UsageErrors
1686 """Show a short message for UsageErrors
1691
1687
1692 These are special exceptions that shouldn't show a traceback.
1688 These are special exceptions that shouldn't show a traceback.
1693 """
1689 """
1694 self.write_err("UsageError: %s" % exc)
1690 self.write_err("UsageError: %s" % exc)
1695
1691
1696 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1692 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1697 exception_only=False):
1693 exception_only=False):
1698 """Display the exception that just occurred.
1694 """Display the exception that just occurred.
1699
1695
1700 If nothing is known about the exception, this is the method which
1696 If nothing is known about the exception, this is the method which
1701 should be used throughout the code for presenting user tracebacks,
1697 should be used throughout the code for presenting user tracebacks,
1702 rather than directly invoking the InteractiveTB object.
1698 rather than directly invoking the InteractiveTB object.
1703
1699
1704 A specific showsyntaxerror() also exists, but this method can take
1700 A specific showsyntaxerror() also exists, but this method can take
1705 care of calling it if needed, so unless you are explicitly catching a
1701 care of calling it if needed, so unless you are explicitly catching a
1706 SyntaxError exception, don't try to analyze the stack manually and
1702 SyntaxError exception, don't try to analyze the stack manually and
1707 simply call this method."""
1703 simply call this method."""
1708
1704
1709 try:
1705 try:
1710 try:
1706 try:
1711 etype, value, tb = self._get_exc_info(exc_tuple)
1707 etype, value, tb = self._get_exc_info(exc_tuple)
1712 except ValueError:
1708 except ValueError:
1713 self.write_err('No traceback available to show.\n')
1709 self.write_err('No traceback available to show.\n')
1714 return
1710 return
1715
1711
1716 if issubclass(etype, SyntaxError):
1712 if issubclass(etype, SyntaxError):
1717 # Though this won't be called by syntax errors in the input
1713 # Though this won't be called by syntax errors in the input
1718 # line, there may be SyntaxError cases with imported code.
1714 # line, there may be SyntaxError cases with imported code.
1719 self.showsyntaxerror(filename)
1715 self.showsyntaxerror(filename)
1720 elif etype is UsageError:
1716 elif etype is UsageError:
1721 self.show_usage_error(value)
1717 self.show_usage_error(value)
1722 else:
1718 else:
1723 if exception_only:
1719 if exception_only:
1724 stb = ['An exception has occurred, use %tb to see '
1720 stb = ['An exception has occurred, use %tb to see '
1725 'the full traceback.\n']
1721 'the full traceback.\n']
1726 stb.extend(self.InteractiveTB.get_exception_only(etype,
1722 stb.extend(self.InteractiveTB.get_exception_only(etype,
1727 value))
1723 value))
1728 else:
1724 else:
1729 try:
1725 try:
1730 # Exception classes can customise their traceback - we
1726 # Exception classes can customise their traceback - we
1731 # use this in IPython.parallel for exceptions occurring
1727 # use this in IPython.parallel for exceptions occurring
1732 # in the engines. This should return a list of strings.
1728 # in the engines. This should return a list of strings.
1733 stb = value._render_traceback_()
1729 stb = value._render_traceback_()
1734 except Exception:
1730 except Exception:
1735 stb = self.InteractiveTB.structured_traceback(etype,
1731 stb = self.InteractiveTB.structured_traceback(etype,
1736 value, tb, tb_offset=tb_offset)
1732 value, tb, tb_offset=tb_offset)
1737
1733
1738 self._showtraceback(etype, value, stb)
1734 self._showtraceback(etype, value, stb)
1739 if self.call_pdb:
1735 if self.call_pdb:
1740 # drop into debugger
1736 # drop into debugger
1741 self.debugger(force=True)
1737 self.debugger(force=True)
1742 return
1738 return
1743
1739
1744 # Actually show the traceback
1740 # Actually show the traceback
1745 self._showtraceback(etype, value, stb)
1741 self._showtraceback(etype, value, stb)
1746
1742
1747 except KeyboardInterrupt:
1743 except KeyboardInterrupt:
1748 self.write_err("\nKeyboardInterrupt\n")
1744 self.write_err("\nKeyboardInterrupt\n")
1749
1745
1750 def _showtraceback(self, etype, evalue, stb):
1746 def _showtraceback(self, etype, evalue, stb):
1751 """Actually show a traceback.
1747 """Actually show a traceback.
1752
1748
1753 Subclasses may override this method to put the traceback on a different
1749 Subclasses may override this method to put the traceback on a different
1754 place, like a side channel.
1750 place, like a side channel.
1755 """
1751 """
1756 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1752 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1757
1753
1758 def showsyntaxerror(self, filename=None):
1754 def showsyntaxerror(self, filename=None):
1759 """Display the syntax error that just occurred.
1755 """Display the syntax error that just occurred.
1760
1756
1761 This doesn't display a stack trace because there isn't one.
1757 This doesn't display a stack trace because there isn't one.
1762
1758
1763 If a filename is given, it is stuffed in the exception instead
1759 If a filename is given, it is stuffed in the exception instead
1764 of what was there before (because Python's parser always uses
1760 of what was there before (because Python's parser always uses
1765 "<string>" when reading from a string).
1761 "<string>" when reading from a string).
1766 """
1762 """
1767 etype, value, last_traceback = self._get_exc_info()
1763 etype, value, last_traceback = self._get_exc_info()
1768
1764
1769 if filename and issubclass(etype, SyntaxError):
1765 if filename and issubclass(etype, SyntaxError):
1770 try:
1766 try:
1771 value.filename = filename
1767 value.filename = filename
1772 except:
1768 except:
1773 # Not the format we expect; leave it alone
1769 # Not the format we expect; leave it alone
1774 pass
1770 pass
1775
1771
1776 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1772 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1777 self._showtraceback(etype, value, stb)
1773 self._showtraceback(etype, value, stb)
1778
1774
1779 # This is overridden in TerminalInteractiveShell to show a message about
1775 # This is overridden in TerminalInteractiveShell to show a message about
1780 # the %paste magic.
1776 # the %paste magic.
1781 def showindentationerror(self):
1777 def showindentationerror(self):
1782 """Called by run_cell when there's an IndentationError in code entered
1778 """Called by run_cell when there's an IndentationError in code entered
1783 at the prompt.
1779 at the prompt.
1784
1780
1785 This is overridden in TerminalInteractiveShell to show a message about
1781 This is overridden in TerminalInteractiveShell to show a message about
1786 the %paste magic."""
1782 the %paste magic."""
1787 self.showsyntaxerror()
1783 self.showsyntaxerror()
1788
1784
1789 #-------------------------------------------------------------------------
1785 #-------------------------------------------------------------------------
1790 # Things related to readline
1786 # Things related to readline
1791 #-------------------------------------------------------------------------
1787 #-------------------------------------------------------------------------
1792
1788
1793 def init_readline(self):
1789 def init_readline(self):
1794 """Command history completion/saving/reloading."""
1790 """Command history completion/saving/reloading."""
1795
1791
1796 if self.readline_use:
1792 if self.readline_use:
1797 import IPython.utils.rlineimpl as readline
1793 import IPython.utils.rlineimpl as readline
1798
1794
1799 self.rl_next_input = None
1795 self.rl_next_input = None
1800 self.rl_do_indent = False
1796 self.rl_do_indent = False
1801
1797
1802 if not self.readline_use or not readline.have_readline:
1798 if not self.readline_use or not readline.have_readline:
1803 self.has_readline = False
1799 self.has_readline = False
1804 self.readline = None
1800 self.readline = None
1805 # Set a number of methods that depend on readline to be no-op
1801 # Set a number of methods that depend on readline to be no-op
1806 self.readline_no_record = no_op_context
1802 self.readline_no_record = no_op_context
1807 self.set_readline_completer = no_op
1803 self.set_readline_completer = no_op
1808 self.set_custom_completer = no_op
1804 self.set_custom_completer = no_op
1809 if self.readline_use:
1805 if self.readline_use:
1810 warn('Readline services not available or not loaded.')
1806 warn('Readline services not available or not loaded.')
1811 else:
1807 else:
1812 self.has_readline = True
1808 self.has_readline = True
1813 self.readline = readline
1809 self.readline = readline
1814 sys.modules['readline'] = readline
1810 sys.modules['readline'] = readline
1815
1811
1816 # Platform-specific configuration
1812 # Platform-specific configuration
1817 if os.name == 'nt':
1813 if os.name == 'nt':
1818 # FIXME - check with Frederick to see if we can harmonize
1814 # FIXME - check with Frederick to see if we can harmonize
1819 # naming conventions with pyreadline to avoid this
1815 # naming conventions with pyreadline to avoid this
1820 # platform-dependent check
1816 # platform-dependent check
1821 self.readline_startup_hook = readline.set_pre_input_hook
1817 self.readline_startup_hook = readline.set_pre_input_hook
1822 else:
1818 else:
1823 self.readline_startup_hook = readline.set_startup_hook
1819 self.readline_startup_hook = readline.set_startup_hook
1824
1820
1825 # Load user's initrc file (readline config)
1821 # Load user's initrc file (readline config)
1826 # Or if libedit is used, load editrc.
1822 # Or if libedit is used, load editrc.
1827 inputrc_name = os.environ.get('INPUTRC')
1823 inputrc_name = os.environ.get('INPUTRC')
1828 if inputrc_name is None:
1824 if inputrc_name is None:
1829 inputrc_name = '.inputrc'
1825 inputrc_name = '.inputrc'
1830 if readline.uses_libedit:
1826 if readline.uses_libedit:
1831 inputrc_name = '.editrc'
1827 inputrc_name = '.editrc'
1832 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1828 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1833 if os.path.isfile(inputrc_name):
1829 if os.path.isfile(inputrc_name):
1834 try:
1830 try:
1835 readline.read_init_file(inputrc_name)
1831 readline.read_init_file(inputrc_name)
1836 except:
1832 except:
1837 warn('Problems reading readline initialization file <%s>'
1833 warn('Problems reading readline initialization file <%s>'
1838 % inputrc_name)
1834 % inputrc_name)
1839
1835
1840 # Configure readline according to user's prefs
1836 # Configure readline according to user's prefs
1841 # This is only done if GNU readline is being used. If libedit
1837 # This is only done if GNU readline is being used. If libedit
1842 # is being used (as on Leopard) the readline config is
1838 # is being used (as on Leopard) the readline config is
1843 # not run as the syntax for libedit is different.
1839 # not run as the syntax for libedit is different.
1844 if not readline.uses_libedit:
1840 if not readline.uses_libedit:
1845 for rlcommand in self.readline_parse_and_bind:
1841 for rlcommand in self.readline_parse_and_bind:
1846 #print "loading rl:",rlcommand # dbg
1842 #print "loading rl:",rlcommand # dbg
1847 readline.parse_and_bind(rlcommand)
1843 readline.parse_and_bind(rlcommand)
1848
1844
1849 # Remove some chars from the delimiters list. If we encounter
1845 # Remove some chars from the delimiters list. If we encounter
1850 # unicode chars, discard them.
1846 # unicode chars, discard them.
1851 delims = readline.get_completer_delims()
1847 delims = readline.get_completer_delims()
1852 if not py3compat.PY3:
1848 if not py3compat.PY3:
1853 delims = delims.encode("ascii", "ignore")
1849 delims = delims.encode("ascii", "ignore")
1854 for d in self.readline_remove_delims:
1850 for d in self.readline_remove_delims:
1855 delims = delims.replace(d, "")
1851 delims = delims.replace(d, "")
1856 delims = delims.replace(ESC_MAGIC, '')
1852 delims = delims.replace(ESC_MAGIC, '')
1857 readline.set_completer_delims(delims)
1853 readline.set_completer_delims(delims)
1858 # Store these so we can restore them if something like rpy2 modifies
1854 # Store these so we can restore them if something like rpy2 modifies
1859 # them.
1855 # them.
1860 self.readline_delims = delims
1856 self.readline_delims = delims
1861 # otherwise we end up with a monster history after a while:
1857 # otherwise we end up with a monster history after a while:
1862 readline.set_history_length(self.history_length)
1858 readline.set_history_length(self.history_length)
1863
1859
1864 self.refill_readline_hist()
1860 self.refill_readline_hist()
1865 self.readline_no_record = ReadlineNoRecord(self)
1861 self.readline_no_record = ReadlineNoRecord(self)
1866
1862
1867 # Configure auto-indent for all platforms
1863 # Configure auto-indent for all platforms
1868 self.set_autoindent(self.autoindent)
1864 self.set_autoindent(self.autoindent)
1869
1865
1870 def refill_readline_hist(self):
1866 def refill_readline_hist(self):
1871 # Load the last 1000 lines from history
1867 # Load the last 1000 lines from history
1872 self.readline.clear_history()
1868 self.readline.clear_history()
1873 stdin_encoding = sys.stdin.encoding or "utf-8"
1869 stdin_encoding = sys.stdin.encoding or "utf-8"
1874 last_cell = u""
1870 last_cell = u""
1875 for _, _, cell in self.history_manager.get_tail(1000,
1871 for _, _, cell in self.history_manager.get_tail(1000,
1876 include_latest=True):
1872 include_latest=True):
1877 # Ignore blank lines and consecutive duplicates
1873 # Ignore blank lines and consecutive duplicates
1878 cell = cell.rstrip()
1874 cell = cell.rstrip()
1879 if cell and (cell != last_cell):
1875 if cell and (cell != last_cell):
1880 try:
1876 try:
1881 if self.multiline_history:
1877 if self.multiline_history:
1882 self.readline.add_history(py3compat.unicode_to_str(cell,
1878 self.readline.add_history(py3compat.unicode_to_str(cell,
1883 stdin_encoding))
1879 stdin_encoding))
1884 else:
1880 else:
1885 for line in cell.splitlines():
1881 for line in cell.splitlines():
1886 self.readline.add_history(py3compat.unicode_to_str(line,
1882 self.readline.add_history(py3compat.unicode_to_str(line,
1887 stdin_encoding))
1883 stdin_encoding))
1888 last_cell = cell
1884 last_cell = cell
1889
1885
1890 except TypeError:
1886 except TypeError:
1891 # The history DB can get corrupted so it returns strings
1887 # The history DB can get corrupted so it returns strings
1892 # containing null bytes, which readline objects to.
1888 # containing null bytes, which readline objects to.
1893 continue
1889 continue
1894
1890
1895 @skip_doctest
1891 @skip_doctest
1896 def set_next_input(self, s):
1892 def set_next_input(self, s):
1897 """ Sets the 'default' input string for the next command line.
1893 """ Sets the 'default' input string for the next command line.
1898
1894
1899 Requires readline.
1895 Requires readline.
1900
1896
1901 Example::
1897 Example::
1902
1898
1903 In [1]: _ip.set_next_input("Hello Word")
1899 In [1]: _ip.set_next_input("Hello Word")
1904 In [2]: Hello Word_ # cursor is here
1900 In [2]: Hello Word_ # cursor is here
1905 """
1901 """
1906 self.rl_next_input = py3compat.cast_bytes_py2(s)
1902 self.rl_next_input = py3compat.cast_bytes_py2(s)
1907
1903
1908 # Maybe move this to the terminal subclass?
1904 # Maybe move this to the terminal subclass?
1909 def pre_readline(self):
1905 def pre_readline(self):
1910 """readline hook to be used at the start of each line.
1906 """readline hook to be used at the start of each line.
1911
1907
1912 Currently it handles auto-indent only."""
1908 Currently it handles auto-indent only."""
1913
1909
1914 if self.rl_do_indent:
1910 if self.rl_do_indent:
1915 self.readline.insert_text(self._indent_current_str())
1911 self.readline.insert_text(self._indent_current_str())
1916 if self.rl_next_input is not None:
1912 if self.rl_next_input is not None:
1917 self.readline.insert_text(self.rl_next_input)
1913 self.readline.insert_text(self.rl_next_input)
1918 self.rl_next_input = None
1914 self.rl_next_input = None
1919
1915
1920 def _indent_current_str(self):
1916 def _indent_current_str(self):
1921 """return the current level of indentation as a string"""
1917 """return the current level of indentation as a string"""
1922 return self.input_splitter.indent_spaces * ' '
1918 return self.input_splitter.indent_spaces * ' '
1923
1919
1924 #-------------------------------------------------------------------------
1920 #-------------------------------------------------------------------------
1925 # Things related to text completion
1921 # Things related to text completion
1926 #-------------------------------------------------------------------------
1922 #-------------------------------------------------------------------------
1927
1923
1928 def init_completer(self):
1924 def init_completer(self):
1929 """Initialize the completion machinery.
1925 """Initialize the completion machinery.
1930
1926
1931 This creates completion machinery that can be used by client code,
1927 This creates completion machinery that can be used by client code,
1932 either interactively in-process (typically triggered by the readline
1928 either interactively in-process (typically triggered by the readline
1933 library), programatically (such as in test suites) or out-of-prcess
1929 library), programatically (such as in test suites) or out-of-prcess
1934 (typically over the network by remote frontends).
1930 (typically over the network by remote frontends).
1935 """
1931 """
1936 from IPython.core.completer import IPCompleter
1932 from IPython.core.completer import IPCompleter
1937 from IPython.core.completerlib import (module_completer,
1933 from IPython.core.completerlib import (module_completer,
1938 magic_run_completer, cd_completer, reset_completer)
1934 magic_run_completer, cd_completer, reset_completer)
1939
1935
1940 self.Completer = IPCompleter(shell=self,
1936 self.Completer = IPCompleter(shell=self,
1941 namespace=self.user_ns,
1937 namespace=self.user_ns,
1942 global_namespace=self.user_global_ns,
1938 global_namespace=self.user_global_ns,
1943 alias_table=self.alias_manager.alias_table,
1944 use_readline=self.has_readline,
1939 use_readline=self.has_readline,
1945 parent=self,
1940 parent=self,
1946 )
1941 )
1947 self.configurables.append(self.Completer)
1942 self.configurables.append(self.Completer)
1948
1943
1949 # Add custom completers to the basic ones built into IPCompleter
1944 # Add custom completers to the basic ones built into IPCompleter
1950 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1945 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1951 self.strdispatchers['complete_command'] = sdisp
1946 self.strdispatchers['complete_command'] = sdisp
1952 self.Completer.custom_completers = sdisp
1947 self.Completer.custom_completers = sdisp
1953
1948
1954 self.set_hook('complete_command', module_completer, str_key = 'import')
1949 self.set_hook('complete_command', module_completer, str_key = 'import')
1955 self.set_hook('complete_command', module_completer, str_key = 'from')
1950 self.set_hook('complete_command', module_completer, str_key = 'from')
1956 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1951 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1957 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1952 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1958 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1953 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1959
1954
1960 # Only configure readline if we truly are using readline. IPython can
1955 # Only configure readline if we truly are using readline. IPython can
1961 # do tab-completion over the network, in GUIs, etc, where readline
1956 # do tab-completion over the network, in GUIs, etc, where readline
1962 # itself may be absent
1957 # itself may be absent
1963 if self.has_readline:
1958 if self.has_readline:
1964 self.set_readline_completer()
1959 self.set_readline_completer()
1965
1960
1966 def complete(self, text, line=None, cursor_pos=None):
1961 def complete(self, text, line=None, cursor_pos=None):
1967 """Return the completed text and a list of completions.
1962 """Return the completed text and a list of completions.
1968
1963
1969 Parameters
1964 Parameters
1970 ----------
1965 ----------
1971
1966
1972 text : string
1967 text : string
1973 A string of text to be completed on. It can be given as empty and
1968 A string of text to be completed on. It can be given as empty and
1974 instead a line/position pair are given. In this case, the
1969 instead a line/position pair are given. In this case, the
1975 completer itself will split the line like readline does.
1970 completer itself will split the line like readline does.
1976
1971
1977 line : string, optional
1972 line : string, optional
1978 The complete line that text is part of.
1973 The complete line that text is part of.
1979
1974
1980 cursor_pos : int, optional
1975 cursor_pos : int, optional
1981 The position of the cursor on the input line.
1976 The position of the cursor on the input line.
1982
1977
1983 Returns
1978 Returns
1984 -------
1979 -------
1985 text : string
1980 text : string
1986 The actual text that was completed.
1981 The actual text that was completed.
1987
1982
1988 matches : list
1983 matches : list
1989 A sorted list with all possible completions.
1984 A sorted list with all possible completions.
1990
1985
1991 The optional arguments allow the completion to take more context into
1986 The optional arguments allow the completion to take more context into
1992 account, and are part of the low-level completion API.
1987 account, and are part of the low-level completion API.
1993
1988
1994 This is a wrapper around the completion mechanism, similar to what
1989 This is a wrapper around the completion mechanism, similar to what
1995 readline does at the command line when the TAB key is hit. By
1990 readline does at the command line when the TAB key is hit. By
1996 exposing it as a method, it can be used by other non-readline
1991 exposing it as a method, it can be used by other non-readline
1997 environments (such as GUIs) for text completion.
1992 environments (such as GUIs) for text completion.
1998
1993
1999 Simple usage example:
1994 Simple usage example:
2000
1995
2001 In [1]: x = 'hello'
1996 In [1]: x = 'hello'
2002
1997
2003 In [2]: _ip.complete('x.l')
1998 In [2]: _ip.complete('x.l')
2004 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1999 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2005 """
2000 """
2006
2001
2007 # Inject names into __builtin__ so we can complete on the added names.
2002 # Inject names into __builtin__ so we can complete on the added names.
2008 with self.builtin_trap:
2003 with self.builtin_trap:
2009 return self.Completer.complete(text, line, cursor_pos)
2004 return self.Completer.complete(text, line, cursor_pos)
2010
2005
2011 def set_custom_completer(self, completer, pos=0):
2006 def set_custom_completer(self, completer, pos=0):
2012 """Adds a new custom completer function.
2007 """Adds a new custom completer function.
2013
2008
2014 The position argument (defaults to 0) is the index in the completers
2009 The position argument (defaults to 0) is the index in the completers
2015 list where you want the completer to be inserted."""
2010 list where you want the completer to be inserted."""
2016
2011
2017 newcomp = types.MethodType(completer,self.Completer)
2012 newcomp = types.MethodType(completer,self.Completer)
2018 self.Completer.matchers.insert(pos,newcomp)
2013 self.Completer.matchers.insert(pos,newcomp)
2019
2014
2020 def set_readline_completer(self):
2015 def set_readline_completer(self):
2021 """Reset readline's completer to be our own."""
2016 """Reset readline's completer to be our own."""
2022 self.readline.set_completer(self.Completer.rlcomplete)
2017 self.readline.set_completer(self.Completer.rlcomplete)
2023
2018
2024 def set_completer_frame(self, frame=None):
2019 def set_completer_frame(self, frame=None):
2025 """Set the frame of the completer."""
2020 """Set the frame of the completer."""
2026 if frame:
2021 if frame:
2027 self.Completer.namespace = frame.f_locals
2022 self.Completer.namespace = frame.f_locals
2028 self.Completer.global_namespace = frame.f_globals
2023 self.Completer.global_namespace = frame.f_globals
2029 else:
2024 else:
2030 self.Completer.namespace = self.user_ns
2025 self.Completer.namespace = self.user_ns
2031 self.Completer.global_namespace = self.user_global_ns
2026 self.Completer.global_namespace = self.user_global_ns
2032
2027
2033 #-------------------------------------------------------------------------
2028 #-------------------------------------------------------------------------
2034 # Things related to magics
2029 # Things related to magics
2035 #-------------------------------------------------------------------------
2030 #-------------------------------------------------------------------------
2036
2031
2037 def init_magics(self):
2032 def init_magics(self):
2038 from IPython.core import magics as m
2033 from IPython.core import magics as m
2039 self.magics_manager = magic.MagicsManager(shell=self,
2034 self.magics_manager = magic.MagicsManager(shell=self,
2040 parent=self,
2035 parent=self,
2041 user_magics=m.UserMagics(self))
2036 user_magics=m.UserMagics(self))
2042 self.configurables.append(self.magics_manager)
2037 self.configurables.append(self.magics_manager)
2043
2038
2044 # Expose as public API from the magics manager
2039 # Expose as public API from the magics manager
2045 self.register_magics = self.magics_manager.register
2040 self.register_magics = self.magics_manager.register
2046 self.define_magic = self.magics_manager.define_magic
2041 self.define_magic = self.magics_manager.define_magic
2047
2042
2048 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2043 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2049 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2044 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2050 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2045 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2051 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2046 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2052 )
2047 )
2053
2048
2054 # Register Magic Aliases
2049 # Register Magic Aliases
2055 mman = self.magics_manager
2050 mman = self.magics_manager
2056 # FIXME: magic aliases should be defined by the Magics classes
2051 # FIXME: magic aliases should be defined by the Magics classes
2057 # or in MagicsManager, not here
2052 # or in MagicsManager, not here
2058 mman.register_alias('ed', 'edit')
2053 mman.register_alias('ed', 'edit')
2059 mman.register_alias('hist', 'history')
2054 mman.register_alias('hist', 'history')
2060 mman.register_alias('rep', 'recall')
2055 mman.register_alias('rep', 'recall')
2061 mman.register_alias('SVG', 'svg', 'cell')
2056 mman.register_alias('SVG', 'svg', 'cell')
2062 mman.register_alias('HTML', 'html', 'cell')
2057 mman.register_alias('HTML', 'html', 'cell')
2063 mman.register_alias('file', 'writefile', 'cell')
2058 mman.register_alias('file', 'writefile', 'cell')
2064
2059
2065 # FIXME: Move the color initialization to the DisplayHook, which
2060 # FIXME: Move the color initialization to the DisplayHook, which
2066 # should be split into a prompt manager and displayhook. We probably
2061 # should be split into a prompt manager and displayhook. We probably
2067 # even need a centralize colors management object.
2062 # even need a centralize colors management object.
2068 self.magic('colors %s' % self.colors)
2063 self.magic('colors %s' % self.colors)
2069
2064
2070 # Defined here so that it's included in the documentation
2065 # Defined here so that it's included in the documentation
2071 @functools.wraps(magic.MagicsManager.register_function)
2066 @functools.wraps(magic.MagicsManager.register_function)
2072 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2067 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2073 self.magics_manager.register_function(func,
2068 self.magics_manager.register_function(func,
2074 magic_kind=magic_kind, magic_name=magic_name)
2069 magic_kind=magic_kind, magic_name=magic_name)
2075
2070
2076 def run_line_magic(self, magic_name, line):
2071 def run_line_magic(self, magic_name, line):
2077 """Execute the given line magic.
2072 """Execute the given line magic.
2078
2073
2079 Parameters
2074 Parameters
2080 ----------
2075 ----------
2081 magic_name : str
2076 magic_name : str
2082 Name of the desired magic function, without '%' prefix.
2077 Name of the desired magic function, without '%' prefix.
2083
2078
2084 line : str
2079 line : str
2085 The rest of the input line as a single string.
2080 The rest of the input line as a single string.
2086 """
2081 """
2087 fn = self.find_line_magic(magic_name)
2082 fn = self.find_line_magic(magic_name)
2088 if fn is None:
2083 if fn is None:
2089 cm = self.find_cell_magic(magic_name)
2084 cm = self.find_cell_magic(magic_name)
2090 etpl = "Line magic function `%%%s` not found%s."
2085 etpl = "Line magic function `%%%s` not found%s."
2091 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2086 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2092 'did you mean that instead?)' % magic_name )
2087 'did you mean that instead?)' % magic_name )
2093 error(etpl % (magic_name, extra))
2088 error(etpl % (magic_name, extra))
2094 else:
2089 else:
2095 # Note: this is the distance in the stack to the user's frame.
2090 # Note: this is the distance in the stack to the user's frame.
2096 # This will need to be updated if the internal calling logic gets
2091 # This will need to be updated if the internal calling logic gets
2097 # refactored, or else we'll be expanding the wrong variables.
2092 # refactored, or else we'll be expanding the wrong variables.
2098 stack_depth = 2
2093 stack_depth = 2
2099 magic_arg_s = self.var_expand(line, stack_depth)
2094 magic_arg_s = self.var_expand(line, stack_depth)
2100 # Put magic args in a list so we can call with f(*a) syntax
2095 # Put magic args in a list so we can call with f(*a) syntax
2101 args = [magic_arg_s]
2096 args = [magic_arg_s]
2102 kwargs = {}
2097 kwargs = {}
2103 # Grab local namespace if we need it:
2098 # Grab local namespace if we need it:
2104 if getattr(fn, "needs_local_scope", False):
2099 if getattr(fn, "needs_local_scope", False):
2105 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2100 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2106 with self.builtin_trap:
2101 with self.builtin_trap:
2107 result = fn(*args,**kwargs)
2102 result = fn(*args,**kwargs)
2108 return result
2103 return result
2109
2104
2110 def run_cell_magic(self, magic_name, line, cell):
2105 def run_cell_magic(self, magic_name, line, cell):
2111 """Execute the given cell magic.
2106 """Execute the given cell magic.
2112
2107
2113 Parameters
2108 Parameters
2114 ----------
2109 ----------
2115 magic_name : str
2110 magic_name : str
2116 Name of the desired magic function, without '%' prefix.
2111 Name of the desired magic function, without '%' prefix.
2117
2112
2118 line : str
2113 line : str
2119 The rest of the first input line as a single string.
2114 The rest of the first input line as a single string.
2120
2115
2121 cell : str
2116 cell : str
2122 The body of the cell as a (possibly multiline) string.
2117 The body of the cell as a (possibly multiline) string.
2123 """
2118 """
2124 fn = self.find_cell_magic(magic_name)
2119 fn = self.find_cell_magic(magic_name)
2125 if fn is None:
2120 if fn is None:
2126 lm = self.find_line_magic(magic_name)
2121 lm = self.find_line_magic(magic_name)
2127 etpl = "Cell magic `%%{0}` not found{1}."
2122 etpl = "Cell magic `%%{0}` not found{1}."
2128 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2123 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2129 'did you mean that instead?)'.format(magic_name))
2124 'did you mean that instead?)'.format(magic_name))
2130 error(etpl.format(magic_name, extra))
2125 error(etpl.format(magic_name, extra))
2131 elif cell == '':
2126 elif cell == '':
2132 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2127 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2133 if self.find_line_magic(magic_name) is not None:
2128 if self.find_line_magic(magic_name) is not None:
2134 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2129 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2135 raise UsageError(message)
2130 raise UsageError(message)
2136 else:
2131 else:
2137 # Note: this is the distance in the stack to the user's frame.
2132 # Note: this is the distance in the stack to the user's frame.
2138 # This will need to be updated if the internal calling logic gets
2133 # This will need to be updated if the internal calling logic gets
2139 # refactored, or else we'll be expanding the wrong variables.
2134 # refactored, or else we'll be expanding the wrong variables.
2140 stack_depth = 2
2135 stack_depth = 2
2141 magic_arg_s = self.var_expand(line, stack_depth)
2136 magic_arg_s = self.var_expand(line, stack_depth)
2142 with self.builtin_trap:
2137 with self.builtin_trap:
2143 result = fn(magic_arg_s, cell)
2138 result = fn(magic_arg_s, cell)
2144 return result
2139 return result
2145
2140
2146 def find_line_magic(self, magic_name):
2141 def find_line_magic(self, magic_name):
2147 """Find and return a line magic by name.
2142 """Find and return a line magic by name.
2148
2143
2149 Returns None if the magic isn't found."""
2144 Returns None if the magic isn't found."""
2150 return self.magics_manager.magics['line'].get(magic_name)
2145 return self.magics_manager.magics['line'].get(magic_name)
2151
2146
2152 def find_cell_magic(self, magic_name):
2147 def find_cell_magic(self, magic_name):
2153 """Find and return a cell magic by name.
2148 """Find and return a cell magic by name.
2154
2149
2155 Returns None if the magic isn't found."""
2150 Returns None if the magic isn't found."""
2156 return self.magics_manager.magics['cell'].get(magic_name)
2151 return self.magics_manager.magics['cell'].get(magic_name)
2157
2152
2158 def find_magic(self, magic_name, magic_kind='line'):
2153 def find_magic(self, magic_name, magic_kind='line'):
2159 """Find and return a magic of the given type by name.
2154 """Find and return a magic of the given type by name.
2160
2155
2161 Returns None if the magic isn't found."""
2156 Returns None if the magic isn't found."""
2162 return self.magics_manager.magics[magic_kind].get(magic_name)
2157 return self.magics_manager.magics[magic_kind].get(magic_name)
2163
2158
2164 def magic(self, arg_s):
2159 def magic(self, arg_s):
2165 """DEPRECATED. Use run_line_magic() instead.
2160 """DEPRECATED. Use run_line_magic() instead.
2166
2161
2167 Call a magic function by name.
2162 Call a magic function by name.
2168
2163
2169 Input: a string containing the name of the magic function to call and
2164 Input: a string containing the name of the magic function to call and
2170 any additional arguments to be passed to the magic.
2165 any additional arguments to be passed to the magic.
2171
2166
2172 magic('name -opt foo bar') is equivalent to typing at the ipython
2167 magic('name -opt foo bar') is equivalent to typing at the ipython
2173 prompt:
2168 prompt:
2174
2169
2175 In[1]: %name -opt foo bar
2170 In[1]: %name -opt foo bar
2176
2171
2177 To call a magic without arguments, simply use magic('name').
2172 To call a magic without arguments, simply use magic('name').
2178
2173
2179 This provides a proper Python function to call IPython's magics in any
2174 This provides a proper Python function to call IPython's magics in any
2180 valid Python code you can type at the interpreter, including loops and
2175 valid Python code you can type at the interpreter, including loops and
2181 compound statements.
2176 compound statements.
2182 """
2177 """
2183 # TODO: should we issue a loud deprecation warning here?
2178 # TODO: should we issue a loud deprecation warning here?
2184 magic_name, _, magic_arg_s = arg_s.partition(' ')
2179 magic_name, _, magic_arg_s = arg_s.partition(' ')
2185 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2180 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2186 return self.run_line_magic(magic_name, magic_arg_s)
2181 return self.run_line_magic(magic_name, magic_arg_s)
2187
2182
2188 #-------------------------------------------------------------------------
2183 #-------------------------------------------------------------------------
2189 # Things related to macros
2184 # Things related to macros
2190 #-------------------------------------------------------------------------
2185 #-------------------------------------------------------------------------
2191
2186
2192 def define_macro(self, name, themacro):
2187 def define_macro(self, name, themacro):
2193 """Define a new macro
2188 """Define a new macro
2194
2189
2195 Parameters
2190 Parameters
2196 ----------
2191 ----------
2197 name : str
2192 name : str
2198 The name of the macro.
2193 The name of the macro.
2199 themacro : str or Macro
2194 themacro : str or Macro
2200 The action to do upon invoking the macro. If a string, a new
2195 The action to do upon invoking the macro. If a string, a new
2201 Macro object is created by passing the string to it.
2196 Macro object is created by passing the string to it.
2202 """
2197 """
2203
2198
2204 from IPython.core import macro
2199 from IPython.core import macro
2205
2200
2206 if isinstance(themacro, basestring):
2201 if isinstance(themacro, basestring):
2207 themacro = macro.Macro(themacro)
2202 themacro = macro.Macro(themacro)
2208 if not isinstance(themacro, macro.Macro):
2203 if not isinstance(themacro, macro.Macro):
2209 raise ValueError('A macro must be a string or a Macro instance.')
2204 raise ValueError('A macro must be a string or a Macro instance.')
2210 self.user_ns[name] = themacro
2205 self.user_ns[name] = themacro
2211
2206
2212 #-------------------------------------------------------------------------
2207 #-------------------------------------------------------------------------
2213 # Things related to the running of system commands
2208 # Things related to the running of system commands
2214 #-------------------------------------------------------------------------
2209 #-------------------------------------------------------------------------
2215
2210
2216 def system_piped(self, cmd):
2211 def system_piped(self, cmd):
2217 """Call the given cmd in a subprocess, piping stdout/err
2212 """Call the given cmd in a subprocess, piping stdout/err
2218
2213
2219 Parameters
2214 Parameters
2220 ----------
2215 ----------
2221 cmd : str
2216 cmd : str
2222 Command to execute (can not end in '&', as background processes are
2217 Command to execute (can not end in '&', as background processes are
2223 not supported. Should not be a command that expects input
2218 not supported. Should not be a command that expects input
2224 other than simple text.
2219 other than simple text.
2225 """
2220 """
2226 if cmd.rstrip().endswith('&'):
2221 if cmd.rstrip().endswith('&'):
2227 # this is *far* from a rigorous test
2222 # this is *far* from a rigorous test
2228 # We do not support backgrounding processes because we either use
2223 # We do not support backgrounding processes because we either use
2229 # pexpect or pipes to read from. Users can always just call
2224 # pexpect or pipes to read from. Users can always just call
2230 # os.system() or use ip.system=ip.system_raw
2225 # os.system() or use ip.system=ip.system_raw
2231 # if they really want a background process.
2226 # if they really want a background process.
2232 raise OSError("Background processes not supported.")
2227 raise OSError("Background processes not supported.")
2233
2228
2234 # we explicitly do NOT return the subprocess status code, because
2229 # we explicitly do NOT return the subprocess status code, because
2235 # a non-None value would trigger :func:`sys.displayhook` calls.
2230 # a non-None value would trigger :func:`sys.displayhook` calls.
2236 # Instead, we store the exit_code in user_ns.
2231 # Instead, we store the exit_code in user_ns.
2237 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2232 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2238
2233
2239 def system_raw(self, cmd):
2234 def system_raw(self, cmd):
2240 """Call the given cmd in a subprocess using os.system
2235 """Call the given cmd in a subprocess using os.system
2241
2236
2242 Parameters
2237 Parameters
2243 ----------
2238 ----------
2244 cmd : str
2239 cmd : str
2245 Command to execute.
2240 Command to execute.
2246 """
2241 """
2247 cmd = self.var_expand(cmd, depth=1)
2242 cmd = self.var_expand(cmd, depth=1)
2248 # protect os.system from UNC paths on Windows, which it can't handle:
2243 # protect os.system from UNC paths on Windows, which it can't handle:
2249 if sys.platform == 'win32':
2244 if sys.platform == 'win32':
2250 from IPython.utils._process_win32 import AvoidUNCPath
2245 from IPython.utils._process_win32 import AvoidUNCPath
2251 with AvoidUNCPath() as path:
2246 with AvoidUNCPath() as path:
2252 if path is not None:
2247 if path is not None:
2253 cmd = '"pushd %s &&"%s' % (path, cmd)
2248 cmd = '"pushd %s &&"%s' % (path, cmd)
2254 cmd = py3compat.unicode_to_str(cmd)
2249 cmd = py3compat.unicode_to_str(cmd)
2255 ec = os.system(cmd)
2250 ec = os.system(cmd)
2256 else:
2251 else:
2257 cmd = py3compat.unicode_to_str(cmd)
2252 cmd = py3compat.unicode_to_str(cmd)
2258 ec = os.system(cmd)
2253 ec = os.system(cmd)
2259 # The high byte is the exit code, the low byte is a signal number
2254 # The high byte is the exit code, the low byte is a signal number
2260 # that we discard for now. See the docs for os.wait()
2255 # that we discard for now. See the docs for os.wait()
2261 if ec > 255:
2256 if ec > 255:
2262 ec >>= 8
2257 ec >>= 8
2263
2258
2264 # We explicitly do NOT return the subprocess status code, because
2259 # We explicitly do NOT return the subprocess status code, because
2265 # a non-None value would trigger :func:`sys.displayhook` calls.
2260 # a non-None value would trigger :func:`sys.displayhook` calls.
2266 # Instead, we store the exit_code in user_ns.
2261 # Instead, we store the exit_code in user_ns.
2267 self.user_ns['_exit_code'] = ec
2262 self.user_ns['_exit_code'] = ec
2268
2263
2269 # use piped system by default, because it is better behaved
2264 # use piped system by default, because it is better behaved
2270 system = system_piped
2265 system = system_piped
2271
2266
2272 def getoutput(self, cmd, split=True, depth=0):
2267 def getoutput(self, cmd, split=True, depth=0):
2273 """Get output (possibly including stderr) from a subprocess.
2268 """Get output (possibly including stderr) from a subprocess.
2274
2269
2275 Parameters
2270 Parameters
2276 ----------
2271 ----------
2277 cmd : str
2272 cmd : str
2278 Command to execute (can not end in '&', as background processes are
2273 Command to execute (can not end in '&', as background processes are
2279 not supported.
2274 not supported.
2280 split : bool, optional
2275 split : bool, optional
2281 If True, split the output into an IPython SList. Otherwise, an
2276 If True, split the output into an IPython SList. Otherwise, an
2282 IPython LSString is returned. These are objects similar to normal
2277 IPython LSString is returned. These are objects similar to normal
2283 lists and strings, with a few convenience attributes for easier
2278 lists and strings, with a few convenience attributes for easier
2284 manipulation of line-based output. You can use '?' on them for
2279 manipulation of line-based output. You can use '?' on them for
2285 details.
2280 details.
2286 depth : int, optional
2281 depth : int, optional
2287 How many frames above the caller are the local variables which should
2282 How many frames above the caller are the local variables which should
2288 be expanded in the command string? The default (0) assumes that the
2283 be expanded in the command string? The default (0) assumes that the
2289 expansion variables are in the stack frame calling this function.
2284 expansion variables are in the stack frame calling this function.
2290 """
2285 """
2291 if cmd.rstrip().endswith('&'):
2286 if cmd.rstrip().endswith('&'):
2292 # this is *far* from a rigorous test
2287 # this is *far* from a rigorous test
2293 raise OSError("Background processes not supported.")
2288 raise OSError("Background processes not supported.")
2294 out = getoutput(self.var_expand(cmd, depth=depth+1))
2289 out = getoutput(self.var_expand(cmd, depth=depth+1))
2295 if split:
2290 if split:
2296 out = SList(out.splitlines())
2291 out = SList(out.splitlines())
2297 else:
2292 else:
2298 out = LSString(out)
2293 out = LSString(out)
2299 return out
2294 return out
2300
2295
2301 #-------------------------------------------------------------------------
2296 #-------------------------------------------------------------------------
2302 # Things related to aliases
2297 # Things related to aliases
2303 #-------------------------------------------------------------------------
2298 #-------------------------------------------------------------------------
2304
2299
2305 def init_alias(self):
2300 def init_alias(self):
2306 self.alias_manager = AliasManager(shell=self, parent=self)
2301 self.alias_manager = AliasManager(shell=self, parent=self)
2307 self.configurables.append(self.alias_manager)
2302 self.configurables.append(self.alias_manager)
2308 self.ns_table['alias'] = self.alias_manager.alias_table,
2309
2303
2310 #-------------------------------------------------------------------------
2304 #-------------------------------------------------------------------------
2311 # Things related to extensions
2305 # Things related to extensions
2312 #-------------------------------------------------------------------------
2306 #-------------------------------------------------------------------------
2313
2307
2314 def init_extension_manager(self):
2308 def init_extension_manager(self):
2315 self.extension_manager = ExtensionManager(shell=self, parent=self)
2309 self.extension_manager = ExtensionManager(shell=self, parent=self)
2316 self.configurables.append(self.extension_manager)
2310 self.configurables.append(self.extension_manager)
2317
2311
2318 #-------------------------------------------------------------------------
2312 #-------------------------------------------------------------------------
2319 # Things related to payloads
2313 # Things related to payloads
2320 #-------------------------------------------------------------------------
2314 #-------------------------------------------------------------------------
2321
2315
2322 def init_payload(self):
2316 def init_payload(self):
2323 self.payload_manager = PayloadManager(parent=self)
2317 self.payload_manager = PayloadManager(parent=self)
2324 self.configurables.append(self.payload_manager)
2318 self.configurables.append(self.payload_manager)
2325
2319
2326 #-------------------------------------------------------------------------
2320 #-------------------------------------------------------------------------
2327 # Things related to the prefilter
2321 # Things related to the prefilter
2328 #-------------------------------------------------------------------------
2322 #-------------------------------------------------------------------------
2329
2323
2330 def init_prefilter(self):
2324 def init_prefilter(self):
2331 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2325 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2332 self.configurables.append(self.prefilter_manager)
2326 self.configurables.append(self.prefilter_manager)
2333 # Ultimately this will be refactored in the new interpreter code, but
2327 # Ultimately this will be refactored in the new interpreter code, but
2334 # for now, we should expose the main prefilter method (there's legacy
2328 # for now, we should expose the main prefilter method (there's legacy
2335 # code out there that may rely on this).
2329 # code out there that may rely on this).
2336 self.prefilter = self.prefilter_manager.prefilter_lines
2330 self.prefilter = self.prefilter_manager.prefilter_lines
2337
2331
2338 def auto_rewrite_input(self, cmd):
2332 def auto_rewrite_input(self, cmd):
2339 """Print to the screen the rewritten form of the user's command.
2333 """Print to the screen the rewritten form of the user's command.
2340
2334
2341 This shows visual feedback by rewriting input lines that cause
2335 This shows visual feedback by rewriting input lines that cause
2342 automatic calling to kick in, like::
2336 automatic calling to kick in, like::
2343
2337
2344 /f x
2338 /f x
2345
2339
2346 into::
2340 into::
2347
2341
2348 ------> f(x)
2342 ------> f(x)
2349
2343
2350 after the user's input prompt. This helps the user understand that the
2344 after the user's input prompt. This helps the user understand that the
2351 input line was transformed automatically by IPython.
2345 input line was transformed automatically by IPython.
2352 """
2346 """
2353 if not self.show_rewritten_input:
2347 if not self.show_rewritten_input:
2354 return
2348 return
2355
2349
2356 rw = self.prompt_manager.render('rewrite') + cmd
2350 rw = self.prompt_manager.render('rewrite') + cmd
2357
2351
2358 try:
2352 try:
2359 # plain ascii works better w/ pyreadline, on some machines, so
2353 # plain ascii works better w/ pyreadline, on some machines, so
2360 # we use it and only print uncolored rewrite if we have unicode
2354 # we use it and only print uncolored rewrite if we have unicode
2361 rw = str(rw)
2355 rw = str(rw)
2362 print(rw, file=io.stdout)
2356 print(rw, file=io.stdout)
2363 except UnicodeEncodeError:
2357 except UnicodeEncodeError:
2364 print("------> " + cmd)
2358 print("------> " + cmd)
2365
2359
2366 #-------------------------------------------------------------------------
2360 #-------------------------------------------------------------------------
2367 # Things related to extracting values/expressions from kernel and user_ns
2361 # Things related to extracting values/expressions from kernel and user_ns
2368 #-------------------------------------------------------------------------
2362 #-------------------------------------------------------------------------
2369
2363
2370 def _user_obj_error(self):
2364 def _user_obj_error(self):
2371 """return simple exception dict
2365 """return simple exception dict
2372
2366
2373 for use in user_variables / expressions
2367 for use in user_variables / expressions
2374 """
2368 """
2375
2369
2376 etype, evalue, tb = self._get_exc_info()
2370 etype, evalue, tb = self._get_exc_info()
2377 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2371 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2378
2372
2379 exc_info = {
2373 exc_info = {
2380 u'status' : 'error',
2374 u'status' : 'error',
2381 u'traceback' : stb,
2375 u'traceback' : stb,
2382 u'ename' : unicode(etype.__name__),
2376 u'ename' : unicode(etype.__name__),
2383 u'evalue' : py3compat.safe_unicode(evalue),
2377 u'evalue' : py3compat.safe_unicode(evalue),
2384 }
2378 }
2385
2379
2386 return exc_info
2380 return exc_info
2387
2381
2388 def _format_user_obj(self, obj):
2382 def _format_user_obj(self, obj):
2389 """format a user object to display dict
2383 """format a user object to display dict
2390
2384
2391 for use in user_expressions / variables
2385 for use in user_expressions / variables
2392 """
2386 """
2393
2387
2394 data, md = self.display_formatter.format(obj)
2388 data, md = self.display_formatter.format(obj)
2395 value = {
2389 value = {
2396 'status' : 'ok',
2390 'status' : 'ok',
2397 'data' : data,
2391 'data' : data,
2398 'metadata' : md,
2392 'metadata' : md,
2399 }
2393 }
2400 return value
2394 return value
2401
2395
2402 def user_variables(self, names):
2396 def user_variables(self, names):
2403 """Get a list of variable names from the user's namespace.
2397 """Get a list of variable names from the user's namespace.
2404
2398
2405 Parameters
2399 Parameters
2406 ----------
2400 ----------
2407 names : list of strings
2401 names : list of strings
2408 A list of names of variables to be read from the user namespace.
2402 A list of names of variables to be read from the user namespace.
2409
2403
2410 Returns
2404 Returns
2411 -------
2405 -------
2412 A dict, keyed by the input names and with the rich mime-type repr(s) of each value.
2406 A dict, keyed by the input names and with the rich mime-type repr(s) of each value.
2413 Each element will be a sub-dict of the same form as a display_data message.
2407 Each element will be a sub-dict of the same form as a display_data message.
2414 """
2408 """
2415 out = {}
2409 out = {}
2416 user_ns = self.user_ns
2410 user_ns = self.user_ns
2417
2411
2418 for varname in names:
2412 for varname in names:
2419 try:
2413 try:
2420 value = self._format_user_obj(user_ns[varname])
2414 value = self._format_user_obj(user_ns[varname])
2421 except:
2415 except:
2422 value = self._user_obj_error()
2416 value = self._user_obj_error()
2423 out[varname] = value
2417 out[varname] = value
2424 return out
2418 return out
2425
2419
2426 def user_expressions(self, expressions):
2420 def user_expressions(self, expressions):
2427 """Evaluate a dict of expressions in the user's namespace.
2421 """Evaluate a dict of expressions in the user's namespace.
2428
2422
2429 Parameters
2423 Parameters
2430 ----------
2424 ----------
2431 expressions : dict
2425 expressions : dict
2432 A dict with string keys and string values. The expression values
2426 A dict with string keys and string values. The expression values
2433 should be valid Python expressions, each of which will be evaluated
2427 should be valid Python expressions, each of which will be evaluated
2434 in the user namespace.
2428 in the user namespace.
2435
2429
2436 Returns
2430 Returns
2437 -------
2431 -------
2438 A dict, keyed like the input expressions dict, with the rich mime-typed
2432 A dict, keyed like the input expressions dict, with the rich mime-typed
2439 display_data of each value.
2433 display_data of each value.
2440 """
2434 """
2441 out = {}
2435 out = {}
2442 user_ns = self.user_ns
2436 user_ns = self.user_ns
2443 global_ns = self.user_global_ns
2437 global_ns = self.user_global_ns
2444
2438
2445 for key, expr in expressions.iteritems():
2439 for key, expr in expressions.iteritems():
2446 try:
2440 try:
2447 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2441 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2448 except:
2442 except:
2449 value = self._user_obj_error()
2443 value = self._user_obj_error()
2450 out[key] = value
2444 out[key] = value
2451 return out
2445 return out
2452
2446
2453 #-------------------------------------------------------------------------
2447 #-------------------------------------------------------------------------
2454 # Things related to the running of code
2448 # Things related to the running of code
2455 #-------------------------------------------------------------------------
2449 #-------------------------------------------------------------------------
2456
2450
2457 def ex(self, cmd):
2451 def ex(self, cmd):
2458 """Execute a normal python statement in user namespace."""
2452 """Execute a normal python statement in user namespace."""
2459 with self.builtin_trap:
2453 with self.builtin_trap:
2460 exec cmd in self.user_global_ns, self.user_ns
2454 exec cmd in self.user_global_ns, self.user_ns
2461
2455
2462 def ev(self, expr):
2456 def ev(self, expr):
2463 """Evaluate python expression expr in user namespace.
2457 """Evaluate python expression expr in user namespace.
2464
2458
2465 Returns the result of evaluation
2459 Returns the result of evaluation
2466 """
2460 """
2467 with self.builtin_trap:
2461 with self.builtin_trap:
2468 return eval(expr, self.user_global_ns, self.user_ns)
2462 return eval(expr, self.user_global_ns, self.user_ns)
2469
2463
2470 def safe_execfile(self, fname, *where, **kw):
2464 def safe_execfile(self, fname, *where, **kw):
2471 """A safe version of the builtin execfile().
2465 """A safe version of the builtin execfile().
2472
2466
2473 This version will never throw an exception, but instead print
2467 This version will never throw an exception, but instead print
2474 helpful error messages to the screen. This only works on pure
2468 helpful error messages to the screen. This only works on pure
2475 Python files with the .py extension.
2469 Python files with the .py extension.
2476
2470
2477 Parameters
2471 Parameters
2478 ----------
2472 ----------
2479 fname : string
2473 fname : string
2480 The name of the file to be executed.
2474 The name of the file to be executed.
2481 where : tuple
2475 where : tuple
2482 One or two namespaces, passed to execfile() as (globals,locals).
2476 One or two namespaces, passed to execfile() as (globals,locals).
2483 If only one is given, it is passed as both.
2477 If only one is given, it is passed as both.
2484 exit_ignore : bool (False)
2478 exit_ignore : bool (False)
2485 If True, then silence SystemExit for non-zero status (it is always
2479 If True, then silence SystemExit for non-zero status (it is always
2486 silenced for zero status, as it is so common).
2480 silenced for zero status, as it is so common).
2487 raise_exceptions : bool (False)
2481 raise_exceptions : bool (False)
2488 If True raise exceptions everywhere. Meant for testing.
2482 If True raise exceptions everywhere. Meant for testing.
2489
2483
2490 """
2484 """
2491 kw.setdefault('exit_ignore', False)
2485 kw.setdefault('exit_ignore', False)
2492 kw.setdefault('raise_exceptions', False)
2486 kw.setdefault('raise_exceptions', False)
2493
2487
2494 fname = os.path.abspath(os.path.expanduser(fname))
2488 fname = os.path.abspath(os.path.expanduser(fname))
2495
2489
2496 # Make sure we can open the file
2490 # Make sure we can open the file
2497 try:
2491 try:
2498 with open(fname) as thefile:
2492 with open(fname) as thefile:
2499 pass
2493 pass
2500 except:
2494 except:
2501 warn('Could not open file <%s> for safe execution.' % fname)
2495 warn('Could not open file <%s> for safe execution.' % fname)
2502 return
2496 return
2503
2497
2504 # Find things also in current directory. This is needed to mimic the
2498 # Find things also in current directory. This is needed to mimic the
2505 # behavior of running a script from the system command line, where
2499 # behavior of running a script from the system command line, where
2506 # Python inserts the script's directory into sys.path
2500 # Python inserts the script's directory into sys.path
2507 dname = os.path.dirname(fname)
2501 dname = os.path.dirname(fname)
2508
2502
2509 with prepended_to_syspath(dname):
2503 with prepended_to_syspath(dname):
2510 try:
2504 try:
2511 py3compat.execfile(fname,*where)
2505 py3compat.execfile(fname,*where)
2512 except SystemExit as status:
2506 except SystemExit as status:
2513 # If the call was made with 0 or None exit status (sys.exit(0)
2507 # If the call was made with 0 or None exit status (sys.exit(0)
2514 # or sys.exit() ), don't bother showing a traceback, as both of
2508 # or sys.exit() ), don't bother showing a traceback, as both of
2515 # these are considered normal by the OS:
2509 # these are considered normal by the OS:
2516 # > python -c'import sys;sys.exit(0)'; echo $?
2510 # > python -c'import sys;sys.exit(0)'; echo $?
2517 # 0
2511 # 0
2518 # > python -c'import sys;sys.exit()'; echo $?
2512 # > python -c'import sys;sys.exit()'; echo $?
2519 # 0
2513 # 0
2520 # For other exit status, we show the exception unless
2514 # For other exit status, we show the exception unless
2521 # explicitly silenced, but only in short form.
2515 # explicitly silenced, but only in short form.
2522 if kw['raise_exceptions']:
2516 if kw['raise_exceptions']:
2523 raise
2517 raise
2524 if status.code and not kw['exit_ignore']:
2518 if status.code and not kw['exit_ignore']:
2525 self.showtraceback(exception_only=True)
2519 self.showtraceback(exception_only=True)
2526 except:
2520 except:
2527 if kw['raise_exceptions']:
2521 if kw['raise_exceptions']:
2528 raise
2522 raise
2529 self.showtraceback()
2523 self.showtraceback()
2530
2524
2531 def safe_execfile_ipy(self, fname):
2525 def safe_execfile_ipy(self, fname):
2532 """Like safe_execfile, but for .ipy files with IPython syntax.
2526 """Like safe_execfile, but for .ipy files with IPython syntax.
2533
2527
2534 Parameters
2528 Parameters
2535 ----------
2529 ----------
2536 fname : str
2530 fname : str
2537 The name of the file to execute. The filename must have a
2531 The name of the file to execute. The filename must have a
2538 .ipy extension.
2532 .ipy extension.
2539 """
2533 """
2540 fname = os.path.abspath(os.path.expanduser(fname))
2534 fname = os.path.abspath(os.path.expanduser(fname))
2541
2535
2542 # Make sure we can open the file
2536 # Make sure we can open the file
2543 try:
2537 try:
2544 with open(fname) as thefile:
2538 with open(fname) as thefile:
2545 pass
2539 pass
2546 except:
2540 except:
2547 warn('Could not open file <%s> for safe execution.' % fname)
2541 warn('Could not open file <%s> for safe execution.' % fname)
2548 return
2542 return
2549
2543
2550 # Find things also in current directory. This is needed to mimic the
2544 # Find things also in current directory. This is needed to mimic the
2551 # behavior of running a script from the system command line, where
2545 # behavior of running a script from the system command line, where
2552 # Python inserts the script's directory into sys.path
2546 # Python inserts the script's directory into sys.path
2553 dname = os.path.dirname(fname)
2547 dname = os.path.dirname(fname)
2554
2548
2555 with prepended_to_syspath(dname):
2549 with prepended_to_syspath(dname):
2556 try:
2550 try:
2557 with open(fname) as thefile:
2551 with open(fname) as thefile:
2558 # self.run_cell currently captures all exceptions
2552 # self.run_cell currently captures all exceptions
2559 # raised in user code. It would be nice if there were
2553 # raised in user code. It would be nice if there were
2560 # versions of runlines, execfile that did raise, so
2554 # versions of runlines, execfile that did raise, so
2561 # we could catch the errors.
2555 # we could catch the errors.
2562 self.run_cell(thefile.read(), store_history=False, shell_futures=False)
2556 self.run_cell(thefile.read(), store_history=False, shell_futures=False)
2563 except:
2557 except:
2564 self.showtraceback()
2558 self.showtraceback()
2565 warn('Unknown failure executing file: <%s>' % fname)
2559 warn('Unknown failure executing file: <%s>' % fname)
2566
2560
2567 def safe_run_module(self, mod_name, where):
2561 def safe_run_module(self, mod_name, where):
2568 """A safe version of runpy.run_module().
2562 """A safe version of runpy.run_module().
2569
2563
2570 This version will never throw an exception, but instead print
2564 This version will never throw an exception, but instead print
2571 helpful error messages to the screen.
2565 helpful error messages to the screen.
2572
2566
2573 `SystemExit` exceptions with status code 0 or None are ignored.
2567 `SystemExit` exceptions with status code 0 or None are ignored.
2574
2568
2575 Parameters
2569 Parameters
2576 ----------
2570 ----------
2577 mod_name : string
2571 mod_name : string
2578 The name of the module to be executed.
2572 The name of the module to be executed.
2579 where : dict
2573 where : dict
2580 The globals namespace.
2574 The globals namespace.
2581 """
2575 """
2582 try:
2576 try:
2583 try:
2577 try:
2584 where.update(
2578 where.update(
2585 runpy.run_module(str(mod_name), run_name="__main__",
2579 runpy.run_module(str(mod_name), run_name="__main__",
2586 alter_sys=True)
2580 alter_sys=True)
2587 )
2581 )
2588 except SystemExit as status:
2582 except SystemExit as status:
2589 if status.code:
2583 if status.code:
2590 raise
2584 raise
2591 except:
2585 except:
2592 self.showtraceback()
2586 self.showtraceback()
2593 warn('Unknown failure executing module: <%s>' % mod_name)
2587 warn('Unknown failure executing module: <%s>' % mod_name)
2594
2588
2595 def _run_cached_cell_magic(self, magic_name, line):
2589 def _run_cached_cell_magic(self, magic_name, line):
2596 """Special method to call a cell magic with the data stored in self.
2590 """Special method to call a cell magic with the data stored in self.
2597 """
2591 """
2598 cell = self._current_cell_magic_body
2592 cell = self._current_cell_magic_body
2599 self._current_cell_magic_body = None
2593 self._current_cell_magic_body = None
2600 return self.run_cell_magic(magic_name, line, cell)
2594 return self.run_cell_magic(magic_name, line, cell)
2601
2595
2602 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2596 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2603 """Run a complete IPython cell.
2597 """Run a complete IPython cell.
2604
2598
2605 Parameters
2599 Parameters
2606 ----------
2600 ----------
2607 raw_cell : str
2601 raw_cell : str
2608 The code (including IPython code such as %magic functions) to run.
2602 The code (including IPython code such as %magic functions) to run.
2609 store_history : bool
2603 store_history : bool
2610 If True, the raw and translated cell will be stored in IPython's
2604 If True, the raw and translated cell will be stored in IPython's
2611 history. For user code calling back into IPython's machinery, this
2605 history. For user code calling back into IPython's machinery, this
2612 should be set to False.
2606 should be set to False.
2613 silent : bool
2607 silent : bool
2614 If True, avoid side-effects, such as implicit displayhooks and
2608 If True, avoid side-effects, such as implicit displayhooks and
2615 and logging. silent=True forces store_history=False.
2609 and logging. silent=True forces store_history=False.
2616 shell_futures : bool
2610 shell_futures : bool
2617 If True, the code will share future statements with the interactive
2611 If True, the code will share future statements with the interactive
2618 shell. It will both be affected by previous __future__ imports, and
2612 shell. It will both be affected by previous __future__ imports, and
2619 any __future__ imports in the code will affect the shell. If False,
2613 any __future__ imports in the code will affect the shell. If False,
2620 __future__ imports are not shared in either direction.
2614 __future__ imports are not shared in either direction.
2621 """
2615 """
2622 if (not raw_cell) or raw_cell.isspace():
2616 if (not raw_cell) or raw_cell.isspace():
2623 return
2617 return
2624
2618
2625 if silent:
2619 if silent:
2626 store_history = False
2620 store_history = False
2627
2621
2628 self.input_transformer_manager.push(raw_cell)
2622 self.input_transformer_manager.push(raw_cell)
2629 cell = self.input_transformer_manager.source_reset()
2623 cell = self.input_transformer_manager.source_reset()
2630
2624
2631 # Our own compiler remembers the __future__ environment. If we want to
2625 # Our own compiler remembers the __future__ environment. If we want to
2632 # run code with a separate __future__ environment, use the default
2626 # run code with a separate __future__ environment, use the default
2633 # compiler
2627 # compiler
2634 compiler = self.compile if shell_futures else CachingCompiler()
2628 compiler = self.compile if shell_futures else CachingCompiler()
2635
2629
2636 with self.builtin_trap:
2630 with self.builtin_trap:
2637 prefilter_failed = False
2631 prefilter_failed = False
2638 if len(cell.splitlines()) == 1:
2632 if len(cell.splitlines()) == 1:
2639 try:
2633 try:
2640 # use prefilter_lines to handle trailing newlines
2634 # use prefilter_lines to handle trailing newlines
2641 # restore trailing newline for ast.parse
2635 # restore trailing newline for ast.parse
2642 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2636 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2643 except AliasError as e:
2637 except AliasError as e:
2644 error(e)
2638 error(e)
2645 prefilter_failed = True
2639 prefilter_failed = True
2646 except Exception:
2640 except Exception:
2647 # don't allow prefilter errors to crash IPython
2641 # don't allow prefilter errors to crash IPython
2648 self.showtraceback()
2642 self.showtraceback()
2649 prefilter_failed = True
2643 prefilter_failed = True
2650
2644
2651 # Store raw and processed history
2645 # Store raw and processed history
2652 if store_history:
2646 if store_history:
2653 self.history_manager.store_inputs(self.execution_count,
2647 self.history_manager.store_inputs(self.execution_count,
2654 cell, raw_cell)
2648 cell, raw_cell)
2655 if not silent:
2649 if not silent:
2656 self.logger.log(cell, raw_cell)
2650 self.logger.log(cell, raw_cell)
2657
2651
2658 if not prefilter_failed:
2652 if not prefilter_failed:
2659 # don't run if prefilter failed
2653 # don't run if prefilter failed
2660 cell_name = self.compile.cache(cell, self.execution_count)
2654 cell_name = self.compile.cache(cell, self.execution_count)
2661
2655
2662 with self.display_trap:
2656 with self.display_trap:
2663 try:
2657 try:
2664 code_ast = compiler.ast_parse(cell, filename=cell_name)
2658 code_ast = compiler.ast_parse(cell, filename=cell_name)
2665 except IndentationError:
2659 except IndentationError:
2666 self.showindentationerror()
2660 self.showindentationerror()
2667 if store_history:
2661 if store_history:
2668 self.execution_count += 1
2662 self.execution_count += 1
2669 return None
2663 return None
2670 except (OverflowError, SyntaxError, ValueError, TypeError,
2664 except (OverflowError, SyntaxError, ValueError, TypeError,
2671 MemoryError):
2665 MemoryError):
2672 self.showsyntaxerror()
2666 self.showsyntaxerror()
2673 if store_history:
2667 if store_history:
2674 self.execution_count += 1
2668 self.execution_count += 1
2675 return None
2669 return None
2676
2670
2677 code_ast = self.transform_ast(code_ast)
2671 code_ast = self.transform_ast(code_ast)
2678
2672
2679 interactivity = "none" if silent else self.ast_node_interactivity
2673 interactivity = "none" if silent else self.ast_node_interactivity
2680 self.run_ast_nodes(code_ast.body, cell_name,
2674 self.run_ast_nodes(code_ast.body, cell_name,
2681 interactivity=interactivity, compiler=compiler)
2675 interactivity=interactivity, compiler=compiler)
2682
2676
2683 # Execute any registered post-execution functions.
2677 # Execute any registered post-execution functions.
2684 # unless we are silent
2678 # unless we are silent
2685 post_exec = [] if silent else self._post_execute.iteritems()
2679 post_exec = [] if silent else self._post_execute.iteritems()
2686
2680
2687 for func, status in post_exec:
2681 for func, status in post_exec:
2688 if self.disable_failing_post_execute and not status:
2682 if self.disable_failing_post_execute and not status:
2689 continue
2683 continue
2690 try:
2684 try:
2691 func()
2685 func()
2692 except KeyboardInterrupt:
2686 except KeyboardInterrupt:
2693 print("\nKeyboardInterrupt", file=io.stderr)
2687 print("\nKeyboardInterrupt", file=io.stderr)
2694 except Exception:
2688 except Exception:
2695 # register as failing:
2689 # register as failing:
2696 self._post_execute[func] = False
2690 self._post_execute[func] = False
2697 self.showtraceback()
2691 self.showtraceback()
2698 print('\n'.join([
2692 print('\n'.join([
2699 "post-execution function %r produced an error." % func,
2693 "post-execution function %r produced an error." % func,
2700 "If this problem persists, you can disable failing post-exec functions with:",
2694 "If this problem persists, you can disable failing post-exec functions with:",
2701 "",
2695 "",
2702 " get_ipython().disable_failing_post_execute = True"
2696 " get_ipython().disable_failing_post_execute = True"
2703 ]), file=io.stderr)
2697 ]), file=io.stderr)
2704
2698
2705 if store_history:
2699 if store_history:
2706 # Write output to the database. Does nothing unless
2700 # Write output to the database. Does nothing unless
2707 # history output logging is enabled.
2701 # history output logging is enabled.
2708 self.history_manager.store_output(self.execution_count)
2702 self.history_manager.store_output(self.execution_count)
2709 # Each cell is a *single* input, regardless of how many lines it has
2703 # Each cell is a *single* input, regardless of how many lines it has
2710 self.execution_count += 1
2704 self.execution_count += 1
2711
2705
2712 def transform_ast(self, node):
2706 def transform_ast(self, node):
2713 """Apply the AST transformations from self.ast_transformers
2707 """Apply the AST transformations from self.ast_transformers
2714
2708
2715 Parameters
2709 Parameters
2716 ----------
2710 ----------
2717 node : ast.Node
2711 node : ast.Node
2718 The root node to be transformed. Typically called with the ast.Module
2712 The root node to be transformed. Typically called with the ast.Module
2719 produced by parsing user input.
2713 produced by parsing user input.
2720
2714
2721 Returns
2715 Returns
2722 -------
2716 -------
2723 An ast.Node corresponding to the node it was called with. Note that it
2717 An ast.Node corresponding to the node it was called with. Note that it
2724 may also modify the passed object, so don't rely on references to the
2718 may also modify the passed object, so don't rely on references to the
2725 original AST.
2719 original AST.
2726 """
2720 """
2727 for transformer in self.ast_transformers:
2721 for transformer in self.ast_transformers:
2728 try:
2722 try:
2729 node = transformer.visit(node)
2723 node = transformer.visit(node)
2730 except Exception:
2724 except Exception:
2731 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2725 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2732 self.ast_transformers.remove(transformer)
2726 self.ast_transformers.remove(transformer)
2733
2727
2734 if self.ast_transformers:
2728 if self.ast_transformers:
2735 ast.fix_missing_locations(node)
2729 ast.fix_missing_locations(node)
2736 return node
2730 return node
2737
2731
2738
2732
2739 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2733 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2740 compiler=compile):
2734 compiler=compile):
2741 """Run a sequence of AST nodes. The execution mode depends on the
2735 """Run a sequence of AST nodes. The execution mode depends on the
2742 interactivity parameter.
2736 interactivity parameter.
2743
2737
2744 Parameters
2738 Parameters
2745 ----------
2739 ----------
2746 nodelist : list
2740 nodelist : list
2747 A sequence of AST nodes to run.
2741 A sequence of AST nodes to run.
2748 cell_name : str
2742 cell_name : str
2749 Will be passed to the compiler as the filename of the cell. Typically
2743 Will be passed to the compiler as the filename of the cell. Typically
2750 the value returned by ip.compile.cache(cell).
2744 the value returned by ip.compile.cache(cell).
2751 interactivity : str
2745 interactivity : str
2752 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2746 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2753 run interactively (displaying output from expressions). 'last_expr'
2747 run interactively (displaying output from expressions). 'last_expr'
2754 will run the last node interactively only if it is an expression (i.e.
2748 will run the last node interactively only if it is an expression (i.e.
2755 expressions in loops or other blocks are not displayed. Other values
2749 expressions in loops or other blocks are not displayed. Other values
2756 for this parameter will raise a ValueError.
2750 for this parameter will raise a ValueError.
2757 compiler : callable
2751 compiler : callable
2758 A function with the same interface as the built-in compile(), to turn
2752 A function with the same interface as the built-in compile(), to turn
2759 the AST nodes into code objects. Default is the built-in compile().
2753 the AST nodes into code objects. Default is the built-in compile().
2760 """
2754 """
2761 if not nodelist:
2755 if not nodelist:
2762 return
2756 return
2763
2757
2764 if interactivity == 'last_expr':
2758 if interactivity == 'last_expr':
2765 if isinstance(nodelist[-1], ast.Expr):
2759 if isinstance(nodelist[-1], ast.Expr):
2766 interactivity = "last"
2760 interactivity = "last"
2767 else:
2761 else:
2768 interactivity = "none"
2762 interactivity = "none"
2769
2763
2770 if interactivity == 'none':
2764 if interactivity == 'none':
2771 to_run_exec, to_run_interactive = nodelist, []
2765 to_run_exec, to_run_interactive = nodelist, []
2772 elif interactivity == 'last':
2766 elif interactivity == 'last':
2773 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2767 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2774 elif interactivity == 'all':
2768 elif interactivity == 'all':
2775 to_run_exec, to_run_interactive = [], nodelist
2769 to_run_exec, to_run_interactive = [], nodelist
2776 else:
2770 else:
2777 raise ValueError("Interactivity was %r" % interactivity)
2771 raise ValueError("Interactivity was %r" % interactivity)
2778
2772
2779 exec_count = self.execution_count
2773 exec_count = self.execution_count
2780
2774
2781 try:
2775 try:
2782 for i, node in enumerate(to_run_exec):
2776 for i, node in enumerate(to_run_exec):
2783 mod = ast.Module([node])
2777 mod = ast.Module([node])
2784 code = compiler(mod, cell_name, "exec")
2778 code = compiler(mod, cell_name, "exec")
2785 if self.run_code(code):
2779 if self.run_code(code):
2786 return True
2780 return True
2787
2781
2788 for i, node in enumerate(to_run_interactive):
2782 for i, node in enumerate(to_run_interactive):
2789 mod = ast.Interactive([node])
2783 mod = ast.Interactive([node])
2790 code = compiler(mod, cell_name, "single")
2784 code = compiler(mod, cell_name, "single")
2791 if self.run_code(code):
2785 if self.run_code(code):
2792 return True
2786 return True
2793
2787
2794 # Flush softspace
2788 # Flush softspace
2795 if softspace(sys.stdout, 0):
2789 if softspace(sys.stdout, 0):
2796 print()
2790 print()
2797
2791
2798 except:
2792 except:
2799 # It's possible to have exceptions raised here, typically by
2793 # It's possible to have exceptions raised here, typically by
2800 # compilation of odd code (such as a naked 'return' outside a
2794 # compilation of odd code (such as a naked 'return' outside a
2801 # function) that did parse but isn't valid. Typically the exception
2795 # function) that did parse but isn't valid. Typically the exception
2802 # is a SyntaxError, but it's safest just to catch anything and show
2796 # is a SyntaxError, but it's safest just to catch anything and show
2803 # the user a traceback.
2797 # the user a traceback.
2804
2798
2805 # We do only one try/except outside the loop to minimize the impact
2799 # We do only one try/except outside the loop to minimize the impact
2806 # on runtime, and also because if any node in the node list is
2800 # on runtime, and also because if any node in the node list is
2807 # broken, we should stop execution completely.
2801 # broken, we should stop execution completely.
2808 self.showtraceback()
2802 self.showtraceback()
2809
2803
2810 return False
2804 return False
2811
2805
2812 def run_code(self, code_obj):
2806 def run_code(self, code_obj):
2813 """Execute a code object.
2807 """Execute a code object.
2814
2808
2815 When an exception occurs, self.showtraceback() is called to display a
2809 When an exception occurs, self.showtraceback() is called to display a
2816 traceback.
2810 traceback.
2817
2811
2818 Parameters
2812 Parameters
2819 ----------
2813 ----------
2820 code_obj : code object
2814 code_obj : code object
2821 A compiled code object, to be executed
2815 A compiled code object, to be executed
2822
2816
2823 Returns
2817 Returns
2824 -------
2818 -------
2825 False : successful execution.
2819 False : successful execution.
2826 True : an error occurred.
2820 True : an error occurred.
2827 """
2821 """
2828
2822
2829 # Set our own excepthook in case the user code tries to call it
2823 # Set our own excepthook in case the user code tries to call it
2830 # directly, so that the IPython crash handler doesn't get triggered
2824 # directly, so that the IPython crash handler doesn't get triggered
2831 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2825 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2832
2826
2833 # we save the original sys.excepthook in the instance, in case config
2827 # we save the original sys.excepthook in the instance, in case config
2834 # code (such as magics) needs access to it.
2828 # code (such as magics) needs access to it.
2835 self.sys_excepthook = old_excepthook
2829 self.sys_excepthook = old_excepthook
2836 outflag = 1 # happens in more places, so it's easier as default
2830 outflag = 1 # happens in more places, so it's easier as default
2837 try:
2831 try:
2838 try:
2832 try:
2839 self.hooks.pre_run_code_hook()
2833 self.hooks.pre_run_code_hook()
2840 #rprint('Running code', repr(code_obj)) # dbg
2834 #rprint('Running code', repr(code_obj)) # dbg
2841 exec code_obj in self.user_global_ns, self.user_ns
2835 exec code_obj in self.user_global_ns, self.user_ns
2842 finally:
2836 finally:
2843 # Reset our crash handler in place
2837 # Reset our crash handler in place
2844 sys.excepthook = old_excepthook
2838 sys.excepthook = old_excepthook
2845 except SystemExit:
2839 except SystemExit:
2846 self.showtraceback(exception_only=True)
2840 self.showtraceback(exception_only=True)
2847 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2841 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2848 except self.custom_exceptions:
2842 except self.custom_exceptions:
2849 etype,value,tb = sys.exc_info()
2843 etype,value,tb = sys.exc_info()
2850 self.CustomTB(etype,value,tb)
2844 self.CustomTB(etype,value,tb)
2851 except:
2845 except:
2852 self.showtraceback()
2846 self.showtraceback()
2853 else:
2847 else:
2854 outflag = 0
2848 outflag = 0
2855 return outflag
2849 return outflag
2856
2850
2857 # For backwards compatibility
2851 # For backwards compatibility
2858 runcode = run_code
2852 runcode = run_code
2859
2853
2860 #-------------------------------------------------------------------------
2854 #-------------------------------------------------------------------------
2861 # Things related to GUI support and pylab
2855 # Things related to GUI support and pylab
2862 #-------------------------------------------------------------------------
2856 #-------------------------------------------------------------------------
2863
2857
2864 def enable_gui(self, gui=None):
2858 def enable_gui(self, gui=None):
2865 raise NotImplementedError('Implement enable_gui in a subclass')
2859 raise NotImplementedError('Implement enable_gui in a subclass')
2866
2860
2867 def enable_matplotlib(self, gui=None):
2861 def enable_matplotlib(self, gui=None):
2868 """Enable interactive matplotlib and inline figure support.
2862 """Enable interactive matplotlib and inline figure support.
2869
2863
2870 This takes the following steps:
2864 This takes the following steps:
2871
2865
2872 1. select the appropriate eventloop and matplotlib backend
2866 1. select the appropriate eventloop and matplotlib backend
2873 2. set up matplotlib for interactive use with that backend
2867 2. set up matplotlib for interactive use with that backend
2874 3. configure formatters for inline figure display
2868 3. configure formatters for inline figure display
2875 4. enable the selected gui eventloop
2869 4. enable the selected gui eventloop
2876
2870
2877 Parameters
2871 Parameters
2878 ----------
2872 ----------
2879 gui : optional, string
2873 gui : optional, string
2880 If given, dictates the choice of matplotlib GUI backend to use
2874 If given, dictates the choice of matplotlib GUI backend to use
2881 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2875 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2882 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2876 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2883 matplotlib (as dictated by the matplotlib build-time options plus the
2877 matplotlib (as dictated by the matplotlib build-time options plus the
2884 user's matplotlibrc configuration file). Note that not all backends
2878 user's matplotlibrc configuration file). Note that not all backends
2885 make sense in all contexts, for example a terminal ipython can't
2879 make sense in all contexts, for example a terminal ipython can't
2886 display figures inline.
2880 display figures inline.
2887 """
2881 """
2888 from IPython.core import pylabtools as pt
2882 from IPython.core import pylabtools as pt
2889 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2883 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2890
2884
2891 if gui != 'inline':
2885 if gui != 'inline':
2892 # If we have our first gui selection, store it
2886 # If we have our first gui selection, store it
2893 if self.pylab_gui_select is None:
2887 if self.pylab_gui_select is None:
2894 self.pylab_gui_select = gui
2888 self.pylab_gui_select = gui
2895 # Otherwise if they are different
2889 # Otherwise if they are different
2896 elif gui != self.pylab_gui_select:
2890 elif gui != self.pylab_gui_select:
2897 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2891 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2898 ' Using %s instead.' % (gui, self.pylab_gui_select))
2892 ' Using %s instead.' % (gui, self.pylab_gui_select))
2899 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2893 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2900
2894
2901 pt.activate_matplotlib(backend)
2895 pt.activate_matplotlib(backend)
2902 pt.configure_inline_support(self, backend)
2896 pt.configure_inline_support(self, backend)
2903
2897
2904 # Now we must activate the gui pylab wants to use, and fix %run to take
2898 # Now we must activate the gui pylab wants to use, and fix %run to take
2905 # plot updates into account
2899 # plot updates into account
2906 self.enable_gui(gui)
2900 self.enable_gui(gui)
2907 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2901 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2908 pt.mpl_runner(self.safe_execfile)
2902 pt.mpl_runner(self.safe_execfile)
2909
2903
2910 return gui, backend
2904 return gui, backend
2911
2905
2912 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2906 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2913 """Activate pylab support at runtime.
2907 """Activate pylab support at runtime.
2914
2908
2915 This turns on support for matplotlib, preloads into the interactive
2909 This turns on support for matplotlib, preloads into the interactive
2916 namespace all of numpy and pylab, and configures IPython to correctly
2910 namespace all of numpy and pylab, and configures IPython to correctly
2917 interact with the GUI event loop. The GUI backend to be used can be
2911 interact with the GUI event loop. The GUI backend to be used can be
2918 optionally selected with the optional ``gui`` argument.
2912 optionally selected with the optional ``gui`` argument.
2919
2913
2920 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2914 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2921
2915
2922 Parameters
2916 Parameters
2923 ----------
2917 ----------
2924 gui : optional, string
2918 gui : optional, string
2925 If given, dictates the choice of matplotlib GUI backend to use
2919 If given, dictates the choice of matplotlib GUI backend to use
2926 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2920 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2927 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2921 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2928 matplotlib (as dictated by the matplotlib build-time options plus the
2922 matplotlib (as dictated by the matplotlib build-time options plus the
2929 user's matplotlibrc configuration file). Note that not all backends
2923 user's matplotlibrc configuration file). Note that not all backends
2930 make sense in all contexts, for example a terminal ipython can't
2924 make sense in all contexts, for example a terminal ipython can't
2931 display figures inline.
2925 display figures inline.
2932 import_all : optional, bool, default: True
2926 import_all : optional, bool, default: True
2933 Whether to do `from numpy import *` and `from pylab import *`
2927 Whether to do `from numpy import *` and `from pylab import *`
2934 in addition to module imports.
2928 in addition to module imports.
2935 welcome_message : deprecated
2929 welcome_message : deprecated
2936 This argument is ignored, no welcome message will be displayed.
2930 This argument is ignored, no welcome message will be displayed.
2937 """
2931 """
2938 from IPython.core.pylabtools import import_pylab
2932 from IPython.core.pylabtools import import_pylab
2939
2933
2940 gui, backend = self.enable_matplotlib(gui)
2934 gui, backend = self.enable_matplotlib(gui)
2941
2935
2942 # We want to prevent the loading of pylab to pollute the user's
2936 # We want to prevent the loading of pylab to pollute the user's
2943 # namespace as shown by the %who* magics, so we execute the activation
2937 # namespace as shown by the %who* magics, so we execute the activation
2944 # code in an empty namespace, and we update *both* user_ns and
2938 # code in an empty namespace, and we update *both* user_ns and
2945 # user_ns_hidden with this information.
2939 # user_ns_hidden with this information.
2946 ns = {}
2940 ns = {}
2947 import_pylab(ns, import_all)
2941 import_pylab(ns, import_all)
2948 # warn about clobbered names
2942 # warn about clobbered names
2949 ignored = set(["__builtins__"])
2943 ignored = set(["__builtins__"])
2950 both = set(ns).intersection(self.user_ns).difference(ignored)
2944 both = set(ns).intersection(self.user_ns).difference(ignored)
2951 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2945 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2952 self.user_ns.update(ns)
2946 self.user_ns.update(ns)
2953 self.user_ns_hidden.update(ns)
2947 self.user_ns_hidden.update(ns)
2954 return gui, backend, clobbered
2948 return gui, backend, clobbered
2955
2949
2956 #-------------------------------------------------------------------------
2950 #-------------------------------------------------------------------------
2957 # Utilities
2951 # Utilities
2958 #-------------------------------------------------------------------------
2952 #-------------------------------------------------------------------------
2959
2953
2960 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2954 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2961 """Expand python variables in a string.
2955 """Expand python variables in a string.
2962
2956
2963 The depth argument indicates how many frames above the caller should
2957 The depth argument indicates how many frames above the caller should
2964 be walked to look for the local namespace where to expand variables.
2958 be walked to look for the local namespace where to expand variables.
2965
2959
2966 The global namespace for expansion is always the user's interactive
2960 The global namespace for expansion is always the user's interactive
2967 namespace.
2961 namespace.
2968 """
2962 """
2969 ns = self.user_ns.copy()
2963 ns = self.user_ns.copy()
2970 ns.update(sys._getframe(depth+1).f_locals)
2964 ns.update(sys._getframe(depth+1).f_locals)
2971 try:
2965 try:
2972 # We have to use .vformat() here, because 'self' is a valid and common
2966 # We have to use .vformat() here, because 'self' is a valid and common
2973 # name, and expanding **ns for .format() would make it collide with
2967 # name, and expanding **ns for .format() would make it collide with
2974 # the 'self' argument of the method.
2968 # the 'self' argument of the method.
2975 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2969 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2976 except Exception:
2970 except Exception:
2977 # if formatter couldn't format, just let it go untransformed
2971 # if formatter couldn't format, just let it go untransformed
2978 pass
2972 pass
2979 return cmd
2973 return cmd
2980
2974
2981 def mktempfile(self, data=None, prefix='ipython_edit_'):
2975 def mktempfile(self, data=None, prefix='ipython_edit_'):
2982 """Make a new tempfile and return its filename.
2976 """Make a new tempfile and return its filename.
2983
2977
2984 This makes a call to tempfile.mktemp, but it registers the created
2978 This makes a call to tempfile.mktemp, but it registers the created
2985 filename internally so ipython cleans it up at exit time.
2979 filename internally so ipython cleans it up at exit time.
2986
2980
2987 Optional inputs:
2981 Optional inputs:
2988
2982
2989 - data(None): if data is given, it gets written out to the temp file
2983 - data(None): if data is given, it gets written out to the temp file
2990 immediately, and the file is closed again."""
2984 immediately, and the file is closed again."""
2991
2985
2992 filename = tempfile.mktemp('.py', prefix)
2986 filename = tempfile.mktemp('.py', prefix)
2993 self.tempfiles.append(filename)
2987 self.tempfiles.append(filename)
2994
2988
2995 if data:
2989 if data:
2996 tmp_file = open(filename,'w')
2990 tmp_file = open(filename,'w')
2997 tmp_file.write(data)
2991 tmp_file.write(data)
2998 tmp_file.close()
2992 tmp_file.close()
2999 return filename
2993 return filename
3000
2994
3001 # TODO: This should be removed when Term is refactored.
2995 # TODO: This should be removed when Term is refactored.
3002 def write(self,data):
2996 def write(self,data):
3003 """Write a string to the default output"""
2997 """Write a string to the default output"""
3004 io.stdout.write(data)
2998 io.stdout.write(data)
3005
2999
3006 # TODO: This should be removed when Term is refactored.
3000 # TODO: This should be removed when Term is refactored.
3007 def write_err(self,data):
3001 def write_err(self,data):
3008 """Write a string to the default error output"""
3002 """Write a string to the default error output"""
3009 io.stderr.write(data)
3003 io.stderr.write(data)
3010
3004
3011 def ask_yes_no(self, prompt, default=None):
3005 def ask_yes_no(self, prompt, default=None):
3012 if self.quiet:
3006 if self.quiet:
3013 return True
3007 return True
3014 return ask_yes_no(prompt,default)
3008 return ask_yes_no(prompt,default)
3015
3009
3016 def show_usage(self):
3010 def show_usage(self):
3017 """Show a usage message"""
3011 """Show a usage message"""
3018 page.page(IPython.core.usage.interactive_usage)
3012 page.page(IPython.core.usage.interactive_usage)
3019
3013
3020 def extract_input_lines(self, range_str, raw=False):
3014 def extract_input_lines(self, range_str, raw=False):
3021 """Return as a string a set of input history slices.
3015 """Return as a string a set of input history slices.
3022
3016
3023 Parameters
3017 Parameters
3024 ----------
3018 ----------
3025 range_str : string
3019 range_str : string
3026 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3020 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3027 since this function is for use by magic functions which get their
3021 since this function is for use by magic functions which get their
3028 arguments as strings. The number before the / is the session
3022 arguments as strings. The number before the / is the session
3029 number: ~n goes n back from the current session.
3023 number: ~n goes n back from the current session.
3030
3024
3031 Optional Parameters:
3025 Optional Parameters:
3032 - raw(False): by default, the processed input is used. If this is
3026 - raw(False): by default, the processed input is used. If this is
3033 true, the raw input history is used instead.
3027 true, the raw input history is used instead.
3034
3028
3035 Note that slices can be called with two notations:
3029 Note that slices can be called with two notations:
3036
3030
3037 N:M -> standard python form, means including items N...(M-1).
3031 N:M -> standard python form, means including items N...(M-1).
3038
3032
3039 N-M -> include items N..M (closed endpoint).
3033 N-M -> include items N..M (closed endpoint).
3040 """
3034 """
3041 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3035 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3042 return "\n".join(x for _, _, x in lines)
3036 return "\n".join(x for _, _, x in lines)
3043
3037
3044 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
3038 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
3045 """Get a code string from history, file, url, or a string or macro.
3039 """Get a code string from history, file, url, or a string or macro.
3046
3040
3047 This is mainly used by magic functions.
3041 This is mainly used by magic functions.
3048
3042
3049 Parameters
3043 Parameters
3050 ----------
3044 ----------
3051
3045
3052 target : str
3046 target : str
3053
3047
3054 A string specifying code to retrieve. This will be tried respectively
3048 A string specifying code to retrieve. This will be tried respectively
3055 as: ranges of input history (see %history for syntax), url,
3049 as: ranges of input history (see %history for syntax), url,
3056 correspnding .py file, filename, or an expression evaluating to a
3050 correspnding .py file, filename, or an expression evaluating to a
3057 string or Macro in the user namespace.
3051 string or Macro in the user namespace.
3058
3052
3059 raw : bool
3053 raw : bool
3060 If true (default), retrieve raw history. Has no effect on the other
3054 If true (default), retrieve raw history. Has no effect on the other
3061 retrieval mechanisms.
3055 retrieval mechanisms.
3062
3056
3063 py_only : bool (default False)
3057 py_only : bool (default False)
3064 Only try to fetch python code, do not try alternative methods to decode file
3058 Only try to fetch python code, do not try alternative methods to decode file
3065 if unicode fails.
3059 if unicode fails.
3066
3060
3067 Returns
3061 Returns
3068 -------
3062 -------
3069 A string of code.
3063 A string of code.
3070
3064
3071 ValueError is raised if nothing is found, and TypeError if it evaluates
3065 ValueError is raised if nothing is found, and TypeError if it evaluates
3072 to an object of another type. In each case, .args[0] is a printable
3066 to an object of another type. In each case, .args[0] is a printable
3073 message.
3067 message.
3074 """
3068 """
3075 code = self.extract_input_lines(target, raw=raw) # Grab history
3069 code = self.extract_input_lines(target, raw=raw) # Grab history
3076 if code:
3070 if code:
3077 return code
3071 return code
3078 utarget = unquote_filename(target)
3072 utarget = unquote_filename(target)
3079 try:
3073 try:
3080 if utarget.startswith(('http://', 'https://')):
3074 if utarget.startswith(('http://', 'https://')):
3081 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3075 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3082 except UnicodeDecodeError:
3076 except UnicodeDecodeError:
3083 if not py_only :
3077 if not py_only :
3084 from urllib import urlopen # Deferred import
3078 from urllib import urlopen # Deferred import
3085 response = urlopen(target)
3079 response = urlopen(target)
3086 return response.read().decode('latin1')
3080 return response.read().decode('latin1')
3087 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3081 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3088
3082
3089 potential_target = [target]
3083 potential_target = [target]
3090 try :
3084 try :
3091 potential_target.insert(0,get_py_filename(target))
3085 potential_target.insert(0,get_py_filename(target))
3092 except IOError:
3086 except IOError:
3093 pass
3087 pass
3094
3088
3095 for tgt in potential_target :
3089 for tgt in potential_target :
3096 if os.path.isfile(tgt): # Read file
3090 if os.path.isfile(tgt): # Read file
3097 try :
3091 try :
3098 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3092 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3099 except UnicodeDecodeError :
3093 except UnicodeDecodeError :
3100 if not py_only :
3094 if not py_only :
3101 with io_open(tgt,'r', encoding='latin1') as f :
3095 with io_open(tgt,'r', encoding='latin1') as f :
3102 return f.read()
3096 return f.read()
3103 raise ValueError(("'%s' seem to be unreadable.") % target)
3097 raise ValueError(("'%s' seem to be unreadable.") % target)
3104 elif os.path.isdir(os.path.expanduser(tgt)):
3098 elif os.path.isdir(os.path.expanduser(tgt)):
3105 raise ValueError("'%s' is a directory, not a regular file." % target)
3099 raise ValueError("'%s' is a directory, not a regular file." % target)
3106
3100
3107 try: # User namespace
3101 try: # User namespace
3108 codeobj = eval(target, self.user_ns)
3102 codeobj = eval(target, self.user_ns)
3109 except Exception:
3103 except Exception:
3110 raise ValueError(("'%s' was not found in history, as a file, url, "
3104 raise ValueError(("'%s' was not found in history, as a file, url, "
3111 "nor in the user namespace.") % target)
3105 "nor in the user namespace.") % target)
3112 if isinstance(codeobj, basestring):
3106 if isinstance(codeobj, basestring):
3113 return codeobj
3107 return codeobj
3114 elif isinstance(codeobj, Macro):
3108 elif isinstance(codeobj, Macro):
3115 return codeobj.value
3109 return codeobj.value
3116
3110
3117 raise TypeError("%s is neither a string nor a macro." % target,
3111 raise TypeError("%s is neither a string nor a macro." % target,
3118 codeobj)
3112 codeobj)
3119
3113
3120 #-------------------------------------------------------------------------
3114 #-------------------------------------------------------------------------
3121 # Things related to IPython exiting
3115 # Things related to IPython exiting
3122 #-------------------------------------------------------------------------
3116 #-------------------------------------------------------------------------
3123 def atexit_operations(self):
3117 def atexit_operations(self):
3124 """This will be executed at the time of exit.
3118 """This will be executed at the time of exit.
3125
3119
3126 Cleanup operations and saving of persistent data that is done
3120 Cleanup operations and saving of persistent data that is done
3127 unconditionally by IPython should be performed here.
3121 unconditionally by IPython should be performed here.
3128
3122
3129 For things that may depend on startup flags or platform specifics (such
3123 For things that may depend on startup flags or platform specifics (such
3130 as having readline or not), register a separate atexit function in the
3124 as having readline or not), register a separate atexit function in the
3131 code that has the appropriate information, rather than trying to
3125 code that has the appropriate information, rather than trying to
3132 clutter
3126 clutter
3133 """
3127 """
3134 # Close the history session (this stores the end time and line count)
3128 # Close the history session (this stores the end time and line count)
3135 # this must be *before* the tempfile cleanup, in case of temporary
3129 # this must be *before* the tempfile cleanup, in case of temporary
3136 # history db
3130 # history db
3137 self.history_manager.end_session()
3131 self.history_manager.end_session()
3138
3132
3139 # Cleanup all tempfiles left around
3133 # Cleanup all tempfiles left around
3140 for tfile in self.tempfiles:
3134 for tfile in self.tempfiles:
3141 try:
3135 try:
3142 os.unlink(tfile)
3136 os.unlink(tfile)
3143 except OSError:
3137 except OSError:
3144 pass
3138 pass
3145
3139
3146 # Clear all user namespaces to release all references cleanly.
3140 # Clear all user namespaces to release all references cleanly.
3147 self.reset(new_session=False)
3141 self.reset(new_session=False)
3148
3142
3149 # Run user hooks
3143 # Run user hooks
3150 self.hooks.shutdown_hook()
3144 self.hooks.shutdown_hook()
3151
3145
3152 def cleanup(self):
3146 def cleanup(self):
3153 self.restore_sys_module_state()
3147 self.restore_sys_module_state()
3154
3148
3155
3149
3156 class InteractiveShellABC(object):
3150 class InteractiveShellABC(object):
3157 """An abstract base class for InteractiveShell."""
3151 """An abstract base class for InteractiveShell."""
3158 __metaclass__ = abc.ABCMeta
3152 __metaclass__ = abc.ABCMeta
3159
3153
3160 InteractiveShellABC.register(InteractiveShell)
3154 InteractiveShellABC.register(InteractiveShell)
@@ -1,728 +1,738 b''
1 """Implementation of magic functions for interaction with the OS.
1 """Implementation of magic functions for interaction with the OS.
2
2
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
4 builtin.
4 builtin.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (c) 2012 The IPython Development Team.
7 # Copyright (c) 2012 The IPython Development Team.
8 #
8 #
9 # Distributed under the terms of the Modified BSD License.
9 # Distributed under the terms of the Modified BSD License.
10 #
10 #
11 # The full license is in the file COPYING.txt, distributed with this software.
11 # The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 # Stdlib
18 # Stdlib
19 import io
19 import io
20 import os
20 import os
21 import re
21 import re
22 import sys
22 import sys
23 from pprint import pformat
23 from pprint import pformat
24
24
25 # Our own packages
25 # Our own packages
26 from IPython.core import magic_arguments
26 from IPython.core import magic_arguments
27 from IPython.core import oinspect
27 from IPython.core import oinspect
28 from IPython.core import page
28 from IPython.core import page
29 from IPython.core.alias import AliasError, Alias
29 from IPython.core.error import UsageError
30 from IPython.core.error import UsageError
30 from IPython.core.magic import (
31 from IPython.core.magic import (
31 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
32 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
32 )
33 )
33 from IPython.testing.skipdoctest import skip_doctest
34 from IPython.testing.skipdoctest import skip_doctest
34 from IPython.utils.openpy import source_to_unicode
35 from IPython.utils.openpy import source_to_unicode
35 from IPython.utils.path import unquote_filename
36 from IPython.utils.path import unquote_filename
36 from IPython.utils.process import abbrev_cwd
37 from IPython.utils.process import abbrev_cwd
37 from IPython.utils.terminal import set_term_title
38 from IPython.utils.terminal import set_term_title
38
39
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40 # Magic implementation classes
41 # Magic implementation classes
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42 @magics_class
43 @magics_class
43 class OSMagics(Magics):
44 class OSMagics(Magics):
44 """Magics to interact with the underlying OS (shell-type functionality).
45 """Magics to interact with the underlying OS (shell-type functionality).
45 """
46 """
46
47
47 @skip_doctest
48 @skip_doctest
48 @line_magic
49 @line_magic
49 def alias(self, parameter_s=''):
50 def alias(self, parameter_s=''):
50 """Define an alias for a system command.
51 """Define an alias for a system command.
51
52
52 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
53 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
53
54
54 Then, typing 'alias_name params' will execute the system command 'cmd
55 Then, typing 'alias_name params' will execute the system command 'cmd
55 params' (from your underlying operating system).
56 params' (from your underlying operating system).
56
57
57 Aliases have lower precedence than magic functions and Python normal
58 Aliases have lower precedence than magic functions and Python normal
58 variables, so if 'foo' is both a Python variable and an alias, the
59 variables, so if 'foo' is both a Python variable and an alias, the
59 alias can not be executed until 'del foo' removes the Python variable.
60 alias can not be executed until 'del foo' removes the Python variable.
60
61
61 You can use the %l specifier in an alias definition to represent the
62 You can use the %l specifier in an alias definition to represent the
62 whole line when the alias is called. For example::
63 whole line when the alias is called. For example::
63
64
64 In [2]: alias bracket echo "Input in brackets: <%l>"
65 In [2]: alias bracket echo "Input in brackets: <%l>"
65 In [3]: bracket hello world
66 In [3]: bracket hello world
66 Input in brackets: <hello world>
67 Input in brackets: <hello world>
67
68
68 You can also define aliases with parameters using %s specifiers (one
69 You can also define aliases with parameters using %s specifiers (one
69 per parameter)::
70 per parameter)::
70
71
71 In [1]: alias parts echo first %s second %s
72 In [1]: alias parts echo first %s second %s
72 In [2]: %parts A B
73 In [2]: %parts A B
73 first A second B
74 first A second B
74 In [3]: %parts A
75 In [3]: %parts A
75 Incorrect number of arguments: 2 expected.
76 Incorrect number of arguments: 2 expected.
76 parts is an alias to: 'echo first %s second %s'
77 parts is an alias to: 'echo first %s second %s'
77
78
78 Note that %l and %s are mutually exclusive. You can only use one or
79 Note that %l and %s are mutually exclusive. You can only use one or
79 the other in your aliases.
80 the other in your aliases.
80
81
81 Aliases expand Python variables just like system calls using ! or !!
82 Aliases expand Python variables just like system calls using ! or !!
82 do: all expressions prefixed with '$' get expanded. For details of
83 do: all expressions prefixed with '$' get expanded. For details of
83 the semantic rules, see PEP-215:
84 the semantic rules, see PEP-215:
84 http://www.python.org/peps/pep-0215.html. This is the library used by
85 http://www.python.org/peps/pep-0215.html. This is the library used by
85 IPython for variable expansion. If you want to access a true shell
86 IPython for variable expansion. If you want to access a true shell
86 variable, an extra $ is necessary to prevent its expansion by
87 variable, an extra $ is necessary to prevent its expansion by
87 IPython::
88 IPython::
88
89
89 In [6]: alias show echo
90 In [6]: alias show echo
90 In [7]: PATH='A Python string'
91 In [7]: PATH='A Python string'
91 In [8]: show $PATH
92 In [8]: show $PATH
92 A Python string
93 A Python string
93 In [9]: show $$PATH
94 In [9]: show $$PATH
94 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
95 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
95
96
96 You can use the alias facility to acess all of $PATH. See the %rehash
97 You can use the alias facility to acess all of $PATH. See the %rehash
97 and %rehashx functions, which automatically create aliases for the
98 and %rehashx functions, which automatically create aliases for the
98 contents of your $PATH.
99 contents of your $PATH.
99
100
100 If called with no parameters, %alias prints the current alias table."""
101 If called with no parameters, %alias prints the current alias table."""
101
102
102 par = parameter_s.strip()
103 par = parameter_s.strip()
103 if not par:
104 if not par:
104 aliases = sorted(self.shell.alias_manager.aliases)
105 aliases = sorted(self.shell.alias_manager.aliases)
105 # stored = self.shell.db.get('stored_aliases', {} )
106 # stored = self.shell.db.get('stored_aliases', {} )
106 # for k, v in stored:
107 # for k, v in stored:
107 # atab.append(k, v[0])
108 # atab.append(k, v[0])
108
109
109 print "Total number of aliases:", len(aliases)
110 print "Total number of aliases:", len(aliases)
110 sys.stdout.flush()
111 sys.stdout.flush()
111 return aliases
112 return aliases
112
113
113 # Now try to define a new one
114 # Now try to define a new one
114 try:
115 try:
115 alias,cmd = par.split(None, 1)
116 alias,cmd = par.split(None, 1)
116 except:
117 except TypeError:
117 print oinspect.getdoc(self.alias)
118 print(oinspect.getdoc(self.alias))
118 else:
119 return
119 self.shell.alias_manager.soft_define_alias(alias, cmd)
120
121 try:
122 self.shell.alias_manager.define_alias(alias, cmd)
123 except AliasError as e:
124 print(e)
120 # end magic_alias
125 # end magic_alias
121
126
122 @line_magic
127 @line_magic
123 def unalias(self, parameter_s=''):
128 def unalias(self, parameter_s=''):
124 """Remove an alias"""
129 """Remove an alias"""
125
130
126 aname = parameter_s.strip()
131 aname = parameter_s.strip()
127 self.shell.alias_manager.undefine_alias(aname)
132 try:
133 self.shell.alias_manager.undefine_alias(aname)
134 except ValueError as e:
135 print(e)
136 return
137
128 stored = self.shell.db.get('stored_aliases', {} )
138 stored = self.shell.db.get('stored_aliases', {} )
129 if aname in stored:
139 if aname in stored:
130 print "Removing %stored alias",aname
140 print "Removing %stored alias",aname
131 del stored[aname]
141 del stored[aname]
132 self.shell.db['stored_aliases'] = stored
142 self.shell.db['stored_aliases'] = stored
133
143
134 @line_magic
144 @line_magic
135 def rehashx(self, parameter_s=''):
145 def rehashx(self, parameter_s=''):
136 """Update the alias table with all executable files in $PATH.
146 """Update the alias table with all executable files in $PATH.
137
147
138 This version explicitly checks that every entry in $PATH is a file
148 This version explicitly checks that every entry in $PATH is a file
139 with execute access (os.X_OK), so it is much slower than %rehash.
149 with execute access (os.X_OK), so it is much slower than %rehash.
140
150
141 Under Windows, it checks executability as a match against a
151 Under Windows, it checks executability as a match against a
142 '|'-separated string of extensions, stored in the IPython config
152 '|'-separated string of extensions, stored in the IPython config
143 variable win_exec_ext. This defaults to 'exe|com|bat'.
153 variable win_exec_ext. This defaults to 'exe|com|bat'.
144
154
145 This function also resets the root module cache of module completer,
155 This function also resets the root module cache of module completer,
146 used on slow filesystems.
156 used on slow filesystems.
147 """
157 """
148 from IPython.core.alias import InvalidAliasError
158 from IPython.core.alias import InvalidAliasError
149
159
150 # for the benefit of module completer in ipy_completers.py
160 # for the benefit of module completer in ipy_completers.py
151 del self.shell.db['rootmodules_cache']
161 del self.shell.db['rootmodules_cache']
152
162
153 path = [os.path.abspath(os.path.expanduser(p)) for p in
163 path = [os.path.abspath(os.path.expanduser(p)) for p in
154 os.environ.get('PATH','').split(os.pathsep)]
164 os.environ.get('PATH','').split(os.pathsep)]
155 path = filter(os.path.isdir,path)
165 path = filter(os.path.isdir,path)
156
166
157 syscmdlist = []
167 syscmdlist = []
158 # Now define isexec in a cross platform manner.
168 # Now define isexec in a cross platform manner.
159 if os.name == 'posix':
169 if os.name == 'posix':
160 isexec = lambda fname:os.path.isfile(fname) and \
170 isexec = lambda fname:os.path.isfile(fname) and \
161 os.access(fname,os.X_OK)
171 os.access(fname,os.X_OK)
162 else:
172 else:
163 try:
173 try:
164 winext = os.environ['pathext'].replace(';','|').replace('.','')
174 winext = os.environ['pathext'].replace(';','|').replace('.','')
165 except KeyError:
175 except KeyError:
166 winext = 'exe|com|bat|py'
176 winext = 'exe|com|bat|py'
167 if 'py' not in winext:
177 if 'py' not in winext:
168 winext += '|py'
178 winext += '|py'
169 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
179 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
170 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
180 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
171 savedir = os.getcwdu()
181 savedir = os.getcwdu()
172
182
173 # Now walk the paths looking for executables to alias.
183 # Now walk the paths looking for executables to alias.
174 try:
184 try:
175 # write the whole loop for posix/Windows so we don't have an if in
185 # write the whole loop for posix/Windows so we don't have an if in
176 # the innermost part
186 # the innermost part
177 if os.name == 'posix':
187 if os.name == 'posix':
178 for pdir in path:
188 for pdir in path:
179 os.chdir(pdir)
189 os.chdir(pdir)
180 for ff in os.listdir(pdir):
190 for ff in os.listdir(pdir):
181 if isexec(ff):
191 if isexec(ff):
182 try:
192 try:
183 # Removes dots from the name since ipython
193 # Removes dots from the name since ipython
184 # will assume names with dots to be python.
194 # will assume names with dots to be python.
185 if ff not in self.shell.alias_manager:
195 if not self.shell.alias_manager.is_alias(ff):
186 self.shell.alias_manager.define_alias(
196 self.shell.alias_manager.define_alias(
187 ff.replace('.',''), ff)
197 ff.replace('.',''), ff)
188 except InvalidAliasError:
198 except InvalidAliasError:
189 pass
199 pass
190 else:
200 else:
191 syscmdlist.append(ff)
201 syscmdlist.append(ff)
192 else:
202 else:
193 no_alias = self.shell.alias_manager.no_alias
203 no_alias = Alias.blacklist
194 for pdir in path:
204 for pdir in path:
195 os.chdir(pdir)
205 os.chdir(pdir)
196 for ff in os.listdir(pdir):
206 for ff in os.listdir(pdir):
197 base, ext = os.path.splitext(ff)
207 base, ext = os.path.splitext(ff)
198 if isexec(ff) and base.lower() not in no_alias:
208 if isexec(ff) and base.lower() not in no_alias:
199 if ext.lower() == '.exe':
209 if ext.lower() == '.exe':
200 ff = base
210 ff = base
201 try:
211 try:
202 # Removes dots from the name since ipython
212 # Removes dots from the name since ipython
203 # will assume names with dots to be python.
213 # will assume names with dots to be python.
204 self.shell.alias_manager.define_alias(
214 self.shell.alias_manager.define_alias(
205 base.lower().replace('.',''), ff)
215 base.lower().replace('.',''), ff)
206 except InvalidAliasError:
216 except InvalidAliasError:
207 pass
217 pass
208 syscmdlist.append(ff)
218 syscmdlist.append(ff)
209 self.shell.db['syscmdlist'] = syscmdlist
219 self.shell.db['syscmdlist'] = syscmdlist
210 finally:
220 finally:
211 os.chdir(savedir)
221 os.chdir(savedir)
212
222
213 @skip_doctest
223 @skip_doctest
214 @line_magic
224 @line_magic
215 def pwd(self, parameter_s=''):
225 def pwd(self, parameter_s=''):
216 """Return the current working directory path.
226 """Return the current working directory path.
217
227
218 Examples
228 Examples
219 --------
229 --------
220 ::
230 ::
221
231
222 In [9]: pwd
232 In [9]: pwd
223 Out[9]: '/home/tsuser/sprint/ipython'
233 Out[9]: '/home/tsuser/sprint/ipython'
224 """
234 """
225 return os.getcwdu()
235 return os.getcwdu()
226
236
227 @skip_doctest
237 @skip_doctest
228 @line_magic
238 @line_magic
229 def cd(self, parameter_s=''):
239 def cd(self, parameter_s=''):
230 """Change the current working directory.
240 """Change the current working directory.
231
241
232 This command automatically maintains an internal list of directories
242 This command automatically maintains an internal list of directories
233 you visit during your IPython session, in the variable _dh. The
243 you visit during your IPython session, in the variable _dh. The
234 command %dhist shows this history nicely formatted. You can also
244 command %dhist shows this history nicely formatted. You can also
235 do 'cd -<tab>' to see directory history conveniently.
245 do 'cd -<tab>' to see directory history conveniently.
236
246
237 Usage:
247 Usage:
238
248
239 cd 'dir': changes to directory 'dir'.
249 cd 'dir': changes to directory 'dir'.
240
250
241 cd -: changes to the last visited directory.
251 cd -: changes to the last visited directory.
242
252
243 cd -<n>: changes to the n-th directory in the directory history.
253 cd -<n>: changes to the n-th directory in the directory history.
244
254
245 cd --foo: change to directory that matches 'foo' in history
255 cd --foo: change to directory that matches 'foo' in history
246
256
247 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
257 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
248 (note: cd <bookmark_name> is enough if there is no
258 (note: cd <bookmark_name> is enough if there is no
249 directory <bookmark_name>, but a bookmark with the name exists.)
259 directory <bookmark_name>, but a bookmark with the name exists.)
250 'cd -b <tab>' allows you to tab-complete bookmark names.
260 'cd -b <tab>' allows you to tab-complete bookmark names.
251
261
252 Options:
262 Options:
253
263
254 -q: quiet. Do not print the working directory after the cd command is
264 -q: quiet. Do not print the working directory after the cd command is
255 executed. By default IPython's cd command does print this directory,
265 executed. By default IPython's cd command does print this directory,
256 since the default prompts do not display path information.
266 since the default prompts do not display path information.
257
267
258 Note that !cd doesn't work for this purpose because the shell where
268 Note that !cd doesn't work for this purpose because the shell where
259 !command runs is immediately discarded after executing 'command'.
269 !command runs is immediately discarded after executing 'command'.
260
270
261 Examples
271 Examples
262 --------
272 --------
263 ::
273 ::
264
274
265 In [10]: cd parent/child
275 In [10]: cd parent/child
266 /home/tsuser/parent/child
276 /home/tsuser/parent/child
267 """
277 """
268
278
269 oldcwd = os.getcwdu()
279 oldcwd = os.getcwdu()
270 numcd = re.match(r'(-)(\d+)$',parameter_s)
280 numcd = re.match(r'(-)(\d+)$',parameter_s)
271 # jump in directory history by number
281 # jump in directory history by number
272 if numcd:
282 if numcd:
273 nn = int(numcd.group(2))
283 nn = int(numcd.group(2))
274 try:
284 try:
275 ps = self.shell.user_ns['_dh'][nn]
285 ps = self.shell.user_ns['_dh'][nn]
276 except IndexError:
286 except IndexError:
277 print 'The requested directory does not exist in history.'
287 print 'The requested directory does not exist in history.'
278 return
288 return
279 else:
289 else:
280 opts = {}
290 opts = {}
281 elif parameter_s.startswith('--'):
291 elif parameter_s.startswith('--'):
282 ps = None
292 ps = None
283 fallback = None
293 fallback = None
284 pat = parameter_s[2:]
294 pat = parameter_s[2:]
285 dh = self.shell.user_ns['_dh']
295 dh = self.shell.user_ns['_dh']
286 # first search only by basename (last component)
296 # first search only by basename (last component)
287 for ent in reversed(dh):
297 for ent in reversed(dh):
288 if pat in os.path.basename(ent) and os.path.isdir(ent):
298 if pat in os.path.basename(ent) and os.path.isdir(ent):
289 ps = ent
299 ps = ent
290 break
300 break
291
301
292 if fallback is None and pat in ent and os.path.isdir(ent):
302 if fallback is None and pat in ent and os.path.isdir(ent):
293 fallback = ent
303 fallback = ent
294
304
295 # if we have no last part match, pick the first full path match
305 # if we have no last part match, pick the first full path match
296 if ps is None:
306 if ps is None:
297 ps = fallback
307 ps = fallback
298
308
299 if ps is None:
309 if ps is None:
300 print "No matching entry in directory history"
310 print "No matching entry in directory history"
301 return
311 return
302 else:
312 else:
303 opts = {}
313 opts = {}
304
314
305
315
306 else:
316 else:
307 #turn all non-space-escaping backslashes to slashes,
317 #turn all non-space-escaping backslashes to slashes,
308 # for c:\windows\directory\names\
318 # for c:\windows\directory\names\
309 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
319 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
310 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
320 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
311 # jump to previous
321 # jump to previous
312 if ps == '-':
322 if ps == '-':
313 try:
323 try:
314 ps = self.shell.user_ns['_dh'][-2]
324 ps = self.shell.user_ns['_dh'][-2]
315 except IndexError:
325 except IndexError:
316 raise UsageError('%cd -: No previous directory to change to.')
326 raise UsageError('%cd -: No previous directory to change to.')
317 # jump to bookmark if needed
327 # jump to bookmark if needed
318 else:
328 else:
319 if not os.path.isdir(ps) or 'b' in opts:
329 if not os.path.isdir(ps) or 'b' in opts:
320 bkms = self.shell.db.get('bookmarks', {})
330 bkms = self.shell.db.get('bookmarks', {})
321
331
322 if ps in bkms:
332 if ps in bkms:
323 target = bkms[ps]
333 target = bkms[ps]
324 print '(bookmark:%s) -> %s' % (ps, target)
334 print '(bookmark:%s) -> %s' % (ps, target)
325 ps = target
335 ps = target
326 else:
336 else:
327 if 'b' in opts:
337 if 'b' in opts:
328 raise UsageError("Bookmark '%s' not found. "
338 raise UsageError("Bookmark '%s' not found. "
329 "Use '%%bookmark -l' to see your bookmarks." % ps)
339 "Use '%%bookmark -l' to see your bookmarks." % ps)
330
340
331 # strip extra quotes on Windows, because os.chdir doesn't like them
341 # strip extra quotes on Windows, because os.chdir doesn't like them
332 ps = unquote_filename(ps)
342 ps = unquote_filename(ps)
333 # at this point ps should point to the target dir
343 # at this point ps should point to the target dir
334 if ps:
344 if ps:
335 try:
345 try:
336 os.chdir(os.path.expanduser(ps))
346 os.chdir(os.path.expanduser(ps))
337 if hasattr(self.shell, 'term_title') and self.shell.term_title:
347 if hasattr(self.shell, 'term_title') and self.shell.term_title:
338 set_term_title('IPython: ' + abbrev_cwd())
348 set_term_title('IPython: ' + abbrev_cwd())
339 except OSError:
349 except OSError:
340 print sys.exc_info()[1]
350 print sys.exc_info()[1]
341 else:
351 else:
342 cwd = os.getcwdu()
352 cwd = os.getcwdu()
343 dhist = self.shell.user_ns['_dh']
353 dhist = self.shell.user_ns['_dh']
344 if oldcwd != cwd:
354 if oldcwd != cwd:
345 dhist.append(cwd)
355 dhist.append(cwd)
346 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
356 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
347
357
348 else:
358 else:
349 os.chdir(self.shell.home_dir)
359 os.chdir(self.shell.home_dir)
350 if hasattr(self.shell, 'term_title') and self.shell.term_title:
360 if hasattr(self.shell, 'term_title') and self.shell.term_title:
351 set_term_title('IPython: ' + '~')
361 set_term_title('IPython: ' + '~')
352 cwd = os.getcwdu()
362 cwd = os.getcwdu()
353 dhist = self.shell.user_ns['_dh']
363 dhist = self.shell.user_ns['_dh']
354
364
355 if oldcwd != cwd:
365 if oldcwd != cwd:
356 dhist.append(cwd)
366 dhist.append(cwd)
357 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
367 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
358 if not 'q' in opts and self.shell.user_ns['_dh']:
368 if not 'q' in opts and self.shell.user_ns['_dh']:
359 print self.shell.user_ns['_dh'][-1]
369 print self.shell.user_ns['_dh'][-1]
360
370
361
371
362 @line_magic
372 @line_magic
363 def env(self, parameter_s=''):
373 def env(self, parameter_s=''):
364 """List environment variables."""
374 """List environment variables."""
365
375
366 return dict(os.environ)
376 return dict(os.environ)
367
377
368 @line_magic
378 @line_magic
369 def pushd(self, parameter_s=''):
379 def pushd(self, parameter_s=''):
370 """Place the current dir on stack and change directory.
380 """Place the current dir on stack and change directory.
371
381
372 Usage:\\
382 Usage:\\
373 %pushd ['dirname']
383 %pushd ['dirname']
374 """
384 """
375
385
376 dir_s = self.shell.dir_stack
386 dir_s = self.shell.dir_stack
377 tgt = os.path.expanduser(unquote_filename(parameter_s))
387 tgt = os.path.expanduser(unquote_filename(parameter_s))
378 cwd = os.getcwdu().replace(self.shell.home_dir,'~')
388 cwd = os.getcwdu().replace(self.shell.home_dir,'~')
379 if tgt:
389 if tgt:
380 self.cd(parameter_s)
390 self.cd(parameter_s)
381 dir_s.insert(0,cwd)
391 dir_s.insert(0,cwd)
382 return self.shell.magic('dirs')
392 return self.shell.magic('dirs')
383
393
384 @line_magic
394 @line_magic
385 def popd(self, parameter_s=''):
395 def popd(self, parameter_s=''):
386 """Change to directory popped off the top of the stack.
396 """Change to directory popped off the top of the stack.
387 """
397 """
388 if not self.shell.dir_stack:
398 if not self.shell.dir_stack:
389 raise UsageError("%popd on empty stack")
399 raise UsageError("%popd on empty stack")
390 top = self.shell.dir_stack.pop(0)
400 top = self.shell.dir_stack.pop(0)
391 self.cd(top)
401 self.cd(top)
392 print "popd ->",top
402 print "popd ->",top
393
403
394 @line_magic
404 @line_magic
395 def dirs(self, parameter_s=''):
405 def dirs(self, parameter_s=''):
396 """Return the current directory stack."""
406 """Return the current directory stack."""
397
407
398 return self.shell.dir_stack
408 return self.shell.dir_stack
399
409
400 @line_magic
410 @line_magic
401 def dhist(self, parameter_s=''):
411 def dhist(self, parameter_s=''):
402 """Print your history of visited directories.
412 """Print your history of visited directories.
403
413
404 %dhist -> print full history\\
414 %dhist -> print full history\\
405 %dhist n -> print last n entries only\\
415 %dhist n -> print last n entries only\\
406 %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
416 %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
407
417
408 This history is automatically maintained by the %cd command, and
418 This history is automatically maintained by the %cd command, and
409 always available as the global list variable _dh. You can use %cd -<n>
419 always available as the global list variable _dh. You can use %cd -<n>
410 to go to directory number <n>.
420 to go to directory number <n>.
411
421
412 Note that most of time, you should view directory history by entering
422 Note that most of time, you should view directory history by entering
413 cd -<TAB>.
423 cd -<TAB>.
414
424
415 """
425 """
416
426
417 dh = self.shell.user_ns['_dh']
427 dh = self.shell.user_ns['_dh']
418 if parameter_s:
428 if parameter_s:
419 try:
429 try:
420 args = map(int,parameter_s.split())
430 args = map(int,parameter_s.split())
421 except:
431 except:
422 self.arg_err(self.dhist)
432 self.arg_err(self.dhist)
423 return
433 return
424 if len(args) == 1:
434 if len(args) == 1:
425 ini,fin = max(len(dh)-(args[0]),0),len(dh)
435 ini,fin = max(len(dh)-(args[0]),0),len(dh)
426 elif len(args) == 2:
436 elif len(args) == 2:
427 ini,fin = args
437 ini,fin = args
428 fin = min(fin, len(dh))
438 fin = min(fin, len(dh))
429 else:
439 else:
430 self.arg_err(self.dhist)
440 self.arg_err(self.dhist)
431 return
441 return
432 else:
442 else:
433 ini,fin = 0,len(dh)
443 ini,fin = 0,len(dh)
434 print 'Directory history (kept in _dh)'
444 print 'Directory history (kept in _dh)'
435 for i in range(ini, fin):
445 for i in range(ini, fin):
436 print "%d: %s" % (i, dh[i])
446 print "%d: %s" % (i, dh[i])
437
447
438 @skip_doctest
448 @skip_doctest
439 @line_magic
449 @line_magic
440 def sc(self, parameter_s=''):
450 def sc(self, parameter_s=''):
441 """Shell capture - run shell command and capture output (DEPRECATED use !).
451 """Shell capture - run shell command and capture output (DEPRECATED use !).
442
452
443 DEPRECATED. Suboptimal, retained for backwards compatibility.
453 DEPRECATED. Suboptimal, retained for backwards compatibility.
444
454
445 You should use the form 'var = !command' instead. Example:
455 You should use the form 'var = !command' instead. Example:
446
456
447 "%sc -l myfiles = ls ~" should now be written as
457 "%sc -l myfiles = ls ~" should now be written as
448
458
449 "myfiles = !ls ~"
459 "myfiles = !ls ~"
450
460
451 myfiles.s, myfiles.l and myfiles.n still apply as documented
461 myfiles.s, myfiles.l and myfiles.n still apply as documented
452 below.
462 below.
453
463
454 --
464 --
455 %sc [options] varname=command
465 %sc [options] varname=command
456
466
457 IPython will run the given command using commands.getoutput(), and
467 IPython will run the given command using commands.getoutput(), and
458 will then update the user's interactive namespace with a variable
468 will then update the user's interactive namespace with a variable
459 called varname, containing the value of the call. Your command can
469 called varname, containing the value of the call. Your command can
460 contain shell wildcards, pipes, etc.
470 contain shell wildcards, pipes, etc.
461
471
462 The '=' sign in the syntax is mandatory, and the variable name you
472 The '=' sign in the syntax is mandatory, and the variable name you
463 supply must follow Python's standard conventions for valid names.
473 supply must follow Python's standard conventions for valid names.
464
474
465 (A special format without variable name exists for internal use)
475 (A special format without variable name exists for internal use)
466
476
467 Options:
477 Options:
468
478
469 -l: list output. Split the output on newlines into a list before
479 -l: list output. Split the output on newlines into a list before
470 assigning it to the given variable. By default the output is stored
480 assigning it to the given variable. By default the output is stored
471 as a single string.
481 as a single string.
472
482
473 -v: verbose. Print the contents of the variable.
483 -v: verbose. Print the contents of the variable.
474
484
475 In most cases you should not need to split as a list, because the
485 In most cases you should not need to split as a list, because the
476 returned value is a special type of string which can automatically
486 returned value is a special type of string which can automatically
477 provide its contents either as a list (split on newlines) or as a
487 provide its contents either as a list (split on newlines) or as a
478 space-separated string. These are convenient, respectively, either
488 space-separated string. These are convenient, respectively, either
479 for sequential processing or to be passed to a shell command.
489 for sequential processing or to be passed to a shell command.
480
490
481 For example::
491 For example::
482
492
483 # Capture into variable a
493 # Capture into variable a
484 In [1]: sc a=ls *py
494 In [1]: sc a=ls *py
485
495
486 # a is a string with embedded newlines
496 # a is a string with embedded newlines
487 In [2]: a
497 In [2]: a
488 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
498 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
489
499
490 # which can be seen as a list:
500 # which can be seen as a list:
491 In [3]: a.l
501 In [3]: a.l
492 Out[3]: ['setup.py', 'win32_manual_post_install.py']
502 Out[3]: ['setup.py', 'win32_manual_post_install.py']
493
503
494 # or as a whitespace-separated string:
504 # or as a whitespace-separated string:
495 In [4]: a.s
505 In [4]: a.s
496 Out[4]: 'setup.py win32_manual_post_install.py'
506 Out[4]: 'setup.py win32_manual_post_install.py'
497
507
498 # a.s is useful to pass as a single command line:
508 # a.s is useful to pass as a single command line:
499 In [5]: !wc -l $a.s
509 In [5]: !wc -l $a.s
500 146 setup.py
510 146 setup.py
501 130 win32_manual_post_install.py
511 130 win32_manual_post_install.py
502 276 total
512 276 total
503
513
504 # while the list form is useful to loop over:
514 # while the list form is useful to loop over:
505 In [6]: for f in a.l:
515 In [6]: for f in a.l:
506 ...: !wc -l $f
516 ...: !wc -l $f
507 ...:
517 ...:
508 146 setup.py
518 146 setup.py
509 130 win32_manual_post_install.py
519 130 win32_manual_post_install.py
510
520
511 Similarly, the lists returned by the -l option are also special, in
521 Similarly, the lists returned by the -l option are also special, in
512 the sense that you can equally invoke the .s attribute on them to
522 the sense that you can equally invoke the .s attribute on them to
513 automatically get a whitespace-separated string from their contents::
523 automatically get a whitespace-separated string from their contents::
514
524
515 In [7]: sc -l b=ls *py
525 In [7]: sc -l b=ls *py
516
526
517 In [8]: b
527 In [8]: b
518 Out[8]: ['setup.py', 'win32_manual_post_install.py']
528 Out[8]: ['setup.py', 'win32_manual_post_install.py']
519
529
520 In [9]: b.s
530 In [9]: b.s
521 Out[9]: 'setup.py win32_manual_post_install.py'
531 Out[9]: 'setup.py win32_manual_post_install.py'
522
532
523 In summary, both the lists and strings used for output capture have
533 In summary, both the lists and strings used for output capture have
524 the following special attributes::
534 the following special attributes::
525
535
526 .l (or .list) : value as list.
536 .l (or .list) : value as list.
527 .n (or .nlstr): value as newline-separated string.
537 .n (or .nlstr): value as newline-separated string.
528 .s (or .spstr): value as space-separated string.
538 .s (or .spstr): value as space-separated string.
529 """
539 """
530
540
531 opts,args = self.parse_options(parameter_s, 'lv')
541 opts,args = self.parse_options(parameter_s, 'lv')
532 # Try to get a variable name and command to run
542 # Try to get a variable name and command to run
533 try:
543 try:
534 # the variable name must be obtained from the parse_options
544 # the variable name must be obtained from the parse_options
535 # output, which uses shlex.split to strip options out.
545 # output, which uses shlex.split to strip options out.
536 var,_ = args.split('=', 1)
546 var,_ = args.split('=', 1)
537 var = var.strip()
547 var = var.strip()
538 # But the command has to be extracted from the original input
548 # But the command has to be extracted from the original input
539 # parameter_s, not on what parse_options returns, to avoid the
549 # parameter_s, not on what parse_options returns, to avoid the
540 # quote stripping which shlex.split performs on it.
550 # quote stripping which shlex.split performs on it.
541 _,cmd = parameter_s.split('=', 1)
551 _,cmd = parameter_s.split('=', 1)
542 except ValueError:
552 except ValueError:
543 var,cmd = '',''
553 var,cmd = '',''
544 # If all looks ok, proceed
554 # If all looks ok, proceed
545 split = 'l' in opts
555 split = 'l' in opts
546 out = self.shell.getoutput(cmd, split=split)
556 out = self.shell.getoutput(cmd, split=split)
547 if 'v' in opts:
557 if 'v' in opts:
548 print '%s ==\n%s' % (var, pformat(out))
558 print '%s ==\n%s' % (var, pformat(out))
549 if var:
559 if var:
550 self.shell.user_ns.update({var:out})
560 self.shell.user_ns.update({var:out})
551 else:
561 else:
552 return out
562 return out
553
563
554 @line_cell_magic
564 @line_cell_magic
555 def sx(self, line='', cell=None):
565 def sx(self, line='', cell=None):
556 """Shell execute - run shell command and capture output (!! is short-hand).
566 """Shell execute - run shell command and capture output (!! is short-hand).
557
567
558 %sx command
568 %sx command
559
569
560 IPython will run the given command using commands.getoutput(), and
570 IPython will run the given command using commands.getoutput(), and
561 return the result formatted as a list (split on '\\n'). Since the
571 return the result formatted as a list (split on '\\n'). Since the
562 output is _returned_, it will be stored in ipython's regular output
572 output is _returned_, it will be stored in ipython's regular output
563 cache Out[N] and in the '_N' automatic variables.
573 cache Out[N] and in the '_N' automatic variables.
564
574
565 Notes:
575 Notes:
566
576
567 1) If an input line begins with '!!', then %sx is automatically
577 1) If an input line begins with '!!', then %sx is automatically
568 invoked. That is, while::
578 invoked. That is, while::
569
579
570 !ls
580 !ls
571
581
572 causes ipython to simply issue system('ls'), typing::
582 causes ipython to simply issue system('ls'), typing::
573
583
574 !!ls
584 !!ls
575
585
576 is a shorthand equivalent to::
586 is a shorthand equivalent to::
577
587
578 %sx ls
588 %sx ls
579
589
580 2) %sx differs from %sc in that %sx automatically splits into a list,
590 2) %sx differs from %sc in that %sx automatically splits into a list,
581 like '%sc -l'. The reason for this is to make it as easy as possible
591 like '%sc -l'. The reason for this is to make it as easy as possible
582 to process line-oriented shell output via further python commands.
592 to process line-oriented shell output via further python commands.
583 %sc is meant to provide much finer control, but requires more
593 %sc is meant to provide much finer control, but requires more
584 typing.
594 typing.
585
595
586 3) Just like %sc -l, this is a list with special attributes:
596 3) Just like %sc -l, this is a list with special attributes:
587 ::
597 ::
588
598
589 .l (or .list) : value as list.
599 .l (or .list) : value as list.
590 .n (or .nlstr): value as newline-separated string.
600 .n (or .nlstr): value as newline-separated string.
591 .s (or .spstr): value as whitespace-separated string.
601 .s (or .spstr): value as whitespace-separated string.
592
602
593 This is very useful when trying to use such lists as arguments to
603 This is very useful when trying to use such lists as arguments to
594 system commands."""
604 system commands."""
595
605
596 if cell is None:
606 if cell is None:
597 # line magic
607 # line magic
598 return self.shell.getoutput(line)
608 return self.shell.getoutput(line)
599 else:
609 else:
600 opts,args = self.parse_options(line, '', 'out=')
610 opts,args = self.parse_options(line, '', 'out=')
601 output = self.shell.getoutput(cell)
611 output = self.shell.getoutput(cell)
602 out_name = opts.get('out', opts.get('o'))
612 out_name = opts.get('out', opts.get('o'))
603 if out_name:
613 if out_name:
604 self.shell.user_ns[out_name] = output
614 self.shell.user_ns[out_name] = output
605 else:
615 else:
606 return output
616 return output
607
617
608 system = line_cell_magic('system')(sx)
618 system = line_cell_magic('system')(sx)
609 bang = cell_magic('!')(sx)
619 bang = cell_magic('!')(sx)
610
620
611 @line_magic
621 @line_magic
612 def bookmark(self, parameter_s=''):
622 def bookmark(self, parameter_s=''):
613 """Manage IPython's bookmark system.
623 """Manage IPython's bookmark system.
614
624
615 %bookmark <name> - set bookmark to current dir
625 %bookmark <name> - set bookmark to current dir
616 %bookmark <name> <dir> - set bookmark to <dir>
626 %bookmark <name> <dir> - set bookmark to <dir>
617 %bookmark -l - list all bookmarks
627 %bookmark -l - list all bookmarks
618 %bookmark -d <name> - remove bookmark
628 %bookmark -d <name> - remove bookmark
619 %bookmark -r - remove all bookmarks
629 %bookmark -r - remove all bookmarks
620
630
621 You can later on access a bookmarked folder with::
631 You can later on access a bookmarked folder with::
622
632
623 %cd -b <name>
633 %cd -b <name>
624
634
625 or simply '%cd <name>' if there is no directory called <name> AND
635 or simply '%cd <name>' if there is no directory called <name> AND
626 there is such a bookmark defined.
636 there is such a bookmark defined.
627
637
628 Your bookmarks persist through IPython sessions, but they are
638 Your bookmarks persist through IPython sessions, but they are
629 associated with each profile."""
639 associated with each profile."""
630
640
631 opts,args = self.parse_options(parameter_s,'drl',mode='list')
641 opts,args = self.parse_options(parameter_s,'drl',mode='list')
632 if len(args) > 2:
642 if len(args) > 2:
633 raise UsageError("%bookmark: too many arguments")
643 raise UsageError("%bookmark: too many arguments")
634
644
635 bkms = self.shell.db.get('bookmarks',{})
645 bkms = self.shell.db.get('bookmarks',{})
636
646
637 if 'd' in opts:
647 if 'd' in opts:
638 try:
648 try:
639 todel = args[0]
649 todel = args[0]
640 except IndexError:
650 except IndexError:
641 raise UsageError(
651 raise UsageError(
642 "%bookmark -d: must provide a bookmark to delete")
652 "%bookmark -d: must provide a bookmark to delete")
643 else:
653 else:
644 try:
654 try:
645 del bkms[todel]
655 del bkms[todel]
646 except KeyError:
656 except KeyError:
647 raise UsageError(
657 raise UsageError(
648 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
658 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
649
659
650 elif 'r' in opts:
660 elif 'r' in opts:
651 bkms = {}
661 bkms = {}
652 elif 'l' in opts:
662 elif 'l' in opts:
653 bks = bkms.keys()
663 bks = bkms.keys()
654 bks.sort()
664 bks.sort()
655 if bks:
665 if bks:
656 size = max(map(len, bks))
666 size = max(map(len, bks))
657 else:
667 else:
658 size = 0
668 size = 0
659 fmt = '%-'+str(size)+'s -> %s'
669 fmt = '%-'+str(size)+'s -> %s'
660 print 'Current bookmarks:'
670 print 'Current bookmarks:'
661 for bk in bks:
671 for bk in bks:
662 print fmt % (bk, bkms[bk])
672 print fmt % (bk, bkms[bk])
663 else:
673 else:
664 if not args:
674 if not args:
665 raise UsageError("%bookmark: You must specify the bookmark name")
675 raise UsageError("%bookmark: You must specify the bookmark name")
666 elif len(args)==1:
676 elif len(args)==1:
667 bkms[args[0]] = os.getcwdu()
677 bkms[args[0]] = os.getcwdu()
668 elif len(args)==2:
678 elif len(args)==2:
669 bkms[args[0]] = args[1]
679 bkms[args[0]] = args[1]
670 self.shell.db['bookmarks'] = bkms
680 self.shell.db['bookmarks'] = bkms
671
681
672 @line_magic
682 @line_magic
673 def pycat(self, parameter_s=''):
683 def pycat(self, parameter_s=''):
674 """Show a syntax-highlighted file through a pager.
684 """Show a syntax-highlighted file through a pager.
675
685
676 This magic is similar to the cat utility, but it will assume the file
686 This magic is similar to the cat utility, but it will assume the file
677 to be Python source and will show it with syntax highlighting.
687 to be Python source and will show it with syntax highlighting.
678
688
679 This magic command can either take a local filename, an url,
689 This magic command can either take a local filename, an url,
680 an history range (see %history) or a macro as argument ::
690 an history range (see %history) or a macro as argument ::
681
691
682 %pycat myscript.py
692 %pycat myscript.py
683 %pycat 7-27
693 %pycat 7-27
684 %pycat myMacro
694 %pycat myMacro
685 %pycat http://www.example.com/myscript.py
695 %pycat http://www.example.com/myscript.py
686 """
696 """
687 if not parameter_s:
697 if not parameter_s:
688 raise UsageError('Missing filename, URL, input history range, '
698 raise UsageError('Missing filename, URL, input history range, '
689 'or macro.')
699 'or macro.')
690
700
691 try :
701 try :
692 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
702 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
693 except (ValueError, IOError):
703 except (ValueError, IOError):
694 print "Error: no such file, variable, URL, history range or macro"
704 print "Error: no such file, variable, URL, history range or macro"
695 return
705 return
696
706
697 page.page(self.shell.pycolorize(source_to_unicode(cont)))
707 page.page(self.shell.pycolorize(source_to_unicode(cont)))
698
708
699 @magic_arguments.magic_arguments()
709 @magic_arguments.magic_arguments()
700 @magic_arguments.argument(
710 @magic_arguments.argument(
701 '-a', '--append', action='store_true', default=False,
711 '-a', '--append', action='store_true', default=False,
702 help='Append contents of the cell to an existing file. '
712 help='Append contents of the cell to an existing file. '
703 'The file will be created if it does not exist.'
713 'The file will be created if it does not exist.'
704 )
714 )
705 @magic_arguments.argument(
715 @magic_arguments.argument(
706 'filename', type=unicode,
716 'filename', type=unicode,
707 help='file to write'
717 help='file to write'
708 )
718 )
709 @cell_magic
719 @cell_magic
710 def writefile(self, line, cell):
720 def writefile(self, line, cell):
711 """Write the contents of the cell to a file.
721 """Write the contents of the cell to a file.
712
722
713 The file will be overwritten unless the -a (--append) flag is specified.
723 The file will be overwritten unless the -a (--append) flag is specified.
714 """
724 """
715 args = magic_arguments.parse_argstring(self.writefile, line)
725 args = magic_arguments.parse_argstring(self.writefile, line)
716 filename = os.path.expanduser(unquote_filename(args.filename))
726 filename = os.path.expanduser(unquote_filename(args.filename))
717
727
718 if os.path.exists(filename):
728 if os.path.exists(filename):
719 if args.append:
729 if args.append:
720 print "Appending to %s" % filename
730 print "Appending to %s" % filename
721 else:
731 else:
722 print "Overwriting %s" % filename
732 print "Overwriting %s" % filename
723 else:
733 else:
724 print "Writing %s" % filename
734 print "Writing %s" % filename
725
735
726 mode = 'a' if args.append else 'w'
736 mode = 'a' if args.append else 'w'
727 with io.open(filename, mode, encoding='utf-8') as f:
737 with io.open(filename, mode, encoding='utf-8') as f:
728 f.write(cell)
738 f.write(cell)
@@ -1,745 +1,713 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Prefiltering components.
3 Prefiltering components.
4
4
5 Prefilters transform user input before it is exec'd by Python. These
5 Prefilters transform user input before it is exec'd by Python. These
6 transforms are used to implement additional syntax such as !ls and %magic.
6 transforms are used to implement additional syntax such as !ls and %magic.
7
7
8 Authors:
8 Authors:
9
9
10 * Brian Granger
10 * Brian Granger
11 * Fernando Perez
11 * Fernando Perez
12 * Dan Milstein
12 * Dan Milstein
13 * Ville Vainio
13 * Ville Vainio
14 """
14 """
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Copyright (C) 2008-2011 The IPython Development Team
17 # Copyright (C) 2008-2011 The IPython Development Team
18 #
18 #
19 # Distributed under the terms of the BSD License. The full license is in
19 # Distributed under the terms of the BSD License. The full license is in
20 # the file COPYING, distributed as part of this software.
20 # the file COPYING, distributed as part of this software.
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Imports
24 # Imports
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 import re
27 import re
28
28
29 from IPython.core.autocall import IPyAutocall
29 from IPython.core.autocall import IPyAutocall
30 from IPython.config.configurable import Configurable
30 from IPython.config.configurable import Configurable
31 from IPython.core.inputsplitter import (
31 from IPython.core.inputsplitter import (
32 ESC_MAGIC,
32 ESC_MAGIC,
33 ESC_QUOTE,
33 ESC_QUOTE,
34 ESC_QUOTE2,
34 ESC_QUOTE2,
35 ESC_PAREN,
35 ESC_PAREN,
36 )
36 )
37 from IPython.core.macro import Macro
37 from IPython.core.macro import Macro
38 from IPython.core.splitinput import LineInfo
38 from IPython.core.splitinput import LineInfo
39
39
40 from IPython.utils.traitlets import (
40 from IPython.utils.traitlets import (
41 List, Integer, Unicode, CBool, Bool, Instance, CRegExp
41 List, Integer, Unicode, CBool, Bool, Instance, CRegExp
42 )
42 )
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # Global utilities, errors and constants
45 # Global utilities, errors and constants
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48
48
49 class PrefilterError(Exception):
49 class PrefilterError(Exception):
50 pass
50 pass
51
51
52
52
53 # RegExp to identify potential function names
53 # RegExp to identify potential function names
54 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
54 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
55
55
56 # RegExp to exclude strings with this start from autocalling. In
56 # RegExp to exclude strings with this start from autocalling. In
57 # particular, all binary operators should be excluded, so that if foo is
57 # particular, all binary operators should be excluded, so that if foo is
58 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
58 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
59 # characters '!=()' don't need to be checked for, as the checkPythonChars
59 # characters '!=()' don't need to be checked for, as the checkPythonChars
60 # routine explicitely does so, to catch direct calls and rebindings of
60 # routine explicitely does so, to catch direct calls and rebindings of
61 # existing names.
61 # existing names.
62
62
63 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
63 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
64 # it affects the rest of the group in square brackets.
64 # it affects the rest of the group in square brackets.
65 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
65 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
66 r'|^is |^not |^in |^and |^or ')
66 r'|^is |^not |^in |^and |^or ')
67
67
68 # try to catch also methods for stuff in lists/tuples/dicts: off
68 # try to catch also methods for stuff in lists/tuples/dicts: off
69 # (experimental). For this to work, the line_split regexp would need
69 # (experimental). For this to work, the line_split regexp would need
70 # to be modified so it wouldn't break things at '['. That line is
70 # to be modified so it wouldn't break things at '['. That line is
71 # nasty enough that I shouldn't change it until I can test it _well_.
71 # nasty enough that I shouldn't change it until I can test it _well_.
72 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
72 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
73
73
74
74
75 # Handler Check Utilities
75 # Handler Check Utilities
76 def is_shadowed(identifier, ip):
76 def is_shadowed(identifier, ip):
77 """Is the given identifier defined in one of the namespaces which shadow
77 """Is the given identifier defined in one of the namespaces which shadow
78 the alias and magic namespaces? Note that an identifier is different
78 the alias and magic namespaces? Note that an identifier is different
79 than ifun, because it can not contain a '.' character."""
79 than ifun, because it can not contain a '.' character."""
80 # This is much safer than calling ofind, which can change state
80 # This is much safer than calling ofind, which can change state
81 return (identifier in ip.user_ns \
81 return (identifier in ip.user_ns \
82 or identifier in ip.user_global_ns \
82 or identifier in ip.user_global_ns \
83 or identifier in ip.ns_table['builtin'])
83 or identifier in ip.ns_table['builtin'])
84
84
85
85
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87 # Main Prefilter manager
87 # Main Prefilter manager
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89
89
90
90
91 class PrefilterManager(Configurable):
91 class PrefilterManager(Configurable):
92 """Main prefilter component.
92 """Main prefilter component.
93
93
94 The IPython prefilter is run on all user input before it is run. The
94 The IPython prefilter is run on all user input before it is run. The
95 prefilter consumes lines of input and produces transformed lines of
95 prefilter consumes lines of input and produces transformed lines of
96 input.
96 input.
97
97
98 The iplementation consists of two phases:
98 The iplementation consists of two phases:
99
99
100 1. Transformers
100 1. Transformers
101 2. Checkers and handlers
101 2. Checkers and handlers
102
102
103 Over time, we plan on deprecating the checkers and handlers and doing
103 Over time, we plan on deprecating the checkers and handlers and doing
104 everything in the transformers.
104 everything in the transformers.
105
105
106 The transformers are instances of :class:`PrefilterTransformer` and have
106 The transformers are instances of :class:`PrefilterTransformer` and have
107 a single method :meth:`transform` that takes a line and returns a
107 a single method :meth:`transform` that takes a line and returns a
108 transformed line. The transformation can be accomplished using any
108 transformed line. The transformation can be accomplished using any
109 tool, but our current ones use regular expressions for speed.
109 tool, but our current ones use regular expressions for speed.
110
110
111 After all the transformers have been run, the line is fed to the checkers,
111 After all the transformers have been run, the line is fed to the checkers,
112 which are instances of :class:`PrefilterChecker`. The line is passed to
112 which are instances of :class:`PrefilterChecker`. The line is passed to
113 the :meth:`check` method, which either returns `None` or a
113 the :meth:`check` method, which either returns `None` or a
114 :class:`PrefilterHandler` instance. If `None` is returned, the other
114 :class:`PrefilterHandler` instance. If `None` is returned, the other
115 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
115 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
116 the line is passed to the :meth:`handle` method of the returned
116 the line is passed to the :meth:`handle` method of the returned
117 handler and no further checkers are tried.
117 handler and no further checkers are tried.
118
118
119 Both transformers and checkers have a `priority` attribute, that determines
119 Both transformers and checkers have a `priority` attribute, that determines
120 the order in which they are called. Smaller priorities are tried first.
120 the order in which they are called. Smaller priorities are tried first.
121
121
122 Both transformers and checkers also have `enabled` attribute, which is
122 Both transformers and checkers also have `enabled` attribute, which is
123 a boolean that determines if the instance is used.
123 a boolean that determines if the instance is used.
124
124
125 Users or developers can change the priority or enabled attribute of
125 Users or developers can change the priority or enabled attribute of
126 transformers or checkers, but they must call the :meth:`sort_checkers`
126 transformers or checkers, but they must call the :meth:`sort_checkers`
127 or :meth:`sort_transformers` method after changing the priority.
127 or :meth:`sort_transformers` method after changing the priority.
128 """
128 """
129
129
130 multi_line_specials = CBool(True, config=True)
130 multi_line_specials = CBool(True, config=True)
131 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
131 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
132
132
133 def __init__(self, shell=None, **kwargs):
133 def __init__(self, shell=None, **kwargs):
134 super(PrefilterManager, self).__init__(shell=shell, **kwargs)
134 super(PrefilterManager, self).__init__(shell=shell, **kwargs)
135 self.shell = shell
135 self.shell = shell
136 self.init_transformers()
136 self.init_transformers()
137 self.init_handlers()
137 self.init_handlers()
138 self.init_checkers()
138 self.init_checkers()
139
139
140 #-------------------------------------------------------------------------
140 #-------------------------------------------------------------------------
141 # API for managing transformers
141 # API for managing transformers
142 #-------------------------------------------------------------------------
142 #-------------------------------------------------------------------------
143
143
144 def init_transformers(self):
144 def init_transformers(self):
145 """Create the default transformers."""
145 """Create the default transformers."""
146 self._transformers = []
146 self._transformers = []
147 for transformer_cls in _default_transformers:
147 for transformer_cls in _default_transformers:
148 transformer_cls(
148 transformer_cls(
149 shell=self.shell, prefilter_manager=self, parent=self
149 shell=self.shell, prefilter_manager=self, parent=self
150 )
150 )
151
151
152 def sort_transformers(self):
152 def sort_transformers(self):
153 """Sort the transformers by priority.
153 """Sort the transformers by priority.
154
154
155 This must be called after the priority of a transformer is changed.
155 This must be called after the priority of a transformer is changed.
156 The :meth:`register_transformer` method calls this automatically.
156 The :meth:`register_transformer` method calls this automatically.
157 """
157 """
158 self._transformers.sort(key=lambda x: x.priority)
158 self._transformers.sort(key=lambda x: x.priority)
159
159
160 @property
160 @property
161 def transformers(self):
161 def transformers(self):
162 """Return a list of checkers, sorted by priority."""
162 """Return a list of checkers, sorted by priority."""
163 return self._transformers
163 return self._transformers
164
164
165 def register_transformer(self, transformer):
165 def register_transformer(self, transformer):
166 """Register a transformer instance."""
166 """Register a transformer instance."""
167 if transformer not in self._transformers:
167 if transformer not in self._transformers:
168 self._transformers.append(transformer)
168 self._transformers.append(transformer)
169 self.sort_transformers()
169 self.sort_transformers()
170
170
171 def unregister_transformer(self, transformer):
171 def unregister_transformer(self, transformer):
172 """Unregister a transformer instance."""
172 """Unregister a transformer instance."""
173 if transformer in self._transformers:
173 if transformer in self._transformers:
174 self._transformers.remove(transformer)
174 self._transformers.remove(transformer)
175
175
176 #-------------------------------------------------------------------------
176 #-------------------------------------------------------------------------
177 # API for managing checkers
177 # API for managing checkers
178 #-------------------------------------------------------------------------
178 #-------------------------------------------------------------------------
179
179
180 def init_checkers(self):
180 def init_checkers(self):
181 """Create the default checkers."""
181 """Create the default checkers."""
182 self._checkers = []
182 self._checkers = []
183 for checker in _default_checkers:
183 for checker in _default_checkers:
184 checker(
184 checker(
185 shell=self.shell, prefilter_manager=self, parent=self
185 shell=self.shell, prefilter_manager=self, parent=self
186 )
186 )
187
187
188 def sort_checkers(self):
188 def sort_checkers(self):
189 """Sort the checkers by priority.
189 """Sort the checkers by priority.
190
190
191 This must be called after the priority of a checker is changed.
191 This must be called after the priority of a checker is changed.
192 The :meth:`register_checker` method calls this automatically.
192 The :meth:`register_checker` method calls this automatically.
193 """
193 """
194 self._checkers.sort(key=lambda x: x.priority)
194 self._checkers.sort(key=lambda x: x.priority)
195
195
196 @property
196 @property
197 def checkers(self):
197 def checkers(self):
198 """Return a list of checkers, sorted by priority."""
198 """Return a list of checkers, sorted by priority."""
199 return self._checkers
199 return self._checkers
200
200
201 def register_checker(self, checker):
201 def register_checker(self, checker):
202 """Register a checker instance."""
202 """Register a checker instance."""
203 if checker not in self._checkers:
203 if checker not in self._checkers:
204 self._checkers.append(checker)
204 self._checkers.append(checker)
205 self.sort_checkers()
205 self.sort_checkers()
206
206
207 def unregister_checker(self, checker):
207 def unregister_checker(self, checker):
208 """Unregister a checker instance."""
208 """Unregister a checker instance."""
209 if checker in self._checkers:
209 if checker in self._checkers:
210 self._checkers.remove(checker)
210 self._checkers.remove(checker)
211
211
212 #-------------------------------------------------------------------------
212 #-------------------------------------------------------------------------
213 # API for managing checkers
213 # API for managing checkers
214 #-------------------------------------------------------------------------
214 #-------------------------------------------------------------------------
215
215
216 def init_handlers(self):
216 def init_handlers(self):
217 """Create the default handlers."""
217 """Create the default handlers."""
218 self._handlers = {}
218 self._handlers = {}
219 self._esc_handlers = {}
219 self._esc_handlers = {}
220 for handler in _default_handlers:
220 for handler in _default_handlers:
221 handler(
221 handler(
222 shell=self.shell, prefilter_manager=self, parent=self
222 shell=self.shell, prefilter_manager=self, parent=self
223 )
223 )
224
224
225 @property
225 @property
226 def handlers(self):
226 def handlers(self):
227 """Return a dict of all the handlers."""
227 """Return a dict of all the handlers."""
228 return self._handlers
228 return self._handlers
229
229
230 def register_handler(self, name, handler, esc_strings):
230 def register_handler(self, name, handler, esc_strings):
231 """Register a handler instance by name with esc_strings."""
231 """Register a handler instance by name with esc_strings."""
232 self._handlers[name] = handler
232 self._handlers[name] = handler
233 for esc_str in esc_strings:
233 for esc_str in esc_strings:
234 self._esc_handlers[esc_str] = handler
234 self._esc_handlers[esc_str] = handler
235
235
236 def unregister_handler(self, name, handler, esc_strings):
236 def unregister_handler(self, name, handler, esc_strings):
237 """Unregister a handler instance by name with esc_strings."""
237 """Unregister a handler instance by name with esc_strings."""
238 try:
238 try:
239 del self._handlers[name]
239 del self._handlers[name]
240 except KeyError:
240 except KeyError:
241 pass
241 pass
242 for esc_str in esc_strings:
242 for esc_str in esc_strings:
243 h = self._esc_handlers.get(esc_str)
243 h = self._esc_handlers.get(esc_str)
244 if h is handler:
244 if h is handler:
245 del self._esc_handlers[esc_str]
245 del self._esc_handlers[esc_str]
246
246
247 def get_handler_by_name(self, name):
247 def get_handler_by_name(self, name):
248 """Get a handler by its name."""
248 """Get a handler by its name."""
249 return self._handlers.get(name)
249 return self._handlers.get(name)
250
250
251 def get_handler_by_esc(self, esc_str):
251 def get_handler_by_esc(self, esc_str):
252 """Get a handler by its escape string."""
252 """Get a handler by its escape string."""
253 return self._esc_handlers.get(esc_str)
253 return self._esc_handlers.get(esc_str)
254
254
255 #-------------------------------------------------------------------------
255 #-------------------------------------------------------------------------
256 # Main prefiltering API
256 # Main prefiltering API
257 #-------------------------------------------------------------------------
257 #-------------------------------------------------------------------------
258
258
259 def prefilter_line_info(self, line_info):
259 def prefilter_line_info(self, line_info):
260 """Prefilter a line that has been converted to a LineInfo object.
260 """Prefilter a line that has been converted to a LineInfo object.
261
261
262 This implements the checker/handler part of the prefilter pipe.
262 This implements the checker/handler part of the prefilter pipe.
263 """
263 """
264 # print "prefilter_line_info: ", line_info
264 # print "prefilter_line_info: ", line_info
265 handler = self.find_handler(line_info)
265 handler = self.find_handler(line_info)
266 return handler.handle(line_info)
266 return handler.handle(line_info)
267
267
268 def find_handler(self, line_info):
268 def find_handler(self, line_info):
269 """Find a handler for the line_info by trying checkers."""
269 """Find a handler for the line_info by trying checkers."""
270 for checker in self.checkers:
270 for checker in self.checkers:
271 if checker.enabled:
271 if checker.enabled:
272 handler = checker.check(line_info)
272 handler = checker.check(line_info)
273 if handler:
273 if handler:
274 return handler
274 return handler
275 return self.get_handler_by_name('normal')
275 return self.get_handler_by_name('normal')
276
276
277 def transform_line(self, line, continue_prompt):
277 def transform_line(self, line, continue_prompt):
278 """Calls the enabled transformers in order of increasing priority."""
278 """Calls the enabled transformers in order of increasing priority."""
279 for transformer in self.transformers:
279 for transformer in self.transformers:
280 if transformer.enabled:
280 if transformer.enabled:
281 line = transformer.transform(line, continue_prompt)
281 line = transformer.transform(line, continue_prompt)
282 return line
282 return line
283
283
284 def prefilter_line(self, line, continue_prompt=False):
284 def prefilter_line(self, line, continue_prompt=False):
285 """Prefilter a single input line as text.
285 """Prefilter a single input line as text.
286
286
287 This method prefilters a single line of text by calling the
287 This method prefilters a single line of text by calling the
288 transformers and then the checkers/handlers.
288 transformers and then the checkers/handlers.
289 """
289 """
290
290
291 # print "prefilter_line: ", line, continue_prompt
291 # print "prefilter_line: ", line, continue_prompt
292 # All handlers *must* return a value, even if it's blank ('').
292 # All handlers *must* return a value, even if it's blank ('').
293
293
294 # save the line away in case we crash, so the post-mortem handler can
294 # save the line away in case we crash, so the post-mortem handler can
295 # record it
295 # record it
296 self.shell._last_input_line = line
296 self.shell._last_input_line = line
297
297
298 if not line:
298 if not line:
299 # Return immediately on purely empty lines, so that if the user
299 # Return immediately on purely empty lines, so that if the user
300 # previously typed some whitespace that started a continuation
300 # previously typed some whitespace that started a continuation
301 # prompt, he can break out of that loop with just an empty line.
301 # prompt, he can break out of that loop with just an empty line.
302 # This is how the default python prompt works.
302 # This is how the default python prompt works.
303 return ''
303 return ''
304
304
305 # At this point, we invoke our transformers.
305 # At this point, we invoke our transformers.
306 if not continue_prompt or (continue_prompt and self.multi_line_specials):
306 if not continue_prompt or (continue_prompt and self.multi_line_specials):
307 line = self.transform_line(line, continue_prompt)
307 line = self.transform_line(line, continue_prompt)
308
308
309 # Now we compute line_info for the checkers and handlers
309 # Now we compute line_info for the checkers and handlers
310 line_info = LineInfo(line, continue_prompt)
310 line_info = LineInfo(line, continue_prompt)
311
311
312 # the input history needs to track even empty lines
312 # the input history needs to track even empty lines
313 stripped = line.strip()
313 stripped = line.strip()
314
314
315 normal_handler = self.get_handler_by_name('normal')
315 normal_handler = self.get_handler_by_name('normal')
316 if not stripped:
316 if not stripped:
317 return normal_handler.handle(line_info)
317 return normal_handler.handle(line_info)
318
318
319 # special handlers are only allowed for single line statements
319 # special handlers are only allowed for single line statements
320 if continue_prompt and not self.multi_line_specials:
320 if continue_prompt and not self.multi_line_specials:
321 return normal_handler.handle(line_info)
321 return normal_handler.handle(line_info)
322
322
323 prefiltered = self.prefilter_line_info(line_info)
323 prefiltered = self.prefilter_line_info(line_info)
324 # print "prefiltered line: %r" % prefiltered
324 # print "prefiltered line: %r" % prefiltered
325 return prefiltered
325 return prefiltered
326
326
327 def prefilter_lines(self, lines, continue_prompt=False):
327 def prefilter_lines(self, lines, continue_prompt=False):
328 """Prefilter multiple input lines of text.
328 """Prefilter multiple input lines of text.
329
329
330 This is the main entry point for prefiltering multiple lines of
330 This is the main entry point for prefiltering multiple lines of
331 input. This simply calls :meth:`prefilter_line` for each line of
331 input. This simply calls :meth:`prefilter_line` for each line of
332 input.
332 input.
333
333
334 This covers cases where there are multiple lines in the user entry,
334 This covers cases where there are multiple lines in the user entry,
335 which is the case when the user goes back to a multiline history
335 which is the case when the user goes back to a multiline history
336 entry and presses enter.
336 entry and presses enter.
337 """
337 """
338 llines = lines.rstrip('\n').split('\n')
338 llines = lines.rstrip('\n').split('\n')
339 # We can get multiple lines in one shot, where multiline input 'blends'
339 # We can get multiple lines in one shot, where multiline input 'blends'
340 # into one line, in cases like recalling from the readline history
340 # into one line, in cases like recalling from the readline history
341 # buffer. We need to make sure that in such cases, we correctly
341 # buffer. We need to make sure that in such cases, we correctly
342 # communicate downstream which line is first and which are continuation
342 # communicate downstream which line is first and which are continuation
343 # ones.
343 # ones.
344 if len(llines) > 1:
344 if len(llines) > 1:
345 out = '\n'.join([self.prefilter_line(line, lnum>0)
345 out = '\n'.join([self.prefilter_line(line, lnum>0)
346 for lnum, line in enumerate(llines) ])
346 for lnum, line in enumerate(llines) ])
347 else:
347 else:
348 out = self.prefilter_line(llines[0], continue_prompt)
348 out = self.prefilter_line(llines[0], continue_prompt)
349
349
350 return out
350 return out
351
351
352 #-----------------------------------------------------------------------------
352 #-----------------------------------------------------------------------------
353 # Prefilter transformers
353 # Prefilter transformers
354 #-----------------------------------------------------------------------------
354 #-----------------------------------------------------------------------------
355
355
356
356
357 class PrefilterTransformer(Configurable):
357 class PrefilterTransformer(Configurable):
358 """Transform a line of user input."""
358 """Transform a line of user input."""
359
359
360 priority = Integer(100, config=True)
360 priority = Integer(100, config=True)
361 # Transformers don't currently use shell or prefilter_manager, but as we
361 # Transformers don't currently use shell or prefilter_manager, but as we
362 # move away from checkers and handlers, they will need them.
362 # move away from checkers and handlers, they will need them.
363 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
363 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
364 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
364 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
365 enabled = Bool(True, config=True)
365 enabled = Bool(True, config=True)
366
366
367 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
367 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
368 super(PrefilterTransformer, self).__init__(
368 super(PrefilterTransformer, self).__init__(
369 shell=shell, prefilter_manager=prefilter_manager, **kwargs
369 shell=shell, prefilter_manager=prefilter_manager, **kwargs
370 )
370 )
371 self.prefilter_manager.register_transformer(self)
371 self.prefilter_manager.register_transformer(self)
372
372
373 def transform(self, line, continue_prompt):
373 def transform(self, line, continue_prompt):
374 """Transform a line, returning the new one."""
374 """Transform a line, returning the new one."""
375 return None
375 return None
376
376
377 def __repr__(self):
377 def __repr__(self):
378 return "<%s(priority=%r, enabled=%r)>" % (
378 return "<%s(priority=%r, enabled=%r)>" % (
379 self.__class__.__name__, self.priority, self.enabled)
379 self.__class__.__name__, self.priority, self.enabled)
380
380
381
381
382 #-----------------------------------------------------------------------------
382 #-----------------------------------------------------------------------------
383 # Prefilter checkers
383 # Prefilter checkers
384 #-----------------------------------------------------------------------------
384 #-----------------------------------------------------------------------------
385
385
386
386
387 class PrefilterChecker(Configurable):
387 class PrefilterChecker(Configurable):
388 """Inspect an input line and return a handler for that line."""
388 """Inspect an input line and return a handler for that line."""
389
389
390 priority = Integer(100, config=True)
390 priority = Integer(100, config=True)
391 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
391 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
392 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
392 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
393 enabled = Bool(True, config=True)
393 enabled = Bool(True, config=True)
394
394
395 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
395 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
396 super(PrefilterChecker, self).__init__(
396 super(PrefilterChecker, self).__init__(
397 shell=shell, prefilter_manager=prefilter_manager, **kwargs
397 shell=shell, prefilter_manager=prefilter_manager, **kwargs
398 )
398 )
399 self.prefilter_manager.register_checker(self)
399 self.prefilter_manager.register_checker(self)
400
400
401 def check(self, line_info):
401 def check(self, line_info):
402 """Inspect line_info and return a handler instance or None."""
402 """Inspect line_info and return a handler instance or None."""
403 return None
403 return None
404
404
405 def __repr__(self):
405 def __repr__(self):
406 return "<%s(priority=%r, enabled=%r)>" % (
406 return "<%s(priority=%r, enabled=%r)>" % (
407 self.__class__.__name__, self.priority, self.enabled)
407 self.__class__.__name__, self.priority, self.enabled)
408
408
409
409
410 class EmacsChecker(PrefilterChecker):
410 class EmacsChecker(PrefilterChecker):
411
411
412 priority = Integer(100, config=True)
412 priority = Integer(100, config=True)
413 enabled = Bool(False, config=True)
413 enabled = Bool(False, config=True)
414
414
415 def check(self, line_info):
415 def check(self, line_info):
416 "Emacs ipython-mode tags certain input lines."
416 "Emacs ipython-mode tags certain input lines."
417 if line_info.line.endswith('# PYTHON-MODE'):
417 if line_info.line.endswith('# PYTHON-MODE'):
418 return self.prefilter_manager.get_handler_by_name('emacs')
418 return self.prefilter_manager.get_handler_by_name('emacs')
419 else:
419 else:
420 return None
420 return None
421
421
422
422
423 class MacroChecker(PrefilterChecker):
423 class MacroChecker(PrefilterChecker):
424
424
425 priority = Integer(250, config=True)
425 priority = Integer(250, config=True)
426
426
427 def check(self, line_info):
427 def check(self, line_info):
428 obj = self.shell.user_ns.get(line_info.ifun)
428 obj = self.shell.user_ns.get(line_info.ifun)
429 if isinstance(obj, Macro):
429 if isinstance(obj, Macro):
430 return self.prefilter_manager.get_handler_by_name('macro')
430 return self.prefilter_manager.get_handler_by_name('macro')
431 else:
431 else:
432 return None
432 return None
433
433
434
434
435 class IPyAutocallChecker(PrefilterChecker):
435 class IPyAutocallChecker(PrefilterChecker):
436
436
437 priority = Integer(300, config=True)
437 priority = Integer(300, config=True)
438
438
439 def check(self, line_info):
439 def check(self, line_info):
440 "Instances of IPyAutocall in user_ns get autocalled immediately"
440 "Instances of IPyAutocall in user_ns get autocalled immediately"
441 obj = self.shell.user_ns.get(line_info.ifun, None)
441 obj = self.shell.user_ns.get(line_info.ifun, None)
442 if isinstance(obj, IPyAutocall):
442 if isinstance(obj, IPyAutocall):
443 obj.set_ip(self.shell)
443 obj.set_ip(self.shell)
444 return self.prefilter_manager.get_handler_by_name('auto')
444 return self.prefilter_manager.get_handler_by_name('auto')
445 else:
445 else:
446 return None
446 return None
447
447
448
448
449 class AssignmentChecker(PrefilterChecker):
449 class AssignmentChecker(PrefilterChecker):
450
450
451 priority = Integer(600, config=True)
451 priority = Integer(600, config=True)
452
452
453 def check(self, line_info):
453 def check(self, line_info):
454 """Check to see if user is assigning to a var for the first time, in
454 """Check to see if user is assigning to a var for the first time, in
455 which case we want to avoid any sort of automagic / autocall games.
455 which case we want to avoid any sort of automagic / autocall games.
456
456
457 This allows users to assign to either alias or magic names true python
457 This allows users to assign to either alias or magic names true python
458 variables (the magic/alias systems always take second seat to true
458 variables (the magic/alias systems always take second seat to true
459 python code). E.g. ls='hi', or ls,that=1,2"""
459 python code). E.g. ls='hi', or ls,that=1,2"""
460 if line_info.the_rest:
460 if line_info.the_rest:
461 if line_info.the_rest[0] in '=,':
461 if line_info.the_rest[0] in '=,':
462 return self.prefilter_manager.get_handler_by_name('normal')
462 return self.prefilter_manager.get_handler_by_name('normal')
463 else:
463 else:
464 return None
464 return None
465
465
466
466
467 class AutoMagicChecker(PrefilterChecker):
467 class AutoMagicChecker(PrefilterChecker):
468
468
469 priority = Integer(700, config=True)
469 priority = Integer(700, config=True)
470
470
471 def check(self, line_info):
471 def check(self, line_info):
472 """If the ifun is magic, and automagic is on, run it. Note: normal,
472 """If the ifun is magic, and automagic is on, run it. Note: normal,
473 non-auto magic would already have been triggered via '%' in
473 non-auto magic would already have been triggered via '%' in
474 check_esc_chars. This just checks for automagic. Also, before
474 check_esc_chars. This just checks for automagic. Also, before
475 triggering the magic handler, make sure that there is nothing in the
475 triggering the magic handler, make sure that there is nothing in the
476 user namespace which could shadow it."""
476 user namespace which could shadow it."""
477 if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
477 if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
478 return None
478 return None
479
479
480 # We have a likely magic method. Make sure we should actually call it.
480 # We have a likely magic method. Make sure we should actually call it.
481 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
481 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
482 return None
482 return None
483
483
484 head = line_info.ifun.split('.',1)[0]
484 head = line_info.ifun.split('.',1)[0]
485 if is_shadowed(head, self.shell):
485 if is_shadowed(head, self.shell):
486 return None
486 return None
487
487
488 return self.prefilter_manager.get_handler_by_name('magic')
488 return self.prefilter_manager.get_handler_by_name('magic')
489
489
490
490
491 class AliasChecker(PrefilterChecker):
492
493 priority = Integer(800, config=True)
494
495 def check(self, line_info):
496 "Check if the initital identifier on the line is an alias."
497 # Note: aliases can not contain '.'
498 head = line_info.ifun.split('.',1)[0]
499 if line_info.ifun not in self.shell.alias_manager \
500 or head not in self.shell.alias_manager \
501 or is_shadowed(head, self.shell):
502 return None
503
504 return self.prefilter_manager.get_handler_by_name('alias')
505
506
507 class PythonOpsChecker(PrefilterChecker):
491 class PythonOpsChecker(PrefilterChecker):
508
492
509 priority = Integer(900, config=True)
493 priority = Integer(900, config=True)
510
494
511 def check(self, line_info):
495 def check(self, line_info):
512 """If the 'rest' of the line begins with a function call or pretty much
496 """If the 'rest' of the line begins with a function call or pretty much
513 any python operator, we should simply execute the line (regardless of
497 any python operator, we should simply execute the line (regardless of
514 whether or not there's a possible autocall expansion). This avoids
498 whether or not there's a possible autocall expansion). This avoids
515 spurious (and very confusing) geattr() accesses."""
499 spurious (and very confusing) geattr() accesses."""
516 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
500 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
517 return self.prefilter_manager.get_handler_by_name('normal')
501 return self.prefilter_manager.get_handler_by_name('normal')
518 else:
502 else:
519 return None
503 return None
520
504
521
505
522 class AutocallChecker(PrefilterChecker):
506 class AutocallChecker(PrefilterChecker):
523
507
524 priority = Integer(1000, config=True)
508 priority = Integer(1000, config=True)
525
509
526 function_name_regexp = CRegExp(re_fun_name, config=True,
510 function_name_regexp = CRegExp(re_fun_name, config=True,
527 help="RegExp to identify potential function names.")
511 help="RegExp to identify potential function names.")
528 exclude_regexp = CRegExp(re_exclude_auto, config=True,
512 exclude_regexp = CRegExp(re_exclude_auto, config=True,
529 help="RegExp to exclude strings with this start from autocalling.")
513 help="RegExp to exclude strings with this start from autocalling.")
530
514
531 def check(self, line_info):
515 def check(self, line_info):
532 "Check if the initial word/function is callable and autocall is on."
516 "Check if the initial word/function is callable and autocall is on."
533 if not self.shell.autocall:
517 if not self.shell.autocall:
534 return None
518 return None
535
519
536 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
520 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
537 if not oinfo['found']:
521 if not oinfo['found']:
538 return None
522 return None
539
523
540 if callable(oinfo['obj']) \
524 if callable(oinfo['obj']) \
541 and (not self.exclude_regexp.match(line_info.the_rest)) \
525 and (not self.exclude_regexp.match(line_info.the_rest)) \
542 and self.function_name_regexp.match(line_info.ifun):
526 and self.function_name_regexp.match(line_info.ifun):
543 return self.prefilter_manager.get_handler_by_name('auto')
527 return self.prefilter_manager.get_handler_by_name('auto')
544 else:
528 else:
545 return None
529 return None
546
530
547
531
548 #-----------------------------------------------------------------------------
532 #-----------------------------------------------------------------------------
549 # Prefilter handlers
533 # Prefilter handlers
550 #-----------------------------------------------------------------------------
534 #-----------------------------------------------------------------------------
551
535
552
536
553 class PrefilterHandler(Configurable):
537 class PrefilterHandler(Configurable):
554
538
555 handler_name = Unicode('normal')
539 handler_name = Unicode('normal')
556 esc_strings = List([])
540 esc_strings = List([])
557 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
541 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
558 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
542 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
559
543
560 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
544 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
561 super(PrefilterHandler, self).__init__(
545 super(PrefilterHandler, self).__init__(
562 shell=shell, prefilter_manager=prefilter_manager, **kwargs
546 shell=shell, prefilter_manager=prefilter_manager, **kwargs
563 )
547 )
564 self.prefilter_manager.register_handler(
548 self.prefilter_manager.register_handler(
565 self.handler_name,
549 self.handler_name,
566 self,
550 self,
567 self.esc_strings
551 self.esc_strings
568 )
552 )
569
553
570 def handle(self, line_info):
554 def handle(self, line_info):
571 # print "normal: ", line_info
555 # print "normal: ", line_info
572 """Handle normal input lines. Use as a template for handlers."""
556 """Handle normal input lines. Use as a template for handlers."""
573
557
574 # With autoindent on, we need some way to exit the input loop, and I
558 # With autoindent on, we need some way to exit the input loop, and I
575 # don't want to force the user to have to backspace all the way to
559 # don't want to force the user to have to backspace all the way to
576 # clear the line. The rule will be in this case, that either two
560 # clear the line. The rule will be in this case, that either two
577 # lines of pure whitespace in a row, or a line of pure whitespace but
561 # lines of pure whitespace in a row, or a line of pure whitespace but
578 # of a size different to the indent level, will exit the input loop.
562 # of a size different to the indent level, will exit the input loop.
579 line = line_info.line
563 line = line_info.line
580 continue_prompt = line_info.continue_prompt
564 continue_prompt = line_info.continue_prompt
581
565
582 if (continue_prompt and
566 if (continue_prompt and
583 self.shell.autoindent and
567 self.shell.autoindent and
584 line.isspace() and
568 line.isspace() and
585 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
569 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
586 line = ''
570 line = ''
587
571
588 return line
572 return line
589
573
590 def __str__(self):
574 def __str__(self):
591 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
575 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
592
576
593
577
594 class AliasHandler(PrefilterHandler):
595
596 handler_name = Unicode('alias')
597
598 def handle(self, line_info):
599 """Handle alias input lines. """
600 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
601 # pre is needed, because it carries the leading whitespace. Otherwise
602 # aliases won't work in indented sections.
603 line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed)
604
605 return line_out
606
607
608 class MacroHandler(PrefilterHandler):
578 class MacroHandler(PrefilterHandler):
609 handler_name = Unicode("macro")
579 handler_name = Unicode("macro")
610
580
611 def handle(self, line_info):
581 def handle(self, line_info):
612 obj = self.shell.user_ns.get(line_info.ifun)
582 obj = self.shell.user_ns.get(line_info.ifun)
613 pre_space = line_info.pre_whitespace
583 pre_space = line_info.pre_whitespace
614 line_sep = "\n" + pre_space
584 line_sep = "\n" + pre_space
615 return pre_space + line_sep.join(obj.value.splitlines())
585 return pre_space + line_sep.join(obj.value.splitlines())
616
586
617
587
618 class MagicHandler(PrefilterHandler):
588 class MagicHandler(PrefilterHandler):
619
589
620 handler_name = Unicode('magic')
590 handler_name = Unicode('magic')
621 esc_strings = List([ESC_MAGIC])
591 esc_strings = List([ESC_MAGIC])
622
592
623 def handle(self, line_info):
593 def handle(self, line_info):
624 """Execute magic functions."""
594 """Execute magic functions."""
625 ifun = line_info.ifun
595 ifun = line_info.ifun
626 the_rest = line_info.the_rest
596 the_rest = line_info.the_rest
627 cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
597 cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
628 (ifun + " " + the_rest))
598 (ifun + " " + the_rest))
629 return cmd
599 return cmd
630
600
631
601
632 class AutoHandler(PrefilterHandler):
602 class AutoHandler(PrefilterHandler):
633
603
634 handler_name = Unicode('auto')
604 handler_name = Unicode('auto')
635 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
605 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
636
606
637 def handle(self, line_info):
607 def handle(self, line_info):
638 """Handle lines which can be auto-executed, quoting if requested."""
608 """Handle lines which can be auto-executed, quoting if requested."""
639 line = line_info.line
609 line = line_info.line
640 ifun = line_info.ifun
610 ifun = line_info.ifun
641 the_rest = line_info.the_rest
611 the_rest = line_info.the_rest
642 pre = line_info.pre
612 pre = line_info.pre
643 esc = line_info.esc
613 esc = line_info.esc
644 continue_prompt = line_info.continue_prompt
614 continue_prompt = line_info.continue_prompt
645 obj = line_info.ofind(self.shell)['obj']
615 obj = line_info.ofind(self.shell)['obj']
646 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
616 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
647
617
648 # This should only be active for single-line input!
618 # This should only be active for single-line input!
649 if continue_prompt:
619 if continue_prompt:
650 return line
620 return line
651
621
652 force_auto = isinstance(obj, IPyAutocall)
622 force_auto = isinstance(obj, IPyAutocall)
653
623
654 # User objects sometimes raise exceptions on attribute access other
624 # User objects sometimes raise exceptions on attribute access other
655 # than AttributeError (we've seen it in the past), so it's safest to be
625 # than AttributeError (we've seen it in the past), so it's safest to be
656 # ultra-conservative here and catch all.
626 # ultra-conservative here and catch all.
657 try:
627 try:
658 auto_rewrite = obj.rewrite
628 auto_rewrite = obj.rewrite
659 except Exception:
629 except Exception:
660 auto_rewrite = True
630 auto_rewrite = True
661
631
662 if esc == ESC_QUOTE:
632 if esc == ESC_QUOTE:
663 # Auto-quote splitting on whitespace
633 # Auto-quote splitting on whitespace
664 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
634 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
665 elif esc == ESC_QUOTE2:
635 elif esc == ESC_QUOTE2:
666 # Auto-quote whole string
636 # Auto-quote whole string
667 newcmd = '%s("%s")' % (ifun,the_rest)
637 newcmd = '%s("%s")' % (ifun,the_rest)
668 elif esc == ESC_PAREN:
638 elif esc == ESC_PAREN:
669 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
639 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
670 else:
640 else:
671 # Auto-paren.
641 # Auto-paren.
672 if force_auto:
642 if force_auto:
673 # Don't rewrite if it is already a call.
643 # Don't rewrite if it is already a call.
674 do_rewrite = not the_rest.startswith('(')
644 do_rewrite = not the_rest.startswith('(')
675 else:
645 else:
676 if not the_rest:
646 if not the_rest:
677 # We only apply it to argument-less calls if the autocall
647 # We only apply it to argument-less calls if the autocall
678 # parameter is set to 2.
648 # parameter is set to 2.
679 do_rewrite = (self.shell.autocall >= 2)
649 do_rewrite = (self.shell.autocall >= 2)
680 elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
650 elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
681 # Don't autocall in this case: item access for an object
651 # Don't autocall in this case: item access for an object
682 # which is BOTH callable and implements __getitem__.
652 # which is BOTH callable and implements __getitem__.
683 do_rewrite = False
653 do_rewrite = False
684 else:
654 else:
685 do_rewrite = True
655 do_rewrite = True
686
656
687 # Figure out the rewritten command
657 # Figure out the rewritten command
688 if do_rewrite:
658 if do_rewrite:
689 if the_rest.endswith(';'):
659 if the_rest.endswith(';'):
690 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
660 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
691 else:
661 else:
692 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
662 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
693 else:
663 else:
694 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
664 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
695 return normal_handler.handle(line_info)
665 return normal_handler.handle(line_info)
696
666
697 # Display the rewritten call
667 # Display the rewritten call
698 if auto_rewrite:
668 if auto_rewrite:
699 self.shell.auto_rewrite_input(newcmd)
669 self.shell.auto_rewrite_input(newcmd)
700
670
701 return newcmd
671 return newcmd
702
672
703
673
704 class EmacsHandler(PrefilterHandler):
674 class EmacsHandler(PrefilterHandler):
705
675
706 handler_name = Unicode('emacs')
676 handler_name = Unicode('emacs')
707 esc_strings = List([])
677 esc_strings = List([])
708
678
709 def handle(self, line_info):
679 def handle(self, line_info):
710 """Handle input lines marked by python-mode."""
680 """Handle input lines marked by python-mode."""
711
681
712 # Currently, nothing is done. Later more functionality can be added
682 # Currently, nothing is done. Later more functionality can be added
713 # here if needed.
683 # here if needed.
714
684
715 # The input cache shouldn't be updated
685 # The input cache shouldn't be updated
716 return line_info.line
686 return line_info.line
717
687
718
688
719 #-----------------------------------------------------------------------------
689 #-----------------------------------------------------------------------------
720 # Defaults
690 # Defaults
721 #-----------------------------------------------------------------------------
691 #-----------------------------------------------------------------------------
722
692
723
693
724 _default_transformers = [
694 _default_transformers = [
725 ]
695 ]
726
696
727 _default_checkers = [
697 _default_checkers = [
728 EmacsChecker,
698 EmacsChecker,
729 MacroChecker,
699 MacroChecker,
730 IPyAutocallChecker,
700 IPyAutocallChecker,
731 AssignmentChecker,
701 AssignmentChecker,
732 AutoMagicChecker,
702 AutoMagicChecker,
733 AliasChecker,
734 PythonOpsChecker,
703 PythonOpsChecker,
735 AutocallChecker
704 AutocallChecker
736 ]
705 ]
737
706
738 _default_handlers = [
707 _default_handlers = [
739 PrefilterHandler,
708 PrefilterHandler,
740 AliasHandler,
741 MacroHandler,
709 MacroHandler,
742 MagicHandler,
710 MagicHandler,
743 AutoHandler,
711 AutoHandler,
744 EmacsHandler
712 EmacsHandler
745 ]
713 ]
@@ -1,119 +1,97 b''
1 """Tests for input handlers.
1 """Tests for input handlers.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # third party
7 # third party
8 import nose.tools as nt
8 import nose.tools as nt
9
9
10 # our own packages
10 # our own packages
11 from IPython.core import autocall
11 from IPython.core import autocall
12 from IPython.testing import tools as tt
12 from IPython.testing import tools as tt
13 from IPython.testing.globalipapp import get_ipython
13 from IPython.testing.globalipapp import get_ipython
14 from IPython.utils import py3compat
14 from IPython.utils import py3compat
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Globals
17 # Globals
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 # Get the public instance of IPython
20 # Get the public instance of IPython
21 ip = get_ipython()
21 ip = get_ipython()
22
22
23 failures = []
23 failures = []
24 num_tests = 0
24 num_tests = 0
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Test functions
27 # Test functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class CallableIndexable(object):
30 class CallableIndexable(object):
31 def __getitem__(self, idx): return True
31 def __getitem__(self, idx): return True
32 def __call__(self, *args, **kws): return True
32 def __call__(self, *args, **kws): return True
33
33
34
34
35 class Autocallable(autocall.IPyAutocall):
35 class Autocallable(autocall.IPyAutocall):
36 def __call__(self):
36 def __call__(self):
37 return "called"
37 return "called"
38
38
39
39
40 def run(tests):
40 def run(tests):
41 """Loop through a list of (pre, post) inputs, where pre is the string
41 """Loop through a list of (pre, post) inputs, where pre is the string
42 handed to ipython, and post is how that string looks after it's been
42 handed to ipython, and post is how that string looks after it's been
43 transformed (i.e. ipython's notion of _i)"""
43 transformed (i.e. ipython's notion of _i)"""
44 tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests)
44 tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests)
45
45
46
46
47 def test_handlers():
47 def test_handlers():
48 # alias expansion
49
50 # We're using 'true' as our syscall of choice because it doesn't
51 # write anything to stdout.
52
53 # Turn off actual execution of aliases, because it's noisy
54 old_system_cmd = ip.system
55 ip.system = lambda cmd: None
56
57
58 ip.alias_manager.alias_table['an_alias'] = (0, 'true')
59 # These are useful for checking a particular recursive alias issue
60 ip.alias_manager.alias_table['top'] = (0, 'd:/cygwin/top')
61 ip.alias_manager.alias_table['d'] = (0, 'true')
62 run([(i,py3compat.u_format(o)) for i,o in \
63 [("an_alias", "get_ipython().system({u}'true ')"), # alias
64 # Below: recursive aliases should expand whitespace-surrounded
65 # chars, *not* initial chars which happen to be aliases:
66 ("top", "get_ipython().system({u}'d:/cygwin/top ')"),
67 ]])
68 ip.system = old_system_cmd
69
70 call_idx = CallableIndexable()
48 call_idx = CallableIndexable()
71 ip.user_ns['call_idx'] = call_idx
49 ip.user_ns['call_idx'] = call_idx
72
50
73 # For many of the below, we're also checking that leading whitespace
51 # For many of the below, we're also checking that leading whitespace
74 # turns off the esc char, which it should unless there is a continuation
52 # turns off the esc char, which it should unless there is a continuation
75 # line.
53 # line.
76 run([(i,py3compat.u_format(o)) for i,o in \
54 run([(i,py3compat.u_format(o)) for i,o in \
77 [('"no change"', '"no change"'), # normal
55 [('"no change"', '"no change"'), # normal
78 (u"lsmagic", "get_ipython().magic({u}'lsmagic ')"), # magic
56 (u"lsmagic", "get_ipython().magic({u}'lsmagic ')"), # magic
79 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
57 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
80 ]])
58 ]])
81
59
82 # Objects which are instances of IPyAutocall are *always* autocalled
60 # Objects which are instances of IPyAutocall are *always* autocalled
83 autocallable = Autocallable()
61 autocallable = Autocallable()
84 ip.user_ns['autocallable'] = autocallable
62 ip.user_ns['autocallable'] = autocallable
85
63
86 # auto
64 # auto
87 ip.magic('autocall 0')
65 ip.magic('autocall 0')
88 # Only explicit escapes or instances of IPyAutocallable should get
66 # Only explicit escapes or instances of IPyAutocallable should get
89 # expanded
67 # expanded
90 run([
68 run([
91 ('len "abc"', 'len "abc"'),
69 ('len "abc"', 'len "abc"'),
92 ('autocallable', 'autocallable()'),
70 ('autocallable', 'autocallable()'),
93 # Don't add extra brackets (gh-1117)
71 # Don't add extra brackets (gh-1117)
94 ('autocallable()', 'autocallable()'),
72 ('autocallable()', 'autocallable()'),
95 ])
73 ])
96 ip.magic('autocall 1')
74 ip.magic('autocall 1')
97 run([
75 run([
98 ('len "abc"', 'len("abc")'),
76 ('len "abc"', 'len("abc")'),
99 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
77 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
100 # Autocall is turned off if first arg is [] and the object
78 # Autocall is turned off if first arg is [] and the object
101 # is both callable and indexable. Like so:
79 # is both callable and indexable. Like so:
102 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
80 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
103 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
81 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
104 ('call_idx 1', 'call_idx(1)'),
82 ('call_idx 1', 'call_idx(1)'),
105 ('len', 'len'), # only at 2 does it auto-call on single args
83 ('len', 'len'), # only at 2 does it auto-call on single args
106 ])
84 ])
107 ip.magic('autocall 2')
85 ip.magic('autocall 2')
108 run([
86 run([
109 ('len "abc"', 'len("abc")'),
87 ('len "abc"', 'len("abc")'),
110 ('len "abc";', 'len("abc");'),
88 ('len "abc";', 'len("abc");'),
111 ('len [1,2]', 'len([1,2])'),
89 ('len [1,2]', 'len([1,2])'),
112 ('call_idx [1]', 'call_idx [1]'),
90 ('call_idx [1]', 'call_idx [1]'),
113 ('call_idx 1', 'call_idx(1)'),
91 ('call_idx 1', 'call_idx(1)'),
114 # This is what's different:
92 # This is what's different:
115 ('len', 'len()'), # only at 2 does it auto-call on single args
93 ('len', 'len()'), # only at 2 does it auto-call on single args
116 ])
94 ])
117 ip.magic('autocall 1')
95 ip.magic('autocall 1')
118
96
119 nt.assert_equal(failures, [])
97 nt.assert_equal(failures, [])
@@ -1,652 +1,641 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for the key interactiveshell module.
2 """Tests for the key interactiveshell module.
3
3
4 Historically the main classes in interactiveshell have been under-tested. This
4 Historically the main classes in interactiveshell have been under-tested. This
5 module should grow as many single-method tests as possible to trap many of the
5 module should grow as many single-method tests as possible to trap many of the
6 recurring bugs we seem to encounter with high-level interaction.
6 recurring bugs we seem to encounter with high-level interaction.
7
7
8 Authors
8 Authors
9 -------
9 -------
10 * Fernando Perez
10 * Fernando Perez
11 """
11 """
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2011 The IPython Development Team
13 # Copyright (C) 2011 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 # stdlib
22 # stdlib
23 import ast
23 import ast
24 import os
24 import os
25 import shutil
25 import shutil
26 import sys
26 import sys
27 import tempfile
27 import tempfile
28 import unittest
28 import unittest
29 from os.path import join
29 from os.path import join
30 from StringIO import StringIO
30 from StringIO import StringIO
31
31
32 # third-party
32 # third-party
33 import nose.tools as nt
33 import nose.tools as nt
34
34
35 # Our own
35 # Our own
36 from IPython.testing.decorators import skipif, onlyif_unicode_paths
36 from IPython.testing.decorators import skipif, onlyif_unicode_paths
37 from IPython.testing import tools as tt
37 from IPython.testing import tools as tt
38 from IPython.utils import io
38 from IPython.utils import io
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Globals
41 # Globals
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # This is used by every single test, no point repeating it ad nauseam
43 # This is used by every single test, no point repeating it ad nauseam
44 ip = get_ipython()
44 ip = get_ipython()
45
45
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47 # Tests
47 # Tests
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49
49
50 class InteractiveShellTestCase(unittest.TestCase):
50 class InteractiveShellTestCase(unittest.TestCase):
51 def test_naked_string_cells(self):
51 def test_naked_string_cells(self):
52 """Test that cells with only naked strings are fully executed"""
52 """Test that cells with only naked strings are fully executed"""
53 # First, single-line inputs
53 # First, single-line inputs
54 ip.run_cell('"a"\n')
54 ip.run_cell('"a"\n')
55 self.assertEqual(ip.user_ns['_'], 'a')
55 self.assertEqual(ip.user_ns['_'], 'a')
56 # And also multi-line cells
56 # And also multi-line cells
57 ip.run_cell('"""a\nb"""\n')
57 ip.run_cell('"""a\nb"""\n')
58 self.assertEqual(ip.user_ns['_'], 'a\nb')
58 self.assertEqual(ip.user_ns['_'], 'a\nb')
59
59
60 def test_run_empty_cell(self):
60 def test_run_empty_cell(self):
61 """Just make sure we don't get a horrible error with a blank
61 """Just make sure we don't get a horrible error with a blank
62 cell of input. Yes, I did overlook that."""
62 cell of input. Yes, I did overlook that."""
63 old_xc = ip.execution_count
63 old_xc = ip.execution_count
64 ip.run_cell('')
64 ip.run_cell('')
65 self.assertEqual(ip.execution_count, old_xc)
65 self.assertEqual(ip.execution_count, old_xc)
66
66
67 def test_run_cell_multiline(self):
67 def test_run_cell_multiline(self):
68 """Multi-block, multi-line cells must execute correctly.
68 """Multi-block, multi-line cells must execute correctly.
69 """
69 """
70 src = '\n'.join(["x=1",
70 src = '\n'.join(["x=1",
71 "y=2",
71 "y=2",
72 "if 1:",
72 "if 1:",
73 " x += 1",
73 " x += 1",
74 " y += 1",])
74 " y += 1",])
75 ip.run_cell(src)
75 ip.run_cell(src)
76 self.assertEqual(ip.user_ns['x'], 2)
76 self.assertEqual(ip.user_ns['x'], 2)
77 self.assertEqual(ip.user_ns['y'], 3)
77 self.assertEqual(ip.user_ns['y'], 3)
78
78
79 def test_multiline_string_cells(self):
79 def test_multiline_string_cells(self):
80 "Code sprinkled with multiline strings should execute (GH-306)"
80 "Code sprinkled with multiline strings should execute (GH-306)"
81 ip.run_cell('tmp=0')
81 ip.run_cell('tmp=0')
82 self.assertEqual(ip.user_ns['tmp'], 0)
82 self.assertEqual(ip.user_ns['tmp'], 0)
83 ip.run_cell('tmp=1;"""a\nb"""\n')
83 ip.run_cell('tmp=1;"""a\nb"""\n')
84 self.assertEqual(ip.user_ns['tmp'], 1)
84 self.assertEqual(ip.user_ns['tmp'], 1)
85
85
86 def test_dont_cache_with_semicolon(self):
86 def test_dont_cache_with_semicolon(self):
87 "Ending a line with semicolon should not cache the returned object (GH-307)"
87 "Ending a line with semicolon should not cache the returned object (GH-307)"
88 oldlen = len(ip.user_ns['Out'])
88 oldlen = len(ip.user_ns['Out'])
89 a = ip.run_cell('1;', store_history=True)
89 a = ip.run_cell('1;', store_history=True)
90 newlen = len(ip.user_ns['Out'])
90 newlen = len(ip.user_ns['Out'])
91 self.assertEqual(oldlen, newlen)
91 self.assertEqual(oldlen, newlen)
92 #also test the default caching behavior
92 #also test the default caching behavior
93 ip.run_cell('1', store_history=True)
93 ip.run_cell('1', store_history=True)
94 newlen = len(ip.user_ns['Out'])
94 newlen = len(ip.user_ns['Out'])
95 self.assertEqual(oldlen+1, newlen)
95 self.assertEqual(oldlen+1, newlen)
96
96
97 def test_In_variable(self):
97 def test_In_variable(self):
98 "Verify that In variable grows with user input (GH-284)"
98 "Verify that In variable grows with user input (GH-284)"
99 oldlen = len(ip.user_ns['In'])
99 oldlen = len(ip.user_ns['In'])
100 ip.run_cell('1;', store_history=True)
100 ip.run_cell('1;', store_history=True)
101 newlen = len(ip.user_ns['In'])
101 newlen = len(ip.user_ns['In'])
102 self.assertEqual(oldlen+1, newlen)
102 self.assertEqual(oldlen+1, newlen)
103 self.assertEqual(ip.user_ns['In'][-1],'1;')
103 self.assertEqual(ip.user_ns['In'][-1],'1;')
104
104
105 def test_magic_names_in_string(self):
105 def test_magic_names_in_string(self):
106 ip.run_cell('a = """\n%exit\n"""')
106 ip.run_cell('a = """\n%exit\n"""')
107 self.assertEqual(ip.user_ns['a'], '\n%exit\n')
107 self.assertEqual(ip.user_ns['a'], '\n%exit\n')
108
108
109 def test_alias_crash(self):
110 """Errors in prefilter can't crash IPython"""
111 ip.run_cell('%alias parts echo first %s second %s')
112 # capture stderr:
113 save_err = io.stderr
114 io.stderr = StringIO()
115 ip.run_cell('parts 1')
116 err = io.stderr.getvalue()
117 io.stderr = save_err
118 self.assertEqual(err.split(':')[0], 'ERROR')
119
120 def test_trailing_newline(self):
109 def test_trailing_newline(self):
121 """test that running !(command) does not raise a SyntaxError"""
110 """test that running !(command) does not raise a SyntaxError"""
122 ip.run_cell('!(true)\n', False)
111 ip.run_cell('!(true)\n', False)
123 ip.run_cell('!(true)\n\n\n', False)
112 ip.run_cell('!(true)\n\n\n', False)
124
113
125 def test_gh_597(self):
114 def test_gh_597(self):
126 """Pretty-printing lists of objects with non-ascii reprs may cause
115 """Pretty-printing lists of objects with non-ascii reprs may cause
127 problems."""
116 problems."""
128 class Spam(object):
117 class Spam(object):
129 def __repr__(self):
118 def __repr__(self):
130 return "\xe9"*50
119 return "\xe9"*50
131 import IPython.core.formatters
120 import IPython.core.formatters
132 f = IPython.core.formatters.PlainTextFormatter()
121 f = IPython.core.formatters.PlainTextFormatter()
133 f([Spam(),Spam()])
122 f([Spam(),Spam()])
134
123
135
124
136 def test_future_flags(self):
125 def test_future_flags(self):
137 """Check that future flags are used for parsing code (gh-777)"""
126 """Check that future flags are used for parsing code (gh-777)"""
138 ip.run_cell('from __future__ import print_function')
127 ip.run_cell('from __future__ import print_function')
139 try:
128 try:
140 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
129 ip.run_cell('prfunc_return_val = print(1,2, sep=" ")')
141 assert 'prfunc_return_val' in ip.user_ns
130 assert 'prfunc_return_val' in ip.user_ns
142 finally:
131 finally:
143 # Reset compiler flags so we don't mess up other tests.
132 # Reset compiler flags so we don't mess up other tests.
144 ip.compile.reset_compiler_flags()
133 ip.compile.reset_compiler_flags()
145
134
146 def test_future_unicode(self):
135 def test_future_unicode(self):
147 """Check that unicode_literals is imported from __future__ (gh #786)"""
136 """Check that unicode_literals is imported from __future__ (gh #786)"""
148 try:
137 try:
149 ip.run_cell(u'byte_str = "a"')
138 ip.run_cell(u'byte_str = "a"')
150 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
139 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
151 ip.run_cell('from __future__ import unicode_literals')
140 ip.run_cell('from __future__ import unicode_literals')
152 ip.run_cell(u'unicode_str = "a"')
141 ip.run_cell(u'unicode_str = "a"')
153 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
142 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
154 finally:
143 finally:
155 # Reset compiler flags so we don't mess up other tests.
144 # Reset compiler flags so we don't mess up other tests.
156 ip.compile.reset_compiler_flags()
145 ip.compile.reset_compiler_flags()
157
146
158 def test_can_pickle(self):
147 def test_can_pickle(self):
159 "Can we pickle objects defined interactively (GH-29)"
148 "Can we pickle objects defined interactively (GH-29)"
160 ip = get_ipython()
149 ip = get_ipython()
161 ip.reset()
150 ip.reset()
162 ip.run_cell(("class Mylist(list):\n"
151 ip.run_cell(("class Mylist(list):\n"
163 " def __init__(self,x=[]):\n"
152 " def __init__(self,x=[]):\n"
164 " list.__init__(self,x)"))
153 " list.__init__(self,x)"))
165 ip.run_cell("w=Mylist([1,2,3])")
154 ip.run_cell("w=Mylist([1,2,3])")
166
155
167 from cPickle import dumps
156 from cPickle import dumps
168
157
169 # We need to swap in our main module - this is only necessary
158 # We need to swap in our main module - this is only necessary
170 # inside the test framework, because IPython puts the interactive module
159 # inside the test framework, because IPython puts the interactive module
171 # in place (but the test framework undoes this).
160 # in place (but the test framework undoes this).
172 _main = sys.modules['__main__']
161 _main = sys.modules['__main__']
173 sys.modules['__main__'] = ip.user_module
162 sys.modules['__main__'] = ip.user_module
174 try:
163 try:
175 res = dumps(ip.user_ns["w"])
164 res = dumps(ip.user_ns["w"])
176 finally:
165 finally:
177 sys.modules['__main__'] = _main
166 sys.modules['__main__'] = _main
178 self.assertTrue(isinstance(res, bytes))
167 self.assertTrue(isinstance(res, bytes))
179
168
180 def test_global_ns(self):
169 def test_global_ns(self):
181 "Code in functions must be able to access variables outside them."
170 "Code in functions must be able to access variables outside them."
182 ip = get_ipython()
171 ip = get_ipython()
183 ip.run_cell("a = 10")
172 ip.run_cell("a = 10")
184 ip.run_cell(("def f(x):\n"
173 ip.run_cell(("def f(x):\n"
185 " return x + a"))
174 " return x + a"))
186 ip.run_cell("b = f(12)")
175 ip.run_cell("b = f(12)")
187 self.assertEqual(ip.user_ns["b"], 22)
176 self.assertEqual(ip.user_ns["b"], 22)
188
177
189 def test_bad_custom_tb(self):
178 def test_bad_custom_tb(self):
190 """Check that InteractiveShell is protected from bad custom exception handlers"""
179 """Check that InteractiveShell is protected from bad custom exception handlers"""
191 from IPython.utils import io
180 from IPython.utils import io
192 save_stderr = io.stderr
181 save_stderr = io.stderr
193 try:
182 try:
194 # capture stderr
183 # capture stderr
195 io.stderr = StringIO()
184 io.stderr = StringIO()
196 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
185 ip.set_custom_exc((IOError,), lambda etype,value,tb: 1/0)
197 self.assertEqual(ip.custom_exceptions, (IOError,))
186 self.assertEqual(ip.custom_exceptions, (IOError,))
198 ip.run_cell(u'raise IOError("foo")')
187 ip.run_cell(u'raise IOError("foo")')
199 self.assertEqual(ip.custom_exceptions, ())
188 self.assertEqual(ip.custom_exceptions, ())
200 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
189 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
201 finally:
190 finally:
202 io.stderr = save_stderr
191 io.stderr = save_stderr
203
192
204 def test_bad_custom_tb_return(self):
193 def test_bad_custom_tb_return(self):
205 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
194 """Check that InteractiveShell is protected from bad return types in custom exception handlers"""
206 from IPython.utils import io
195 from IPython.utils import io
207 save_stderr = io.stderr
196 save_stderr = io.stderr
208 try:
197 try:
209 # capture stderr
198 # capture stderr
210 io.stderr = StringIO()
199 io.stderr = StringIO()
211 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
200 ip.set_custom_exc((NameError,),lambda etype,value,tb, tb_offset=None: 1)
212 self.assertEqual(ip.custom_exceptions, (NameError,))
201 self.assertEqual(ip.custom_exceptions, (NameError,))
213 ip.run_cell(u'a=abracadabra')
202 ip.run_cell(u'a=abracadabra')
214 self.assertEqual(ip.custom_exceptions, ())
203 self.assertEqual(ip.custom_exceptions, ())
215 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
204 self.assertTrue("Custom TB Handler failed" in io.stderr.getvalue())
216 finally:
205 finally:
217 io.stderr = save_stderr
206 io.stderr = save_stderr
218
207
219 def test_drop_by_id(self):
208 def test_drop_by_id(self):
220 myvars = {"a":object(), "b":object(), "c": object()}
209 myvars = {"a":object(), "b":object(), "c": object()}
221 ip.push(myvars, interactive=False)
210 ip.push(myvars, interactive=False)
222 for name in myvars:
211 for name in myvars:
223 assert name in ip.user_ns, name
212 assert name in ip.user_ns, name
224 assert name in ip.user_ns_hidden, name
213 assert name in ip.user_ns_hidden, name
225 ip.user_ns['b'] = 12
214 ip.user_ns['b'] = 12
226 ip.drop_by_id(myvars)
215 ip.drop_by_id(myvars)
227 for name in ["a", "c"]:
216 for name in ["a", "c"]:
228 assert name not in ip.user_ns, name
217 assert name not in ip.user_ns, name
229 assert name not in ip.user_ns_hidden, name
218 assert name not in ip.user_ns_hidden, name
230 assert ip.user_ns['b'] == 12
219 assert ip.user_ns['b'] == 12
231 ip.reset()
220 ip.reset()
232
221
233 def test_var_expand(self):
222 def test_var_expand(self):
234 ip.user_ns['f'] = u'Ca\xf1o'
223 ip.user_ns['f'] = u'Ca\xf1o'
235 self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o')
224 self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o')
236 self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o')
225 self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o')
237 self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1')
226 self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1')
238 self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2')
227 self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2')
239
228
240 ip.user_ns['f'] = b'Ca\xc3\xb1o'
229 ip.user_ns['f'] = b'Ca\xc3\xb1o'
241 # This should not raise any exception:
230 # This should not raise any exception:
242 ip.var_expand(u'echo $f')
231 ip.var_expand(u'echo $f')
243
232
244 def test_var_expand_local(self):
233 def test_var_expand_local(self):
245 """Test local variable expansion in !system and %magic calls"""
234 """Test local variable expansion in !system and %magic calls"""
246 # !system
235 # !system
247 ip.run_cell('def test():\n'
236 ip.run_cell('def test():\n'
248 ' lvar = "ttt"\n'
237 ' lvar = "ttt"\n'
249 ' ret = !echo {lvar}\n'
238 ' ret = !echo {lvar}\n'
250 ' return ret[0]\n')
239 ' return ret[0]\n')
251 res = ip.user_ns['test']()
240 res = ip.user_ns['test']()
252 nt.assert_in('ttt', res)
241 nt.assert_in('ttt', res)
253
242
254 # %magic
243 # %magic
255 ip.run_cell('def makemacro():\n'
244 ip.run_cell('def makemacro():\n'
256 ' macroname = "macro_var_expand_locals"\n'
245 ' macroname = "macro_var_expand_locals"\n'
257 ' %macro {macroname} codestr\n')
246 ' %macro {macroname} codestr\n')
258 ip.user_ns['codestr'] = "str(12)"
247 ip.user_ns['codestr'] = "str(12)"
259 ip.run_cell('makemacro()')
248 ip.run_cell('makemacro()')
260 nt.assert_in('macro_var_expand_locals', ip.user_ns)
249 nt.assert_in('macro_var_expand_locals', ip.user_ns)
261
250
262 def test_var_expand_self(self):
251 def test_var_expand_self(self):
263 """Test variable expansion with the name 'self', which was failing.
252 """Test variable expansion with the name 'self', which was failing.
264
253
265 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
254 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
266 """
255 """
267 ip.run_cell('class cTest:\n'
256 ip.run_cell('class cTest:\n'
268 ' classvar="see me"\n'
257 ' classvar="see me"\n'
269 ' def test(self):\n'
258 ' def test(self):\n'
270 ' res = !echo Variable: {self.classvar}\n'
259 ' res = !echo Variable: {self.classvar}\n'
271 ' return res[0]\n')
260 ' return res[0]\n')
272 nt.assert_in('see me', ip.user_ns['cTest']().test())
261 nt.assert_in('see me', ip.user_ns['cTest']().test())
273
262
274 def test_bad_var_expand(self):
263 def test_bad_var_expand(self):
275 """var_expand on invalid formats shouldn't raise"""
264 """var_expand on invalid formats shouldn't raise"""
276 # SyntaxError
265 # SyntaxError
277 self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}")
266 self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}")
278 # NameError
267 # NameError
279 self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}")
268 self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}")
280 # ZeroDivisionError
269 # ZeroDivisionError
281 self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}")
270 self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}")
282
271
283 def test_silent_nopostexec(self):
272 def test_silent_nopostexec(self):
284 """run_cell(silent=True) doesn't invoke post-exec funcs"""
273 """run_cell(silent=True) doesn't invoke post-exec funcs"""
285 d = dict(called=False)
274 d = dict(called=False)
286 def set_called():
275 def set_called():
287 d['called'] = True
276 d['called'] = True
288
277
289 ip.register_post_execute(set_called)
278 ip.register_post_execute(set_called)
290 ip.run_cell("1", silent=True)
279 ip.run_cell("1", silent=True)
291 self.assertFalse(d['called'])
280 self.assertFalse(d['called'])
292 # double-check that non-silent exec did what we expected
281 # double-check that non-silent exec did what we expected
293 # silent to avoid
282 # silent to avoid
294 ip.run_cell("1")
283 ip.run_cell("1")
295 self.assertTrue(d['called'])
284 self.assertTrue(d['called'])
296 # remove post-exec
285 # remove post-exec
297 ip._post_execute.pop(set_called)
286 ip._post_execute.pop(set_called)
298
287
299 def test_silent_noadvance(self):
288 def test_silent_noadvance(self):
300 """run_cell(silent=True) doesn't advance execution_count"""
289 """run_cell(silent=True) doesn't advance execution_count"""
301 ec = ip.execution_count
290 ec = ip.execution_count
302 # silent should force store_history=False
291 # silent should force store_history=False
303 ip.run_cell("1", store_history=True, silent=True)
292 ip.run_cell("1", store_history=True, silent=True)
304
293
305 self.assertEqual(ec, ip.execution_count)
294 self.assertEqual(ec, ip.execution_count)
306 # double-check that non-silent exec did what we expected
295 # double-check that non-silent exec did what we expected
307 # silent to avoid
296 # silent to avoid
308 ip.run_cell("1", store_history=True)
297 ip.run_cell("1", store_history=True)
309 self.assertEqual(ec+1, ip.execution_count)
298 self.assertEqual(ec+1, ip.execution_count)
310
299
311 def test_silent_nodisplayhook(self):
300 def test_silent_nodisplayhook(self):
312 """run_cell(silent=True) doesn't trigger displayhook"""
301 """run_cell(silent=True) doesn't trigger displayhook"""
313 d = dict(called=False)
302 d = dict(called=False)
314
303
315 trap = ip.display_trap
304 trap = ip.display_trap
316 save_hook = trap.hook
305 save_hook = trap.hook
317
306
318 def failing_hook(*args, **kwargs):
307 def failing_hook(*args, **kwargs):
319 d['called'] = True
308 d['called'] = True
320
309
321 try:
310 try:
322 trap.hook = failing_hook
311 trap.hook = failing_hook
323 ip.run_cell("1", silent=True)
312 ip.run_cell("1", silent=True)
324 self.assertFalse(d['called'])
313 self.assertFalse(d['called'])
325 # double-check that non-silent exec did what we expected
314 # double-check that non-silent exec did what we expected
326 # silent to avoid
315 # silent to avoid
327 ip.run_cell("1")
316 ip.run_cell("1")
328 self.assertTrue(d['called'])
317 self.assertTrue(d['called'])
329 finally:
318 finally:
330 trap.hook = save_hook
319 trap.hook = save_hook
331
320
332 @skipif(sys.version_info[0] >= 3, "softspace removed in py3")
321 @skipif(sys.version_info[0] >= 3, "softspace removed in py3")
333 def test_print_softspace(self):
322 def test_print_softspace(self):
334 """Verify that softspace is handled correctly when executing multiple
323 """Verify that softspace is handled correctly when executing multiple
335 statements.
324 statements.
336
325
337 In [1]: print 1; print 2
326 In [1]: print 1; print 2
338 1
327 1
339 2
328 2
340
329
341 In [2]: print 1,; print 2
330 In [2]: print 1,; print 2
342 1 2
331 1 2
343 """
332 """
344
333
345 def test_ofind_line_magic(self):
334 def test_ofind_line_magic(self):
346 from IPython.core.magic import register_line_magic
335 from IPython.core.magic import register_line_magic
347
336
348 @register_line_magic
337 @register_line_magic
349 def lmagic(line):
338 def lmagic(line):
350 "A line magic"
339 "A line magic"
351
340
352 # Get info on line magic
341 # Get info on line magic
353 lfind = ip._ofind('lmagic')
342 lfind = ip._ofind('lmagic')
354 info = dict(found=True, isalias=False, ismagic=True,
343 info = dict(found=True, isalias=False, ismagic=True,
355 namespace = 'IPython internal', obj= lmagic.__wrapped__,
344 namespace = 'IPython internal', obj= lmagic.__wrapped__,
356 parent = None)
345 parent = None)
357 nt.assert_equal(lfind, info)
346 nt.assert_equal(lfind, info)
358
347
359 def test_ofind_cell_magic(self):
348 def test_ofind_cell_magic(self):
360 from IPython.core.magic import register_cell_magic
349 from IPython.core.magic import register_cell_magic
361
350
362 @register_cell_magic
351 @register_cell_magic
363 def cmagic(line, cell):
352 def cmagic(line, cell):
364 "A cell magic"
353 "A cell magic"
365
354
366 # Get info on cell magic
355 # Get info on cell magic
367 find = ip._ofind('cmagic')
356 find = ip._ofind('cmagic')
368 info = dict(found=True, isalias=False, ismagic=True,
357 info = dict(found=True, isalias=False, ismagic=True,
369 namespace = 'IPython internal', obj= cmagic.__wrapped__,
358 namespace = 'IPython internal', obj= cmagic.__wrapped__,
370 parent = None)
359 parent = None)
371 nt.assert_equal(find, info)
360 nt.assert_equal(find, info)
372
361
373 def test_custom_exception(self):
362 def test_custom_exception(self):
374 called = []
363 called = []
375 def my_handler(shell, etype, value, tb, tb_offset=None):
364 def my_handler(shell, etype, value, tb, tb_offset=None):
376 called.append(etype)
365 called.append(etype)
377 shell.showtraceback((etype, value, tb), tb_offset=tb_offset)
366 shell.showtraceback((etype, value, tb), tb_offset=tb_offset)
378
367
379 ip.set_custom_exc((ValueError,), my_handler)
368 ip.set_custom_exc((ValueError,), my_handler)
380 try:
369 try:
381 ip.run_cell("raise ValueError('test')")
370 ip.run_cell("raise ValueError('test')")
382 # Check that this was called, and only once.
371 # Check that this was called, and only once.
383 self.assertEqual(called, [ValueError])
372 self.assertEqual(called, [ValueError])
384 finally:
373 finally:
385 # Reset the custom exception hook
374 # Reset the custom exception hook
386 ip.set_custom_exc((), None)
375 ip.set_custom_exc((), None)
387
376
388 @skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
377 @skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
389 def test_future_environment(self):
378 def test_future_environment(self):
390 "Can we run code with & without the shell's __future__ imports?"
379 "Can we run code with & without the shell's __future__ imports?"
391 ip.run_cell("from __future__ import division")
380 ip.run_cell("from __future__ import division")
392 ip.run_cell("a = 1/2", shell_futures=True)
381 ip.run_cell("a = 1/2", shell_futures=True)
393 self.assertEqual(ip.user_ns['a'], 0.5)
382 self.assertEqual(ip.user_ns['a'], 0.5)
394 ip.run_cell("b = 1/2", shell_futures=False)
383 ip.run_cell("b = 1/2", shell_futures=False)
395 self.assertEqual(ip.user_ns['b'], 0)
384 self.assertEqual(ip.user_ns['b'], 0)
396
385
397 ip.compile.reset_compiler_flags()
386 ip.compile.reset_compiler_flags()
398 # This shouldn't leak to the shell's compiler
387 # This shouldn't leak to the shell's compiler
399 ip.run_cell("from __future__ import division \nc=1/2", shell_futures=False)
388 ip.run_cell("from __future__ import division \nc=1/2", shell_futures=False)
400 self.assertEqual(ip.user_ns['c'], 0.5)
389 self.assertEqual(ip.user_ns['c'], 0.5)
401 ip.run_cell("d = 1/2", shell_futures=True)
390 ip.run_cell("d = 1/2", shell_futures=True)
402 self.assertEqual(ip.user_ns['d'], 0)
391 self.assertEqual(ip.user_ns['d'], 0)
403
392
404
393
405 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
394 class TestSafeExecfileNonAsciiPath(unittest.TestCase):
406
395
407 @onlyif_unicode_paths
396 @onlyif_unicode_paths
408 def setUp(self):
397 def setUp(self):
409 self.BASETESTDIR = tempfile.mkdtemp()
398 self.BASETESTDIR = tempfile.mkdtemp()
410 self.TESTDIR = join(self.BASETESTDIR, u"Γ₯Àâ")
399 self.TESTDIR = join(self.BASETESTDIR, u"Γ₯Àâ")
411 os.mkdir(self.TESTDIR)
400 os.mkdir(self.TESTDIR)
412 with open(join(self.TESTDIR, u"Γ₯Àâtestscript.py"), "w") as sfile:
401 with open(join(self.TESTDIR, u"Γ₯Àâtestscript.py"), "w") as sfile:
413 sfile.write("pass\n")
402 sfile.write("pass\n")
414 self.oldpath = os.getcwdu()
403 self.oldpath = os.getcwdu()
415 os.chdir(self.TESTDIR)
404 os.chdir(self.TESTDIR)
416 self.fname = u"Γ₯Àâtestscript.py"
405 self.fname = u"Γ₯Àâtestscript.py"
417
406
418 def tearDown(self):
407 def tearDown(self):
419 os.chdir(self.oldpath)
408 os.chdir(self.oldpath)
420 shutil.rmtree(self.BASETESTDIR)
409 shutil.rmtree(self.BASETESTDIR)
421
410
422 @onlyif_unicode_paths
411 @onlyif_unicode_paths
423 def test_1(self):
412 def test_1(self):
424 """Test safe_execfile with non-ascii path
413 """Test safe_execfile with non-ascii path
425 """
414 """
426 ip.safe_execfile(self.fname, {}, raise_exceptions=True)
415 ip.safe_execfile(self.fname, {}, raise_exceptions=True)
427
416
428
417
429 class TestSystemRaw(unittest.TestCase):
418 class TestSystemRaw(unittest.TestCase):
430 @onlyif_unicode_paths
419 @onlyif_unicode_paths
431 def test_1(self):
420 def test_1(self):
432 """Test system_raw with non-ascii cmd
421 """Test system_raw with non-ascii cmd
433 """
422 """
434 cmd = ur'''python -c "'Γ₯Àâ'" '''
423 cmd = ur'''python -c "'Γ₯Àâ'" '''
435 ip.system_raw(cmd)
424 ip.system_raw(cmd)
436
425
437 def test_exit_code(self):
426 def test_exit_code(self):
438 """Test that the exit code is parsed correctly."""
427 """Test that the exit code is parsed correctly."""
439 ip.system_raw('exit 1')
428 ip.system_raw('exit 1')
440 self.assertEqual(ip.user_ns['_exit_code'], 1)
429 self.assertEqual(ip.user_ns['_exit_code'], 1)
441
430
442 class TestModules(unittest.TestCase, tt.TempFileMixin):
431 class TestModules(unittest.TestCase, tt.TempFileMixin):
443 def test_extraneous_loads(self):
432 def test_extraneous_loads(self):
444 """Test we're not loading modules on startup that we shouldn't.
433 """Test we're not loading modules on startup that we shouldn't.
445 """
434 """
446 self.mktmp("import sys\n"
435 self.mktmp("import sys\n"
447 "print('numpy' in sys.modules)\n"
436 "print('numpy' in sys.modules)\n"
448 "print('IPython.parallel' in sys.modules)\n"
437 "print('IPython.parallel' in sys.modules)\n"
449 "print('IPython.kernel.zmq' in sys.modules)\n"
438 "print('IPython.kernel.zmq' in sys.modules)\n"
450 )
439 )
451 out = "False\nFalse\nFalse\n"
440 out = "False\nFalse\nFalse\n"
452 tt.ipexec_validate(self.fname, out)
441 tt.ipexec_validate(self.fname, out)
453
442
454 class Negator(ast.NodeTransformer):
443 class Negator(ast.NodeTransformer):
455 """Negates all number literals in an AST."""
444 """Negates all number literals in an AST."""
456 def visit_Num(self, node):
445 def visit_Num(self, node):
457 node.n = -node.n
446 node.n = -node.n
458 return node
447 return node
459
448
460 class TestAstTransform(unittest.TestCase):
449 class TestAstTransform(unittest.TestCase):
461 def setUp(self):
450 def setUp(self):
462 self.negator = Negator()
451 self.negator = Negator()
463 ip.ast_transformers.append(self.negator)
452 ip.ast_transformers.append(self.negator)
464
453
465 def tearDown(self):
454 def tearDown(self):
466 ip.ast_transformers.remove(self.negator)
455 ip.ast_transformers.remove(self.negator)
467
456
468 def test_run_cell(self):
457 def test_run_cell(self):
469 with tt.AssertPrints('-34'):
458 with tt.AssertPrints('-34'):
470 ip.run_cell('print (12 + 22)')
459 ip.run_cell('print (12 + 22)')
471
460
472 # A named reference to a number shouldn't be transformed.
461 # A named reference to a number shouldn't be transformed.
473 ip.user_ns['n'] = 55
462 ip.user_ns['n'] = 55
474 with tt.AssertNotPrints('-55'):
463 with tt.AssertNotPrints('-55'):
475 ip.run_cell('print (n)')
464 ip.run_cell('print (n)')
476
465
477 def test_timeit(self):
466 def test_timeit(self):
478 called = set()
467 called = set()
479 def f(x):
468 def f(x):
480 called.add(x)
469 called.add(x)
481 ip.push({'f':f})
470 ip.push({'f':f})
482
471
483 with tt.AssertPrints("best of "):
472 with tt.AssertPrints("best of "):
484 ip.run_line_magic("timeit", "-n1 f(1)")
473 ip.run_line_magic("timeit", "-n1 f(1)")
485 self.assertEqual(called, set([-1]))
474 self.assertEqual(called, set([-1]))
486 called.clear()
475 called.clear()
487
476
488 with tt.AssertPrints("best of "):
477 with tt.AssertPrints("best of "):
489 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
478 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
490 self.assertEqual(called, set([-2, -3]))
479 self.assertEqual(called, set([-2, -3]))
491
480
492 def test_time(self):
481 def test_time(self):
493 called = []
482 called = []
494 def f(x):
483 def f(x):
495 called.append(x)
484 called.append(x)
496 ip.push({'f':f})
485 ip.push({'f':f})
497
486
498 # Test with an expression
487 # Test with an expression
499 with tt.AssertPrints("Wall time: "):
488 with tt.AssertPrints("Wall time: "):
500 ip.run_line_magic("time", "f(5+9)")
489 ip.run_line_magic("time", "f(5+9)")
501 self.assertEqual(called, [-14])
490 self.assertEqual(called, [-14])
502 called[:] = []
491 called[:] = []
503
492
504 # Test with a statement (different code path)
493 # Test with a statement (different code path)
505 with tt.AssertPrints("Wall time: "):
494 with tt.AssertPrints("Wall time: "):
506 ip.run_line_magic("time", "a = f(-3 + -2)")
495 ip.run_line_magic("time", "a = f(-3 + -2)")
507 self.assertEqual(called, [5])
496 self.assertEqual(called, [5])
508
497
509 def test_macro(self):
498 def test_macro(self):
510 ip.push({'a':10})
499 ip.push({'a':10})
511 # The AST transformation makes this do a+=-1
500 # The AST transformation makes this do a+=-1
512 ip.define_macro("amacro", "a+=1\nprint(a)")
501 ip.define_macro("amacro", "a+=1\nprint(a)")
513
502
514 with tt.AssertPrints("9"):
503 with tt.AssertPrints("9"):
515 ip.run_cell("amacro")
504 ip.run_cell("amacro")
516 with tt.AssertPrints("8"):
505 with tt.AssertPrints("8"):
517 ip.run_cell("amacro")
506 ip.run_cell("amacro")
518
507
519 class IntegerWrapper(ast.NodeTransformer):
508 class IntegerWrapper(ast.NodeTransformer):
520 """Wraps all integers in a call to Integer()"""
509 """Wraps all integers in a call to Integer()"""
521 def visit_Num(self, node):
510 def visit_Num(self, node):
522 if isinstance(node.n, int):
511 if isinstance(node.n, int):
523 return ast.Call(func=ast.Name(id='Integer', ctx=ast.Load()),
512 return ast.Call(func=ast.Name(id='Integer', ctx=ast.Load()),
524 args=[node], keywords=[])
513 args=[node], keywords=[])
525 return node
514 return node
526
515
527 class TestAstTransform2(unittest.TestCase):
516 class TestAstTransform2(unittest.TestCase):
528 def setUp(self):
517 def setUp(self):
529 self.intwrapper = IntegerWrapper()
518 self.intwrapper = IntegerWrapper()
530 ip.ast_transformers.append(self.intwrapper)
519 ip.ast_transformers.append(self.intwrapper)
531
520
532 self.calls = []
521 self.calls = []
533 def Integer(*args):
522 def Integer(*args):
534 self.calls.append(args)
523 self.calls.append(args)
535 return args
524 return args
536 ip.push({"Integer": Integer})
525 ip.push({"Integer": Integer})
537
526
538 def tearDown(self):
527 def tearDown(self):
539 ip.ast_transformers.remove(self.intwrapper)
528 ip.ast_transformers.remove(self.intwrapper)
540 del ip.user_ns['Integer']
529 del ip.user_ns['Integer']
541
530
542 def test_run_cell(self):
531 def test_run_cell(self):
543 ip.run_cell("n = 2")
532 ip.run_cell("n = 2")
544 self.assertEqual(self.calls, [(2,)])
533 self.assertEqual(self.calls, [(2,)])
545
534
546 # This shouldn't throw an error
535 # This shouldn't throw an error
547 ip.run_cell("o = 2.0")
536 ip.run_cell("o = 2.0")
548 self.assertEqual(ip.user_ns['o'], 2.0)
537 self.assertEqual(ip.user_ns['o'], 2.0)
549
538
550 def test_timeit(self):
539 def test_timeit(self):
551 called = set()
540 called = set()
552 def f(x):
541 def f(x):
553 called.add(x)
542 called.add(x)
554 ip.push({'f':f})
543 ip.push({'f':f})
555
544
556 with tt.AssertPrints("best of "):
545 with tt.AssertPrints("best of "):
557 ip.run_line_magic("timeit", "-n1 f(1)")
546 ip.run_line_magic("timeit", "-n1 f(1)")
558 self.assertEqual(called, set([(1,)]))
547 self.assertEqual(called, set([(1,)]))
559 called.clear()
548 called.clear()
560
549
561 with tt.AssertPrints("best of "):
550 with tt.AssertPrints("best of "):
562 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
551 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
563 self.assertEqual(called, set([(2,), (3,)]))
552 self.assertEqual(called, set([(2,), (3,)]))
564
553
565 class ErrorTransformer(ast.NodeTransformer):
554 class ErrorTransformer(ast.NodeTransformer):
566 """Throws an error when it sees a number."""
555 """Throws an error when it sees a number."""
567 def visit_Num(self):
556 def visit_Num(self):
568 raise ValueError("test")
557 raise ValueError("test")
569
558
570 class TestAstTransformError(unittest.TestCase):
559 class TestAstTransformError(unittest.TestCase):
571 def test_unregistering(self):
560 def test_unregistering(self):
572 err_transformer = ErrorTransformer()
561 err_transformer = ErrorTransformer()
573 ip.ast_transformers.append(err_transformer)
562 ip.ast_transformers.append(err_transformer)
574
563
575 with tt.AssertPrints("unregister", channel='stderr'):
564 with tt.AssertPrints("unregister", channel='stderr'):
576 ip.run_cell("1 + 2")
565 ip.run_cell("1 + 2")
577
566
578 # This should have been removed.
567 # This should have been removed.
579 nt.assert_not_in(err_transformer, ip.ast_transformers)
568 nt.assert_not_in(err_transformer, ip.ast_transformers)
580
569
581 def test__IPYTHON__():
570 def test__IPYTHON__():
582 # This shouldn't raise a NameError, that's all
571 # This shouldn't raise a NameError, that's all
583 __IPYTHON__
572 __IPYTHON__
584
573
585
574
586 class DummyRepr(object):
575 class DummyRepr(object):
587 def __repr__(self):
576 def __repr__(self):
588 return "DummyRepr"
577 return "DummyRepr"
589
578
590 def _repr_html_(self):
579 def _repr_html_(self):
591 return "<b>dummy</b>"
580 return "<b>dummy</b>"
592
581
593 def _repr_javascript_(self):
582 def _repr_javascript_(self):
594 return "console.log('hi');", {'key': 'value'}
583 return "console.log('hi');", {'key': 'value'}
595
584
596
585
597 def test_user_variables():
586 def test_user_variables():
598 # enable all formatters
587 # enable all formatters
599 ip.display_formatter.active_types = ip.display_formatter.format_types
588 ip.display_formatter.active_types = ip.display_formatter.format_types
600
589
601 ip.user_ns['dummy'] = d = DummyRepr()
590 ip.user_ns['dummy'] = d = DummyRepr()
602 keys = set(['dummy', 'doesnotexist'])
591 keys = set(['dummy', 'doesnotexist'])
603 r = ip.user_variables(keys)
592 r = ip.user_variables(keys)
604
593
605 nt.assert_equal(keys, set(r.keys()))
594 nt.assert_equal(keys, set(r.keys()))
606 dummy = r['dummy']
595 dummy = r['dummy']
607 nt.assert_equal(set(['status', 'data', 'metadata']), set(dummy.keys()))
596 nt.assert_equal(set(['status', 'data', 'metadata']), set(dummy.keys()))
608 nt.assert_equal(dummy['status'], 'ok')
597 nt.assert_equal(dummy['status'], 'ok')
609 data = dummy['data']
598 data = dummy['data']
610 metadata = dummy['metadata']
599 metadata = dummy['metadata']
611 nt.assert_equal(data.get('text/html'), d._repr_html_())
600 nt.assert_equal(data.get('text/html'), d._repr_html_())
612 js, jsmd = d._repr_javascript_()
601 js, jsmd = d._repr_javascript_()
613 nt.assert_equal(data.get('application/javascript'), js)
602 nt.assert_equal(data.get('application/javascript'), js)
614 nt.assert_equal(metadata.get('application/javascript'), jsmd)
603 nt.assert_equal(metadata.get('application/javascript'), jsmd)
615
604
616 dne = r['doesnotexist']
605 dne = r['doesnotexist']
617 nt.assert_equal(dne['status'], 'error')
606 nt.assert_equal(dne['status'], 'error')
618 nt.assert_equal(dne['ename'], 'KeyError')
607 nt.assert_equal(dne['ename'], 'KeyError')
619
608
620 # back to text only
609 # back to text only
621 ip.display_formatter.active_types = ['text/plain']
610 ip.display_formatter.active_types = ['text/plain']
622
611
623 def test_user_expression():
612 def test_user_expression():
624 # enable all formatters
613 # enable all formatters
625 ip.display_formatter.active_types = ip.display_formatter.format_types
614 ip.display_formatter.active_types = ip.display_formatter.format_types
626 query = {
615 query = {
627 'a' : '1 + 2',
616 'a' : '1 + 2',
628 'b' : '1/0',
617 'b' : '1/0',
629 }
618 }
630 r = ip.user_expressions(query)
619 r = ip.user_expressions(query)
631 import pprint
620 import pprint
632 pprint.pprint(r)
621 pprint.pprint(r)
633 nt.assert_equal(r.keys(), query.keys())
622 nt.assert_equal(r.keys(), query.keys())
634 a = r['a']
623 a = r['a']
635 nt.assert_equal(set(['status', 'data', 'metadata']), set(a.keys()))
624 nt.assert_equal(set(['status', 'data', 'metadata']), set(a.keys()))
636 nt.assert_equal(a['status'], 'ok')
625 nt.assert_equal(a['status'], 'ok')
637 data = a['data']
626 data = a['data']
638 metadata = a['metadata']
627 metadata = a['metadata']
639 nt.assert_equal(data.get('text/plain'), '3')
628 nt.assert_equal(data.get('text/plain'), '3')
640
629
641 b = r['b']
630 b = r['b']
642 nt.assert_equal(b['status'], 'error')
631 nt.assert_equal(b['status'], 'error')
643 nt.assert_equal(b['ename'], 'ZeroDivisionError')
632 nt.assert_equal(b['ename'], 'ZeroDivisionError')
644
633
645 # back to text only
634 # back to text only
646 ip.display_formatter.active_types = ['text/plain']
635 ip.display_formatter.active_types = ['text/plain']
647
636
648
637
649
638
650
639
651
640
652
641
@@ -1,895 +1,895 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for various magic functions.
2 """Tests for various magic functions.
3
3
4 Needs to be run by nose (to make ipython session available).
4 Needs to be run by nose (to make ipython session available).
5 """
5 """
6 from __future__ import absolute_import
6 from __future__ import absolute_import
7
7
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9 # Imports
9 # Imports
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 import io
12 import io
13 import os
13 import os
14 import sys
14 import sys
15 from StringIO import StringIO
15 from StringIO import StringIO
16 from unittest import TestCase
16 from unittest import TestCase
17
17
18 try:
18 try:
19 from importlib import invalidate_caches # Required from Python 3.3
19 from importlib import invalidate_caches # Required from Python 3.3
20 except ImportError:
20 except ImportError:
21 def invalidate_caches():
21 def invalidate_caches():
22 pass
22 pass
23
23
24 import nose.tools as nt
24 import nose.tools as nt
25
25
26 from IPython.core import magic
26 from IPython.core import magic
27 from IPython.core.magic import (Magics, magics_class, line_magic,
27 from IPython.core.magic import (Magics, magics_class, line_magic,
28 cell_magic, line_cell_magic,
28 cell_magic, line_cell_magic,
29 register_line_magic, register_cell_magic,
29 register_line_magic, register_cell_magic,
30 register_line_cell_magic)
30 register_line_cell_magic)
31 from IPython.core.magics import execution, script, code
31 from IPython.core.magics import execution, script, code
32 from IPython.nbformat.v3.tests.nbexamples import nb0
32 from IPython.nbformat.v3.tests.nbexamples import nb0
33 from IPython.nbformat import current
33 from IPython.nbformat import current
34 from IPython.testing import decorators as dec
34 from IPython.testing import decorators as dec
35 from IPython.testing import tools as tt
35 from IPython.testing import tools as tt
36 from IPython.utils import py3compat
36 from IPython.utils import py3compat
37 from IPython.utils.io import capture_output
37 from IPython.utils.io import capture_output
38 from IPython.utils.tempdir import TemporaryDirectory
38 from IPython.utils.tempdir import TemporaryDirectory
39 from IPython.utils.process import find_cmd
39 from IPython.utils.process import find_cmd
40
40
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42 # Test functions begin
42 # Test functions begin
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44
44
45 @magic.magics_class
45 @magic.magics_class
46 class DummyMagics(magic.Magics): pass
46 class DummyMagics(magic.Magics): pass
47
47
48 def test_rehashx():
48 def test_rehashx():
49 # clear up everything
49 # clear up everything
50 _ip = get_ipython()
50 _ip = get_ipython()
51 _ip.alias_manager.alias_table.clear()
51 _ip.alias_manager.clear_aliases()
52 del _ip.db['syscmdlist']
52 del _ip.db['syscmdlist']
53
53
54 _ip.magic('rehashx')
54 _ip.magic('rehashx')
55 # Practically ALL ipython development systems will have more than 10 aliases
55 # Practically ALL ipython development systems will have more than 10 aliases
56
56
57 nt.assert_true(len(_ip.alias_manager.alias_table) > 10)
57 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
58 for key, val in _ip.alias_manager.alias_table.iteritems():
58 for name, cmd in _ip.alias_manager.aliases:
59 # we must strip dots from alias names
59 # we must strip dots from alias names
60 nt.assert_not_in('.', key)
60 nt.assert_not_in('.', name)
61
61
62 # rehashx must fill up syscmdlist
62 # rehashx must fill up syscmdlist
63 scoms = _ip.db['syscmdlist']
63 scoms = _ip.db['syscmdlist']
64 nt.assert_true(len(scoms) > 10)
64 nt.assert_true(len(scoms) > 10)
65
65
66
66
67 def test_magic_parse_options():
67 def test_magic_parse_options():
68 """Test that we don't mangle paths when parsing magic options."""
68 """Test that we don't mangle paths when parsing magic options."""
69 ip = get_ipython()
69 ip = get_ipython()
70 path = 'c:\\x'
70 path = 'c:\\x'
71 m = DummyMagics(ip)
71 m = DummyMagics(ip)
72 opts = m.parse_options('-f %s' % path,'f:')[0]
72 opts = m.parse_options('-f %s' % path,'f:')[0]
73 # argv splitting is os-dependent
73 # argv splitting is os-dependent
74 if os.name == 'posix':
74 if os.name == 'posix':
75 expected = 'c:x'
75 expected = 'c:x'
76 else:
76 else:
77 expected = path
77 expected = path
78 nt.assert_equal(opts['f'], expected)
78 nt.assert_equal(opts['f'], expected)
79
79
80 def test_magic_parse_long_options():
80 def test_magic_parse_long_options():
81 """Magic.parse_options can handle --foo=bar long options"""
81 """Magic.parse_options can handle --foo=bar long options"""
82 ip = get_ipython()
82 ip = get_ipython()
83 m = DummyMagics(ip)
83 m = DummyMagics(ip)
84 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
84 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
85 nt.assert_in('foo', opts)
85 nt.assert_in('foo', opts)
86 nt.assert_in('bar', opts)
86 nt.assert_in('bar', opts)
87 nt.assert_equal(opts['bar'], "bubble")
87 nt.assert_equal(opts['bar'], "bubble")
88
88
89
89
90 @dec.skip_without('sqlite3')
90 @dec.skip_without('sqlite3')
91 def doctest_hist_f():
91 def doctest_hist_f():
92 """Test %hist -f with temporary filename.
92 """Test %hist -f with temporary filename.
93
93
94 In [9]: import tempfile
94 In [9]: import tempfile
95
95
96 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
96 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
97
97
98 In [11]: %hist -nl -f $tfile 3
98 In [11]: %hist -nl -f $tfile 3
99
99
100 In [13]: import os; os.unlink(tfile)
100 In [13]: import os; os.unlink(tfile)
101 """
101 """
102
102
103
103
104 @dec.skip_without('sqlite3')
104 @dec.skip_without('sqlite3')
105 def doctest_hist_r():
105 def doctest_hist_r():
106 """Test %hist -r
106 """Test %hist -r
107
107
108 XXX - This test is not recording the output correctly. For some reason, in
108 XXX - This test is not recording the output correctly. For some reason, in
109 testing mode the raw history isn't getting populated. No idea why.
109 testing mode the raw history isn't getting populated. No idea why.
110 Disabling the output checking for now, though at least we do run it.
110 Disabling the output checking for now, though at least we do run it.
111
111
112 In [1]: 'hist' in _ip.lsmagic()
112 In [1]: 'hist' in _ip.lsmagic()
113 Out[1]: True
113 Out[1]: True
114
114
115 In [2]: x=1
115 In [2]: x=1
116
116
117 In [3]: %hist -rl 2
117 In [3]: %hist -rl 2
118 x=1 # random
118 x=1 # random
119 %hist -r 2
119 %hist -r 2
120 """
120 """
121
121
122
122
123 @dec.skip_without('sqlite3')
123 @dec.skip_without('sqlite3')
124 def doctest_hist_op():
124 def doctest_hist_op():
125 """Test %hist -op
125 """Test %hist -op
126
126
127 In [1]: class b(float):
127 In [1]: class b(float):
128 ...: pass
128 ...: pass
129 ...:
129 ...:
130
130
131 In [2]: class s(object):
131 In [2]: class s(object):
132 ...: def __str__(self):
132 ...: def __str__(self):
133 ...: return 's'
133 ...: return 's'
134 ...:
134 ...:
135
135
136 In [3]:
136 In [3]:
137
137
138 In [4]: class r(b):
138 In [4]: class r(b):
139 ...: def __repr__(self):
139 ...: def __repr__(self):
140 ...: return 'r'
140 ...: return 'r'
141 ...:
141 ...:
142
142
143 In [5]: class sr(s,r): pass
143 In [5]: class sr(s,r): pass
144 ...:
144 ...:
145
145
146 In [6]:
146 In [6]:
147
147
148 In [7]: bb=b()
148 In [7]: bb=b()
149
149
150 In [8]: ss=s()
150 In [8]: ss=s()
151
151
152 In [9]: rr=r()
152 In [9]: rr=r()
153
153
154 In [10]: ssrr=sr()
154 In [10]: ssrr=sr()
155
155
156 In [11]: 4.5
156 In [11]: 4.5
157 Out[11]: 4.5
157 Out[11]: 4.5
158
158
159 In [12]: str(ss)
159 In [12]: str(ss)
160 Out[12]: 's'
160 Out[12]: 's'
161
161
162 In [13]:
162 In [13]:
163
163
164 In [14]: %hist -op
164 In [14]: %hist -op
165 >>> class b:
165 >>> class b:
166 ... pass
166 ... pass
167 ...
167 ...
168 >>> class s(b):
168 >>> class s(b):
169 ... def __str__(self):
169 ... def __str__(self):
170 ... return 's'
170 ... return 's'
171 ...
171 ...
172 >>>
172 >>>
173 >>> class r(b):
173 >>> class r(b):
174 ... def __repr__(self):
174 ... def __repr__(self):
175 ... return 'r'
175 ... return 'r'
176 ...
176 ...
177 >>> class sr(s,r): pass
177 >>> class sr(s,r): pass
178 >>>
178 >>>
179 >>> bb=b()
179 >>> bb=b()
180 >>> ss=s()
180 >>> ss=s()
181 >>> rr=r()
181 >>> rr=r()
182 >>> ssrr=sr()
182 >>> ssrr=sr()
183 >>> 4.5
183 >>> 4.5
184 4.5
184 4.5
185 >>> str(ss)
185 >>> str(ss)
186 's'
186 's'
187 >>>
187 >>>
188 """
188 """
189
189
190
190
191 @dec.skip_without('sqlite3')
191 @dec.skip_without('sqlite3')
192 def test_macro():
192 def test_macro():
193 ip = get_ipython()
193 ip = get_ipython()
194 ip.history_manager.reset() # Clear any existing history.
194 ip.history_manager.reset() # Clear any existing history.
195 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
195 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
196 for i, cmd in enumerate(cmds, start=1):
196 for i, cmd in enumerate(cmds, start=1):
197 ip.history_manager.store_inputs(i, cmd)
197 ip.history_manager.store_inputs(i, cmd)
198 ip.magic("macro test 1-3")
198 ip.magic("macro test 1-3")
199 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
199 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
200
200
201 # List macros
201 # List macros
202 nt.assert_in("test", ip.magic("macro"))
202 nt.assert_in("test", ip.magic("macro"))
203
203
204
204
205 @dec.skip_without('sqlite3')
205 @dec.skip_without('sqlite3')
206 def test_macro_run():
206 def test_macro_run():
207 """Test that we can run a multi-line macro successfully."""
207 """Test that we can run a multi-line macro successfully."""
208 ip = get_ipython()
208 ip = get_ipython()
209 ip.history_manager.reset()
209 ip.history_manager.reset()
210 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
210 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
211 "%macro test 2-3"]
211 "%macro test 2-3"]
212 for cmd in cmds:
212 for cmd in cmds:
213 ip.run_cell(cmd, store_history=True)
213 ip.run_cell(cmd, store_history=True)
214 nt.assert_equal(ip.user_ns["test"].value,
214 nt.assert_equal(ip.user_ns["test"].value,
215 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
215 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
216 with tt.AssertPrints("12"):
216 with tt.AssertPrints("12"):
217 ip.run_cell("test")
217 ip.run_cell("test")
218 with tt.AssertPrints("13"):
218 with tt.AssertPrints("13"):
219 ip.run_cell("test")
219 ip.run_cell("test")
220
220
221
221
222 def test_magic_magic():
222 def test_magic_magic():
223 """Test %magic"""
223 """Test %magic"""
224 ip = get_ipython()
224 ip = get_ipython()
225 with capture_output() as captured:
225 with capture_output() as captured:
226 ip.magic("magic")
226 ip.magic("magic")
227
227
228 stdout = captured.stdout
228 stdout = captured.stdout
229 nt.assert_in('%magic', stdout)
229 nt.assert_in('%magic', stdout)
230 nt.assert_in('IPython', stdout)
230 nt.assert_in('IPython', stdout)
231 nt.assert_in('Available', stdout)
231 nt.assert_in('Available', stdout)
232
232
233
233
234 @dec.skipif_not_numpy
234 @dec.skipif_not_numpy
235 def test_numpy_reset_array_undec():
235 def test_numpy_reset_array_undec():
236 "Test '%reset array' functionality"
236 "Test '%reset array' functionality"
237 _ip.ex('import numpy as np')
237 _ip.ex('import numpy as np')
238 _ip.ex('a = np.empty(2)')
238 _ip.ex('a = np.empty(2)')
239 nt.assert_in('a', _ip.user_ns)
239 nt.assert_in('a', _ip.user_ns)
240 _ip.magic('reset -f array')
240 _ip.magic('reset -f array')
241 nt.assert_not_in('a', _ip.user_ns)
241 nt.assert_not_in('a', _ip.user_ns)
242
242
243 def test_reset_out():
243 def test_reset_out():
244 "Test '%reset out' magic"
244 "Test '%reset out' magic"
245 _ip.run_cell("parrot = 'dead'", store_history=True)
245 _ip.run_cell("parrot = 'dead'", store_history=True)
246 # test '%reset -f out', make an Out prompt
246 # test '%reset -f out', make an Out prompt
247 _ip.run_cell("parrot", store_history=True)
247 _ip.run_cell("parrot", store_history=True)
248 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
248 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
249 _ip.magic('reset -f out')
249 _ip.magic('reset -f out')
250 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
250 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
251 nt.assert_equal(len(_ip.user_ns['Out']), 0)
251 nt.assert_equal(len(_ip.user_ns['Out']), 0)
252
252
253 def test_reset_in():
253 def test_reset_in():
254 "Test '%reset in' magic"
254 "Test '%reset in' magic"
255 # test '%reset -f in'
255 # test '%reset -f in'
256 _ip.run_cell("parrot", store_history=True)
256 _ip.run_cell("parrot", store_history=True)
257 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
257 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
258 _ip.magic('%reset -f in')
258 _ip.magic('%reset -f in')
259 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
259 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
260 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
260 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
261
261
262 def test_reset_dhist():
262 def test_reset_dhist():
263 "Test '%reset dhist' magic"
263 "Test '%reset dhist' magic"
264 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
264 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
265 _ip.magic('cd ' + os.path.dirname(nt.__file__))
265 _ip.magic('cd ' + os.path.dirname(nt.__file__))
266 _ip.magic('cd -')
266 _ip.magic('cd -')
267 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
267 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
268 _ip.magic('reset -f dhist')
268 _ip.magic('reset -f dhist')
269 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
269 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
270 _ip.run_cell("_dh = [d for d in tmp]") #restore
270 _ip.run_cell("_dh = [d for d in tmp]") #restore
271
271
272 def test_reset_in_length():
272 def test_reset_in_length():
273 "Test that '%reset in' preserves In[] length"
273 "Test that '%reset in' preserves In[] length"
274 _ip.run_cell("print 'foo'")
274 _ip.run_cell("print 'foo'")
275 _ip.run_cell("reset -f in")
275 _ip.run_cell("reset -f in")
276 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
276 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
277
277
278 def test_tb_syntaxerror():
278 def test_tb_syntaxerror():
279 """test %tb after a SyntaxError"""
279 """test %tb after a SyntaxError"""
280 ip = get_ipython()
280 ip = get_ipython()
281 ip.run_cell("for")
281 ip.run_cell("for")
282
282
283 # trap and validate stdout
283 # trap and validate stdout
284 save_stdout = sys.stdout
284 save_stdout = sys.stdout
285 try:
285 try:
286 sys.stdout = StringIO()
286 sys.stdout = StringIO()
287 ip.run_cell("%tb")
287 ip.run_cell("%tb")
288 out = sys.stdout.getvalue()
288 out = sys.stdout.getvalue()
289 finally:
289 finally:
290 sys.stdout = save_stdout
290 sys.stdout = save_stdout
291 # trim output, and only check the last line
291 # trim output, and only check the last line
292 last_line = out.rstrip().splitlines()[-1].strip()
292 last_line = out.rstrip().splitlines()[-1].strip()
293 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
293 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
294
294
295
295
296 def test_time():
296 def test_time():
297 ip = get_ipython()
297 ip = get_ipython()
298
298
299 with tt.AssertPrints("Wall time: "):
299 with tt.AssertPrints("Wall time: "):
300 ip.run_cell("%time None")
300 ip.run_cell("%time None")
301
301
302 ip.run_cell("def f(kmjy):\n"
302 ip.run_cell("def f(kmjy):\n"
303 " %time print (2*kmjy)")
303 " %time print (2*kmjy)")
304
304
305 with tt.AssertPrints("Wall time: "):
305 with tt.AssertPrints("Wall time: "):
306 with tt.AssertPrints("hihi", suppress=False):
306 with tt.AssertPrints("hihi", suppress=False):
307 ip.run_cell("f('hi')")
307 ip.run_cell("f('hi')")
308
308
309
309
310 @dec.skip_win32
310 @dec.skip_win32
311 def test_time2():
311 def test_time2():
312 ip = get_ipython()
312 ip = get_ipython()
313
313
314 with tt.AssertPrints("CPU times: user "):
314 with tt.AssertPrints("CPU times: user "):
315 ip.run_cell("%time None")
315 ip.run_cell("%time None")
316
316
317 def test_time3():
317 def test_time3():
318 """Erroneous magic function calls, issue gh-3334"""
318 """Erroneous magic function calls, issue gh-3334"""
319 ip = get_ipython()
319 ip = get_ipython()
320 ip.user_ns.pop('run', None)
320 ip.user_ns.pop('run', None)
321
321
322 with tt.AssertNotPrints("not found", channel='stderr'):
322 with tt.AssertNotPrints("not found", channel='stderr'):
323 ip.run_cell("%%time\n"
323 ip.run_cell("%%time\n"
324 "run = 0\n"
324 "run = 0\n"
325 "run += 1")
325 "run += 1")
326
326
327 def test_doctest_mode():
327 def test_doctest_mode():
328 "Toggle doctest_mode twice, it should be a no-op and run without error"
328 "Toggle doctest_mode twice, it should be a no-op and run without error"
329 _ip.magic('doctest_mode')
329 _ip.magic('doctest_mode')
330 _ip.magic('doctest_mode')
330 _ip.magic('doctest_mode')
331
331
332
332
333 def test_parse_options():
333 def test_parse_options():
334 """Tests for basic options parsing in magics."""
334 """Tests for basic options parsing in magics."""
335 # These are only the most minimal of tests, more should be added later. At
335 # These are only the most minimal of tests, more should be added later. At
336 # the very least we check that basic text/unicode calls work OK.
336 # the very least we check that basic text/unicode calls work OK.
337 m = DummyMagics(_ip)
337 m = DummyMagics(_ip)
338 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
338 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
339 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
339 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
340
340
341
341
342 def test_dirops():
342 def test_dirops():
343 """Test various directory handling operations."""
343 """Test various directory handling operations."""
344 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
344 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
345 curpath = os.getcwdu
345 curpath = os.getcwdu
346 startdir = os.getcwdu()
346 startdir = os.getcwdu()
347 ipdir = os.path.realpath(_ip.ipython_dir)
347 ipdir = os.path.realpath(_ip.ipython_dir)
348 try:
348 try:
349 _ip.magic('cd "%s"' % ipdir)
349 _ip.magic('cd "%s"' % ipdir)
350 nt.assert_equal(curpath(), ipdir)
350 nt.assert_equal(curpath(), ipdir)
351 _ip.magic('cd -')
351 _ip.magic('cd -')
352 nt.assert_equal(curpath(), startdir)
352 nt.assert_equal(curpath(), startdir)
353 _ip.magic('pushd "%s"' % ipdir)
353 _ip.magic('pushd "%s"' % ipdir)
354 nt.assert_equal(curpath(), ipdir)
354 nt.assert_equal(curpath(), ipdir)
355 _ip.magic('popd')
355 _ip.magic('popd')
356 nt.assert_equal(curpath(), startdir)
356 nt.assert_equal(curpath(), startdir)
357 finally:
357 finally:
358 os.chdir(startdir)
358 os.chdir(startdir)
359
359
360
360
361 def test_xmode():
361 def test_xmode():
362 # Calling xmode three times should be a no-op
362 # Calling xmode three times should be a no-op
363 xmode = _ip.InteractiveTB.mode
363 xmode = _ip.InteractiveTB.mode
364 for i in range(3):
364 for i in range(3):
365 _ip.magic("xmode")
365 _ip.magic("xmode")
366 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
366 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
367
367
368 def test_reset_hard():
368 def test_reset_hard():
369 monitor = []
369 monitor = []
370 class A(object):
370 class A(object):
371 def __del__(self):
371 def __del__(self):
372 monitor.append(1)
372 monitor.append(1)
373 def __repr__(self):
373 def __repr__(self):
374 return "<A instance>"
374 return "<A instance>"
375
375
376 _ip.user_ns["a"] = A()
376 _ip.user_ns["a"] = A()
377 _ip.run_cell("a")
377 _ip.run_cell("a")
378
378
379 nt.assert_equal(monitor, [])
379 nt.assert_equal(monitor, [])
380 _ip.magic("reset -f")
380 _ip.magic("reset -f")
381 nt.assert_equal(monitor, [1])
381 nt.assert_equal(monitor, [1])
382
382
383 class TestXdel(tt.TempFileMixin):
383 class TestXdel(tt.TempFileMixin):
384 def test_xdel(self):
384 def test_xdel(self):
385 """Test that references from %run are cleared by xdel."""
385 """Test that references from %run are cleared by xdel."""
386 src = ("class A(object):\n"
386 src = ("class A(object):\n"
387 " monitor = []\n"
387 " monitor = []\n"
388 " def __del__(self):\n"
388 " def __del__(self):\n"
389 " self.monitor.append(1)\n"
389 " self.monitor.append(1)\n"
390 "a = A()\n")
390 "a = A()\n")
391 self.mktmp(src)
391 self.mktmp(src)
392 # %run creates some hidden references...
392 # %run creates some hidden references...
393 _ip.magic("run %s" % self.fname)
393 _ip.magic("run %s" % self.fname)
394 # ... as does the displayhook.
394 # ... as does the displayhook.
395 _ip.run_cell("a")
395 _ip.run_cell("a")
396
396
397 monitor = _ip.user_ns["A"].monitor
397 monitor = _ip.user_ns["A"].monitor
398 nt.assert_equal(monitor, [])
398 nt.assert_equal(monitor, [])
399
399
400 _ip.magic("xdel a")
400 _ip.magic("xdel a")
401
401
402 # Check that a's __del__ method has been called.
402 # Check that a's __del__ method has been called.
403 nt.assert_equal(monitor, [1])
403 nt.assert_equal(monitor, [1])
404
404
405 def doctest_who():
405 def doctest_who():
406 """doctest for %who
406 """doctest for %who
407
407
408 In [1]: %reset -f
408 In [1]: %reset -f
409
409
410 In [2]: alpha = 123
410 In [2]: alpha = 123
411
411
412 In [3]: beta = 'beta'
412 In [3]: beta = 'beta'
413
413
414 In [4]: %who int
414 In [4]: %who int
415 alpha
415 alpha
416
416
417 In [5]: %who str
417 In [5]: %who str
418 beta
418 beta
419
419
420 In [6]: %whos
420 In [6]: %whos
421 Variable Type Data/Info
421 Variable Type Data/Info
422 ----------------------------
422 ----------------------------
423 alpha int 123
423 alpha int 123
424 beta str beta
424 beta str beta
425
425
426 In [7]: %who_ls
426 In [7]: %who_ls
427 Out[7]: ['alpha', 'beta']
427 Out[7]: ['alpha', 'beta']
428 """
428 """
429
429
430 def test_whos():
430 def test_whos():
431 """Check that whos is protected against objects where repr() fails."""
431 """Check that whos is protected against objects where repr() fails."""
432 class A(object):
432 class A(object):
433 def __repr__(self):
433 def __repr__(self):
434 raise Exception()
434 raise Exception()
435 _ip.user_ns['a'] = A()
435 _ip.user_ns['a'] = A()
436 _ip.magic("whos")
436 _ip.magic("whos")
437
437
438 @py3compat.u_format
438 @py3compat.u_format
439 def doctest_precision():
439 def doctest_precision():
440 """doctest for %precision
440 """doctest for %precision
441
441
442 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
442 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
443
443
444 In [2]: %precision 5
444 In [2]: %precision 5
445 Out[2]: {u}'%.5f'
445 Out[2]: {u}'%.5f'
446
446
447 In [3]: f.float_format
447 In [3]: f.float_format
448 Out[3]: {u}'%.5f'
448 Out[3]: {u}'%.5f'
449
449
450 In [4]: %precision %e
450 In [4]: %precision %e
451 Out[4]: {u}'%e'
451 Out[4]: {u}'%e'
452
452
453 In [5]: f(3.1415927)
453 In [5]: f(3.1415927)
454 Out[5]: {u}'3.141593e+00'
454 Out[5]: {u}'3.141593e+00'
455 """
455 """
456
456
457 def test_psearch():
457 def test_psearch():
458 with tt.AssertPrints("dict.fromkeys"):
458 with tt.AssertPrints("dict.fromkeys"):
459 _ip.run_cell("dict.fr*?")
459 _ip.run_cell("dict.fr*?")
460
460
461 def test_timeit_shlex():
461 def test_timeit_shlex():
462 """test shlex issues with timeit (#1109)"""
462 """test shlex issues with timeit (#1109)"""
463 _ip.ex("def f(*a,**kw): pass")
463 _ip.ex("def f(*a,**kw): pass")
464 _ip.magic('timeit -n1 "this is a bug".count(" ")')
464 _ip.magic('timeit -n1 "this is a bug".count(" ")')
465 _ip.magic('timeit -r1 -n1 f(" ", 1)')
465 _ip.magic('timeit -r1 -n1 f(" ", 1)')
466 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
466 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
467 _ip.magic('timeit -r1 -n1 ("a " + "b")')
467 _ip.magic('timeit -r1 -n1 ("a " + "b")')
468 _ip.magic('timeit -r1 -n1 f("a " + "b")')
468 _ip.magic('timeit -r1 -n1 f("a " + "b")')
469 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
469 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
470
470
471
471
472 def test_timeit_arguments():
472 def test_timeit_arguments():
473 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
473 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
474 _ip.magic("timeit ('#')")
474 _ip.magic("timeit ('#')")
475
475
476
476
477 def test_timeit_special_syntax():
477 def test_timeit_special_syntax():
478 "Test %%timeit with IPython special syntax"
478 "Test %%timeit with IPython special syntax"
479 @register_line_magic
479 @register_line_magic
480 def lmagic(line):
480 def lmagic(line):
481 ip = get_ipython()
481 ip = get_ipython()
482 ip.user_ns['lmagic_out'] = line
482 ip.user_ns['lmagic_out'] = line
483
483
484 # line mode test
484 # line mode test
485 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
485 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
486 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
486 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
487 # cell mode test
487 # cell mode test
488 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
488 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
489 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
489 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
490
490
491 def test_timeit_return():
491 def test_timeit_return():
492 """
492 """
493 test wether timeit -o return object
493 test wether timeit -o return object
494 """
494 """
495
495
496 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
496 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
497 assert(res is not None)
497 assert(res is not None)
498
498
499 def test_timeit_quiet():
499 def test_timeit_quiet():
500 """
500 """
501 test quiet option of timeit magic
501 test quiet option of timeit magic
502 """
502 """
503 with tt.AssertNotPrints("loops"):
503 with tt.AssertNotPrints("loops"):
504 _ip.run_cell("%timeit -n1 -r1 -q 1")
504 _ip.run_cell("%timeit -n1 -r1 -q 1")
505
505
506 @dec.skipif(execution.profile is None)
506 @dec.skipif(execution.profile is None)
507 def test_prun_special_syntax():
507 def test_prun_special_syntax():
508 "Test %%prun with IPython special syntax"
508 "Test %%prun with IPython special syntax"
509 @register_line_magic
509 @register_line_magic
510 def lmagic(line):
510 def lmagic(line):
511 ip = get_ipython()
511 ip = get_ipython()
512 ip.user_ns['lmagic_out'] = line
512 ip.user_ns['lmagic_out'] = line
513
513
514 # line mode test
514 # line mode test
515 _ip.run_line_magic('prun', '-q %lmagic my line')
515 _ip.run_line_magic('prun', '-q %lmagic my line')
516 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
516 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
517 # cell mode test
517 # cell mode test
518 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
518 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
519 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
519 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
520
520
521 @dec.skipif(execution.profile is None)
521 @dec.skipif(execution.profile is None)
522 def test_prun_quotes():
522 def test_prun_quotes():
523 "Test that prun does not clobber string escapes (GH #1302)"
523 "Test that prun does not clobber string escapes (GH #1302)"
524 _ip.magic(r"prun -q x = '\t'")
524 _ip.magic(r"prun -q x = '\t'")
525 nt.assert_equal(_ip.user_ns['x'], '\t')
525 nt.assert_equal(_ip.user_ns['x'], '\t')
526
526
527 def test_extension():
527 def test_extension():
528 tmpdir = TemporaryDirectory()
528 tmpdir = TemporaryDirectory()
529 orig_ipython_dir = _ip.ipython_dir
529 orig_ipython_dir = _ip.ipython_dir
530 try:
530 try:
531 _ip.ipython_dir = tmpdir.name
531 _ip.ipython_dir = tmpdir.name
532 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
532 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
533 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
533 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
534 _ip.magic("install_ext %s" % url)
534 _ip.magic("install_ext %s" % url)
535 _ip.user_ns.pop('arq', None)
535 _ip.user_ns.pop('arq', None)
536 invalidate_caches() # Clear import caches
536 invalidate_caches() # Clear import caches
537 _ip.magic("load_ext daft_extension")
537 _ip.magic("load_ext daft_extension")
538 nt.assert_equal(_ip.user_ns['arq'], 185)
538 nt.assert_equal(_ip.user_ns['arq'], 185)
539 _ip.magic("unload_ext daft_extension")
539 _ip.magic("unload_ext daft_extension")
540 assert 'arq' not in _ip.user_ns
540 assert 'arq' not in _ip.user_ns
541 finally:
541 finally:
542 _ip.ipython_dir = orig_ipython_dir
542 _ip.ipython_dir = orig_ipython_dir
543 tmpdir.cleanup()
543 tmpdir.cleanup()
544
544
545 def test_notebook_export_json():
545 def test_notebook_export_json():
546 with TemporaryDirectory() as td:
546 with TemporaryDirectory() as td:
547 outfile = os.path.join(td, "nb.ipynb")
547 outfile = os.path.join(td, "nb.ipynb")
548 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
548 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
549 _ip.magic("notebook -e %s" % outfile)
549 _ip.magic("notebook -e %s" % outfile)
550
550
551 def test_notebook_export_py():
551 def test_notebook_export_py():
552 with TemporaryDirectory() as td:
552 with TemporaryDirectory() as td:
553 outfile = os.path.join(td, "nb.py")
553 outfile = os.path.join(td, "nb.py")
554 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
554 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
555 _ip.magic("notebook -e %s" % outfile)
555 _ip.magic("notebook -e %s" % outfile)
556
556
557 def test_notebook_reformat_py():
557 def test_notebook_reformat_py():
558 with TemporaryDirectory() as td:
558 with TemporaryDirectory() as td:
559 infile = os.path.join(td, "nb.ipynb")
559 infile = os.path.join(td, "nb.ipynb")
560 with io.open(infile, 'w', encoding='utf-8') as f:
560 with io.open(infile, 'w', encoding='utf-8') as f:
561 current.write(nb0, f, 'json')
561 current.write(nb0, f, 'json')
562
562
563 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
563 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
564 _ip.magic("notebook -f py %s" % infile)
564 _ip.magic("notebook -f py %s" % infile)
565
565
566 def test_notebook_reformat_json():
566 def test_notebook_reformat_json():
567 with TemporaryDirectory() as td:
567 with TemporaryDirectory() as td:
568 infile = os.path.join(td, "nb.py")
568 infile = os.path.join(td, "nb.py")
569 with io.open(infile, 'w', encoding='utf-8') as f:
569 with io.open(infile, 'w', encoding='utf-8') as f:
570 current.write(nb0, f, 'py')
570 current.write(nb0, f, 'py')
571
571
572 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
572 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
573 _ip.magic("notebook -f ipynb %s" % infile)
573 _ip.magic("notebook -f ipynb %s" % infile)
574 _ip.magic("notebook -f json %s" % infile)
574 _ip.magic("notebook -f json %s" % infile)
575
575
576 def test_env():
576 def test_env():
577 env = _ip.magic("env")
577 env = _ip.magic("env")
578 assert isinstance(env, dict), type(env)
578 assert isinstance(env, dict), type(env)
579
579
580
580
581 class CellMagicTestCase(TestCase):
581 class CellMagicTestCase(TestCase):
582
582
583 def check_ident(self, magic):
583 def check_ident(self, magic):
584 # Manually called, we get the result
584 # Manually called, we get the result
585 out = _ip.run_cell_magic(magic, 'a', 'b')
585 out = _ip.run_cell_magic(magic, 'a', 'b')
586 nt.assert_equal(out, ('a','b'))
586 nt.assert_equal(out, ('a','b'))
587 # Via run_cell, it goes into the user's namespace via displayhook
587 # Via run_cell, it goes into the user's namespace via displayhook
588 _ip.run_cell('%%' + magic +' c\nd')
588 _ip.run_cell('%%' + magic +' c\nd')
589 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
589 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
590
590
591 def test_cell_magic_func_deco(self):
591 def test_cell_magic_func_deco(self):
592 "Cell magic using simple decorator"
592 "Cell magic using simple decorator"
593 @register_cell_magic
593 @register_cell_magic
594 def cellm(line, cell):
594 def cellm(line, cell):
595 return line, cell
595 return line, cell
596
596
597 self.check_ident('cellm')
597 self.check_ident('cellm')
598
598
599 def test_cell_magic_reg(self):
599 def test_cell_magic_reg(self):
600 "Cell magic manually registered"
600 "Cell magic manually registered"
601 def cellm(line, cell):
601 def cellm(line, cell):
602 return line, cell
602 return line, cell
603
603
604 _ip.register_magic_function(cellm, 'cell', 'cellm2')
604 _ip.register_magic_function(cellm, 'cell', 'cellm2')
605 self.check_ident('cellm2')
605 self.check_ident('cellm2')
606
606
607 def test_cell_magic_class(self):
607 def test_cell_magic_class(self):
608 "Cell magics declared via a class"
608 "Cell magics declared via a class"
609 @magics_class
609 @magics_class
610 class MyMagics(Magics):
610 class MyMagics(Magics):
611
611
612 @cell_magic
612 @cell_magic
613 def cellm3(self, line, cell):
613 def cellm3(self, line, cell):
614 return line, cell
614 return line, cell
615
615
616 _ip.register_magics(MyMagics)
616 _ip.register_magics(MyMagics)
617 self.check_ident('cellm3')
617 self.check_ident('cellm3')
618
618
619 def test_cell_magic_class2(self):
619 def test_cell_magic_class2(self):
620 "Cell magics declared via a class, #2"
620 "Cell magics declared via a class, #2"
621 @magics_class
621 @magics_class
622 class MyMagics2(Magics):
622 class MyMagics2(Magics):
623
623
624 @cell_magic('cellm4')
624 @cell_magic('cellm4')
625 def cellm33(self, line, cell):
625 def cellm33(self, line, cell):
626 return line, cell
626 return line, cell
627
627
628 _ip.register_magics(MyMagics2)
628 _ip.register_magics(MyMagics2)
629 self.check_ident('cellm4')
629 self.check_ident('cellm4')
630 # Check that nothing is registered as 'cellm33'
630 # Check that nothing is registered as 'cellm33'
631 c33 = _ip.find_cell_magic('cellm33')
631 c33 = _ip.find_cell_magic('cellm33')
632 nt.assert_equal(c33, None)
632 nt.assert_equal(c33, None)
633
633
634 def test_file():
634 def test_file():
635 """Basic %%file"""
635 """Basic %%file"""
636 ip = get_ipython()
636 ip = get_ipython()
637 with TemporaryDirectory() as td:
637 with TemporaryDirectory() as td:
638 fname = os.path.join(td, 'file1')
638 fname = os.path.join(td, 'file1')
639 ip.run_cell_magic("file", fname, u'\n'.join([
639 ip.run_cell_magic("file", fname, u'\n'.join([
640 'line1',
640 'line1',
641 'line2',
641 'line2',
642 ]))
642 ]))
643 with open(fname) as f:
643 with open(fname) as f:
644 s = f.read()
644 s = f.read()
645 nt.assert_in('line1\n', s)
645 nt.assert_in('line1\n', s)
646 nt.assert_in('line2', s)
646 nt.assert_in('line2', s)
647
647
648 def test_file_var_expand():
648 def test_file_var_expand():
649 """%%file $filename"""
649 """%%file $filename"""
650 ip = get_ipython()
650 ip = get_ipython()
651 with TemporaryDirectory() as td:
651 with TemporaryDirectory() as td:
652 fname = os.path.join(td, 'file1')
652 fname = os.path.join(td, 'file1')
653 ip.user_ns['filename'] = fname
653 ip.user_ns['filename'] = fname
654 ip.run_cell_magic("file", '$filename', u'\n'.join([
654 ip.run_cell_magic("file", '$filename', u'\n'.join([
655 'line1',
655 'line1',
656 'line2',
656 'line2',
657 ]))
657 ]))
658 with open(fname) as f:
658 with open(fname) as f:
659 s = f.read()
659 s = f.read()
660 nt.assert_in('line1\n', s)
660 nt.assert_in('line1\n', s)
661 nt.assert_in('line2', s)
661 nt.assert_in('line2', s)
662
662
663 def test_file_unicode():
663 def test_file_unicode():
664 """%%file with unicode cell"""
664 """%%file with unicode cell"""
665 ip = get_ipython()
665 ip = get_ipython()
666 with TemporaryDirectory() as td:
666 with TemporaryDirectory() as td:
667 fname = os.path.join(td, 'file1')
667 fname = os.path.join(td, 'file1')
668 ip.run_cell_magic("file", fname, u'\n'.join([
668 ip.run_cell_magic("file", fname, u'\n'.join([
669 u'linΓ©1',
669 u'linΓ©1',
670 u'linΓ©2',
670 u'linΓ©2',
671 ]))
671 ]))
672 with io.open(fname, encoding='utf-8') as f:
672 with io.open(fname, encoding='utf-8') as f:
673 s = f.read()
673 s = f.read()
674 nt.assert_in(u'linΓ©1\n', s)
674 nt.assert_in(u'linΓ©1\n', s)
675 nt.assert_in(u'linΓ©2', s)
675 nt.assert_in(u'linΓ©2', s)
676
676
677 def test_file_amend():
677 def test_file_amend():
678 """%%file -a amends files"""
678 """%%file -a amends files"""
679 ip = get_ipython()
679 ip = get_ipython()
680 with TemporaryDirectory() as td:
680 with TemporaryDirectory() as td:
681 fname = os.path.join(td, 'file2')
681 fname = os.path.join(td, 'file2')
682 ip.run_cell_magic("file", fname, u'\n'.join([
682 ip.run_cell_magic("file", fname, u'\n'.join([
683 'line1',
683 'line1',
684 'line2',
684 'line2',
685 ]))
685 ]))
686 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
686 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
687 'line3',
687 'line3',
688 'line4',
688 'line4',
689 ]))
689 ]))
690 with open(fname) as f:
690 with open(fname) as f:
691 s = f.read()
691 s = f.read()
692 nt.assert_in('line1\n', s)
692 nt.assert_in('line1\n', s)
693 nt.assert_in('line3\n', s)
693 nt.assert_in('line3\n', s)
694
694
695
695
696 def test_script_config():
696 def test_script_config():
697 ip = get_ipython()
697 ip = get_ipython()
698 ip.config.ScriptMagics.script_magics = ['whoda']
698 ip.config.ScriptMagics.script_magics = ['whoda']
699 sm = script.ScriptMagics(shell=ip)
699 sm = script.ScriptMagics(shell=ip)
700 nt.assert_in('whoda', sm.magics['cell'])
700 nt.assert_in('whoda', sm.magics['cell'])
701
701
702 @dec.skip_win32
702 @dec.skip_win32
703 def test_script_out():
703 def test_script_out():
704 ip = get_ipython()
704 ip = get_ipython()
705 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
705 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
706 nt.assert_equal(ip.user_ns['output'], 'hi\n')
706 nt.assert_equal(ip.user_ns['output'], 'hi\n')
707
707
708 @dec.skip_win32
708 @dec.skip_win32
709 def test_script_err():
709 def test_script_err():
710 ip = get_ipython()
710 ip = get_ipython()
711 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
711 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
712 nt.assert_equal(ip.user_ns['error'], 'hello\n')
712 nt.assert_equal(ip.user_ns['error'], 'hello\n')
713
713
714 @dec.skip_win32
714 @dec.skip_win32
715 def test_script_out_err():
715 def test_script_out_err():
716 ip = get_ipython()
716 ip = get_ipython()
717 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
717 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
718 nt.assert_equal(ip.user_ns['output'], 'hi\n')
718 nt.assert_equal(ip.user_ns['output'], 'hi\n')
719 nt.assert_equal(ip.user_ns['error'], 'hello\n')
719 nt.assert_equal(ip.user_ns['error'], 'hello\n')
720
720
721 @dec.skip_win32
721 @dec.skip_win32
722 def test_script_bg_out():
722 def test_script_bg_out():
723 ip = get_ipython()
723 ip = get_ipython()
724 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
724 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
725 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
725 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
726
726
727 @dec.skip_win32
727 @dec.skip_win32
728 def test_script_bg_err():
728 def test_script_bg_err():
729 ip = get_ipython()
729 ip = get_ipython()
730 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
730 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
731 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
731 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
732
732
733 @dec.skip_win32
733 @dec.skip_win32
734 def test_script_bg_out_err():
734 def test_script_bg_out_err():
735 ip = get_ipython()
735 ip = get_ipython()
736 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
736 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
737 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
737 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
738 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
738 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
739
739
740 def test_script_defaults():
740 def test_script_defaults():
741 ip = get_ipython()
741 ip = get_ipython()
742 for cmd in ['sh', 'bash', 'perl', 'ruby']:
742 for cmd in ['sh', 'bash', 'perl', 'ruby']:
743 try:
743 try:
744 find_cmd(cmd)
744 find_cmd(cmd)
745 except Exception:
745 except Exception:
746 pass
746 pass
747 else:
747 else:
748 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
748 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
749
749
750
750
751 @magics_class
751 @magics_class
752 class FooFoo(Magics):
752 class FooFoo(Magics):
753 """class with both %foo and %%foo magics"""
753 """class with both %foo and %%foo magics"""
754 @line_magic('foo')
754 @line_magic('foo')
755 def line_foo(self, line):
755 def line_foo(self, line):
756 "I am line foo"
756 "I am line foo"
757 pass
757 pass
758
758
759 @cell_magic("foo")
759 @cell_magic("foo")
760 def cell_foo(self, line, cell):
760 def cell_foo(self, line, cell):
761 "I am cell foo, not line foo"
761 "I am cell foo, not line foo"
762 pass
762 pass
763
763
764 def test_line_cell_info():
764 def test_line_cell_info():
765 """%%foo and %foo magics are distinguishable to inspect"""
765 """%%foo and %foo magics are distinguishable to inspect"""
766 ip = get_ipython()
766 ip = get_ipython()
767 ip.magics_manager.register(FooFoo)
767 ip.magics_manager.register(FooFoo)
768 oinfo = ip.object_inspect('foo')
768 oinfo = ip.object_inspect('foo')
769 nt.assert_true(oinfo['found'])
769 nt.assert_true(oinfo['found'])
770 nt.assert_true(oinfo['ismagic'])
770 nt.assert_true(oinfo['ismagic'])
771
771
772 oinfo = ip.object_inspect('%%foo')
772 oinfo = ip.object_inspect('%%foo')
773 nt.assert_true(oinfo['found'])
773 nt.assert_true(oinfo['found'])
774 nt.assert_true(oinfo['ismagic'])
774 nt.assert_true(oinfo['ismagic'])
775 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
775 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
776
776
777 oinfo = ip.object_inspect('%foo')
777 oinfo = ip.object_inspect('%foo')
778 nt.assert_true(oinfo['found'])
778 nt.assert_true(oinfo['found'])
779 nt.assert_true(oinfo['ismagic'])
779 nt.assert_true(oinfo['ismagic'])
780 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
780 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
781
781
782 def test_multiple_magics():
782 def test_multiple_magics():
783 ip = get_ipython()
783 ip = get_ipython()
784 foo1 = FooFoo(ip)
784 foo1 = FooFoo(ip)
785 foo2 = FooFoo(ip)
785 foo2 = FooFoo(ip)
786 mm = ip.magics_manager
786 mm = ip.magics_manager
787 mm.register(foo1)
787 mm.register(foo1)
788 nt.assert_true(mm.magics['line']['foo'].im_self is foo1)
788 nt.assert_true(mm.magics['line']['foo'].im_self is foo1)
789 mm.register(foo2)
789 mm.register(foo2)
790 nt.assert_true(mm.magics['line']['foo'].im_self is foo2)
790 nt.assert_true(mm.magics['line']['foo'].im_self is foo2)
791
791
792 def test_alias_magic():
792 def test_alias_magic():
793 """Test %alias_magic."""
793 """Test %alias_magic."""
794 ip = get_ipython()
794 ip = get_ipython()
795 mm = ip.magics_manager
795 mm = ip.magics_manager
796
796
797 # Basic operation: both cell and line magics are created, if possible.
797 # Basic operation: both cell and line magics are created, if possible.
798 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
798 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
799 nt.assert_in('timeit_alias', mm.magics['line'])
799 nt.assert_in('timeit_alias', mm.magics['line'])
800 nt.assert_in('timeit_alias', mm.magics['cell'])
800 nt.assert_in('timeit_alias', mm.magics['cell'])
801
801
802 # --cell is specified, line magic not created.
802 # --cell is specified, line magic not created.
803 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
803 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
804 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
804 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
805 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
805 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
806
806
807 # Test that line alias is created successfully.
807 # Test that line alias is created successfully.
808 ip.run_line_magic('alias_magic', '--line env_alias env')
808 ip.run_line_magic('alias_magic', '--line env_alias env')
809 nt.assert_equal(ip.run_line_magic('env', ''),
809 nt.assert_equal(ip.run_line_magic('env', ''),
810 ip.run_line_magic('env_alias', ''))
810 ip.run_line_magic('env_alias', ''))
811
811
812 def test_save():
812 def test_save():
813 """Test %save."""
813 """Test %save."""
814 ip = get_ipython()
814 ip = get_ipython()
815 ip.history_manager.reset() # Clear any existing history.
815 ip.history_manager.reset() # Clear any existing history.
816 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
816 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
817 for i, cmd in enumerate(cmds, start=1):
817 for i, cmd in enumerate(cmds, start=1):
818 ip.history_manager.store_inputs(i, cmd)
818 ip.history_manager.store_inputs(i, cmd)
819 with TemporaryDirectory() as tmpdir:
819 with TemporaryDirectory() as tmpdir:
820 file = os.path.join(tmpdir, "testsave.py")
820 file = os.path.join(tmpdir, "testsave.py")
821 ip.run_line_magic("save", "%s 1-10" % file)
821 ip.run_line_magic("save", "%s 1-10" % file)
822 with open(file) as f:
822 with open(file) as f:
823 content = f.read()
823 content = f.read()
824 nt.assert_equal(content.count(cmds[0]), 1)
824 nt.assert_equal(content.count(cmds[0]), 1)
825 nt.assert_in('coding: utf-8', content)
825 nt.assert_in('coding: utf-8', content)
826 ip.run_line_magic("save", "-a %s 1-10" % file)
826 ip.run_line_magic("save", "-a %s 1-10" % file)
827 with open(file) as f:
827 with open(file) as f:
828 content = f.read()
828 content = f.read()
829 nt.assert_equal(content.count(cmds[0]), 2)
829 nt.assert_equal(content.count(cmds[0]), 2)
830 nt.assert_in('coding: utf-8', content)
830 nt.assert_in('coding: utf-8', content)
831
831
832
832
833 def test_store():
833 def test_store():
834 """Test %store."""
834 """Test %store."""
835 ip = get_ipython()
835 ip = get_ipython()
836 ip.run_line_magic('load_ext', 'storemagic')
836 ip.run_line_magic('load_ext', 'storemagic')
837
837
838 # make sure the storage is empty
838 # make sure the storage is empty
839 ip.run_line_magic('store', '-z')
839 ip.run_line_magic('store', '-z')
840 ip.user_ns['var'] = 42
840 ip.user_ns['var'] = 42
841 ip.run_line_magic('store', 'var')
841 ip.run_line_magic('store', 'var')
842 ip.user_ns['var'] = 39
842 ip.user_ns['var'] = 39
843 ip.run_line_magic('store', '-r')
843 ip.run_line_magic('store', '-r')
844 nt.assert_equal(ip.user_ns['var'], 42)
844 nt.assert_equal(ip.user_ns['var'], 42)
845
845
846 ip.run_line_magic('store', '-d var')
846 ip.run_line_magic('store', '-d var')
847 ip.user_ns['var'] = 39
847 ip.user_ns['var'] = 39
848 ip.run_line_magic('store' , '-r')
848 ip.run_line_magic('store' , '-r')
849 nt.assert_equal(ip.user_ns['var'], 39)
849 nt.assert_equal(ip.user_ns['var'], 39)
850
850
851
851
852 def _run_edit_test(arg_s, exp_filename=None,
852 def _run_edit_test(arg_s, exp_filename=None,
853 exp_lineno=-1,
853 exp_lineno=-1,
854 exp_contents=None,
854 exp_contents=None,
855 exp_is_temp=None):
855 exp_is_temp=None):
856 ip = get_ipython()
856 ip = get_ipython()
857 M = code.CodeMagics(ip)
857 M = code.CodeMagics(ip)
858 last_call = ['','']
858 last_call = ['','']
859 opts,args = M.parse_options(arg_s,'prxn:')
859 opts,args = M.parse_options(arg_s,'prxn:')
860 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
860 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
861
861
862 if exp_filename is not None:
862 if exp_filename is not None:
863 nt.assert_equal(exp_filename, filename)
863 nt.assert_equal(exp_filename, filename)
864 if exp_contents is not None:
864 if exp_contents is not None:
865 with io.open(filename, 'r') as f:
865 with io.open(filename, 'r') as f:
866 contents = f.read()
866 contents = f.read()
867 nt.assert_equal(exp_contents, contents)
867 nt.assert_equal(exp_contents, contents)
868 if exp_lineno != -1:
868 if exp_lineno != -1:
869 nt.assert_equal(exp_lineno, lineno)
869 nt.assert_equal(exp_lineno, lineno)
870 if exp_is_temp is not None:
870 if exp_is_temp is not None:
871 nt.assert_equal(exp_is_temp, is_temp)
871 nt.assert_equal(exp_is_temp, is_temp)
872
872
873
873
874 def test_edit_interactive():
874 def test_edit_interactive():
875 """%edit on interactively defined objects"""
875 """%edit on interactively defined objects"""
876 ip = get_ipython()
876 ip = get_ipython()
877 n = ip.execution_count
877 n = ip.execution_count
878 ip.run_cell(u"def foo(): return 1", store_history=True)
878 ip.run_cell(u"def foo(): return 1", store_history=True)
879
879
880 try:
880 try:
881 _run_edit_test("foo")
881 _run_edit_test("foo")
882 except code.InteractivelyDefined as e:
882 except code.InteractivelyDefined as e:
883 nt.assert_equal(e.index, n)
883 nt.assert_equal(e.index, n)
884 else:
884 else:
885 raise AssertionError("Should have raised InteractivelyDefined")
885 raise AssertionError("Should have raised InteractivelyDefined")
886
886
887
887
888 def test_edit_cell():
888 def test_edit_cell():
889 """%edit [cell id]"""
889 """%edit [cell id]"""
890 ip = get_ipython()
890 ip = get_ipython()
891
891
892 ip.run_cell(u"def foo(): return 1", store_history=True)
892 ip.run_cell(u"def foo(): return 1", store_history=True)
893
893
894 # test
894 # test
895 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
895 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
@@ -1,243 +1,243 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 %store magic for lightweight persistence.
3 %store magic for lightweight persistence.
4
4
5 Stores variables, aliases and macros in IPython's database.
5 Stores variables, aliases and macros in IPython's database.
6
6
7 To automatically restore stored variables at startup, add this to your
7 To automatically restore stored variables at startup, add this to your
8 :file:`ipython_config.py` file::
8 :file:`ipython_config.py` file::
9
9
10 c.StoreMagic.autorestore = True
10 c.StoreMagic.autorestore = True
11 """
11 """
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (c) 2012, The IPython Development Team.
13 # Copyright (c) 2012, The IPython Development Team.
14 #
14 #
15 # Distributed under the terms of the Modified BSD License.
15 # Distributed under the terms of the Modified BSD License.
16 #
16 #
17 # The full license is in the file COPYING.txt, distributed with this software.
17 # The full license is in the file COPYING.txt, distributed with this software.
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Imports
21 # Imports
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 # Stdlib
24 # Stdlib
25 import inspect, os, sys, textwrap
25 import inspect, os, sys, textwrap
26
26
27 # Our own
27 # Our own
28 from IPython.config.configurable import Configurable
28 from IPython.config.configurable import Configurable
29 from IPython.core.error import UsageError
29 from IPython.core.error import UsageError
30 from IPython.core.magic import Magics, magics_class, line_magic
30 from IPython.core.magic import Magics, magics_class, line_magic
31 from IPython.testing.skipdoctest import skip_doctest
31 from IPython.testing.skipdoctest import skip_doctest
32 from IPython.utils.traitlets import Bool
32 from IPython.utils.traitlets import Bool
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Functions and classes
35 # Functions and classes
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 def restore_aliases(ip):
38 def restore_aliases(ip):
39 staliases = ip.db.get('stored_aliases', {})
39 staliases = ip.db.get('stored_aliases', {})
40 for k,v in staliases.items():
40 for k,v in staliases.items():
41 #print "restore alias",k,v # dbg
41 #print "restore alias",k,v # dbg
42 #self.alias_table[k] = v
42 #self.alias_table[k] = v
43 ip.alias_manager.define_alias(k,v)
43 ip.alias_manager.define_alias(k,v)
44
44
45
45
46 def refresh_variables(ip):
46 def refresh_variables(ip):
47 db = ip.db
47 db = ip.db
48 for key in db.keys('autorestore/*'):
48 for key in db.keys('autorestore/*'):
49 # strip autorestore
49 # strip autorestore
50 justkey = os.path.basename(key)
50 justkey = os.path.basename(key)
51 try:
51 try:
52 obj = db[key]
52 obj = db[key]
53 except KeyError:
53 except KeyError:
54 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey
54 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey
55 print "The error was:", sys.exc_info()[0]
55 print "The error was:", sys.exc_info()[0]
56 else:
56 else:
57 #print "restored",justkey,"=",obj #dbg
57 #print "restored",justkey,"=",obj #dbg
58 ip.user_ns[justkey] = obj
58 ip.user_ns[justkey] = obj
59
59
60
60
61 def restore_dhist(ip):
61 def restore_dhist(ip):
62 ip.user_ns['_dh'] = ip.db.get('dhist',[])
62 ip.user_ns['_dh'] = ip.db.get('dhist',[])
63
63
64
64
65 def restore_data(ip):
65 def restore_data(ip):
66 refresh_variables(ip)
66 refresh_variables(ip)
67 restore_aliases(ip)
67 restore_aliases(ip)
68 restore_dhist(ip)
68 restore_dhist(ip)
69
69
70
70
71 @magics_class
71 @magics_class
72 class StoreMagics(Magics, Configurable):
72 class StoreMagics(Magics, Configurable):
73 """Lightweight persistence for python variables.
73 """Lightweight persistence for python variables.
74
74
75 Provides the %store magic."""
75 Provides the %store magic."""
76
76
77 autorestore = Bool(False, config=True, help=
77 autorestore = Bool(False, config=True, help=
78 """If True, any %store-d variables will be automatically restored
78 """If True, any %store-d variables will be automatically restored
79 when IPython starts.
79 when IPython starts.
80 """
80 """
81 )
81 )
82
82
83 def __init__(self, shell):
83 def __init__(self, shell):
84 Configurable.__init__(self, config=shell.config)
84 Configurable.__init__(self, config=shell.config)
85 Magics.__init__(self, shell=shell)
85 Magics.__init__(self, shell=shell)
86 self.shell.configurables.append(self)
86 self.shell.configurables.append(self)
87 if self.autorestore:
87 if self.autorestore:
88 restore_data(self.shell)
88 restore_data(self.shell)
89
89
90 @skip_doctest
90 @skip_doctest
91 @line_magic
91 @line_magic
92 def store(self, parameter_s=''):
92 def store(self, parameter_s=''):
93 """Lightweight persistence for python variables.
93 """Lightweight persistence for python variables.
94
94
95 Example::
95 Example::
96
96
97 In [1]: l = ['hello',10,'world']
97 In [1]: l = ['hello',10,'world']
98 In [2]: %store l
98 In [2]: %store l
99 In [3]: exit
99 In [3]: exit
100
100
101 (IPython session is closed and started again...)
101 (IPython session is closed and started again...)
102
102
103 ville@badger:~$ ipython
103 ville@badger:~$ ipython
104 In [1]: l
104 In [1]: l
105 NameError: name 'l' is not defined
105 NameError: name 'l' is not defined
106 In [2]: %store -r
106 In [2]: %store -r
107 In [3]: l
107 In [3]: l
108 Out[3]: ['hello', 10, 'world']
108 Out[3]: ['hello', 10, 'world']
109
109
110 Usage:
110 Usage:
111
111
112 * ``%store`` - Show list of all variables and their current
112 * ``%store`` - Show list of all variables and their current
113 values
113 values
114 * ``%store spam`` - Store the *current* value of the variable spam
114 * ``%store spam`` - Store the *current* value of the variable spam
115 to disk
115 to disk
116 * ``%store -d spam`` - Remove the variable and its value from storage
116 * ``%store -d spam`` - Remove the variable and its value from storage
117 * ``%store -z`` - Remove all variables from storage
117 * ``%store -z`` - Remove all variables from storage
118 * ``%store -r`` - Refresh all variables from store (overwrite
118 * ``%store -r`` - Refresh all variables from store (overwrite
119 current vals)
119 current vals)
120 * ``%store -r spam bar`` - Refresh specified variables from store
120 * ``%store -r spam bar`` - Refresh specified variables from store
121 (delete current val)
121 (delete current val)
122 * ``%store foo >a.txt`` - Store value of foo to new file a.txt
122 * ``%store foo >a.txt`` - Store value of foo to new file a.txt
123 * ``%store foo >>a.txt`` - Append value of foo to file a.txt
123 * ``%store foo >>a.txt`` - Append value of foo to file a.txt
124
124
125 It should be noted that if you change the value of a variable, you
125 It should be noted that if you change the value of a variable, you
126 need to %store it again if you want to persist the new value.
126 need to %store it again if you want to persist the new value.
127
127
128 Note also that the variables will need to be pickleable; most basic
128 Note also that the variables will need to be pickleable; most basic
129 python types can be safely %store'd.
129 python types can be safely %store'd.
130
130
131 Also aliases can be %store'd across sessions.
131 Also aliases can be %store'd across sessions.
132 """
132 """
133
133
134 opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
134 opts,argsl = self.parse_options(parameter_s,'drz',mode='string')
135 args = argsl.split(None,1)
135 args = argsl.split(None,1)
136 ip = self.shell
136 ip = self.shell
137 db = ip.db
137 db = ip.db
138 # delete
138 # delete
139 if 'd' in opts:
139 if 'd' in opts:
140 try:
140 try:
141 todel = args[0]
141 todel = args[0]
142 except IndexError:
142 except IndexError:
143 raise UsageError('You must provide the variable to forget')
143 raise UsageError('You must provide the variable to forget')
144 else:
144 else:
145 try:
145 try:
146 del db['autorestore/' + todel]
146 del db['autorestore/' + todel]
147 except:
147 except:
148 raise UsageError("Can't delete variable '%s'" % todel)
148 raise UsageError("Can't delete variable '%s'" % todel)
149 # reset
149 # reset
150 elif 'z' in opts:
150 elif 'z' in opts:
151 for k in db.keys('autorestore/*'):
151 for k in db.keys('autorestore/*'):
152 del db[k]
152 del db[k]
153
153
154 elif 'r' in opts:
154 elif 'r' in opts:
155 if args:
155 if args:
156 for arg in args:
156 for arg in args:
157 try:
157 try:
158 obj = db['autorestore/' + arg]
158 obj = db['autorestore/' + arg]
159 except KeyError:
159 except KeyError:
160 print "no stored variable %s" % arg
160 print "no stored variable %s" % arg
161 else:
161 else:
162 ip.user_ns[arg] = obj
162 ip.user_ns[arg] = obj
163 else:
163 else:
164 restore_data(ip)
164 restore_data(ip)
165
165
166 # run without arguments -> list variables & values
166 # run without arguments -> list variables & values
167 elif not args:
167 elif not args:
168 vars = db.keys('autorestore/*')
168 vars = db.keys('autorestore/*')
169 vars.sort()
169 vars.sort()
170 if vars:
170 if vars:
171 size = max(map(len, vars))
171 size = max(map(len, vars))
172 else:
172 else:
173 size = 0
173 size = 0
174
174
175 print 'Stored variables and their in-db values:'
175 print 'Stored variables and their in-db values:'
176 fmt = '%-'+str(size)+'s -> %s'
176 fmt = '%-'+str(size)+'s -> %s'
177 get = db.get
177 get = db.get
178 for var in vars:
178 for var in vars:
179 justkey = os.path.basename(var)
179 justkey = os.path.basename(var)
180 # print 30 first characters from every var
180 # print 30 first characters from every var
181 print fmt % (justkey, repr(get(var, '<unavailable>'))[:50])
181 print fmt % (justkey, repr(get(var, '<unavailable>'))[:50])
182
182
183 # default action - store the variable
183 # default action - store the variable
184 else:
184 else:
185 # %store foo >file.txt or >>file.txt
185 # %store foo >file.txt or >>file.txt
186 if len(args) > 1 and args[1].startswith('>'):
186 if len(args) > 1 and args[1].startswith('>'):
187 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
187 fnam = os.path.expanduser(args[1].lstrip('>').lstrip())
188 if args[1].startswith('>>'):
188 if args[1].startswith('>>'):
189 fil = open(fnam, 'a')
189 fil = open(fnam, 'a')
190 else:
190 else:
191 fil = open(fnam, 'w')
191 fil = open(fnam, 'w')
192 obj = ip.ev(args[0])
192 obj = ip.ev(args[0])
193 print "Writing '%s' (%s) to file '%s'." % (args[0],
193 print "Writing '%s' (%s) to file '%s'." % (args[0],
194 obj.__class__.__name__, fnam)
194 obj.__class__.__name__, fnam)
195
195
196
196
197 if not isinstance (obj, basestring):
197 if not isinstance (obj, basestring):
198 from pprint import pprint
198 from pprint import pprint
199 pprint(obj, fil)
199 pprint(obj, fil)
200 else:
200 else:
201 fil.write(obj)
201 fil.write(obj)
202 if not obj.endswith('\n'):
202 if not obj.endswith('\n'):
203 fil.write('\n')
203 fil.write('\n')
204
204
205 fil.close()
205 fil.close()
206 return
206 return
207
207
208 # %store foo
208 # %store foo
209 try:
209 try:
210 obj = ip.user_ns[args[0]]
210 obj = ip.user_ns[args[0]]
211 except KeyError:
211 except KeyError:
212 # it might be an alias
212 # it might be an alias
213 # This needs to be refactored to use the new AliasManager stuff.
213 name = args[0]
214 if args[0] in ip.alias_manager:
214 try:
215 name = args[0]
215 cmd = ip.alias_manager.retrieve_alias(name)
216 nargs, cmd = ip.alias_manager.alias_table[ name ]
216 except ValueError:
217 staliases = db.get('stored_aliases',{})
217 raise UsageError("Unknown variable '%s'" % name)
218 staliases[ name ] = cmd
218
219 db['stored_aliases'] = staliases
219 staliases = db.get('stored_aliases',{})
220 print "Alias stored: %s (%s)" % (name, cmd)
220 staliases[name] = cmd
221 return
221 db['stored_aliases'] = staliases
222 else:
222 print "Alias stored: %s (%s)" % (name, cmd)
223 raise UsageError("Unknown variable '%s'" % args[0])
223 return
224
224
225 else:
225 else:
226 modname = getattr(inspect.getmodule(obj), '__name__', '')
226 modname = getattr(inspect.getmodule(obj), '__name__', '')
227 if modname == '__main__':
227 if modname == '__main__':
228 print textwrap.dedent("""\
228 print textwrap.dedent("""\
229 Warning:%s is %s
229 Warning:%s is %s
230 Proper storage of interactively declared classes (or instances
230 Proper storage of interactively declared classes (or instances
231 of those classes) is not possible! Only instances
231 of those classes) is not possible! Only instances
232 of classes in real modules on file system can be %%store'd.
232 of classes in real modules on file system can be %%store'd.
233 """ % (args[0], obj) )
233 """ % (args[0], obj) )
234 return
234 return
235 #pickled = pickle.dumps(obj)
235 #pickled = pickle.dumps(obj)
236 db[ 'autorestore/' + args[0] ] = obj
236 db[ 'autorestore/' + args[0] ] = obj
237 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
237 print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__)
238
238
239
239
240 def load_ipython_extension(ip):
240 def load_ipython_extension(ip):
241 """Load the extension in IPython."""
241 """Load the extension in IPython."""
242 ip.register_magics(StoreMagics)
242 ip.register_magics(StoreMagics)
243
243
@@ -1,50 +1,50 b''
1 import tempfile, os
1 import tempfile, os
2
2
3 from IPython.config.loader import Config
3 from IPython.config.loader import Config
4 import nose.tools as nt
4 import nose.tools as nt
5
5
6 ip = get_ipython()
6 ip = get_ipython()
7 ip.magic('load_ext storemagic')
7 ip.magic('load_ext storemagic')
8
8
9 def test_store_restore():
9 def test_store_restore():
10 ip.user_ns['foo'] = 78
10 ip.user_ns['foo'] = 78
11 ip.magic('alias bar echo "hello"')
11 ip.magic('alias bar echo "hello"')
12 tmpd = tempfile.mkdtemp()
12 tmpd = tempfile.mkdtemp()
13 ip.magic('cd ' + tmpd)
13 ip.magic('cd ' + tmpd)
14 ip.magic('store foo')
14 ip.magic('store foo')
15 ip.magic('store bar')
15 ip.magic('store bar')
16
16
17 # Check storing
17 # Check storing
18 nt.assert_equal(ip.db['autorestore/foo'], 78)
18 nt.assert_equal(ip.db['autorestore/foo'], 78)
19 nt.assert_in('bar', ip.db['stored_aliases'])
19 nt.assert_in('bar', ip.db['stored_aliases'])
20
20
21 # Remove those items
21 # Remove those items
22 ip.user_ns.pop('foo', None)
22 ip.user_ns.pop('foo', None)
23 ip.alias_manager.undefine_alias('bar')
23 ip.alias_manager.undefine_alias('bar')
24 ip.magic('cd -')
24 ip.magic('cd -')
25 ip.user_ns['_dh'][:] = []
25 ip.user_ns['_dh'][:] = []
26
26
27 # Check restoring
27 # Check restoring
28 ip.magic('store -r')
28 ip.magic('store -r')
29 nt.assert_equal(ip.user_ns['foo'], 78)
29 nt.assert_equal(ip.user_ns['foo'], 78)
30 nt.assert_in('bar', ip.alias_manager.alias_table)
30 assert ip.alias_manager.is_alias('bar')
31 nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh'])
31 nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh'])
32
32
33 os.rmdir(tmpd)
33 os.rmdir(tmpd)
34
34
35 def test_autorestore():
35 def test_autorestore():
36 ip.user_ns['foo'] = 95
36 ip.user_ns['foo'] = 95
37 ip.magic('store foo')
37 ip.magic('store foo')
38 del ip.user_ns['foo']
38 del ip.user_ns['foo']
39 c = Config()
39 c = Config()
40 c.StoreMagics.autorestore = False
40 c.StoreMagics.autorestore = False
41 orig_config = ip.config
41 orig_config = ip.config
42 try:
42 try:
43 ip.config = c
43 ip.config = c
44 ip.extension_manager.reload_extension('storemagic')
44 ip.extension_manager.reload_extension('storemagic')
45 nt.assert_not_in('foo', ip.user_ns)
45 nt.assert_not_in('foo', ip.user_ns)
46 c.StoreMagics.autorestore = True
46 c.StoreMagics.autorestore = True
47 ip.extension_manager.reload_extension('storemagic')
47 ip.extension_manager.reload_extension('storemagic')
48 nt.assert_equal(ip.user_ns['foo'], 95)
48 nt.assert_equal(ip.user_ns['foo'], 95)
49 finally:
49 finally:
50 ip.config = orig_config
50 ip.config = orig_config
@@ -1,690 +1,690 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 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 from __future__ import print_function
16 from __future__ import print_function
17
17
18 import bdb
18 import bdb
19 import os
19 import os
20 import sys
20 import sys
21
21
22 from IPython.core.error import TryNext, UsageError
22 from IPython.core.error import TryNext, UsageError
23 from IPython.core.usage import interactive_usage, default_banner
23 from IPython.core.usage import interactive_usage, default_banner
24 from IPython.core.inputsplitter import IPythonInputSplitter
24 from IPython.core.inputsplitter import IPythonInputSplitter
25 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
25 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
26 from IPython.core.magic import Magics, magics_class, line_magic
26 from IPython.core.magic import Magics, magics_class, line_magic
27 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.utils.encoding import get_stream_enc
28 from IPython.utils.encoding import get_stream_enc
29 from IPython.utils import py3compat
29 from IPython.utils import py3compat
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.process import abbrev_cwd
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn, error
32 from IPython.utils.warn import warn, error
33 from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes
33 from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes
34 from IPython.utils.traitlets import Integer, CBool, Unicode
34 from IPython.utils.traitlets import Integer, CBool, Unicode
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Utilities
37 # Utilities
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 def get_default_editor():
40 def get_default_editor():
41 try:
41 try:
42 ed = os.environ['EDITOR']
42 ed = os.environ['EDITOR']
43 except KeyError:
43 except KeyError:
44 if os.name == 'posix':
44 if os.name == 'posix':
45 ed = 'vi' # the only one guaranteed to be there!
45 ed = 'vi' # the only one guaranteed to be there!
46 else:
46 else:
47 ed = 'notepad' # same in Windows!
47 ed = 'notepad' # same in Windows!
48 return ed
48 return ed
49
49
50
50
51 def get_pasted_lines(sentinel, l_input=py3compat.input):
51 def get_pasted_lines(sentinel, l_input=py3compat.input):
52 """ Yield pasted lines until the user enters the given sentinel value.
52 """ Yield pasted lines until the user enters the given sentinel value.
53 """
53 """
54 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
54 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
55 % sentinel)
55 % sentinel)
56 while True:
56 while True:
57 try:
57 try:
58 l = l_input(':')
58 l = l_input(':')
59 if l == sentinel:
59 if l == sentinel:
60 return
60 return
61 else:
61 else:
62 yield l
62 yield l
63 except EOFError:
63 except EOFError:
64 print('<EOF>')
64 print('<EOF>')
65 return
65 return
66
66
67
67
68 #------------------------------------------------------------------------
68 #------------------------------------------------------------------------
69 # Terminal-specific magics
69 # Terminal-specific magics
70 #------------------------------------------------------------------------
70 #------------------------------------------------------------------------
71
71
72 @magics_class
72 @magics_class
73 class TerminalMagics(Magics):
73 class TerminalMagics(Magics):
74 def __init__(self, shell):
74 def __init__(self, shell):
75 super(TerminalMagics, self).__init__(shell)
75 super(TerminalMagics, self).__init__(shell)
76 self.input_splitter = IPythonInputSplitter()
76 self.input_splitter = IPythonInputSplitter()
77
77
78 def store_or_execute(self, block, name):
78 def store_or_execute(self, block, name):
79 """ Execute a block, or store it in a variable, per the user's request.
79 """ Execute a block, or store it in a variable, per the user's request.
80 """
80 """
81 if name:
81 if name:
82 # If storing it for further editing
82 # If storing it for further editing
83 self.shell.user_ns[name] = SList(block.splitlines())
83 self.shell.user_ns[name] = SList(block.splitlines())
84 print("Block assigned to '%s'" % name)
84 print("Block assigned to '%s'" % name)
85 else:
85 else:
86 b = self.preclean_input(block)
86 b = self.preclean_input(block)
87 self.shell.user_ns['pasted_block'] = b
87 self.shell.user_ns['pasted_block'] = b
88 self.shell.using_paste_magics = True
88 self.shell.using_paste_magics = True
89 try:
89 try:
90 self.shell.run_cell(b)
90 self.shell.run_cell(b)
91 finally:
91 finally:
92 self.shell.using_paste_magics = False
92 self.shell.using_paste_magics = False
93
93
94 def preclean_input(self, block):
94 def preclean_input(self, block):
95 lines = block.splitlines()
95 lines = block.splitlines()
96 while lines and not lines[0].strip():
96 while lines and not lines[0].strip():
97 lines = lines[1:]
97 lines = lines[1:]
98 return strip_email_quotes('\n'.join(lines))
98 return strip_email_quotes('\n'.join(lines))
99
99
100 def rerun_pasted(self, name='pasted_block'):
100 def rerun_pasted(self, name='pasted_block'):
101 """ Rerun a previously pasted command.
101 """ Rerun a previously pasted command.
102 """
102 """
103 b = self.shell.user_ns.get(name)
103 b = self.shell.user_ns.get(name)
104
104
105 # Sanity checks
105 # Sanity checks
106 if b is None:
106 if b is None:
107 raise UsageError('No previous pasted block available')
107 raise UsageError('No previous pasted block available')
108 if not isinstance(b, basestring):
108 if not isinstance(b, basestring):
109 raise UsageError(
109 raise UsageError(
110 "Variable 'pasted_block' is not a string, can't execute")
110 "Variable 'pasted_block' is not a string, can't execute")
111
111
112 print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
112 print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
113 self.shell.run_cell(b)
113 self.shell.run_cell(b)
114
114
115 @line_magic
115 @line_magic
116 def autoindent(self, parameter_s = ''):
116 def autoindent(self, parameter_s = ''):
117 """Toggle autoindent on/off (if available)."""
117 """Toggle autoindent on/off (if available)."""
118
118
119 self.shell.set_autoindent()
119 self.shell.set_autoindent()
120 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
120 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
121
121
122 @skip_doctest
122 @skip_doctest
123 @line_magic
123 @line_magic
124 def cpaste(self, parameter_s=''):
124 def cpaste(self, parameter_s=''):
125 """Paste & execute a pre-formatted code block from clipboard.
125 """Paste & execute a pre-formatted code block from clipboard.
126
126
127 You must terminate the block with '--' (two minus-signs) or Ctrl-D
127 You must terminate the block with '--' (two minus-signs) or Ctrl-D
128 alone on the line. You can also provide your own sentinel with '%paste
128 alone on the line. You can also provide your own sentinel with '%paste
129 -s %%' ('%%' is the new sentinel for this operation)
129 -s %%' ('%%' is the new sentinel for this operation)
130
130
131 The block is dedented prior to execution to enable execution of method
131 The block is dedented prior to execution to enable execution of method
132 definitions. '>' and '+' characters at the beginning of a line are
132 definitions. '>' and '+' characters at the beginning of a line are
133 ignored, to allow pasting directly from e-mails, diff files and
133 ignored, to allow pasting directly from e-mails, diff files and
134 doctests (the '...' continuation prompt is also stripped). The
134 doctests (the '...' continuation prompt is also stripped). The
135 executed block is also assigned to variable named 'pasted_block' for
135 executed block is also assigned to variable named 'pasted_block' for
136 later editing with '%edit pasted_block'.
136 later editing with '%edit pasted_block'.
137
137
138 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
138 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
139 This assigns the pasted block to variable 'foo' as string, without
139 This assigns the pasted block to variable 'foo' as string, without
140 dedenting or executing it (preceding >>> and + is still stripped)
140 dedenting or executing it (preceding >>> and + is still stripped)
141
141
142 '%cpaste -r' re-executes the block previously entered by cpaste.
142 '%cpaste -r' re-executes the block previously entered by cpaste.
143
143
144 Do not be alarmed by garbled output on Windows (it's a readline bug).
144 Do not be alarmed by garbled output on Windows (it's a readline bug).
145 Just press enter and type -- (and press enter again) and the block
145 Just press enter and type -- (and press enter again) and the block
146 will be what was just pasted.
146 will be what was just pasted.
147
147
148 IPython statements (magics, shell escapes) are not supported (yet).
148 IPython statements (magics, shell escapes) are not supported (yet).
149
149
150 See also
150 See also
151 --------
151 --------
152 paste: automatically pull code from clipboard.
152 paste: automatically pull code from clipboard.
153
153
154 Examples
154 Examples
155 --------
155 --------
156 ::
156 ::
157
157
158 In [8]: %cpaste
158 In [8]: %cpaste
159 Pasting code; enter '--' alone on the line to stop.
159 Pasting code; enter '--' alone on the line to stop.
160 :>>> a = ["world!", "Hello"]
160 :>>> a = ["world!", "Hello"]
161 :>>> print " ".join(sorted(a))
161 :>>> print " ".join(sorted(a))
162 :--
162 :--
163 Hello world!
163 Hello world!
164 """
164 """
165 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
165 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
166 if 'r' in opts:
166 if 'r' in opts:
167 self.rerun_pasted()
167 self.rerun_pasted()
168 return
168 return
169
169
170 sentinel = opts.get('s', '--')
170 sentinel = opts.get('s', '--')
171 block = '\n'.join(get_pasted_lines(sentinel))
171 block = '\n'.join(get_pasted_lines(sentinel))
172 self.store_or_execute(block, name)
172 self.store_or_execute(block, name)
173
173
174 @line_magic
174 @line_magic
175 def paste(self, parameter_s=''):
175 def paste(self, parameter_s=''):
176 """Paste & execute a pre-formatted code block from clipboard.
176 """Paste & execute a pre-formatted code block from clipboard.
177
177
178 The text is pulled directly from the clipboard without user
178 The text is pulled directly from the clipboard without user
179 intervention and printed back on the screen before execution (unless
179 intervention and printed back on the screen before execution (unless
180 the -q flag is given to force quiet mode).
180 the -q flag is given to force quiet mode).
181
181
182 The block is dedented prior to execution to enable execution of method
182 The block is dedented prior to execution to enable execution of method
183 definitions. '>' and '+' characters at the beginning of a line are
183 definitions. '>' and '+' characters at the beginning of a line are
184 ignored, to allow pasting directly from e-mails, diff files and
184 ignored, to allow pasting directly from e-mails, diff files and
185 doctests (the '...' continuation prompt is also stripped). The
185 doctests (the '...' continuation prompt is also stripped). The
186 executed block is also assigned to variable named 'pasted_block' for
186 executed block is also assigned to variable named 'pasted_block' for
187 later editing with '%edit pasted_block'.
187 later editing with '%edit pasted_block'.
188
188
189 You can also pass a variable name as an argument, e.g. '%paste foo'.
189 You can also pass a variable name as an argument, e.g. '%paste foo'.
190 This assigns the pasted block to variable 'foo' as string, without
190 This assigns the pasted block to variable 'foo' as string, without
191 executing it (preceding >>> and + is still stripped).
191 executing it (preceding >>> and + is still stripped).
192
192
193 Options
193 Options
194 -------
194 -------
195
195
196 -r: re-executes the block previously entered by cpaste.
196 -r: re-executes the block previously entered by cpaste.
197
197
198 -q: quiet mode: do not echo the pasted text back to the terminal.
198 -q: quiet mode: do not echo the pasted text back to the terminal.
199
199
200 IPython statements (magics, shell escapes) are not supported (yet).
200 IPython statements (magics, shell escapes) are not supported (yet).
201
201
202 See also
202 See also
203 --------
203 --------
204 cpaste: manually paste code into terminal until you mark its end.
204 cpaste: manually paste code into terminal until you mark its end.
205 """
205 """
206 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
206 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
207 if 'r' in opts:
207 if 'r' in opts:
208 self.rerun_pasted()
208 self.rerun_pasted()
209 return
209 return
210 try:
210 try:
211 block = self.shell.hooks.clipboard_get()
211 block = self.shell.hooks.clipboard_get()
212 except TryNext as clipboard_exc:
212 except TryNext as clipboard_exc:
213 message = getattr(clipboard_exc, 'args')
213 message = getattr(clipboard_exc, 'args')
214 if message:
214 if message:
215 error(message[0])
215 error(message[0])
216 else:
216 else:
217 error('Could not get text from the clipboard.')
217 error('Could not get text from the clipboard.')
218 return
218 return
219
219
220 # By default, echo back to terminal unless quiet mode is requested
220 # By default, echo back to terminal unless quiet mode is requested
221 if 'q' not in opts:
221 if 'q' not in opts:
222 write = self.shell.write
222 write = self.shell.write
223 write(self.shell.pycolorize(block))
223 write(self.shell.pycolorize(block))
224 if not block.endswith('\n'):
224 if not block.endswith('\n'):
225 write('\n')
225 write('\n')
226 write("## -- End pasted text --\n")
226 write("## -- End pasted text --\n")
227
227
228 self.store_or_execute(block, name)
228 self.store_or_execute(block, name)
229
229
230 # Class-level: add a '%cls' magic only on Windows
230 # Class-level: add a '%cls' magic only on Windows
231 if sys.platform == 'win32':
231 if sys.platform == 'win32':
232 @line_magic
232 @line_magic
233 def cls(self, s):
233 def cls(self, s):
234 """Clear screen.
234 """Clear screen.
235 """
235 """
236 os.system("cls")
236 os.system("cls")
237
237
238 #-----------------------------------------------------------------------------
238 #-----------------------------------------------------------------------------
239 # Main class
239 # Main class
240 #-----------------------------------------------------------------------------
240 #-----------------------------------------------------------------------------
241
241
242 class TerminalInteractiveShell(InteractiveShell):
242 class TerminalInteractiveShell(InteractiveShell):
243
243
244 autoedit_syntax = CBool(False, config=True,
244 autoedit_syntax = CBool(False, config=True,
245 help="auto editing of files with syntax errors.")
245 help="auto editing of files with syntax errors.")
246 banner = Unicode('')
246 banner = Unicode('')
247 banner1 = Unicode(default_banner, config=True,
247 banner1 = Unicode(default_banner, config=True,
248 help="""The part of the banner to be printed before the profile"""
248 help="""The part of the banner to be printed before the profile"""
249 )
249 )
250 banner2 = Unicode('', config=True,
250 banner2 = Unicode('', config=True,
251 help="""The part of the banner to be printed after the profile"""
251 help="""The part of the banner to be printed after the profile"""
252 )
252 )
253 confirm_exit = CBool(True, config=True,
253 confirm_exit = CBool(True, config=True,
254 help="""
254 help="""
255 Set to confirm when you try to exit IPython with an EOF (Control-D
255 Set to confirm when you try to exit IPython with an EOF (Control-D
256 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
256 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
257 you can force a direct exit without any confirmation.""",
257 you can force a direct exit without any confirmation.""",
258 )
258 )
259 # This display_banner only controls whether or not self.show_banner()
259 # This display_banner only controls whether or not self.show_banner()
260 # is called when mainloop/interact are called. The default is False
260 # is called when mainloop/interact are called. The default is False
261 # because for the terminal based application, the banner behavior
261 # because for the terminal based application, the banner behavior
262 # is controlled by Global.display_banner, which IPythonApp looks at
262 # is controlled by Global.display_banner, which IPythonApp looks at
263 # to determine if *it* should call show_banner() by hand or not.
263 # to determine if *it* should call show_banner() by hand or not.
264 display_banner = CBool(False) # This isn't configurable!
264 display_banner = CBool(False) # This isn't configurable!
265 embedded = CBool(False)
265 embedded = CBool(False)
266 embedded_active = CBool(False)
266 embedded_active = CBool(False)
267 editor = Unicode(get_default_editor(), config=True,
267 editor = Unicode(get_default_editor(), config=True,
268 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
268 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
269 )
269 )
270 pager = Unicode('less', config=True,
270 pager = Unicode('less', config=True,
271 help="The shell program to be used for paging.")
271 help="The shell program to be used for paging.")
272
272
273 screen_length = Integer(0, config=True,
273 screen_length = Integer(0, config=True,
274 help=
274 help=
275 """Number of lines of your screen, used to control printing of very
275 """Number of lines of your screen, used to control printing of very
276 long strings. Strings longer than this number of lines will be sent
276 long strings. Strings longer than this number of lines will be sent
277 through a pager instead of directly printed. The default value for
277 through a pager instead of directly printed. The default value for
278 this is 0, which means IPython will auto-detect your screen size every
278 this is 0, which means IPython will auto-detect your screen size every
279 time it needs to print certain potentially long strings (this doesn't
279 time it needs to print certain potentially long strings (this doesn't
280 change the behavior of the 'print' keyword, it's only triggered
280 change the behavior of the 'print' keyword, it's only triggered
281 internally). If for some reason this isn't working well (it needs
281 internally). If for some reason this isn't working well (it needs
282 curses support), specify it yourself. Otherwise don't change the
282 curses support), specify it yourself. Otherwise don't change the
283 default.""",
283 default.""",
284 )
284 )
285 term_title = CBool(False, config=True,
285 term_title = CBool(False, config=True,
286 help="Enable auto setting the terminal title."
286 help="Enable auto setting the terminal title."
287 )
287 )
288
288
289 # This `using_paste_magics` is used to detect whether the code is being
289 # This `using_paste_magics` is used to detect whether the code is being
290 # executed via paste magics functions
290 # executed via paste magics functions
291 using_paste_magics = CBool(False)
291 using_paste_magics = CBool(False)
292
292
293 # In the terminal, GUI control is done via PyOS_InputHook
293 # In the terminal, GUI control is done via PyOS_InputHook
294 @staticmethod
294 @staticmethod
295 def enable_gui(gui=None, app=None):
295 def enable_gui(gui=None, app=None):
296 """Switch amongst GUI input hooks by name.
296 """Switch amongst GUI input hooks by name.
297 """
297 """
298 # Deferred import
298 # Deferred import
299 from IPython.lib.inputhook import enable_gui as real_enable_gui
299 from IPython.lib.inputhook import enable_gui as real_enable_gui
300 try:
300 try:
301 return real_enable_gui(gui, app)
301 return real_enable_gui(gui, app)
302 except ValueError as e:
302 except ValueError as e:
303 raise UsageError("%s" % e)
303 raise UsageError("%s" % e)
304
304
305 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
305 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
306 user_ns=None, user_module=None, custom_exceptions=((),None),
306 user_ns=None, user_module=None, custom_exceptions=((),None),
307 usage=None, banner1=None, banner2=None, display_banner=None,
307 usage=None, banner1=None, banner2=None, display_banner=None,
308 **kwargs):
308 **kwargs):
309
309
310 super(TerminalInteractiveShell, self).__init__(
310 super(TerminalInteractiveShell, self).__init__(
311 config=config, ipython_dir=ipython_dir, profile_dir=profile_dir, user_ns=user_ns,
311 config=config, ipython_dir=ipython_dir, profile_dir=profile_dir, user_ns=user_ns,
312 user_module=user_module, custom_exceptions=custom_exceptions,
312 user_module=user_module, custom_exceptions=custom_exceptions,
313 **kwargs
313 **kwargs
314 )
314 )
315 # use os.system instead of utils.process.system by default,
315 # use os.system instead of utils.process.system by default,
316 # because piped system doesn't make sense in the Terminal:
316 # because piped system doesn't make sense in the Terminal:
317 self.system = self.system_raw
317 self.system = self.system_raw
318
318
319 self.init_term_title()
319 self.init_term_title()
320 self.init_usage(usage)
320 self.init_usage(usage)
321 self.init_banner(banner1, banner2, display_banner)
321 self.init_banner(banner1, banner2, display_banner)
322
322
323 #-------------------------------------------------------------------------
323 #-------------------------------------------------------------------------
324 # Overrides of init stages
324 # Overrides of init stages
325 #-------------------------------------------------------------------------
325 #-------------------------------------------------------------------------
326
326
327 def init_display_formatter(self):
327 def init_display_formatter(self):
328 super(TerminalInteractiveShell, self).init_display_formatter()
328 super(TerminalInteractiveShell, self).init_display_formatter()
329 # terminal only supports plaintext
329 # terminal only supports plaintext
330 self.display_formatter.active_types = ['text/plain']
330 self.display_formatter.active_types = ['text/plain']
331
331
332 #-------------------------------------------------------------------------
332 #-------------------------------------------------------------------------
333 # Things related to the terminal
333 # Things related to the terminal
334 #-------------------------------------------------------------------------
334 #-------------------------------------------------------------------------
335
335
336 @property
336 @property
337 def usable_screen_length(self):
337 def usable_screen_length(self):
338 if self.screen_length == 0:
338 if self.screen_length == 0:
339 return 0
339 return 0
340 else:
340 else:
341 num_lines_bot = self.separate_in.count('\n')+1
341 num_lines_bot = self.separate_in.count('\n')+1
342 return self.screen_length - num_lines_bot
342 return self.screen_length - num_lines_bot
343
343
344 def init_term_title(self):
344 def init_term_title(self):
345 # Enable or disable the terminal title.
345 # Enable or disable the terminal title.
346 if self.term_title:
346 if self.term_title:
347 toggle_set_term_title(True)
347 toggle_set_term_title(True)
348 set_term_title('IPython: ' + abbrev_cwd())
348 set_term_title('IPython: ' + abbrev_cwd())
349 else:
349 else:
350 toggle_set_term_title(False)
350 toggle_set_term_title(False)
351
351
352 #-------------------------------------------------------------------------
352 #-------------------------------------------------------------------------
353 # Things related to aliases
353 # Things related to aliases
354 #-------------------------------------------------------------------------
354 #-------------------------------------------------------------------------
355
355
356 def init_alias(self):
356 def init_alias(self):
357 # The parent class defines aliases that can be safely used with any
357 # The parent class defines aliases that can be safely used with any
358 # frontend.
358 # frontend.
359 super(TerminalInteractiveShell, self).init_alias()
359 super(TerminalInteractiveShell, self).init_alias()
360
360
361 # Now define aliases that only make sense on the terminal, because they
361 # Now define aliases that only make sense on the terminal, because they
362 # need direct access to the console in a way that we can't emulate in
362 # need direct access to the console in a way that we can't emulate in
363 # GUI or web frontend
363 # GUI or web frontend
364 if os.name == 'posix':
364 if os.name == 'posix':
365 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
365 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
366 ('man', 'man')]
366 ('man', 'man')]
367 elif os.name == 'nt':
367 elif os.name == 'nt':
368 aliases = [('cls', 'cls')]
368 aliases = [('cls', 'cls')]
369
369
370
370
371 for name, cmd in aliases:
371 for name, cmd in aliases:
372 self.alias_manager.define_alias(name, cmd)
372 self.alias_manager.soft_define_alias(name, cmd)
373
373
374 #-------------------------------------------------------------------------
374 #-------------------------------------------------------------------------
375 # Things related to the banner and usage
375 # Things related to the banner and usage
376 #-------------------------------------------------------------------------
376 #-------------------------------------------------------------------------
377
377
378 def _banner1_changed(self):
378 def _banner1_changed(self):
379 self.compute_banner()
379 self.compute_banner()
380
380
381 def _banner2_changed(self):
381 def _banner2_changed(self):
382 self.compute_banner()
382 self.compute_banner()
383
383
384 def _term_title_changed(self, name, new_value):
384 def _term_title_changed(self, name, new_value):
385 self.init_term_title()
385 self.init_term_title()
386
386
387 def init_banner(self, banner1, banner2, display_banner):
387 def init_banner(self, banner1, banner2, display_banner):
388 if banner1 is not None:
388 if banner1 is not None:
389 self.banner1 = banner1
389 self.banner1 = banner1
390 if banner2 is not None:
390 if banner2 is not None:
391 self.banner2 = banner2
391 self.banner2 = banner2
392 if display_banner is not None:
392 if display_banner is not None:
393 self.display_banner = display_banner
393 self.display_banner = display_banner
394 self.compute_banner()
394 self.compute_banner()
395
395
396 def show_banner(self, banner=None):
396 def show_banner(self, banner=None):
397 if banner is None:
397 if banner is None:
398 banner = self.banner
398 banner = self.banner
399 self.write(banner)
399 self.write(banner)
400
400
401 def compute_banner(self):
401 def compute_banner(self):
402 self.banner = self.banner1
402 self.banner = self.banner1
403 if self.profile and self.profile != 'default':
403 if self.profile and self.profile != 'default':
404 self.banner += '\nIPython profile: %s\n' % self.profile
404 self.banner += '\nIPython profile: %s\n' % self.profile
405 if self.banner2:
405 if self.banner2:
406 self.banner += '\n' + self.banner2
406 self.banner += '\n' + self.banner2
407
407
408 def init_usage(self, usage=None):
408 def init_usage(self, usage=None):
409 if usage is None:
409 if usage is None:
410 self.usage = interactive_usage
410 self.usage = interactive_usage
411 else:
411 else:
412 self.usage = usage
412 self.usage = usage
413
413
414 #-------------------------------------------------------------------------
414 #-------------------------------------------------------------------------
415 # Mainloop and code execution logic
415 # Mainloop and code execution logic
416 #-------------------------------------------------------------------------
416 #-------------------------------------------------------------------------
417
417
418 def mainloop(self, display_banner=None):
418 def mainloop(self, display_banner=None):
419 """Start the mainloop.
419 """Start the mainloop.
420
420
421 If an optional banner argument is given, it will override the
421 If an optional banner argument is given, it will override the
422 internally created default banner.
422 internally created default banner.
423 """
423 """
424
424
425 with self.builtin_trap, self.display_trap:
425 with self.builtin_trap, self.display_trap:
426
426
427 while 1:
427 while 1:
428 try:
428 try:
429 self.interact(display_banner=display_banner)
429 self.interact(display_banner=display_banner)
430 #self.interact_with_readline()
430 #self.interact_with_readline()
431 # XXX for testing of a readline-decoupled repl loop, call
431 # XXX for testing of a readline-decoupled repl loop, call
432 # interact_with_readline above
432 # interact_with_readline above
433 break
433 break
434 except KeyboardInterrupt:
434 except KeyboardInterrupt:
435 # this should not be necessary, but KeyboardInterrupt
435 # this should not be necessary, but KeyboardInterrupt
436 # handling seems rather unpredictable...
436 # handling seems rather unpredictable...
437 self.write("\nKeyboardInterrupt in interact()\n")
437 self.write("\nKeyboardInterrupt in interact()\n")
438
438
439 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
439 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
440 """Store multiple lines as a single entry in history"""
440 """Store multiple lines as a single entry in history"""
441
441
442 # do nothing without readline or disabled multiline
442 # do nothing without readline or disabled multiline
443 if not self.has_readline or not self.multiline_history:
443 if not self.has_readline or not self.multiline_history:
444 return hlen_before_cell
444 return hlen_before_cell
445
445
446 # windows rl has no remove_history_item
446 # windows rl has no remove_history_item
447 if not hasattr(self.readline, "remove_history_item"):
447 if not hasattr(self.readline, "remove_history_item"):
448 return hlen_before_cell
448 return hlen_before_cell
449
449
450 # skip empty cells
450 # skip empty cells
451 if not source_raw.rstrip():
451 if not source_raw.rstrip():
452 return hlen_before_cell
452 return hlen_before_cell
453
453
454 # nothing changed do nothing, e.g. when rl removes consecutive dups
454 # nothing changed do nothing, e.g. when rl removes consecutive dups
455 hlen = self.readline.get_current_history_length()
455 hlen = self.readline.get_current_history_length()
456 if hlen == hlen_before_cell:
456 if hlen == hlen_before_cell:
457 return hlen_before_cell
457 return hlen_before_cell
458
458
459 for i in range(hlen - hlen_before_cell):
459 for i in range(hlen - hlen_before_cell):
460 self.readline.remove_history_item(hlen - i - 1)
460 self.readline.remove_history_item(hlen - i - 1)
461 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
461 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
462 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
462 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
463 stdin_encoding))
463 stdin_encoding))
464 return self.readline.get_current_history_length()
464 return self.readline.get_current_history_length()
465
465
466 def interact(self, display_banner=None):
466 def interact(self, display_banner=None):
467 """Closely emulate the interactive Python console."""
467 """Closely emulate the interactive Python console."""
468
468
469 # batch run -> do not interact
469 # batch run -> do not interact
470 if self.exit_now:
470 if self.exit_now:
471 return
471 return
472
472
473 if display_banner is None:
473 if display_banner is None:
474 display_banner = self.display_banner
474 display_banner = self.display_banner
475
475
476 if isinstance(display_banner, basestring):
476 if isinstance(display_banner, basestring):
477 self.show_banner(display_banner)
477 self.show_banner(display_banner)
478 elif display_banner:
478 elif display_banner:
479 self.show_banner()
479 self.show_banner()
480
480
481 more = False
481 more = False
482
482
483 if self.has_readline:
483 if self.has_readline:
484 self.readline_startup_hook(self.pre_readline)
484 self.readline_startup_hook(self.pre_readline)
485 hlen_b4_cell = self.readline.get_current_history_length()
485 hlen_b4_cell = self.readline.get_current_history_length()
486 else:
486 else:
487 hlen_b4_cell = 0
487 hlen_b4_cell = 0
488 # exit_now is set by a call to %Exit or %Quit, through the
488 # exit_now is set by a call to %Exit or %Quit, through the
489 # ask_exit callback.
489 # ask_exit callback.
490
490
491 while not self.exit_now:
491 while not self.exit_now:
492 self.hooks.pre_prompt_hook()
492 self.hooks.pre_prompt_hook()
493 if more:
493 if more:
494 try:
494 try:
495 prompt = self.prompt_manager.render('in2')
495 prompt = self.prompt_manager.render('in2')
496 except:
496 except:
497 self.showtraceback()
497 self.showtraceback()
498 if self.autoindent:
498 if self.autoindent:
499 self.rl_do_indent = True
499 self.rl_do_indent = True
500
500
501 else:
501 else:
502 try:
502 try:
503 prompt = self.separate_in + self.prompt_manager.render('in')
503 prompt = self.separate_in + self.prompt_manager.render('in')
504 except:
504 except:
505 self.showtraceback()
505 self.showtraceback()
506 try:
506 try:
507 line = self.raw_input(prompt)
507 line = self.raw_input(prompt)
508 if self.exit_now:
508 if self.exit_now:
509 # quick exit on sys.std[in|out] close
509 # quick exit on sys.std[in|out] close
510 break
510 break
511 if self.autoindent:
511 if self.autoindent:
512 self.rl_do_indent = False
512 self.rl_do_indent = False
513
513
514 except KeyboardInterrupt:
514 except KeyboardInterrupt:
515 #double-guard against keyboardinterrupts during kbdint handling
515 #double-guard against keyboardinterrupts during kbdint handling
516 try:
516 try:
517 self.write('\nKeyboardInterrupt\n')
517 self.write('\nKeyboardInterrupt\n')
518 source_raw = self.input_splitter.source_raw_reset()[1]
518 source_raw = self.input_splitter.source_raw_reset()[1]
519 hlen_b4_cell = \
519 hlen_b4_cell = \
520 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
520 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
521 more = False
521 more = False
522 except KeyboardInterrupt:
522 except KeyboardInterrupt:
523 pass
523 pass
524 except EOFError:
524 except EOFError:
525 if self.autoindent:
525 if self.autoindent:
526 self.rl_do_indent = False
526 self.rl_do_indent = False
527 if self.has_readline:
527 if self.has_readline:
528 self.readline_startup_hook(None)
528 self.readline_startup_hook(None)
529 self.write('\n')
529 self.write('\n')
530 self.exit()
530 self.exit()
531 except bdb.BdbQuit:
531 except bdb.BdbQuit:
532 warn('The Python debugger has exited with a BdbQuit exception.\n'
532 warn('The Python debugger has exited with a BdbQuit exception.\n'
533 'Because of how pdb handles the stack, it is impossible\n'
533 'Because of how pdb handles the stack, it is impossible\n'
534 'for IPython to properly format this particular exception.\n'
534 'for IPython to properly format this particular exception.\n'
535 'IPython will resume normal operation.')
535 'IPython will resume normal operation.')
536 except:
536 except:
537 # exceptions here are VERY RARE, but they can be triggered
537 # exceptions here are VERY RARE, but they can be triggered
538 # asynchronously by signal handlers, for example.
538 # asynchronously by signal handlers, for example.
539 self.showtraceback()
539 self.showtraceback()
540 else:
540 else:
541 self.input_splitter.push(line)
541 self.input_splitter.push(line)
542 more = self.input_splitter.push_accepts_more()
542 more = self.input_splitter.push_accepts_more()
543 if (self.SyntaxTB.last_syntax_error and
543 if (self.SyntaxTB.last_syntax_error and
544 self.autoedit_syntax):
544 self.autoedit_syntax):
545 self.edit_syntax_error()
545 self.edit_syntax_error()
546 if not more:
546 if not more:
547 source_raw = self.input_splitter.source_raw_reset()[1]
547 source_raw = self.input_splitter.source_raw_reset()[1]
548 self.run_cell(source_raw, store_history=True)
548 self.run_cell(source_raw, store_history=True)
549 hlen_b4_cell = \
549 hlen_b4_cell = \
550 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
550 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
551
551
552 # Turn off the exit flag, so the mainloop can be restarted if desired
552 # Turn off the exit flag, so the mainloop can be restarted if desired
553 self.exit_now = False
553 self.exit_now = False
554
554
555 def raw_input(self, prompt=''):
555 def raw_input(self, prompt=''):
556 """Write a prompt and read a line.
556 """Write a prompt and read a line.
557
557
558 The returned line does not include the trailing newline.
558 The returned line does not include the trailing newline.
559 When the user enters the EOF key sequence, EOFError is raised.
559 When the user enters the EOF key sequence, EOFError is raised.
560
560
561 Optional inputs:
561 Optional inputs:
562
562
563 - prompt(''): a string to be printed to prompt the user.
563 - prompt(''): a string to be printed to prompt the user.
564
564
565 - continue_prompt(False): whether this line is the first one or a
565 - continue_prompt(False): whether this line is the first one or a
566 continuation in a sequence of inputs.
566 continuation in a sequence of inputs.
567 """
567 """
568 # Code run by the user may have modified the readline completer state.
568 # Code run by the user may have modified the readline completer state.
569 # We must ensure that our completer is back in place.
569 # We must ensure that our completer is back in place.
570
570
571 if self.has_readline:
571 if self.has_readline:
572 self.set_readline_completer()
572 self.set_readline_completer()
573
573
574 # raw_input expects str, but we pass it unicode sometimes
574 # raw_input expects str, but we pass it unicode sometimes
575 prompt = py3compat.cast_bytes_py2(prompt)
575 prompt = py3compat.cast_bytes_py2(prompt)
576
576
577 try:
577 try:
578 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
578 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
579 except ValueError:
579 except ValueError:
580 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
580 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
581 " or sys.stdout.close()!\nExiting IPython!\n")
581 " or sys.stdout.close()!\nExiting IPython!\n")
582 self.ask_exit()
582 self.ask_exit()
583 return ""
583 return ""
584
584
585 # Try to be reasonably smart about not re-indenting pasted input more
585 # Try to be reasonably smart about not re-indenting pasted input more
586 # than necessary. We do this by trimming out the auto-indent initial
586 # than necessary. We do this by trimming out the auto-indent initial
587 # spaces, if the user's actual input started itself with whitespace.
587 # spaces, if the user's actual input started itself with whitespace.
588 if self.autoindent:
588 if self.autoindent:
589 if num_ini_spaces(line) > self.indent_current_nsp:
589 if num_ini_spaces(line) > self.indent_current_nsp:
590 line = line[self.indent_current_nsp:]
590 line = line[self.indent_current_nsp:]
591 self.indent_current_nsp = 0
591 self.indent_current_nsp = 0
592
592
593 return line
593 return line
594
594
595 #-------------------------------------------------------------------------
595 #-------------------------------------------------------------------------
596 # Methods to support auto-editing of SyntaxErrors.
596 # Methods to support auto-editing of SyntaxErrors.
597 #-------------------------------------------------------------------------
597 #-------------------------------------------------------------------------
598
598
599 def edit_syntax_error(self):
599 def edit_syntax_error(self):
600 """The bottom half of the syntax error handler called in the main loop.
600 """The bottom half of the syntax error handler called in the main loop.
601
601
602 Loop until syntax error is fixed or user cancels.
602 Loop until syntax error is fixed or user cancels.
603 """
603 """
604
604
605 while self.SyntaxTB.last_syntax_error:
605 while self.SyntaxTB.last_syntax_error:
606 # copy and clear last_syntax_error
606 # copy and clear last_syntax_error
607 err = self.SyntaxTB.clear_err_state()
607 err = self.SyntaxTB.clear_err_state()
608 if not self._should_recompile(err):
608 if not self._should_recompile(err):
609 return
609 return
610 try:
610 try:
611 # may set last_syntax_error again if a SyntaxError is raised
611 # may set last_syntax_error again if a SyntaxError is raised
612 self.safe_execfile(err.filename,self.user_ns)
612 self.safe_execfile(err.filename,self.user_ns)
613 except:
613 except:
614 self.showtraceback()
614 self.showtraceback()
615 else:
615 else:
616 try:
616 try:
617 f = open(err.filename)
617 f = open(err.filename)
618 try:
618 try:
619 # This should be inside a display_trap block and I
619 # This should be inside a display_trap block and I
620 # think it is.
620 # think it is.
621 sys.displayhook(f.read())
621 sys.displayhook(f.read())
622 finally:
622 finally:
623 f.close()
623 f.close()
624 except:
624 except:
625 self.showtraceback()
625 self.showtraceback()
626
626
627 def _should_recompile(self,e):
627 def _should_recompile(self,e):
628 """Utility routine for edit_syntax_error"""
628 """Utility routine for edit_syntax_error"""
629
629
630 if e.filename in ('<ipython console>','<input>','<string>',
630 if e.filename in ('<ipython console>','<input>','<string>',
631 '<console>','<BackgroundJob compilation>',
631 '<console>','<BackgroundJob compilation>',
632 None):
632 None):
633
633
634 return False
634 return False
635 try:
635 try:
636 if (self.autoedit_syntax and
636 if (self.autoedit_syntax and
637 not self.ask_yes_no('Return to editor to correct syntax error? '
637 not self.ask_yes_no('Return to editor to correct syntax error? '
638 '[Y/n] ','y')):
638 '[Y/n] ','y')):
639 return False
639 return False
640 except EOFError:
640 except EOFError:
641 return False
641 return False
642
642
643 def int0(x):
643 def int0(x):
644 try:
644 try:
645 return int(x)
645 return int(x)
646 except TypeError:
646 except TypeError:
647 return 0
647 return 0
648 # always pass integer line and offset values to editor hook
648 # always pass integer line and offset values to editor hook
649 try:
649 try:
650 self.hooks.fix_error_editor(e.filename,
650 self.hooks.fix_error_editor(e.filename,
651 int0(e.lineno),int0(e.offset),e.msg)
651 int0(e.lineno),int0(e.offset),e.msg)
652 except TryNext:
652 except TryNext:
653 warn('Could not open editor')
653 warn('Could not open editor')
654 return False
654 return False
655 return True
655 return True
656
656
657 #-------------------------------------------------------------------------
657 #-------------------------------------------------------------------------
658 # Things related to exiting
658 # Things related to exiting
659 #-------------------------------------------------------------------------
659 #-------------------------------------------------------------------------
660
660
661 def ask_exit(self):
661 def ask_exit(self):
662 """ Ask the shell to exit. Can be overiden and used as a callback. """
662 """ Ask the shell to exit. Can be overiden and used as a callback. """
663 self.exit_now = True
663 self.exit_now = True
664
664
665 def exit(self):
665 def exit(self):
666 """Handle interactive exit.
666 """Handle interactive exit.
667
667
668 This method calls the ask_exit callback."""
668 This method calls the ask_exit callback."""
669 if self.confirm_exit:
669 if self.confirm_exit:
670 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
670 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
671 self.ask_exit()
671 self.ask_exit()
672 else:
672 else:
673 self.ask_exit()
673 self.ask_exit()
674
674
675 #-------------------------------------------------------------------------
675 #-------------------------------------------------------------------------
676 # Things related to magics
676 # Things related to magics
677 #-------------------------------------------------------------------------
677 #-------------------------------------------------------------------------
678
678
679 def init_magics(self):
679 def init_magics(self):
680 super(TerminalInteractiveShell, self).init_magics()
680 super(TerminalInteractiveShell, self).init_magics()
681 self.register_magics(TerminalMagics)
681 self.register_magics(TerminalMagics)
682
682
683 def showindentationerror(self):
683 def showindentationerror(self):
684 super(TerminalInteractiveShell, self).showindentationerror()
684 super(TerminalInteractiveShell, self).showindentationerror()
685 if not self.using_paste_magics:
685 if not self.using_paste_magics:
686 print("If you want to paste code into IPython, try the "
686 print("If you want to paste code into IPython, try the "
687 "%paste and %cpaste magic functions.")
687 "%paste and %cpaste magic functions.")
688
688
689
689
690 InteractiveShellABC.register(TerminalInteractiveShell)
690 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now